From ebb38b380300a77e48e2b0bdd67b2807da396fed Mon Sep 17 00:00:00 2001 From: Maurice Faber Date: Tue, 24 Nov 2026 20:05:56 +0100 Subject: [PATCH 01/11] fix(deps): hold the logger below 0.7 and keep Dependabot from lifting the bound itsup imports instrukt_ai_logging.cli, which the logger stopped shipping in 0.7.0. The bound set for that was rewritten to <0.11 by the next grouped Dependabot bump, because a 0.x minor is not a semver-major and the existing ignore rule let it through. The lock moved to 0.10.2 and the container host installed it on its next self-update, after which every itsup command failed on import: boot bringup, the nightly apply, the API and the monitor start. Restore the bound, relock to 0.6.7, and tell Dependabot to ignore logger releases from 0.7 so the bound is not rewritten again. Session: t3:5128ca34-972f-4682-ada6-678a5e45024e Human-Involved: true --- .github/dependabot.yml | 6 ++++++ pyproject.toml | 2 +- uv.lock | 8 ++++---- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index d6b29695..16d11f58 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -21,6 +21,12 @@ updates: - dependency-name: '*' update-types: - version-update:semver-major + # itsup imports instrukt_ai_logging.cli, which releases from 0.7.0 no + # longer ship. A 0.x minor is not a semver-major, so the rule above lets + # it through and the bump rewrites the upper bound in pyproject.toml. + - dependency-name: 'instruktai-python-logger' + versions: + - '>=0.7' groups: all-dependencies: patterns: diff --git a/pyproject.toml b/pyproject.toml index 1b76670b..a2a9ec96 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -24,7 +24,7 @@ dependencies = [ "fastapi", # itsup logs imports instrukt_ai_logging.cli, which releases from 0.7.0 no # longer ship; without the upper bound the CLI fails to start. - "instruktai-python-logger>=0.6.6,<0.11", + "instruktai-python-logger>=0.6.6,<0.7", "ipwhois", "jinja2-cli", "netifaces", diff --git a/uv.lock b/uv.lock index 8f586363..f5872b28 100644 --- a/uv.lock +++ b/uv.lock @@ -538,11 +538,11 @@ wheels = [ [[package]] name = "instruktai-python-logger" -version = "0.10.2" +version = "0.6.7" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/51/42/4add0fc4138b6b8615bfc96d09d6f694c5fbcfd4108fe49dc9c6e672bb53/instruktai_python_logger-0.10.2.tar.gz", hash = "sha256:89a21ba1bf6fccf6f3ee7e3f6887b4eed510f33ea533523e0c81c54767c3f608", size = 41430, upload-time = "2026-11-13T07:07:57.692Z" } +sdist = { url = "https://files.pythonhosted.org/packages/d1/29/dcba997577464c67c9e16a669d1aed360c6b3172685317a75615c5d6e35c/instruktai_python_logger-0.6.7.tar.gz", hash = "sha256:0baa3f882e32c99da753ec8c2b4e4d2151f20eac9e33725f8da89bbe46e6d29e", size = 26568, upload-time = "2026-10-09T17:30:43.587Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/5c/e5/50e6c201fa706d0a6f8e7ec948ba4d0f8d033614523ceab623866989736e/instruktai_python_logger-0.10.2-py3-none-any.whl", hash = "sha256:47b57e10825e41c79ce9da579f3b649e77e9172be98dba484211d41fe6bb08da", size = 21769, upload-time = "2026-11-13T07:07:56.61Z" }, + { url = "https://files.pythonhosted.org/packages/5f/37/05993af519b3d9e697d54740b045925bcc6d796edfea2eab2d22240d9e2b/instruktai_python_logger-0.6.7-py3-none-any.whl", hash = "sha256:34d563de5071a4130ca9cc4337ed4a617707bf1c21f640ed02df30bf17f153fc", size = 18594, upload-time = "2026-10-09T17:30:42.744Z" }, ] [[package]] @@ -603,7 +603,7 @@ requires-dist = [ { name = "boto3" }, { name = "click" }, { name = "fastapi" }, - { name = "instruktai-python-logger", specifier = ">=0.6.6,<0.11" }, + { name = "instruktai-python-logger", specifier = ">=0.6.6,<0.7" }, { name = "ipwhois" }, { name = "jinja2-cli" }, { name = "netifaces" }, From 3524d91f59c5972eaa49b4b378917a3bd2048c37 Mon Sep 17 00:00:00 2001 From: Maurice Faber Date: Tue, 24 Nov 2026 23:19:12 +0100 Subject: [PATCH 02/11] refactor(logs): own the --since duration grammar and the file follower The logs command took both from the logger's reader side, which the logger removed in 0.7.0 when its Python package became the writer SDK only. The CLI imports the logs command at start, so that one import kept every itsup command from starting on a current logger. itsUP now carries the two helpers in lib/log_reading.py. The follower keeps the behaviour the access log needs: it follows an existing file from its end and keeps going across truncation in place (copytruncate), replacement at the same path, and a file that is not there yet. Three things differ from the code it replaces. A line is held until its newline arrives, so --grep and --since see whole records, and a file that appears after the follow started is read from its beginning instead of from its end; the logger project's current follower does both. The file is read as bytes, so truncation is judged against a true byte offset and line endings pass through unchanged, as they already do when the file is read without --follow. The third-party note that documented the removed reader primitives as something itsUP reuses goes with the imports. Session: t3:5128ca34-972f-4682-ada6-678a5e45024e Human-Involved: true --- commands/logs.py | 7 +- .../log-reading-primitives.md | 57 -------------- lib/log_reading.py | 78 +++++++++++++++++++ 3 files changed, 81 insertions(+), 61 deletions(-) delete mode 100644 docs/third-party/instrukt-ai-logging/log-reading-primitives.md create mode 100644 lib/log_reading.py diff --git a/commands/logs.py b/commands/logs.py index 6cf5a54b..bb16d49c 100644 --- a/commands/logs.py +++ b/commands/logs.py @@ -12,10 +12,9 @@ from pathlib import Path import click -from instrukt_ai_logging.cli import iter_follow_lines -from instrukt_ai_logging.logging import parse_since from commands.common import fail +from lib.log_reading import follow_lines, parse_duration from lib.paths import access_log_file, display_path @@ -83,7 +82,7 @@ def _parse_options(follow: bool, since: str | None, pattern: str | None) -> LogO cutoff = None if since is not None: try: - cutoff = datetime.now(timezone.utc) - parse_since(since) + cutoff = datetime.now(timezone.utc) - parse_duration(since) except ValueError as exc: _fail(f"Invalid --since value: {exc}") raise AssertionError("unreachable") from exc @@ -208,7 +207,7 @@ def _read_file(path: Path, options: LogOptions, *, is_access_log: bool) -> None: try: if options.follow: - for line in iter_follow_lines(path, start_at_end=True): + for line in follow_lines(path): _emit_file_line(line, options, is_access_log=is_access_log) return diff --git a/docs/third-party/instrukt-ai-logging/log-reading-primitives.md b/docs/third-party/instrukt-ai-logging/log-reading-primitives.md deleted file mode 100644 index d7d1eb57..00000000 --- a/docs/third-party/instrukt-ai-logging/log-reading-primitives.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -description: Verified read-side contracts of the installed instrukt-ai-logging package that itsUP reuses — parse_since duration grammar, the rotation-aware iter_follow_lines follower, and why iter_recent_log_lines_merged cannot window Traefik's JSON access log. ---- - -# instrukt-ai-logging — Read-Side Primitives - -Curated from the installed package -(`.venv/lib/python3.14/site-packages/instrukt_ai_logging/`) for the `itsup logs` -router, which reuses the library's readers rather than re-deriving them. The -write side (`configure_logging`, `get_logger`) is covered by -`project/itsup/design/logging`; only what the router consumes is recorded here. - -## Export surface - -`instrukt_ai_logging.__all__` exports the write side plus `resolve_log_file` / -`resolve_log_files`. The three read primitives below are **not** in `__all__`; -the package's own shipped viewer (`instrukt_ai_logging.cli:main`) imports them -from `instrukt_ai_logging.logging` and `instrukt_ai_logging.cli` directly, which -is the same import path a consumer must use. Treat them as a supported-by-usage -surface, not a declared public API: a package upgrade can move them without a -deprecation cycle. - -## `logging.parse_since(value: str) -> timedelta` - -- Accepts `` where unit is one of `s`, `m`, `h`, `d` - (case-insensitive, surrounding whitespace stripped). The number part is - validated with `str.isdigit()`, so `0s` is accepted and yields a zero window; - a sign or a decimal point is rejected. -- Raises `ValueError` on an empty string, a non-digit number part, or an - unrecognised unit. -- Returns a `timedelta` only — it never formats a timestamp, so a consumer - targeting a backend with its own time grammar does that conversion itself. - -## `cli.iter_follow_lines(log_file, *, poll_interval_s=0.25, start_at_end=True, max_lines=None, max_seconds=None)` - -- Yields lines appended to a file, `tail -f` style, by polling. -- Waits for the file to appear if it does not exist yet. -- Detects **rotation** (inode change — reopens and reads the new file from the - start) and **truncation** (offset beyond size — seeks back to the start). -- `max_lines` / `max_seconds` bound the generator. - -## `logging.iter_recent_log_lines_merged(files, since: timedelta)` - -- Merges multiple files into one chronologically ordered stream, skipping files - whose mtime predates the cutoff. -- Keys entirely on `parse_log_timestamp`, which reads the **first - whitespace-delimited token** of each line and requires the form - `YYYY-MM-DDTHH:MM:SS.mmmZ`. A line without that leading token inherits the - previous parsed timestamp from its own file. -- **Not usable for Traefik's JSON access log**: those lines begin with `{`, carry - their time inside a `time` / `StartUTC` field, and therefore have no leading - token to parse. A consumer windowing that format supplies its own predicate over - the JSON field. - -Verified directly against the installed package source in this repository's -`.venv` — `instrukt_ai_logging/logging.py`, `instrukt_ai_logging/cli.py`, and -`instrukt_ai_logging/__init__.py`. diff --git a/lib/log_reading.py b/lib/log_reading.py new file mode 100644 index 00000000..9e253e53 --- /dev/null +++ b/lib/log_reading.py @@ -0,0 +1,78 @@ +"""Read-side primitives for log files: a duration grammar and a file follower.""" + +import os +import time +from collections.abc import Iterator +from datetime import timedelta +from pathlib import Path +from typing import BinaryIO + +_POLL_INTERVAL_SECONDS = 0.25 +_DURATION_UNITS = { + "s": timedelta(seconds=1), + "m": timedelta(minutes=1), + "h": timedelta(hours=1), + "d": timedelta(days=1), +} + + +def parse_duration(value: str) -> timedelta: + """Parse a whole number followed by a unit from `_DURATION_UNITS`.""" + text = value.strip().lower() + number, unit = text[:-1], text[-1:] + if not (number.isascii() and number.isdigit()) or unit not in _DURATION_UNITS: + units = ", ".join(_DURATION_UNITS) + raise ValueError(f"expected a whole number followed by one of {units}, got {value!r}") + return int(number) * _DURATION_UNITS[unit] + + +def follow_lines(path: Path) -> Iterator[str]: + """Yield each line written to `path` from now on; never returns. + + A file present at the start is followed from its end. A file that appears + later, replaces the followed one at the same path, or is truncated in place + is read from its start. + """ + skip_existing = True + while True: + try: + log_file = path.open("rb") + except FileNotFoundError: + skip_existing = False + time.sleep(_POLL_INTERVAL_SECONDS) + continue + with log_file: + if skip_existing: + log_file.seek(0, os.SEEK_END) + skip_existing = False + yield from _lines_while_current(log_file, path) + + +def _lines_while_current(log_file: BinaryIO, path: Path) -> Iterator[str]: + """Yield complete lines from the open file for as long as `path` still names it. + + A line whose end has not arrived when the file stops being current is + yielded as it stands. + """ + inode = os.fstat(log_file.fileno()).st_ino + pending = b"" + while True: + pending += log_file.readline() + if pending.endswith(b"\n"): + yield pending.decode("utf-8", errors="replace") + pending = b"" + elif _is_current(log_file, path, inode): + time.sleep(_POLL_INTERVAL_SECONDS) + else: + break + if pending: + yield pending.decode("utf-8", errors="replace") + + +def _is_current(log_file: BinaryIO, path: Path, inode: int) -> bool: + """Return whether `path` still names the open file and has not been truncated below the read position.""" + try: + status = path.stat() + except FileNotFoundError: + return False + return status.st_ino == inode and status.st_size >= log_file.tell() From 1cb41e4e161d9bc1384412e9729ae72ef485ff69 Mon Sep 17 00:00:00 2001 From: Maurice Faber Date: Tue, 24 Nov 2026 23:19:13 +0100 Subject: [PATCH 03/11] fix(deps): require the current logger instead of holding it below 0.7 Nothing in itsUP imports the logger's removed reader side any more, so the upper bound has no reason left. The requirement becomes a floor at the 0.10 line, the lock moves to 0.10.3, and the Dependabot rule that kept updates from lifting the bound is removed so the logger follows the same update path as every other dependency. The writer API itsUP calls, configure_logging and get_logger, has the same signatures on that release. The logging design follows: the diagnostic viewer is a standalone tool that the Python package no longer installs, the handler is no longer named after a class the logger replaced, and the read path of itsup logs is stated as itsUP's own. Session: t3:5128ca34-972f-4682-ada6-678a5e45024e Human-Involved: true --- .github/dependabot.yml | 6 ------ docs/project/design/logging.md | 32 +++++++++++++++++++------------- pyproject.toml | 4 +--- uv.lock | 8 ++++---- 4 files changed, 24 insertions(+), 26 deletions(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 16d11f58..d6b29695 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -21,12 +21,6 @@ updates: - dependency-name: '*' update-types: - version-update:semver-major - # itsup imports instrukt_ai_logging.cli, which releases from 0.7.0 no - # longer ship. A 0.x minor is not a semver-major, so the rule above lets - # it through and the bump rewrites the upper bound in pyproject.toml. - - dependency-name: 'instruktai-python-logger' - versions: - - '>=0.7' groups: all-dependencies: patterns: diff --git a/docs/project/design/logging.md b/docs/project/design/logging.md index 78d19fa2..46389d4b 100644 --- a/docs/project/design/logging.md +++ b/docs/project/design/logging.md @@ -70,8 +70,8 @@ The library writes a single folder per app, `$XDG_STATE_HOME/instrukt-ai/itsup/` (fallback `~/.local/state/instrukt-ai/itsup/`), and one plain-text logfmt file per producing process, selected by the `source=` argument of `configure_logging` (`configure_logging(app, *, source=None)` → `f"{source or app}.log"`, a single -file-only `WatchedFileHandler` on the root logger — the library has no console -mode, which is why the daemon paths configure their own stdout handler instead): +file-only handler on the root logger — the library has no console mode, which is +why the daemon paths configure their own stdout handler instead): - `instrukt-ai/itsup/itsup.log` — the `itsup` CLI and the ephemeral CLI-family one-shots (`bin/migrate_to_v2.py`, `bin/write_artifacts.py`), via @@ -81,8 +81,8 @@ mode, which is why the daemon paths configure their own stdout handler instead): Each producing process declares its own `source`; the empty-source default (one shared `.log`) is deliberately avoided because multiple independent -processes must not share one `WatchedFileHandler` file. This mirrors TeleClaude's -convention (`configure_logging("teleclaude", source="cron")`). +processes must not share one log file. This mirrors TeleClaude's convention +(`configure_logging("teleclaude", source="cron")`). **Container logs (ephemeral):** every Docker container also writes to Docker's default json-file driver. Read via `docker logs` / `docker compose logs`. These @@ -96,10 +96,12 @@ are not part of the `logs/` directory contract. detection feed. - **`journalctl -u `** (Linux) / the agent's `StandardOutPath` file (macOS) — the daemon diagnostics. -- **`instrukt-ai-logs itsup`** — the logger's shipped viewer (console script - `instrukt_ai_logging.cli:main`) tails the diagnostic folder: folder- and - rotation-aware, with `--since`, `--include `, and `--grep`. itsUP - carries no diagnostic-log viewer of its own. +- **`instrukt-ai-logs itsup`** — the logger project's viewer tails the + diagnostic folder: folder- and rotation-aware, with `--since`, + `--include `, and `--grep`. It is a standalone tool installed on its + own: the `instruktai-python-logger` package itsUP depends on is the writer + only, so syncing itsUP's environment does not provide it. itsUP carries no + diagnostic-log viewer of its own. - **Operators** via direct `tail`/`zcat` on `logs/access.log`. - **`itsup logs `** — the itsUP-side front door to these sinks, host-only like the other runtime commands because every backend it reads exists only on @@ -110,8 +112,11 @@ are not part of the `logs/` directory contract. whose lines it emits verbatim. Bare `itsup logs` lists the targets with descriptions; `--follow`, `--grep`, and `--since` narrow the read, with `--since` refused for a macOS unit target whose supervisor-less stream carries - no per-line time. No target exists for an upstream project — those stay - `docker`-led via `itsup svc`/`proxy`/`dns` — and none for interactive CLI runs. + no per-line time. The `--since` duration grammar and the file follower behind + `--follow` are itsUP's own (`lib/log_reading.py`); nothing on this read path + comes from the logger package. No target exists for an upstream project — + those stay `docker`-led via `itsup svc`/`proxy`/`dns` — and none for + interactive CLI runs. ## Invariants @@ -186,9 +191,10 @@ restarts of the unit and rotate under the host's journald retention. On macOS th API's equivalent is `~/Library/Logs/itsup.api.log`. **Viewing CLI and one-shot diagnostics (`instrukt-ai-logs itsup [--include -] [--since W] [--grep RE]`):** the shipped viewer resolves the files -under `instrukt-ai/itsup/` and follows them (rotation-aware). `--include backup` -narrows to `backup.log`; with no filter it merges every source in the folder. +] [--since W] [--grep RE]`):** the logger project's viewer resolves the +files under `instrukt-ai/itsup/` and follows them (rotation-aware). `--include +backup` narrows to `backup.log`; with no filter it merges every source in the +folder. **Viewing the access log:** `itsup logs access` on the container host, or `tail`/`zcat` on `logs/access.log` directly. Either way the JSON record is what diff --git a/pyproject.toml b/pyproject.toml index a2a9ec96..b28033bc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -22,9 +22,7 @@ dependencies = [ "boto3", "click", "fastapi", - # itsup logs imports instrukt_ai_logging.cli, which releases from 0.7.0 no - # longer ship; without the upper bound the CLI fails to start. - "instruktai-python-logger>=0.6.6,<0.7", + "instruktai-python-logger>=0.10", "ipwhois", "jinja2-cli", "netifaces", diff --git a/uv.lock b/uv.lock index f5872b28..ef807ace 100644 --- a/uv.lock +++ b/uv.lock @@ -538,11 +538,11 @@ wheels = [ [[package]] name = "instruktai-python-logger" -version = "0.6.7" +version = "0.10.3" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/d1/29/dcba997577464c67c9e16a669d1aed360c6b3172685317a75615c5d6e35c/instruktai_python_logger-0.6.7.tar.gz", hash = "sha256:0baa3f882e32c99da753ec8c2b4e4d2151f20eac9e33725f8da89bbe46e6d29e", size = 26568, upload-time = "2026-10-09T17:30:43.587Z" } +sdist = { url = "https://files.pythonhosted.org/packages/10/e8/38e58474e1a8b22519415ea7c4909b6a8d58484f6a23c4922e13589b2ec3/instruktai_python_logger-0.10.3.tar.gz", hash = "sha256:33e103f593bfc96d9c7e97986de455d9e6d340803a006b23e9f8d33300747cbd", size = 42334, upload-time = "2026-11-21T13:49:13.707Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/5f/37/05993af519b3d9e697d54740b045925bcc6d796edfea2eab2d22240d9e2b/instruktai_python_logger-0.6.7-py3-none-any.whl", hash = "sha256:34d563de5071a4130ca9cc4337ed4a617707bf1c21f640ed02df30bf17f153fc", size = 18594, upload-time = "2026-10-09T17:30:42.744Z" }, + { url = "https://files.pythonhosted.org/packages/4d/7f/eb72b0bb6278d39695f36dd6d746ae06307fcb0a9bc3794bd54a3c57516b/instruktai_python_logger-0.10.3-py3-none-any.whl", hash = "sha256:62939f277b1b513677066bee5afc01e434cd8841179a0205f9a9e204c5caa767", size = 22248, upload-time = "2026-11-21T13:49:12.789Z" }, ] [[package]] @@ -603,7 +603,7 @@ requires-dist = [ { name = "boto3" }, { name = "click" }, { name = "fastapi" }, - { name = "instruktai-python-logger", specifier = ">=0.6.6,<0.7" }, + { name = "instruktai-python-logger", specifier = ">=0.10" }, { name = "ipwhois" }, { name = "jinja2-cli" }, { name = "netifaces" }, From c15927df2fa987f1eb98a32ee3a7659c89a16a1c Mon Sep 17 00:00:00 2001 From: Maurice Faber Date: Tue, 24 Nov 2026 23:55:22 +0100 Subject: [PATCH 04/11] fix(cli): remove the itsup logs reader itsUP uses the organisation's one logger so that every project carries the same instruction for reading its own logs, `instrukt-ai-logs `. An itsUP-owned reader stands against that: it is a second place to read logs, and because the CLI imported it at start, the reader helpers it borrowed from the logger package took every itsup command down when the logger dropped its reader side. Copying those helpers into itsUP kept the second reader alive under itsUP's ownership instead of removing it. The command, its helpers, its host-gate entry and the path helpers nothing else uses are gone. The CLI spec, the logging design, the host-boundary rules and the README state where each log is read with the tool that owns it: logger-written diagnostics with instrukt-ai-logs (the logger project's standalone tool, with its install step), the supervised units in the supervisor journal, and the Traefik access log as Traefik's own file. Session: t3:thread:delegated-task:command%3Amcp%3A90097403-c516-484c-8d66-e31ba569c0c1%3Adelegate-task%3A07981b9a-bc91-45b2-a78c-d360166c6c63 Human-Involved: true --- AGENTS.md | 2 +- README.md | 17 +- commands/logs.py | 274 ------------------ docs/domain/itsup/policy/host-boundary.md | 2 +- docs/project/design/logging.md | 74 ++--- docs/project/policy/repository-conventions.md | 2 +- docs/project/spec/cli.md | 87 +----- .../systemd/journalctl-querying.md | 7 +- .../systemd/systemctl-unit-introspection.md | 7 +- itsup/cli.py | 4 +- lib/log_reading.py | 78 ----- lib/paths.py | 10 - 12 files changed, 58 insertions(+), 506 deletions(-) delete mode 100644 commands/logs.py delete mode 100644 lib/log_reading.py diff --git a/AGENTS.md b/AGENTS.md index 7e97b59c..1f60b777 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,7 +9,7 @@ This repository holds itsUP, a Docker-based GitOps deployment platform, together ### Rules -- **Runtime-mutating commands run only on the container host** — the machine whose own LAN IP equals `SSH_HOST` in `.env`. The `itsup` CLI enforces this fail-closed: `run`, `apply`, `down`, `dns`, `proxy`, `svc`, `monitor`, and `logs` refuse on any machine whose detected LAN IP does not match `SSH_HOST`, and `make install-runtime` refuses off-host before it touches systemd/launchd. `make uninstall-runtime` is the recovery exception: it may run off-host to remove stale local systemd/launchd integration and local remnants from the current checkout, but it does not invoke the host-only `itsup down` path there. The GitOps, config, secrets, and read commands (`pull`, `commit`, `status`, `create`, `init`, `validate`, `migrate`, `encrypt`, `decrypt`, `diff-secrets`, `edit-secret`, `sops-key`) run anywhere. Off-host a runtime-mutating command would spin up the entire stack locally; the gate is not self-grantable. The command-level contract is in `project/itsup/spec/cli`; operational detail in `project/itsup/spec/runtime-operations`. +- **Runtime-mutating commands run only on the container host** — the machine whose own LAN IP equals `SSH_HOST` in `.env`. The `itsup` CLI enforces this fail-closed: `run`, `apply`, `down`, `dns`, `proxy`, `svc`, and `monitor` refuse on any machine whose detected LAN IP does not match `SSH_HOST`, and `make install-runtime` refuses off-host before it touches systemd/launchd. `make uninstall-runtime` is the recovery exception: it may run off-host to remove stale local systemd/launchd integration and local remnants from the current checkout, but it does not invoke the host-only `itsup down` path there. The GitOps, config, secrets, and read commands (`pull`, `commit`, `status`, `create`, `init`, `validate`, `migrate`, `encrypt`, `decrypt`, `diff-secrets`, `edit-secret`, `sops-key`) run anywhere. Off-host a runtime-mutating command would spin up the entire stack locally; the gate is not self-grantable. The command-level contract is in `project/itsup/spec/cli`; operational detail in `project/itsup/spec/runtime-operations`. - **Operate from the repository root.** Never stay `cd`'d into a subdirectory. For directory-scoped work use `(cd && )` with relative paths. - **Operate from the repository root.** Never stay `cd`'d into a subdirectory. For directory-scoped work use `(cd && )` with relative paths. - **itsUP's own code is not containerized.** The Python CLI (`itsup`), API server, monitoring, DNS honeypot-management, and proxy-config code all run on the host. Only upstream project services are containerized. Never containerize itsUP code. diff --git a/README.md b/README.md index b179f6df..d86eeac7 100644 --- a/README.md +++ b/README.md @@ -509,25 +509,30 @@ On Linux hosts, `make install-runtime` (via `bin/install-bringup.sh`) configures ##### Runtime logs -`itsup logs` is the front door for API, monitor, and supervised runtime logs: +itsUP has no log command of its own; each log is read with the tool that owns it. + +**Application logs** — what itsUP's own code writes through the shared InstruktAI logger (the `itsup` CLI and the one-shot jobs) — are read with the InstruktAI logs tool, the same instruction as for every other InstruktAI project: ```bash -itsup logs api -f +instrukt-ai-logs itsup --since 1h # Everything from the last hour, merged by time +instrukt-ai-logs itsup --follow # Print the recent window, then follow ``` -Application logs can also be queried with the InstruktAI logs CLI: +`instrukt-ai-logs` is the logger project's standalone tool ([InstruktAI/logging](https://github.com/InstruktAI/logging)). The Python package itsUP depends on only writes logs, so `make install` does not provide the tool. Install it once on each machine that reads these logs: ```bash -instrukt-ai-logs -f itsup +curl -LsSf https://github.com/InstruktAI/logging/releases/latest/download/instrukt-ai-logs-installer.sh | sh ``` -Systemd-managed units (bringup, healthcheck, backup) log to stdout/stderr, captured by the journal: `journalctl -u `. On macOS, launchd captures agent output to `~/Library/Logs/itsup..log`. +**Supervised units** — the API server, the security monitor, bringup, apply, backup, and the healthcheck — write to stdout/stderr, captured by the journal: `journalctl -u ` (for example `journalctl -u itsup-api -f`). On macOS, launchd captures agent output to `~/Library/Logs/itsup..log`. + +**The Traefik access log** is Traefik's own JSON file, `logs/access.log`, read with ordinary tools. #### 6. Monitor ```bash # Follow raw Traefik access records -itsup logs access -f +tail -f logs/access.log ``` ### Configure services diff --git a/commands/logs.py b/commands/logs.py deleted file mode 100644 index bb16d49c..00000000 --- a/commands/logs.py +++ /dev/null @@ -1,274 +0,0 @@ -"""Route itsUP runtime logs to the backend that owns each target.""" - -import json -import platform -import plistlib -import re -import shutil -import subprocess -from dataclasses import dataclass -from datetime import datetime, timezone -from enum import StrEnum -from pathlib import Path - -import click - -from commands.common import fail -from lib.log_reading import follow_lines, parse_duration -from lib.paths import access_log_file, display_path - - -class LogTarget(StrEnum): - """The closed set of runtime logs itsUP exposes.""" - - API = "api" - MONITOR = "monitor" - BRINGUP = "bringup" - APPLY = "apply" - BACKUP = "backup" - HEALTHCHECK = "healthcheck" - ACCESS = "access" - - -@dataclass(frozen=True) -class LogDescriptor: - """Describe one target and the backend identities that can serve it.""" - - description: str - linux_unit: str | None = None - macos_agent: str | None = None - - -@dataclass(frozen=True) -class LogOptions: - """The selection predicates shared by every backend.""" - - follow: bool - cutoff: datetime | None - pattern: re.Pattern[str] | None - - -LOG_TARGETS: dict[LogTarget, LogDescriptor] = { - LogTarget.API: LogDescriptor("API service requests and failures", "itsup-api", "api"), - LogTarget.MONITOR: LogDescriptor("container security monitor lifecycle", "itsup-monitor"), - LogTarget.BRINGUP: LogDescriptor("runtime bringup service", "itsup-bringup", "bringup"), - LogTarget.APPLY: LogDescriptor("configuration apply service", "itsup-apply", "apply"), - LogTarget.BACKUP: LogDescriptor("backup service", "itsup-backup", "backup"), - LogTarget.HEALTHCHECK: LogDescriptor("host healthcheck service", "pi-healthcheck"), - LogTarget.ACCESS: LogDescriptor("Traefik access records"), -} - - -def complete_log_target(ctx: click.Context, param: click.Parameter, incomplete: str) -> list[str]: - """Complete log targets from the router's single target registry.""" - return [target.value for target in LogTarget if target.value.startswith(incomplete)] - - -def _fail(message: str) -> None: - fail(message) - raise SystemExit(1) - - -def _parse_target(value: str) -> LogTarget: - try: - return LogTarget(value) - except ValueError as exc: - valid_targets = ", ".join(target.value for target in LogTarget) - _fail(f"Unknown log target: {value}. Valid targets: {valid_targets}") - raise AssertionError("unreachable") from exc - - -def _parse_options(follow: bool, since: str | None, pattern: str | None) -> LogOptions: - cutoff = None - if since is not None: - try: - cutoff = datetime.now(timezone.utc) - parse_duration(since) - except ValueError as exc: - _fail(f"Invalid --since value: {exc}") - raise AssertionError("unreachable") from exc - - compiled_pattern = None - if pattern is not None: - try: - compiled_pattern = re.compile(pattern) - except re.error as exc: - _fail(f"Invalid --grep pattern: {exc}") - raise AssertionError("unreachable") from exc - - return LogOptions(follow=follow, cutoff=cutoff, pattern=compiled_pattern) - - -def _emit_if_selected(line: str, options: LogOptions) -> None: - if options.pattern is None or options.pattern.search(line): - click.echo(line, nl=False) - - -def _load_state(systemctl: str, unit: str) -> str | None: - try: - # systemctl has no project-provided or Python-native binding. - result = subprocess.run( - [systemctl, "show", unit, "--property=LoadState"], - capture_output=True, - check=True, - text=True, - ) - except subprocess.CalledProcessError: - return None - - key, separator, value = result.stdout.strip().partition("=") - return value if key == "LoadState" and separator else None - - -def _journal_tools() -> tuple[str, str]: - journalctl = shutil.which("journalctl") - systemctl = shutil.which("systemctl") - if journalctl is None: - _fail("Cannot read unit logs: journalctl is not available.") - if systemctl is None: - _fail("Cannot inspect unit logs: systemctl is not available.") - - assert journalctl is not None - assert systemctl is not None - return journalctl, systemctl - - -def _require_loaded_unit(systemctl: str, unit: str) -> None: - """Refuse a journal query when its unit is absent or unusable.""" - load_state = _load_state(systemctl, unit) - if load_state == "loaded": - return - - observed = load_state if load_state is not None else "unavailable" - _fail(f"Cannot read {unit}: unit LoadState is {observed}.") - - -def _journal_command(journalctl: str, unit: str, options: LogOptions) -> list[str]: - command = [journalctl, "-u", unit] - if options.cutoff is not None: - command.extend(["--since", options.cutoff.astimezone().strftime("%Y-%m-%d %H:%M:%S")]) - if options.follow: - command.extend(["-n", "0", "-f"]) - return command - - -def _stream_journal(command: list[str], options: LogOptions, unit: str) -> None: - try: - # journalctl has no project-provided or Python-native binding. - with subprocess.Popen(command, stdout=subprocess.PIPE, text=True) as process: - if process.stdout is None: - _fail(f"Cannot read {unit}: journalctl produced no output stream.") - try: - for line in process.stdout: - _emit_if_selected(line, options) - except KeyboardInterrupt: - process.terminate() - return - return_code = process.wait() - except OSError as exc: - _fail(f"Cannot read {unit}: unable to start journalctl ({exc}).") - return - - if return_code != 0: - raise SystemExit(return_code) - - -def _read_journal(unit: str, options: LogOptions) -> None: - journalctl, systemctl = _journal_tools() - _require_loaded_unit(systemctl, unit) - _stream_journal(_journal_command(journalctl, unit, options), options, unit) - - -def _access_line_is_in_window(line: str, cutoff: datetime) -> bool: - """Return whether a raw Traefik record proves it is inside the time window.""" - try: - record = json.loads(line) - if not isinstance(record, dict): - return False - timestamp = record.get("time", record.get("StartUTC")) - if not isinstance(timestamp, str): - return False - parsed = datetime.fromisoformat(timestamp.replace("Z", "+00:00")) - if parsed.tzinfo is None: - return False - return parsed.astimezone(timezone.utc) >= cutoff - except (json.JSONDecodeError, ValueError, TypeError): - return False - - -def _emit_file_line(line: str, options: LogOptions, *, is_access_log: bool) -> None: - if options.cutoff is not None and (not is_access_log or not _access_line_is_in_window(line, options.cutoff)): - return - _emit_if_selected(line, options) - - -def _read_file(path: Path, options: LogOptions, *, is_access_log: bool) -> None: - if not path.exists(): - _fail(f"Cannot read log file: {display_path(path)} does not exist.") - - try: - if options.follow: - for line in follow_lines(path): - _emit_file_line(line, options, is_access_log=is_access_log) - return - - with path.open("r", encoding="utf-8", errors="replace", newline="") as log_file: - for line in log_file: - _emit_file_line(line, options, is_access_log=is_access_log) - except KeyboardInterrupt: - return - except OSError as exc: - _fail(f"Cannot read log file {display_path(path)}: {exc}.") - - -def _macos_log_file(agent: str) -> Path: - plist_path = Path.home() / "Library" / "LaunchAgents" / f"ai.itsup.{agent}.plist" - if not plist_path.is_file(): - _fail(f"Cannot read macOS log: {display_path(plist_path)} does not exist.") - - try: - with plist_path.open("rb") as plist_file: - plist = plistlib.load(plist_file) - except (OSError, plistlib.InvalidFileException) as exc: - _fail(f"Cannot read macOS log configuration {display_path(plist_path)}: {exc}.") - raise AssertionError("unreachable") from exc - - stdout_path = plist.get("StandardOutPath") - if not isinstance(stdout_path, str) or not stdout_path: - _fail(f"Cannot read macOS log: {display_path(plist_path)} has no StandardOutPath.") - assert isinstance(stdout_path, str) - return Path(stdout_path) - - -@click.command() -@click.argument("target", required=False, shell_complete=complete_log_target) -@click.option("--follow", "follow", "-f", is_flag=True, help="Print new records as they arrive.") -@click.option("--since", help="Select records from a duration such as 10m or 2h ago.") -@click.option("--grep", "pattern", help="Select records matching this case-sensitive regular expression.") -def logs(target: str | None, follow: bool, since: str | None, pattern: str | None) -> None: - """View TARGET's runtime logs, or list the available targets.""" - if target is None: - for log_target, descriptor in LOG_TARGETS.items(): - click.echo(f"{log_target.value} — {descriptor.description}") - return - - log_target = _parse_target(target) - options = _parse_options(follow, since, pattern) - if log_target is LogTarget.ACCESS: - _read_file(access_log_file(), options, is_access_log=True) - return - - descriptor = LOG_TARGETS[log_target] - operating_system = platform.system() - if operating_system == "Linux" and descriptor.linux_unit is not None: - _read_journal(descriptor.linux_unit, options) - return - - if operating_system == "Darwin": - if descriptor.macos_agent is None: - _fail(f"{log_target.value} logs are available only on Linux.") - if options.cutoff is not None: - _fail("Cannot use --since for macOS unit logs: launchd output has no per-line timestamp.") - _read_file(_macos_log_file(descriptor.macos_agent), options, is_access_log=False) - return - - _fail(f"{log_target.value} logs are unavailable on {operating_system}.") diff --git a/docs/domain/itsup/policy/host-boundary.md b/docs/domain/itsup/policy/host-boundary.md index 7e3281a5..a862a769 100644 --- a/docs/domain/itsup/policy/host-boundary.md +++ b/docs/domain/itsup/policy/host-boundary.md @@ -7,7 +7,7 @@ description: Which itsUP CLI commands may run on which machine — runtime-mutat - **Runtime-mutating commands run only on the container host** — the machine whose own LAN IP equals `SSH_HOST` in `.env`. These deploy or stop containers: `apply`, `run`, `down`, and the - stack-management commands (`dns`, `proxy`, `svc`, `monitor`, `logs`), plus host provisioning + stack-management commands (`dns`, `proxy`, `svc`, `monitor`), plus host provisioning (`make install-runtime`). On the host, the full command set is available. - **GitOps, config, secret, and read commands run anywhere.** `pull`, `commit`, `status`, `create`, `init`, `validate`, `migrate`, `edit-secret`, `encrypt`, `decrypt`, `diff-secrets`, diff --git a/docs/project/design/logging.md b/docs/project/design/logging.md index 46389d4b..ea9f9720 100644 --- a/docs/project/design/logging.md +++ b/docs/project/design/logging.md @@ -96,27 +96,20 @@ are not part of the `logs/` directory contract. detection feed. - **`journalctl -u `** (Linux) / the agent's `StandardOutPath` file (macOS) — the daemon diagnostics. -- **`instrukt-ai-logs itsup`** — the logger project's viewer tails the - diagnostic folder: folder- and rotation-aware, with `--since`, - `--include `, and `--grep`. It is a standalone tool installed on its - own: the `instruktai-python-logger` package itsUP depends on is the writer - only, so syncing itsUP's environment does not provide it. itsUP carries no - diagnostic-log viewer of its own. +- **`instrukt-ai-logs itsup`** — the logger project's reader for the + diagnostic folder, and the one instruction for reading what itsUP's own code + logged through the logger: it merges the per-source files by timestamp, + rotated archives included, and narrows with `--since`, `--include `, + `--grep`, and `--follow`. It is the logger project's standalone tool, + released and installed separately from the `instruktai-python-logger` + package itsUP depends on, which is the writer only: neither `make install` + nor syncing itsUP's environment provides it. Each machine that reads these + logs installs it once with the logger project's own installer, whose README + carries the step. - **Operators** via direct `tail`/`zcat` on `logs/access.log`. -- **`itsup logs `** — the itsUP-side front door to these sinks, host-only - like the other runtime commands because every backend it reads exists only on - the container host. It routes each target to whichever backend already holds it: - the supervised units (`api`, `monitor`, `bringup`, `apply`, `backup`, - `healthcheck`) to their journal (`journalctl -u ` on Linux, the launchd - agent's `StandardOutPath` file on macOS), and `access` to `logs/access.log`, - whose lines it emits verbatim. Bare `itsup logs` lists the targets with - descriptions; `--follow`, `--grep`, and `--since` narrow the read, with - `--since` refused for a macOS unit target whose supervisor-less stream carries - no per-line time. The `--since` duration grammar and the file follower behind - `--follow` are itsUP's own (`lib/log_reading.py`); nothing on this read path - comes from the logger package. No target exists for an upstream project — - those stay `docker`-led via `itsup svc`/`proxy`/`dns` — and none for - interactive CLI runs. + +itsUP carries no log reader of its own: every sink above is read with the tool +that owns it. ## Invariants @@ -153,15 +146,10 @@ are not part of the `logs/` directory contract. CrowdSec parses it for threat detection; a second writer in a second format would corrupt the feed. The API's access records go to its own journal. - **The access log is read as-is; itsUP renders no access line.** Every reader — - operator `tail`, `itsup logs access`, CrowdSec — sees Traefik's JSON record - byte-for-byte. itsUP ships no formatter for it, because the record's single - format is the thing that makes it a parseable threat-detection feed, and a - second rendering of the same line is a second format to keep in step. Selecting - which lines to emit is not rendering: `itsup logs access --grep` matches a regex - against the raw line and `--since` reads the record's own timestamp field - (`time`, else `StartUTC` — RFC3339, emitted by default because the generated - static config declares no `accessLog.fields` drop), then emits the line - unchanged. + operator `tail`, CrowdSec — sees Traefik's JSON record byte-for-byte. itsUP + ships no formatter for it, because the record's single format is the thing + that makes it a parseable threat-detection feed, and a second rendering of the + same line is a second format to keep in step. - **The access log rotates in place, so `logs/access.log` is stable across rotation for every reader on it.** The host's daily logrotate run rotates it with `copytruncate`: Traefik holds the file open with `O_APPEND` and takes no @@ -191,14 +179,15 @@ restarts of the unit and rotate under the host's journald retention. On macOS th API's equivalent is `~/Library/Logs/itsup.api.log`. **Viewing CLI and one-shot diagnostics (`instrukt-ai-logs itsup [--include -] [--since W] [--grep RE]`):** the logger project's viewer resolves the -files under `instrukt-ai/itsup/` and follows them (rotation-aware). `--include -backup` narrows to `backup.log`; with no filter it merges every source in the -folder. +] [--since W] [--grep RE] [--follow]`):** the logger project's reader +resolves the files under `instrukt-ai/itsup/` and prints the requested window +merged by timestamp; `--follow` then keeps printing new lines across rotation. +`--include backup` narrows to `backup.log`; with no filter it merges every +source in the folder. -**Viewing the access log:** `itsup logs access` on the container host, or -`tail`/`zcat` on `logs/access.log` directly. Either way the JSON record is what -the reader sees; nothing reformats it. +**Viewing the access log:** `tail`/`zcat` on `logs/access.log`, or any other +ordinary text tool. The JSON record is what the reader sees; nothing reformats +it. **Threat detection:** Traefik appends each request to `logs/access.log` → the CrowdSec acquisition source (`crowdsec/acquis.yml`) parses it under the `traefik` @@ -231,13 +220,12 @@ and operator banners are unaffected. marker, `monitor/core.py:_get_last_processed_timestamp` returns `None` and the monitor reprocesses the docker-log window from scratch — correct, just less efficient. -- **Access-log line with no readable timestamp.** Nothing parses the record on the - read path, so a malformed line reaches every reader intact and reading never - fails on it. Only a time filter needs the field: under `itsup logs access - --since`, a line whose `time`/`StartUTC` is absent or unparseable is **excluded** - — the reader cannot prove it falls inside the requested window, and admitting it - would silently widen the window the operator asked for. Without `--since` the - same line is emitted like any other. - **Container removal.** Container (Docker json-file) logs are lost when the container is removed; only the `logs/` files, the journal, and the instrukt-ai diagnostic folder persist. + +## See Also + +- https://github.com/InstruktAI/logging — the logger project: its README + carries the `instrukt-ai-logs` install step and the reader's options, and + `docs/contract.md` the file location, format, and permission contract. diff --git a/docs/project/policy/repository-conventions.md b/docs/project/policy/repository-conventions.md index 66d676f4..e6290ed6 100644 --- a/docs/project/policy/repository-conventions.md +++ b/docs/project/policy/repository-conventions.md @@ -7,7 +7,7 @@ visibility: 'internal' ## Rules -- **Runtime-mutating commands run only on the container host** — the machine whose own LAN IP equals `SSH_HOST` in `.env`. The `itsup` CLI enforces this fail-closed: `run`, `apply`, `down`, `dns`, `proxy`, `svc`, `monitor`, and `logs` refuse on any machine whose detected LAN IP does not match `SSH_HOST`, and `make install-runtime` refuses off-host before it touches systemd/launchd. `make uninstall-runtime` is the recovery exception: it may run off-host to remove stale local systemd/launchd integration and local remnants from the current checkout, but it does not invoke the host-only `itsup down` path there. The GitOps, config, secrets, and read commands (`pull`, `commit`, `status`, `create`, `init`, `validate`, `migrate`, `encrypt`, `decrypt`, `diff-secrets`, `edit-secret`, `sops-key`) run anywhere. Off-host a runtime-mutating command would spin up the entire stack locally; the gate is not self-grantable. The command-level contract is in `project/itsup/spec/cli`; operational detail in `project/itsup/spec/runtime-operations`. +- **Runtime-mutating commands run only on the container host** — the machine whose own LAN IP equals `SSH_HOST` in `.env`. The `itsup` CLI enforces this fail-closed: `run`, `apply`, `down`, `dns`, `proxy`, `svc`, and `monitor` refuse on any machine whose detected LAN IP does not match `SSH_HOST`, and `make install-runtime` refuses off-host before it touches systemd/launchd. `make uninstall-runtime` is the recovery exception: it may run off-host to remove stale local systemd/launchd integration and local remnants from the current checkout, but it does not invoke the host-only `itsup down` path there. The GitOps, config, secrets, and read commands (`pull`, `commit`, `status`, `create`, `init`, `validate`, `migrate`, `encrypt`, `decrypt`, `diff-secrets`, `edit-secret`, `sops-key`) run anywhere. Off-host a runtime-mutating command would spin up the entire stack locally; the gate is not self-grantable. The command-level contract is in `project/itsup/spec/cli`; operational detail in `project/itsup/spec/runtime-operations`. - **Operate from the repository root.** Never stay `cd`'d into a subdirectory. For directory-scoped work use `(cd && )` with relative paths. - **Operate from the repository root.** Never stay `cd`'d into a subdirectory. For directory-scoped work use `(cd && )` with relative paths. - **itsUP's own code is not containerized.** The Python CLI (`itsup`), API server, monitoring, DNS honeypot-management, and proxy-config code all run on the host. Only upstream project services are containerized. Never containerize itsUP code. diff --git a/docs/project/spec/cli.md b/docs/project/spec/cli.md index 9683fe8e..c7bc863a 100644 --- a/docs/project/spec/cli.md +++ b/docs/project/spec/cli.md @@ -114,83 +114,6 @@ in `project/itsup/spec/secrets-management`. (`lib/deploy.py:62`, `lib/deploy.py:257`) -### `logs` — the routing front door over fragmented log backends - -`itsup logs [TARGET]` is the single entry point to itsUP's host-side logs. Each -target names a producer, and the command routes it to whichever backend actually -holds that producer's records; the operator never needs to know which. It is -host-only (see the gate below) and read-only. - -**Bare invocation is discovery**: `itsup logs` with no target prints every -routable target with its description, one pair per line, and exits 0. An -unrecognised target exits 1 and prints the routable set. Every rejection the -router owns — unknown target, malformed option value, unavailable backend — exits -1; the CLI declares no exit-2 contract, so parameter failures are translated -rather than left to the parser's own usage exit. - -**Targets and their backends.** Six supervised-unit targets — `api`, `monitor`, -`bringup`, `apply`, `backup`, `healthcheck` — plus the file-backed `access` -(Traefik's JSON access log under `logs/`, emitted verbatim: the router is a raw -passthrough reader of that file and formats nothing, because the record's single -JSON format is what makes it CrowdSec's parseable feed). -The unit targets resolve per platform, following the supervision contract in -`project/itsup/design/logging`: on Linux to `journalctl -u `; on macOS to the -launchd agent's `StandardOutPath`, read from the installed agent's own plist so -the path comes from what launchd actually loaded. `monitor` and `healthcheck` are -Linux-only daemons and have no macOS agent, so on macOS they are refused with -that reason rather than routed to a file that will never exist. - -There is deliberately **no `` target** — container logs stay docker-led -through `itsup svc` / `proxy` / `dns` — and **no `cli` target**: interactive runs -are observed live, and their diagnostic file is read with `instrukt-ai-logs -itsup`. - -**One option surface, translated per backend.** `-f/--follow`, `--since`, and -`--grep` mean the same thing on every target. They **select** which lines are -emitted; none of them changes a line's content, on any backend. Every line the -router prints is the line its backend produced. - -- `--since` takes the duration grammar `{s,m,h,d}`. The journal's own - `--since` rejects a bare duration, so the router parses the duration and hands - the journal an absolute timestamp. The `access` backend has no such grammar to - delegate to, so the router applies the same cutoff itself, reading each JSON - record's own timestamp field (`time`, else `StartUTC`) to decide inclusion and - then emitting the record unchanged. A record whose timestamp field is absent or - unparseable is excluded: the router cannot prove it is inside the window, and - admitting it would silently widen the window that was asked for. -- `--grep` is a case-sensitive Python regular expression, applied by the router - itself to each complete line just before it is printed — on every backend. For - `access` that line is the raw JSON record, so a pattern can match a field name - as readily as a value. The journal's own `-g` is not used: it matches only the - record's message field, while the line the operator sees also carries the - supervisor's timestamp and identity, and its smart-case default would make the - same pattern mean different things on different backends. -- `--follow` is future-only everywhere: it streams what arrives after the - command starts and never replays history first. The journal is asked for - `-n 0` alongside `-f` so it does not emit its recent window, matching the - file backend, which follows from the end of the file. Following `access` - survives the host's `copytruncate` rotation of that file - (`project/itsup/design/logging`). -- An invalid duration or an invalid regex is rejected at the option boundary with - exit 1 before any backend is reached. - -**`--since` has one designed exception: macOS unit targets.** Filtering by time -requires a per-line time, and the supervisor is what supplies it — journald does, -launchd does not. A launchd agent's `StandardOutPath` captures the daemon's -stream verbatim, and that stream deliberately carries no timestamp because the -supervisor is expected to add one. So `--since` against a macOS unit target exits -1 naming that reason, while `--follow` and `--grep` remain available there. The -`access` target is unaffected on either platform: its record carries its own -RFC3339 timestamp field, which is what the router reads. - -**Every unavailability path refuses, never degrades.** A unit target with no -reader on this platform, and a unit target whose unit is not installed, each exit -1 naming the reason. Unit existence is established before the query — a unit is -usable only when its `LoadState` is `loaded`, and any other value is reported -rather than interpreted — because a journal query against an absent unit succeeds -with empty output. - - ### Host-identity gate (runtime-mutating commands are host-only) The CLI group refuses runtime-mutating commands on any machine that is not the @@ -204,8 +127,8 @@ per-command argument parsing, and off-host even `itsup --help` i refused. - **Host-only** (refused off-host, exit 1): `run`, `apply`, `down`, `dns`, - `proxy`, `svc`, `monitor`, `logs`. `make install-runtime` refuses off-host - before it touches systemd/launchd (`bin/install-bringup.sh`). + `proxy`, `svc`, `monitor`. `make install-runtime` refuses off-host before it + touches systemd/launchd (`bin/install-bringup.sh`). - **Available anywhere** (GitOps + config + secrets + read): `pull`, `commit`, `status`, `create`, `init`, `validate`, `migrate`, `encrypt`, `decrypt`, @@ -275,10 +198,8 @@ The CLI emits only these — there is no 2/3/130 contract. running container's `com.docker.compose.config-hash` label (container-label based), not a hash stored on disk. - Runtime-mutating commands (`run`, `apply`, `down`, `dns`, `proxy`, `svc`, - `monitor`) and the read-only `logs` router are **host-only** and refuse - fail-closed off-host (detected LAN IP ≠ `SSH_HOST`); see the host-identity - gate above. `logs` is gated not because it mutates but because every backend - it reads exists only on the container host. + `monitor`) are **host-only** and refuse fail-closed off-host (detected LAN IP + ≠ `SSH_HOST`); see the host-identity gate above. ## See Also diff --git a/docs/third-party/systemd/journalctl-querying.md b/docs/third-party/systemd/journalctl-querying.md index 492fe0d2..2dd4bb87 100644 --- a/docs/third-party/systemd/journalctl-querying.md +++ b/docs/third-party/systemd/journalctl-querying.md @@ -4,9 +4,10 @@ description: Verified journalctl query semantics itsUP delegates to — the --si # journalctl — Query Semantics -Curated from the `journalctl(1)` manual page for the `itsup logs` router, which -delegates its unit-backed targets to `journalctl` rather than reading the journal -itself. Only the flags the router composes are covered. +Curated from the `journalctl(1)` manual page for the journal reads itsUP +relies on rather than reading the journal itself: an operator's +`journalctl -u ` on a supervised unit, and the failure alert composer's +bounded tail of a failed unit (`lib/alerting.py`). ## Time window — `--since` / `--until` diff --git a/docs/third-party/systemd/systemctl-unit-introspection.md b/docs/third-party/systemd/systemctl-unit-introspection.md index 0dabe618..933a7f2d 100644 --- a/docs/third-party/systemd/systemctl-unit-introspection.md +++ b/docs/third-party/systemd/systemctl-unit-introspection.md @@ -4,9 +4,10 @@ description: 'What systemctl documents — and does not document — for decidin # systemctl — Unit Introspection for an Existence Predicate -Curated for the `itsup logs` router, which must distinguish "this unit is not -installed" from "this unit is installed and quiet" before querying the journal. -Only what bears on that predicate is recorded. +Curated for a caller that must distinguish "this unit is not installed" from +"this unit is installed and quiet", as the runtime installer does when it +checks whether the daemon units are registered (`bin/install-bringup.sh`). Only +what bears on that predicate is recorded. ## What is not documented diff --git a/itsup/cli.py b/itsup/cli.py index a9fdb124..c9f2fb79 100644 --- a/itsup/cli.py +++ b/itsup/cli.py @@ -19,7 +19,6 @@ from commands.edit_secret import edit_secret from commands.encrypt import encrypt from commands.init import init -from commands.logs import logs from commands.migrate import migrate_cmd from commands.monitor import monitor from commands.projects import projects @@ -32,7 +31,7 @@ from commands.validate import validate from lib.host_gate import require_host -HOST_ONLY = frozenset({"run", "apply", "down", "dns", "proxy", "svc", "monitor", "logs"}) +HOST_ONLY = frozenset({"run", "apply", "down", "dns", "proxy", "svc", "monitor"}) @click.group(context_settings={"allow_interspersed_args": False, "help_option_names": ["-h", "--help"]}) @@ -100,7 +99,6 @@ def cli(ctx: click.Context, verbose: int) -> None: cli.add_command(edit_secret) cli.add_command(sops_key) cli.add_command(projects) -cli.add_command(logs) def main() -> None: diff --git a/lib/log_reading.py b/lib/log_reading.py deleted file mode 100644 index 9e253e53..00000000 --- a/lib/log_reading.py +++ /dev/null @@ -1,78 +0,0 @@ -"""Read-side primitives for log files: a duration grammar and a file follower.""" - -import os -import time -from collections.abc import Iterator -from datetime import timedelta -from pathlib import Path -from typing import BinaryIO - -_POLL_INTERVAL_SECONDS = 0.25 -_DURATION_UNITS = { - "s": timedelta(seconds=1), - "m": timedelta(minutes=1), - "h": timedelta(hours=1), - "d": timedelta(days=1), -} - - -def parse_duration(value: str) -> timedelta: - """Parse a whole number followed by a unit from `_DURATION_UNITS`.""" - text = value.strip().lower() - number, unit = text[:-1], text[-1:] - if not (number.isascii() and number.isdigit()) or unit not in _DURATION_UNITS: - units = ", ".join(_DURATION_UNITS) - raise ValueError(f"expected a whole number followed by one of {units}, got {value!r}") - return int(number) * _DURATION_UNITS[unit] - - -def follow_lines(path: Path) -> Iterator[str]: - """Yield each line written to `path` from now on; never returns. - - A file present at the start is followed from its end. A file that appears - later, replaces the followed one at the same path, or is truncated in place - is read from its start. - """ - skip_existing = True - while True: - try: - log_file = path.open("rb") - except FileNotFoundError: - skip_existing = False - time.sleep(_POLL_INTERVAL_SECONDS) - continue - with log_file: - if skip_existing: - log_file.seek(0, os.SEEK_END) - skip_existing = False - yield from _lines_while_current(log_file, path) - - -def _lines_while_current(log_file: BinaryIO, path: Path) -> Iterator[str]: - """Yield complete lines from the open file for as long as `path` still names it. - - A line whose end has not arrived when the file stops being current is - yielded as it stands. - """ - inode = os.fstat(log_file.fileno()).st_ino - pending = b"" - while True: - pending += log_file.readline() - if pending.endswith(b"\n"): - yield pending.decode("utf-8", errors="replace") - pending = b"" - elif _is_current(log_file, path, inode): - time.sleep(_POLL_INTERVAL_SECONDS) - else: - break - if pending: - yield pending.decode("utf-8", errors="replace") - - -def _is_current(log_file: BinaryIO, path: Path, inode: int) -> bool: - """Return whether `path` still names the open file and has not been truncated below the read position.""" - try: - status = path.stat() - except FileNotFoundError: - return False - return status.st_ino == inode and status.st_size >= log_file.tell() diff --git a/lib/paths.py b/lib/paths.py index 8828390b..96db9ca6 100644 --- a/lib/paths.py +++ b/lib/paths.py @@ -63,16 +63,6 @@ def projects_dir() -> Path: return root() / "projects" -def logs_dir() -> Path: - """Resolve the runtime logs tree.""" - return root() / "logs" - - -def access_log_file() -> Path: - """Resolve Traefik's JSON access-log file.""" - return logs_dir() / "access.log" - - def project_dir(name: str) -> Path: """Resolve one project's config directory.""" return projects_dir() / name From 3ef2863903caa4948600b3e8465ff4eed8c15318 Mon Sep 17 00:00:00 2001 From: Maurice Faber Date: Tue, 24 Nov 2026 23:55:48 +0100 Subject: [PATCH 05/11] docs(monitor): point monitor diagnostics at the supervisor journal The README and the itsup domain's CLI surface still sent readers to `instrukt-ai-logs itsup --include monitor`. The monitor has logged to its supervised unit's stdout since it became a supervised daemon and writes no file in the logger's directory, so that instruction shows none of its current records. They now name the journal, where the records are. Session: t3:thread:delegated-task:command%3Amcp%3A90097403-c516-484c-8d66-e31ba569c0c1%3Adelegate-task%3A07981b9a-bc91-45b2-a78c-d360166c6c63 Human-Involved: true --- README.md | 6 +++--- docs/domain/itsup/spec/cli-surface.md | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index d86eeac7..d88b203e 100644 --- a/README.md +++ b/README.md @@ -238,7 +238,7 @@ itsup svc exec web sh # Execute commands in containers # Container Security Monitor itsup monitor start [--flags] # Start security monitor itsup monitor stop # Stop monitor -instrukt-ai-logs itsup --include monitor # Tail monitor diagnostics +journalctl -u itsup-monitor -f # Follow monitor diagnostics (container host) itsup monitor cleanup # Review blacklist itsup monitor report # Generate threat report @@ -379,8 +379,8 @@ itsup monitor start --report-only --use-opensnitch # Stop monitor itsup monitor stop -# View diagnostics -instrukt-ai-logs itsup --include monitor +# View diagnostics (container host) +journalctl -u itsup-monitor # Generate threat intelligence report itsup monitor report diff --git a/docs/domain/itsup/spec/cli-surface.md b/docs/domain/itsup/spec/cli-surface.md index 9f739689..7348e9d4 100644 --- a/docs/domain/itsup/spec/cli-surface.md +++ b/docs/domain/itsup/spec/cli-surface.md @@ -43,8 +43,8 @@ Container host only — runtime-mutating (see itsUP Host Boundary): - `itsup down` — stop all containers. - `itsup dns` / `itsup proxy` — DNS and proxy stack management. - `itsup svc ` — service operations for a project. -- `itsup monitor` — container security monitor management. Diagnostics are viewed via - `instrukt-ai-logs itsup --include monitor`, not a subcommand. +- `itsup monitor` — container security monitor management. Its diagnostics are in the host + supervisor's journal (`journalctl -u itsup-monitor`), not behind a subcommand. ## Known caveats From 1200c6af3bd30ac6286d7c22860b5801c88b932b Mon Sep 17 00:00:00 2001 From: Maurice Faber Date: Tue, 24 Nov 2026 23:56:16 +0100 Subject: [PATCH 06/11] ci(test): start the CLI from the installed environment The Test workflow formats and lints `api` and `lib` and never starts `itsup`, so a dependency update that stops the CLI from importing merges green and fails first on the host, where boot bringup, the nightly apply and the daemon starts all go through that CLI. `make smoke` starts it from the synced environment and the workflow runs it after lint, so an import that no longer resolves fails the check before merge. Session: t3:thread:delegated-task:command%3Amcp%3A90097403-c516-484c-8d66-e31ba569c0c1%3Adelegate-task%3A07981b9a-bc91-45b2-a78c-d360166c6c63 Human-Involved: true --- .github/workflows/test.yml | 1 + Makefile | 6 +++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index d60dba8d..35a34ea1 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -34,3 +34,4 @@ jobs: run: | make format make lint + make smoke diff --git a/Makefile b/Makefile index e74f8c9f..b0618112 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: help install install-runtime uninstall-runtime restart status lint format clean +.PHONY: help install install-runtime uninstall-runtime restart status lint format smoke clean help: ## Show this help message @echo 'Usage: make [target]' @@ -31,6 +31,10 @@ format: ## Format code lint: ## Run linter @FILES_FROM="$(FILES_FROM)" ./bin/lint.sh +smoke: ## Start the CLI from the installed environment + @test -x .venv/bin/itsup || { echo "Run 'make install' first — no .venv/bin/itsup found"; exit 1; } + @.venv/bin/itsup --help >/dev/null + clean: ## Remove generated artifacts and caches find . -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null || true find . -type f -name '*.pyc' -delete From 43781823765cfdd6092728d1884f8e0b407f3bb0 Mon Sep 17 00:00:00 2001 From: Maurice Faber Date: Wed, 25 Nov 2026 00:00:16 +0100 Subject: [PATCH 07/11] docs(logging): record that root-written log files break the user's read Moving the API server and the security monitor onto the logger's files was meant to make `instrukt-ai-logs itsup` show everything itsUP's own code logs. The monitor runs as root with HOME pinned to the itsUP user. At the locked logger release the writer keeps each file private to the user that wrote it, and the reader refuses a merged read that includes a file it cannot open, so a root-run producer in that directory breaks the itsUP user's read instead of completing it. The backup job is already such a producer. The logging design now states this as a failure mode, together with the case where root is the first writer and locks the itsUP user out of its own state directory, and the README tells an operator what to expect on the container host. The daemons keep logging to the supervisor journal: making root and user share the directory is a change to the logger or to how the units run, not to itsUP's logging setup. Session: t3:thread:delegated-task:command%3Amcp%3A90097403-c516-484c-8d66-e31ba569c0c1%3Adelegate-task%3A07981b9a-bc91-45b2-a78c-d360166c6c63 Human-Involved: true --- README.md | 2 ++ docs/project/design/logging.md | 35 +++++++++++++++++++++++++++++++--- 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index d88b203e..422e477d 100644 --- a/README.md +++ b/README.md @@ -518,6 +518,8 @@ instrukt-ai-logs itsup --since 1h # Everything from the last hour, merged by instrukt-ai-logs itsup --follow # Print the recent window, then follow ``` +On the container host the nightly backup runs as root and writes its own file into the same log directory. The logger keeps each file private to the user that wrote it, so run as the itsUP user the unfiltered command stops with a permission error whenever its time window reaches back to the backup's last log line: `instrukt-ai-logs itsup --include itsup` reads the CLI's file in any window, and the backup's file needs root. + `instrukt-ai-logs` is the logger project's standalone tool ([InstruktAI/logging](https://github.com/InstruktAI/logging)). The Python package itsUP depends on only writes logs, so `make install` does not provide the tool. Install it once on each machine that reads these logs: ```bash diff --git a/docs/project/design/logging.md b/docs/project/design/logging.md index ea9f9720..3aecec3e 100644 --- a/docs/project/design/logging.md +++ b/docs/project/design/logging.md @@ -77,7 +77,9 @@ why the daemon paths configure their own stdout handler instead): one-shots (`bin/migrate_to_v2.py`, `bin/write_artifacts.py`), via `configure_logging("itsup")` (default source). - `instrukt-ai/itsup/backup.log` — the backup job, via - `configure_logging("itsup", source="backup")`. + `configure_logging("itsup", source="backup")`. The job runs as root with + `HOME` pinned to the itsUP user, so root owns this file inside that user's + folder (Failure modes). Each producing process declares its own `source`; the empty-source default (one shared `.log`) is deliberately avoided because multiple independent @@ -182,8 +184,10 @@ API's equivalent is `~/Library/Logs/itsup.api.log`. ] [--since W] [--grep RE] [--follow]`):** the logger project's reader resolves the files under `instrukt-ai/itsup/` and prints the requested window merged by timestamp; `--follow` then keeps printing new lines across rotation. -`--include backup` narrows to `backup.log`; with no filter it merges every -source in the folder. +`--include itsup` narrows to `itsup.log`; with no filter it merges every source +written inside the window, each of which the reading user must be able to open. +On the container host the root-run backup's file is one the itsUP user cannot +open (Failure modes). **Viewing the access log:** `tail`/`zcat` on `logs/access.log`, or any other ordinary text tool. The JSON record is what the reader sees; nothing reformats @@ -212,6 +216,31 @@ and operator banners are unaffected. written — there is no degraded or console-fallback mode. A process that cannot open its file fails fast rather than starting blind. The daemon paths have no such failure: stdout is always available. +- **A root-written file in the itsUP user's diagnostic folder.** The backup + job runs as root with `HOME` pinned to the itsUP user + (`samples/systemd/itsup-backup.service`), so root creates `backup.log` in that + user's folder. At the logger release itsUP locks, the writer keeps every file + readable by its producing user only and re-applies that each time it opens + the file, so the itsUP user cannot read `backup.log` at all, and the reader + refuses the whole merged read when a file it cannot open was written inside + the requested window. Run as the itsUP user, `instrukt-ai-logs itsup` + therefore exits with a permission error, printing nothing from the sources + it could read, whenever its window reaches back to the backup's last record; + a shorter window skips the file. Naming only sources that user owns + (`--include itsup`) reads them in any window; `backup.log` is readable only + as root. The same holds for every further root-run producer routed through + the logger. The container security monitor runs as root and logs + continuously, so its file would sit inside every window and the itsUP user's + unfiltered read would fail every time. +- **Root as the first writer.** The writer creates every missing directory on + the way to the folder owned by the process that asks and closed to everyone + else. When a root-run producer is the first to log on a host where the itsUP + user's state directory does not exist yet, those directories end up owned by + root, and the itsUP user's own processes then fail at `configure_logging`: + the `itsup` CLI does not start. On an installed host the itsUP user has + normally logged first — `make install-runtime` starts bringup, which runs + `itsup` as that user — so the folder exists and is user-owned before the + nightly backup writes into it. - **Journal retention exhausted.** journald caps its own store; once the cap is reached the oldest records are discarded. A host that needs a longer daemon history raises the cap rather than reintroducing a file sink, which would put From 172337db39e2b241e8af256fdd8160ebbebec52b Mon Sep 17 00:00:00 2001 From: Maurice Faber Date: Wed, 25 Nov 2026 00:15:55 +0100 Subject: [PATCH 08/11] docs(logging): state when the root-written file fails the read, and on which hosts The failure mode said a window shorter than the backup's last write skips the root-written file. The reader also fails in a short window: when nothing in the window matches, it reports the newest entry in the folder and opens the most recently written file to find it. A bare `instrukt-ai-logs itsup` therefore fails from a backup run that wrote to its file until the CLI next logs, which is the common state on a host. The text also said the backup runs as root on the container host without qualification. Only the systemd units run a producer as root; the launchd agents run as the user, whose files are then its own. The reader's behaviour is no longer attributed to the lock, which pins the writer only, and the claim that the monitor's file would fail every read is reduced to what is established: its unit runs as root. Session: t3:thread:delegated-task:command%3Amcp%3A90097403-c516-484c-8d66-e31ba569c0c1%3Adelegate-task%3A07981b9a-bc91-45b2-a78c-d360166c6c63 Human-Involved: true --- README.md | 2 +- docs/project/design/logging.md | 43 ++++++++++++++++++---------------- 2 files changed, 24 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 422e477d..2c1c1c03 100644 --- a/README.md +++ b/README.md @@ -518,7 +518,7 @@ instrukt-ai-logs itsup --since 1h # Everything from the last hour, merged by instrukt-ai-logs itsup --follow # Print the recent window, then follow ``` -On the container host the nightly backup runs as root and writes its own file into the same log directory. The logger keeps each file private to the user that wrote it, so run as the itsUP user the unfiltered command stops with a permission error whenever its time window reaches back to the backup's last log line: `instrukt-ai-logs itsup --include itsup` reads the CLI's file in any window, and the backup's file needs root. +On a systemd host the nightly backup's unit runs as root and writes its own file into the same log directory; a launchd agent runs as the user and is not affected. The logger keeps each file private to the user that wrote it, so run as the itsUP user the unfiltered command stops with a permission error when the backup's file was written inside the time window, and also when nothing in the window matches and the backup's file holds the most recent write in the directory, which a bare `instrukt-ai-logs itsup` meets after a backup run until the CLI next logs. `instrukt-ai-logs itsup --include itsup` reads the CLI's file in both cases, and the backup's file needs root. `instrukt-ai-logs` is the logger project's standalone tool ([InstruktAI/logging](https://github.com/InstruktAI/logging)). The Python package itsUP depends on only writes logs, so `make install` does not provide the tool. Install it once on each machine that reads these logs: diff --git a/docs/project/design/logging.md b/docs/project/design/logging.md index 3aecec3e..bb7d98bf 100644 --- a/docs/project/design/logging.md +++ b/docs/project/design/logging.md @@ -77,9 +77,10 @@ why the daemon paths configure their own stdout handler instead): one-shots (`bin/migrate_to_v2.py`, `bin/write_artifacts.py`), via `configure_logging("itsup")` (default source). - `instrukt-ai/itsup/backup.log` — the backup job, via - `configure_logging("itsup", source="backup")`. The job runs as root with - `HOME` pinned to the itsUP user, so root owns this file inside that user's - folder (Failure modes). + `configure_logging("itsup", source="backup")`. The systemd unit runs the job + as root with `HOME` pinned to the itsUP user, so on a systemd host root owns + this file inside that user's folder (Failure modes); the launchd agent runs + it as the user, who then owns the file. Each producing process declares its own `source`; the empty-source default (one shared `.log`) is deliberately avoided because multiple independent @@ -186,8 +187,8 @@ resolves the files under `instrukt-ai/itsup/` and prints the requested window merged by timestamp; `--follow` then keeps printing new lines across rotation. `--include itsup` narrows to `itsup.log`; with no filter it merges every source written inside the window, each of which the reading user must be able to open. -On the container host the root-run backup's file is one the itsUP user cannot -open (Failure modes). +On a systemd host the backup's file is one the itsUP user cannot open (Failure +modes). **Viewing the access log:** `tail`/`zcat` on `logs/access.log`, or any other ordinary text tool. The JSON record is what the reader sees; nothing reformats @@ -216,22 +217,24 @@ and operator banners are unaffected. written — there is no degraded or console-fallback mode. A process that cannot open its file fails fast rather than starting blind. The daemon paths have no such failure: stdout is always available. -- **A root-written file in the itsUP user's diagnostic folder.** The backup - job runs as root with `HOME` pinned to the itsUP user - (`samples/systemd/itsup-backup.service`), so root creates `backup.log` in that - user's folder. At the logger release itsUP locks, the writer keeps every file - readable by its producing user only and re-applies that each time it opens - the file, so the itsUP user cannot read `backup.log` at all, and the reader - refuses the whole merged read when a file it cannot open was written inside - the requested window. Run as the itsUP user, `instrukt-ai-logs itsup` - therefore exits with a permission error, printing nothing from the sources - it could read, whenever its window reaches back to the backup's last record; - a shorter window skips the file. Naming only sources that user owns - (`--include itsup`) reads them in any window; `backup.log` is readable only +- **A root-written file in the itsUP user's diagnostic folder.** On a systemd + host the backup unit runs the job as root with `HOME` pinned to the itsUP + user (`samples/systemd/itsup-backup.service`), so root creates `backup.log` + in that user's folder; a launchd agent runs as the user and is not affected. + At the logger release itsUP locks, the writer keeps every file readable by + its producing user only and re-applies that each time it opens the file, so + the itsUP user cannot read `backup.log` at all. The reader is installed + separately and itsUP pins no release of it; the release that matches the + lock answers an unfiltered `instrukt-ai-logs itsup` from the itsUP user with + a permission error in two cases. When the file it cannot open was last + written inside the requested window, it prints nothing, not even from the + sources it could read. When nothing in the window matches and that file + holds the folder's most recent write, it fails as well, whatever the length + of the window: that is the state from a backup run that wrote to its file + until an `itsup` command next logs. Naming only sources that user owns + (`--include itsup`) reads them in both cases; `backup.log` is readable only as root. The same holds for every further root-run producer routed through - the logger. The container security monitor runs as root and logs - continuously, so its file would sit inside every window and the itsUP user's - unfiltered read would fail every time. + the logger, and the container security monitor's unit also runs as root. - **Root as the first writer.** The writer creates every missing directory on the way to the folder owned by the process that asks and closed to everyone else. When a root-run producer is the first to log on a host where the itsUP From 87eed2ca101ea116835311ef1e7149ef1fb0c0dc Mon Sep 17 00:00:00 2001 From: Maurice Faber Date: Wed, 25 Nov 2026 00:18:01 +0100 Subject: [PATCH 09/11] build(make): make the smoke recipe one delegation line The recipe carried a guard for a missing environment: a conditional with its own error handling inside the Makefile, where no linter or reviewer of scripts sees it. The recipe now only names the CLI. A missing environment or an import that no longer resolves both end the recipe non-zero, so the Test workflow still fails before merge. Session: t3:thread:delegated-task:command%3Amcp%3A90097403-c516-484c-8d66-e31ba569c0c1%3Adelegate-task%3A07981b9a-bc91-45b2-a78c-d360166c6c63 Human-Involved: true --- Makefile | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Makefile b/Makefile index b0618112..1c798302 100644 --- a/Makefile +++ b/Makefile @@ -32,8 +32,7 @@ lint: ## Run linter @FILES_FROM="$(FILES_FROM)" ./bin/lint.sh smoke: ## Start the CLI from the installed environment - @test -x .venv/bin/itsup || { echo "Run 'make install' first — no .venv/bin/itsup found"; exit 1; } - @.venv/bin/itsup --help >/dev/null + @.venv/bin/itsup --help clean: ## Remove generated artifacts and caches find . -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null || true From d8fa92c221537b741cc051e994e6835e217236a6 Mon Sep 17 00:00:00 2001 From: Maurice Faber Date: Wed, 25 Nov 2026 00:18:19 +0100 Subject: [PATCH 10/11] docs(logging): say which producers share the default log file The design said the default source is avoided because independent processes must not share one log file. The CLI and the two CLI-family one-shots do share the default file, and the logger writes each line whole so that they can. The sentence now states what the code does: a producer with its own trigger declares a source, the CLI family shares the default. Session: t3:thread:delegated-task:command%3Amcp%3A90097403-c516-484c-8d66-e31ba569c0c1%3Adelegate-task%3A07981b9a-bc91-45b2-a78c-d360166c6c63 Human-Involved: true --- docs/project/design/logging.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/project/design/logging.md b/docs/project/design/logging.md index ea9f9720..96699124 100644 --- a/docs/project/design/logging.md +++ b/docs/project/design/logging.md @@ -79,9 +79,9 @@ why the daemon paths configure their own stdout handler instead): - `instrukt-ai/itsup/backup.log` — the backup job, via `configure_logging("itsup", source="backup")`. -Each producing process declares its own `source`; the empty-source default (one -shared `.log`) is deliberately avoided because multiple independent -processes must not share one log file. This mirrors TeleClaude's convention +A producer that runs on its own trigger declares its own `source` and gets its +own file; the CLI and the CLI-family one-shots share the default `itsup.log`. +This mirrors TeleClaude's convention (`configure_logging("teleclaude", source="cron")`). **Container logs (ephemeral):** every Docker container also writes to Docker's From cf0ad129a20f2e5998c6b01a6b1c3b97fc2143c9 Mon Sep 17 00:00:00 2001 From: Maurice Faber Date: Wed, 25 Nov 2026 00:32:48 +0100 Subject: [PATCH 11/11] docs(logging): describe the root-written file per reader path, follow included The failure mode stated that a read with nothing matching fails when the root-written file holds the newest write, without excluding `--follow`. The reader looks for the newest entry only when it is not following; a follow starts without an error and drops the file it cannot open, so the backup's later lines are silently absent. The cases are now laid out by what the reader does: the file inside the window, the file before the window without follow, and the file before the window with follow. Earlier wordings named one failing case at a time and each left another path misdescribed. Session: t3:thread:delegated-task:command%3Amcp%3A90097403-c516-484c-8d66-e31ba569c0c1%3Adelegate-task%3A07981b9a-bc91-45b2-a78c-d360166c6c63 Human-Involved: true --- README.md | 8 +++++++- docs/project/design/logging.md | 32 +++++++++++++++++++++----------- 2 files changed, 28 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 2c1c1c03..5ef784ad 100644 --- a/README.md +++ b/README.md @@ -518,7 +518,13 @@ instrukt-ai-logs itsup --since 1h # Everything from the last hour, merged by instrukt-ai-logs itsup --follow # Print the recent window, then follow ``` -On a systemd host the nightly backup's unit runs as root and writes its own file into the same log directory; a launchd agent runs as the user and is not affected. The logger keeps each file private to the user that wrote it, so run as the itsUP user the unfiltered command stops with a permission error when the backup's file was written inside the time window, and also when nothing in the window matches and the backup's file holds the most recent write in the directory, which a bare `instrukt-ai-logs itsup` meets after a backup run until the CLI next logs. `instrukt-ai-logs itsup --include itsup` reads the CLI's file in both cases, and the backup's file needs root. +On a systemd host the nightly backup's unit runs as root and writes its own file into the same log directory; a launchd agent runs as the user and is not affected. The logger keeps each file private to the user that wrote it, so the itsUP user cannot read the backup's file, and the unfiltered commands above meet it in one of three ways: + +- The backup's file was written inside the time window: the command stops with a permission error and prints nothing, with or without `--follow`. +- It was written before the window and `--follow` is not given: lines from the other sources print as usual, but when nothing in the window matches and the backup's file holds the most recent write in the directory, the command stops with a permission error. A bare `instrukt-ai-logs itsup` meets that after a backup run that wrote to its file, until the CLI next logs. +- It was written before the window and `--follow` is given: no error, but the backup's new lines are left out and nothing says so. + +`instrukt-ai-logs itsup --include itsup` reads and follows the CLI's file in every case, and the backup's file needs root. `instrukt-ai-logs` is the logger project's standalone tool ([InstruktAI/logging](https://github.com/InstruktAI/logging)). The Python package itsUP depends on only writes logs, so `make install` does not provide the tool. Install it once on each machine that reads these logs: diff --git a/docs/project/design/logging.md b/docs/project/design/logging.md index 17347f6e..b76ffd98 100644 --- a/docs/project/design/logging.md +++ b/docs/project/design/logging.md @@ -224,17 +224,27 @@ and operator banners are unaffected. At the logger release itsUP locks, the writer keeps every file readable by its producing user only and re-applies that each time it opens the file, so the itsUP user cannot read `backup.log` at all. The reader is installed - separately and itsUP pins no release of it; the release that matches the - lock answers an unfiltered `instrukt-ai-logs itsup` from the itsUP user with - a permission error in two cases. When the file it cannot open was last - written inside the requested window, it prints nothing, not even from the - sources it could read. When nothing in the window matches and that file - holds the folder's most recent write, it fails as well, whatever the length - of the window: that is the state from a backup run that wrote to its file - until an `itsup` command next logs. Naming only sources that user owns - (`--include itsup`) reads them in both cases; `backup.log` is readable only - as root. The same holds for every further root-run producer routed through - the logger, and the container security monitor's unit also runs as root. + separately and itsUP pins no release of it. At the release that matches the + lock, an unfiltered `instrukt-ai-logs itsup` from the itsUP user meets that + file in one of three ways: + + - **The file was last written inside the requested window.** The read ends + with a permission error and prints nothing, not even from the sources it + could read, with or without `--follow`. + - **The file was last written before the window, without `--follow`.** Lines + from the readable sources inside the window print as usual. When nothing in + the window matches, the read ends with a permission error if that file + holds the folder's most recent write: that is the state from a backup run + that wrote to its file until an `itsup` command next logs. + - **The file was last written before the window, with `--follow`.** The + window prints from the readable sources and the follow starts without an + error, but the file is left out of it: lines the backup writes from then on + never appear, and nothing reports that they are missing. + + Naming only sources that user owns (`--include itsup`) reads and follows them + in every case; `backup.log` is readable only as root. The same holds for + every further root-run producer routed through the logger, and the container + security monitor's unit also runs as root. - **Root as the first writer.** The writer creates every missing directory on the way to the folder owned by the process that asks and closed to everyone else. When a root-run producer is the first to log on a host where the itsUP