diff --git a/README.md b/README.md index 950e9f0..6b61dd5 100644 --- a/README.md +++ b/README.md @@ -462,7 +462,7 @@ Copy the skills into a specific project (`/.agents/skills` and `/.cl make project TARGET=/path/to/repo ``` -Both commands also patch the target's `.claude/settings.local.json` — the machine-local, untracked file, so a project's reviewed `.claude/settings.json` is never rewritten by an install: the caveman and ponytail plugins are enabled so their modes auto-activate on session start, and two reminder hooks are registered, both silent until switched on in the hub's Controls › Schedules tab (`/schedules.json`) — `kvb-dream` points each agent at `/kvb-dream` once every N hours (default 12, stamped per session in `~/.claude/.dream-stamps/`), and `kvb-coach` from the coach repository runs its short form at the first prompt every N hours (default 1), once across all agents (stamped in `~/.claude/.coach-hours/`); the global install also copies the `kvb-dream-notify.timer` systemd user timer, which recommends `/kvb-dream` in a GNOME notification daily at the set times (default 17:00, off) and catches up once after a missed run, enables the `kvb-org-queue-cleanup.timer` and `kvb-org-queue-cleanup.path` user units, which start a `kvb-org-queue-cleanup` round at 00:00 and 12:00 local time without catch-up and whenever an agent runs `cleanup.py request`, and enables `kvb-schedules.path` and `kvb-schedules.timer`, which run `skills/kvb-org-organize/scripts/schedules.py run` on every change of `schedules.json` and every 5 minutes: it switches and retimes the first-party units to their rows and lists every other user timer and hook for the hub. A PreToolUse gate from the `kvb-org-organize` skill blocks edits to files in a git worktree until the session holds a claim (`skills/kvb-org-organize/scripts/council.py`), and its resource watch (`skills/kvb-org-organize/scripts/watch.py`) measures disk, Docker and caches, cleans up low-risk data and blocks new heavy jobs before the disk runs out; it stays inactive until `~/.claude/agents-council/config.json` exists, and because its hooks run that config's commands outside the sandbox, the install adds `Edit(~/.claude/agents-council/**)` to `permissions.deny`, which also covers Write in every permission mode; `Edit(~/.local/state/agents-council/**)` joins it, so the state the skills' scripts keep there changes only through those scripts. The global install writes both rules into `~/.claude/settings.json` too (`scripts/council-deny.js`), the only user-wide settings file, so they bind sessions in every repository. The `kvb-org-radio` skill registers five hooks: its prompt hook and a PostToolBatch hook deliver the immediate radio (`call`, `broadcast`, `security`, `pan-pan`, `mayday`) mid-turn, a Stop hook delivers the post (`post`, `newsletter` and call receipts) when the turn ends, an `asyncRewake` Stop hook wakes an idle session for the radio, and a PreToolUse hook refuses every writing action while a mayday holds, except those of its sender and of the agents that join it with `radio.py assist`. The PreToolUse hook of the `kvb-org-queue` skill sends heavy commands through `queue.py hold` once the config sets `queue_enforce`, and holds a held command to the settings' Bash deny and ask rules, which see only `queue.py hold`. The global install also installs the MEDUSA security scanner with pipx for `kvb-check-security`, unless `medusa` is already on the PATH. It clones microsoft/TokenEconomizer at the commit pinned in `plugins-lock.json` to `~/Repositories/github.com/microsoft/TokenEconomizer` and installs it for Claude Code and, when `codex` is on the PATH, for Codex, which runs its hooks once they are approved with `/hooks`; tool pruning only proposes deny lists and never drops `AskUserQuestion`, `Artifact`, `Skill`, `Agent`, `ToolSearch` or the hub and code graph MCP tools, micro-skills learn only from repeated failures, and the loop guard stays on (requirement 021). Two hooks of the `kvb-org-perform` skill (`skills/kvb-org-perform/scripts/log.py`) log every Agent spawn with its task class, model and effort, and store the quality feedback a sandboxed session prints, in `~/.local/state/agents-council/subagent-model.jsonl`. Every hook runs `/usr/bin/python3 -I`, so neither the `python3` of a sandbox-writable virtualenv on the `PATH` nor `PYTHONPATH` reaches the hooks, which run outside the sandbox; older bare `python3` hook entries are rewritten. On a Bash call the radio, watch, queue, code graph and log hooks run in one interpreter per event, `skills/kvb-org-organize/scripts/hooks.py pre-bash` and `post-bash`, each handler in its own `try`; an exit 2 of any handler still blocks with its text, and the six older separate Bash entries are rewritten to these two. The reminder hooks run `/usr/bin/bash` and pin `PATH=/usr/bin:/bin`, and the council scripts keep only the `PATH` directories this uid cannot write (`skills/kvb-org-organize/scripts/hookpath.py`), so no binary an agent plants on the inherited `PATH` runs outside the sandbox. Existing settings are preserved. +Both commands also patch the target's `.claude/settings.local.json`, the machine-local, untracked file, so a project's reviewed `.claude/settings.json` is never rewritten by an install: the caveman and ponytail plugins are enabled so their modes auto-activate on session start, and two reminder hooks are registered, both silent until switched on in the hub's Controls › Schedules tab (`/schedules.json`): `kvb-dream` points each agent at `/kvb-dream` once every N hours (default 12, stamped per session in `~/.claude/.dream-stamps/`), and `kvb-coach` from the coach repository runs its short form at the first prompt every N hours (default 1), once across all agents (stamped in `~/.claude/.coach-hours/`); the global install also copies the `kvb-dream-notify.timer` systemd user timer, which recommends `/kvb-dream` in a GNOME notification daily at the set times (default 17:00, off) and catches up once after a missed run, enables the `kvb-org-queue-cleanup.timer` and `kvb-org-queue-cleanup.path` user units, which start a `kvb-org-queue-cleanup` round at 00:00 and 12:00 local time without catch-up and whenever an agent runs `cleanup.py request`, and enables `kvb-schedules.path` and `kvb-schedules.timer`, which run `skills/kvb-org-organize/scripts/schedules.py run` on every change of `schedules.json` and every 5 minutes: it switches and retimes the first-party units and the `kvb-orchestrator-*` timers to their rows (a drop-in `schedule.conf`; an `OnCalendar` that `systemd-analyze calendar` refuses keeps the old schedule and shows as the row's error) and lists every user timer and every Claude task of a `.claude/scheduled_tasks.json` under `~/Repositories` for the hub. A PreToolUse gate from the `kvb-org-organize` skill blocks edits to files in a git worktree until the session holds a claim (`skills/kvb-org-organize/scripts/council.py`), and its resource watch (`skills/kvb-org-organize/scripts/watch.py`) measures disk, Docker and caches, cleans up low-risk data and blocks new heavy jobs before the disk runs out; it stays inactive until `~/.claude/agents-council/config.json` exists, and because its hooks run that config's commands outside the sandbox, the install adds `Edit(~/.claude/agents-council/**)` to `permissions.deny`, which also covers Write in every permission mode; `Edit(~/.local/state/agents-council/**)` joins it, so the state the skills' scripts keep there changes only through those scripts. The global install writes both rules into `~/.claude/settings.json` too (`scripts/council-deny.js`), the only user-wide settings file, so they bind sessions in every repository. The `kvb-org-radio` skill registers five hooks: its prompt hook and a PostToolBatch hook deliver the immediate radio (`call`, `broadcast`, `security`, `pan-pan`, `mayday`) mid-turn, a Stop hook delivers the post (`post`, `newsletter` and call receipts) when the turn ends, an `asyncRewake` Stop hook wakes an idle session for the radio, and a PreToolUse hook refuses every writing action while a mayday holds, except those of its sender and of the agents that join it with `radio.py assist`. The PreToolUse hook of the `kvb-org-queue` skill sends heavy commands through `queue.py hold` once the config sets `queue_enforce`, and holds a held command to the settings' Bash deny and ask rules, which see only `queue.py hold`. The global install also installs the MEDUSA security scanner with pipx for `kvb-check-security`, unless `medusa` is already on the PATH. It clones microsoft/TokenEconomizer at the commit pinned in `plugins-lock.json` to `~/Repositories/github.com/microsoft/TokenEconomizer` and installs it for Claude Code and, when `codex` is on the PATH, for Codex, which runs its hooks once they are approved with `/hooks`; tool pruning only proposes deny lists and never drops `AskUserQuestion`, `Artifact`, `Skill`, `Agent`, `ToolSearch` or the hub and code graph MCP tools, micro-skills learn only from repeated failures, and the loop guard stays on (requirement 021). Two hooks of the `kvb-org-perform` skill (`skills/kvb-org-perform/scripts/log.py`) log every Agent spawn with its task class, model and effort, and store the quality feedback a sandboxed session prints, in `~/.local/state/agents-council/subagent-model.jsonl`. Every hook runs `/usr/bin/python3 -I`, so neither the `python3` of a sandbox-writable virtualenv on the `PATH` nor `PYTHONPATH` reaches the hooks, which run outside the sandbox; older bare `python3` hook entries are rewritten. On a Bash call the radio, watch, queue, code graph and log hooks run in one interpreter per event, `skills/kvb-org-organize/scripts/hooks.py pre-bash` and `post-bash`, each handler in its own `try`; an exit 2 of any handler still blocks with its text, and the six older separate Bash entries are rewritten to these two. The reminder hooks run `/usr/bin/bash` and pin `PATH=/usr/bin:/bin`, and the council scripts keep only the `PATH` directories this uid cannot write (`skills/kvb-org-organize/scripts/hookpath.py`), so no binary an agent plants on the inherited `PATH` runs outside the sandbox. Existing settings are preserved. The council root is the one directory every `kvb-org` script, hook and the hub share: the register, radio, queue, claims, operator rows, score journal, gate receipts, security cache and night state, plus `pages/` (the `kvb-git-diff` review pages the hub reads), `approvals/` (the replay stores of `approval.py verify`) and `gates/` (gate logs). `skills/kvb-org-organize/scripts/councilroot.py` alone resolves it: `$AGENTS_COUNCIL_ROOT`, else `$XDG_STATE_HOME/agents-shared`, else `~/.local/state/agents-shared`, so it survives a reboot; `councilroot.py root` prints it and `councilroot.py dir ` creates and prints a part. It and `agents-release` below are the only state paths a sandbox's `allowWrite` may name. Its sibling `~/.local/state/agents-council` (`councilroot.py durable`) is host-only and never belongs in `allowWrite`: only hooks, the runner and the systemd units write it (`gates.db`, the watch hook's copies of the receipt, parent, acceptance and queue-history journals, `queue-cleanup.json`, `resources/`, `subagent-model.jsonl`), and the hub mounts it read-only; no directory is both agent-writable and host-written except the council root, where every host writer opens files through `nofollow.py`. The `kvb-release` drafts lie in `agents-release/` beside both (`councilroot.py release `). The global install first runs `councilroot.py preflight` and stops before it copies anything unless `~/.claude/settings.json` lists both `agents-shared` and `agents-release` in `sandbox.filesystem.allowWrite`, no `allowWrite` entry reaches `agents-council` in the managed file, its `managed-settings.d` drop-ins, the user or user-local file (the list `councilroot.py` shares with the queue's permission check), in a project `.claude/settings.json` or `.claude/settings.local.json` below the pkgmgr repositories and worktrees directories (directory and file links followed), or in the start directory of any session listed in `~/.claude/projects`, and the move below would succeed; it warns while the agents are not suspended. Fixing those entries is the operator's step. It then builds the skills, stops the hub, the runner, the offices, resources and queue-cleanup units, runs `councilroot.py migrate`, which moves an earlier council root in `/tmp/agents-council` into the council root, copies the skills, runs `migrate --catch-up` for what the old skills wrote meanwhile, and starts the units again; the hub image is built before the container is replaced, and a failed build leaves the hub down and fails the install until `bash scripts/orchestrator.sh install` succeeds. Migrate refuses while a lock there is held or a queue job waits, and, checked under those locks, moves nothing (exit 4) while a file cannot be moved or a whole file both roots hold differs; the install then stops with the earlier root intact. Each file is renamed to a `.migrating` name before it is copied, so a writer that opens the old name meanwhile makes a new file the catch-up moves. An identical file leaves one copy, a `.jsonl` journal gets the rows it lacks (by id, else each exact line as often as the earlier root holds it more often, in `ts` order), links are skipped, and a second run moves nothing and duplicates no row. The catch-up keeps a differing whole file beside its namesake as `.legacy-` (exit 3); a file that fails after the check stays behind (exit 5). After exit 3 or 5 the install goes on so the new skills read the new root, names every such file and exits 1 at the end. `~/.local/state/agents-council/migrate.started` exists from the first move to the end of a run; when a crash leaves it, the install copies the new skills anyway, names it and exits 1, and the next completed migrate removes it. Because the council root survives reboots, each `kvb-org-queue-cleanup` round first runs `councilroot.py retire`, which moves gate logs and review pages older than 30 days into `archive//`, and the radio appends the rows it drops past its last 500 to `archive/news-.jsonl`; no reader opens `archive/`, which `kvb-cleanup` offers for deletion. Run the install with every agent suspended (`kvb-org-suspend`) and the queue empty, so nothing writes either root during the move. @@ -476,9 +476,19 @@ The Agents view "Hierarchy" draws the council's formal offices as a collapsible The Tasks tab (key 4, `#tasks/list`, `#tasks/board`, `#tasks/rasci`) shows the `kvb-org-rasci` register as a list, a board by status and a RASCI matrix; queue jobs from `council/queue.json` appear as "waiting for a grant", and the filter "Waits on Operator" is the inbox, which the Inbox entry under Stream opens: every pending review, ask, rule request, operator row and choice card, with no Choices column of its own. The Tasks toolbar is one row that wraps on narrow screens (views, filter, estimation, sort and business value, trend on the burn view), the status chips the second; every list row shows its ETA, and `#tasks/3d` draws the tasks and their dependencies on the 3D engine. Its "Request choices" dropdown has one button per channel, post and call to the agents ticked in it, newsletter, broadcast, pan-pan, Sécurité and mayday to all, that sends the fixed request "send me your open decisions as choices" without a text field, one passkey assertion over every recipient (`/api/choices/sign`, then `/api/choices`). Agents answer with `decision_request`, shown as choice cards, and a click on an option is the passkey-signed answer: after the 3 s undo the hub verifies the signature and posts the answer to the asking agent, whose `decision_wait` returns it as `message` and `answer` for `operator_message`. A task's sheet pins its priority (`rasci.py set --prio `) or sets and drops the operator's WSJF estimate (`rasci.py estimate Operator --value --complexity ` or `--drop`) after a passkey signature; the hub writes an argv-only job, and the runner, started with `--rasci --council `, verifies it like an operator command and runs `rasci.py` from `/` without a shell, killing it after 30 s. Agent order stays untouched. The install copies the fresh runner unit and restarts the runner when it is enabled, and only while the installed `council.py`, `nofollow.py` and `rasci.py` match this tree: otherwise it disables the runner and asks for `make install`. The home install and `orchestrator.sh install`, `stop` and `runner` refuse while `~/.local/state/kvb-orchestrator/runner-job.json` names a live runner pid, which the runner keeps only while it runs a hub row, because stopping the runner kills that row; run them in a terminal once no row runs, never as a hub row. A starting runner has the hub fail every job an earlier runner left running back to its agent (`/api/runner/restart`). The runner unit pins `PATH` to `/usr/bin:/bin`, so a signed command names any other program by its full path; a runner started without `--rasci` and `--council` keeps running signed commands and refuses task changes, and so does one whose council is a symlink or another uid's. Each worktree in the tree file may carry `"flow": {"pull": [...], "push": [...], "source": "file"}` or `null`, which the Tree, the Chord edges, the detail panel and the matching task show; a malformed flow shows as `invalid`. Worktrees and tasks with open work (uncommitted, unpushed, unmerged, task not done) carry a warning bar. +The board marks what runs right now (requirement 074), one labelled chip per mark in this order: a running queue job of the task or the queue card's own (`bi-cpu`, accent, its kind and runtime) from the active entries of `council/queue.json`; an agent working (`bi-person-workspace`, ok, the agent and how long ago it beat) when the task's worker or one of its R beat within the last 5 minutes, read from the busy sessions of the host snapshot `agent-sessions.json` and the council claims (state field `beats`); a hub job running (`bi-terminal`, info, the command's head) while `runner-job.json` in the hub state dir names the task (state field `runner`, read without following a link and dropped once the hub records the job as ended). A marked card gets a 2 px border in its first mark's tone and a 3 s glow that animates opacity only; with `prefers-reduced-motion` the border stays and the glow stops. The board chip "Running" shows only marked cards, kept in the page like "Older Done". + Without reinstalling the skills, `make orchestrator-install` installs, builds and starts only the hub, `make orchestrator-check` checks the installed hub (image, container, logs, HTTP, pinned keys, hook, runner, tree timer, disk; exit 1 on a failure), `make orchestrator-pin CREDENTIAL=` pins the passkey that "Register passkey" shows, `make orchestrator-runner` enables the runner service, and `make orchestrator-hook` registers the PermissionRequest hook in `~/.claude/settings.json`, replacing an earlier Agent Orchestrator entry and keeping the file mode, after a copy to `settings.json.before-kvb-orchestrator-hook` (Claude Code reads `~/.claude/settings.local.json` only in sessions started in the home directory). Agents that reach the Docker socket are root-equivalent: until the agent VMs of core requirement 093 isolate them, the signatures do not hold against such an agent. `make watch-check` shows whether the resource watch hook is stuck (running hooks, holders of the kept queue history, age of the stored stage). -For approvals the hub is only a relay: every approval of an ask, a staged commit or an operator command is signed end to end with a WebAuthn passkey held in KeePassXC (through KeePassXC-Browser, relying party `localhost`, origin `http://localhost:`; ES256, EdDSA and RS256, so a hardware key can be pinned beside it). To register, open the hub at `http://localhost:/` (WebAuthn needs the domain; on `127.0.0.1` the page links there), choose "Register passkey" in the settings and run the host command the page shows, `python3 ~/.local/share/kvb-orchestrator/client/approval.py pin --port --approvers ~/.config/kvb-orchestrator/approvers.json --credential ''`, in a terminal outside every sandbox: it pins the key in `~/.config/kvb-orchestrator/approvers.json` with mode 0600, a file no sandboxed agent can write and the hub mounts read-only; the hub never pins. Each approval, or one bulk selection, is one signature over the hashes of every item, a nonce and an expiry; each auto-approval rule is signed once. In the inbox, an operator command run with "Run" shows the runner's output in a console under its row until "Close". "Deny" on an ask, an operator row or a rule request signs the denial with its channel and optional reason (a hash no approval shares) and, after the 3 s undo, tells the requesting agent by post or by the radio class picked, never mayday; the hub verifies that signature against the pinned keys before it stores or sends anything, the hook passes the reason on only when it verifies the signature too, and a denied operator row ends as `stopped`. Agents ask for an auto-approval rule with the MCP tool `rule_request` (the rules form's limits; a request stays open for the ask lifetime of one hour, at most 20 in all, and 3 per agent name, which only spreads the queue since MCP names no caller); its row shows a dry run over the last 7 days, and only "Accept" with the passkey stores it. The hub stores no rule, of any kind, whose passkey assertion it cannot verify. The executors verify it themselves against the pinned keys and fail closed: the runner (`client/runner.py`, the `kvb-orchestrator-runner` user service) runs only signed commands, each signature once, recorded in `~/.local/state/kvb-orchestrator-approvals/runner.json`; the PermissionRequest hook (`client/permission_hook.py --port --timeout --approvers ~/.config/kvb-orchestrator/approvers.json --replay ~/.local/state/kvb-orchestrator-approvals/hook.json`) allows only a signed item that matches its own tool, command, cwd and session, else it leaves the decision to Claude Code's own prompt; it runs for every tool, and its command is a Bash call's command line, or for any other call, and for a Bash call that sets more than its command, description, timeout and background flag, the whole tool input as sorted JSON, so a signature never covers a value the hub did not show (over 4000 characters Claude Code asks itself); the inbox, the stream and Match show an ask like Claude Code's dialog, 1 Yes, 2 No and "Tell Claude what to do instead", whose text denies with it as the reason; it also turns each question of an AskUserQuestion call into a decision card that expires with its timeout, answering the call only once a pinned key signed the pick of every question (a multi-select card toggles options and sends them with one signature, and every such card also takes one signed line of "Other" text); the commit skills run `approval.py verify` on the staged tree before committing, else they ask in the terminal. With no key pinned, every executor refuses; review rejections and a decision a rule takes stay unsigned. A signed rule never covers a command holding `;`, `&`, `|`, a backtick, `$`, `<`, `>`, parentheses or a line break: such a command always asks. The hub page is trusted while it asks for a signature or shows the blob to pin: whoever controls the hub container can show one item and have another signed, or hand over a key of its own. Any local process, sandboxed agents included, can also send the unsigned operator actions (the bare decision choice `/api/decisions//choose`, which sends no answer, the priority order, settings that add no stream origin, review rejections, the bare ask denial `/api/asks//deny`, console dismissals) with the hub's guard headers, and the container reads the review pages from `pages/` of the council root, which every sandboxed agent can write; it mounts the council root at its host path and no longer reads the host `/tmp`. All three close with the agent VMs of core requirement 093, like the Docker-socket gap. +The Controls › Queue tab lists the waiting queue jobs, the learnings `queue.py learned --json` prints (per kind the runs, shares, slot limit and caps, per signature the learned values, the last 20 history rows) and the settings `budget_percent`, `ram_cap_percent` and `slot_limits` per kind and `load_limits`. The hub runs `queue.py` read-only with the queue config mounted read-only at `/queue-config` and never writes the config. "Start now" on a waiting job, there and on the queue job rows of a Kanban card, signs `queue.py override `; staged settings are signed together under one passkey assertion as one `queue.py config set ` each (`POST /api/queue`). The runner, started with `--queue --council `, verifies each like a gate change and runs `queue.py` from `/` without a shell with the operator's HOME, refusing every argv but `override ` and `config set` of a known key with a plain number; queue.py itself refuses a value its config check rejects, leaving the file unchanged. An overridden job skips the band, slot limits, reservations and rank, never the live guard (`load_limits`) or the disk (`skills/kvb-org-queue/controls.md`). + +The Hardware chart of Resources draws the limits of `/limits.json` (requirements 083 and 084): for the metric picked above the chart (CPU, RAM, swap, disk or PSI) a labelled line each for lower, upper, STOP and MAYDAY, and for CPU and RAM a thin line at the live AIMD target of `limits-target.json`. A click on a line opens the dial for that value; the Calm (band 50 to 70), Balanced (70 to 90) and Max (80 to 95) switch sets every value at once (`orchestrator/kvb_orchestrator/limiting.py`, `PROFILE_TABLE`), and the Limits sheet lists all of them in one table, each cell opening its dial. The hub checks every save with the installed `kvb-org-organize/scripts/limits.py` (a broken lower < upper < STOP < MAYDAY is refused, 400) and writes the file itself through `nofollow.py`, as the council root is mounted read-write. A value at or below the one in force saves at once (`POST /api/limits` with `{limits, proof: null}`); a higher one, or any save while no limits file is in force, needs a passkey signature over the whole limits object (`POST /api/limits/sign`), else nothing is written. + +"Prune" on the board's toolbar opens the stale task prune: a checklist of every open register task without a register change for N days and without a running mark (N from the days field, 3 to start with; changing it recomputes the list, all ticked), and the answer window on the analog dial, one dial component shared with the undo window (1 to 60 minutes, 10 to start with). One passkey assertion signs two runner jobs (`POST /api/prune`): the announce job, which the runner runs at once as `radio.py send security`, naming every task and the deadline in local HH:MM and ISO 8601, and the apply job `rasci.py prune --since ...`, whose signed `not_before` is the deadline: the runner leaves a job with a `not_before` ahead queued and unclaimed and runs the next one, never waiting on it. At the deadline `rasci.py prune` sets every listed task stopped that is still open, has no active queue job and no register change since the list was taken; an agent keeps a task before then with `rasci.py keep `, which only touches its change time. The board shows a countdown chip until the deadline. The runner needs `--radio ` beside `--rasci` and `--council` and refuses a prune without them, an argv of another shape, more than 50 tasks, an operator/ or hotfix/ row, an announce whose deadline passed or lies over an hour ahead, and an apply job before its deadline; its replay store accepts the approval's counter again for the apply job, which runs after later signatures moved the counter on. + +The Controls › Schedules tab is one table of every timer and cron on the host (requirement 068): Source (Skills, Hub, Claude, System, one filter chip each), Name, Schedule, Next, Last and On, with the reconciler's last run once in the header. A click on a schedule cell turns it into a field and Enter saves: daily times (`17:00, 21:30`) or a raw `OnCalendar` expression for a timer, whole hours for a reminder hook, a 5-field cron for a Claude task, which the hub checks, naming the field it refuses (400). Skills and Hub rows go into `schedules.json` without a passkey (`POST /api/schedules` with `{row, value}` or `{unit, value}`); a System timer or a Claude task needs a passkey signature over `schedules.py timer --on|--off|--reset|--calendar |--at ...` or `schedules.py cron --cron |--remove` (`{items, proof}`; 403 without a valid proof, nothing stored). The runner, started with `--schedules --council `, verifies each like a queue change and runs `schedules.py` from `/` without a shell, refusing every other argv and every `kvb-orchestrator-*` unit; `schedules.py` writes the drop-in and reloads, or edits the task's cron keeping every other byte of the file, and refreshes the view. Reset removes only the drop-in; the hub never deletes a unit file. + +For approvals the hub is only a relay: every approval of an ask, a staged commit or an operator command is signed end to end with a WebAuthn passkey held in KeePassXC (through KeePassXC-Browser, relying party `localhost`, origin `http://localhost:`; ES256, EdDSA and RS256, so a hardware key can be pinned beside it). To register, open the hub at `http://localhost:/` (WebAuthn needs the domain; on `127.0.0.1` the page links there), choose "Register passkey" in the settings and run the host command the page shows, `python3 ~/.local/share/kvb-orchestrator/client/approval.py pin --port --approvers ~/.config/kvb-orchestrator/approvers.json --credential ''`, in a terminal outside every sandbox: it pins the key in `~/.config/kvb-orchestrator/approvers.json` with mode 0600, a file no sandboxed agent can write and the hub mounts read-only; the hub never pins. Each approval, or one bulk selection, is one signature over the hashes of every item, a nonce and an expiry; each auto-approval rule is signed once. In the inbox, an operator command run with "Run" shows the runner's output in a console under its row until "Close". "Deny" on an ask, an operator row or a rule request signs the denial with its channel and optional reason (a hash no approval shares) and, after the 3 s undo, tells the requesting agent by post or by the radio class picked, never mayday; the hub verifies that signature against the pinned keys before it stores or sends anything, the hook passes the reason on only when it verifies the signature too, and a denied operator row ends as `stopped`. Agents ask for an auto-approval rule with the MCP tool `rule_request` (the rules form's limits; a request stays open for the ask lifetime of one hour, at most 20 in all, and 3 per agent name, which only spreads the queue since MCP names no caller); its row shows a dry run over the last 7 days, and only "Accept" with the passkey stores it. The Controls › Rules tab lists the stored rules grouped as Ask, Review and Decision, each row with its on switch, pattern, directory, the agents it applies to, an expiry chip that turns red under 2 days, and how many of the last 50 asks, reviews or decisions of its kind the rule matcher would have granted; "New rule" opens the rules form in a sheet whose live count `POST /api/rules/match` answers for the draft with the same matcher, reading only and granting nothing, and the settings files, the never-granted patterns, the agent groups and the rule sets follow as sections collapsed by default. The hub stores no rule, of any kind, whose passkey assertion it cannot verify. The executors verify it themselves against the pinned keys and fail closed: the runner (`client/runner.py`, the `kvb-orchestrator-runner` user service) runs only signed commands, each signature once, recorded in `~/.local/state/kvb-orchestrator-approvals/runner.json`; the PermissionRequest hook (`client/permission_hook.py --port --timeout --approvers ~/.config/kvb-orchestrator/approvers.json --replay ~/.local/state/kvb-orchestrator-approvals/hook.json`) allows only a signed item that matches its own tool, command, cwd and session, else it leaves the decision to Claude Code's own prompt; it runs for every tool, and its command is a Bash call's command line, or for any other call, and for a Bash call that sets more than its command, description, timeout and background flag, the whole tool input as sorted JSON, so a signature never covers a value the hub did not show (over 4000 characters Claude Code asks itself); the inbox, the stream and Match show an ask like Claude Code's dialog, 1 Yes, 2 No and "Tell Claude what to do instead", whose text denies with it as the reason; it also turns each question of an AskUserQuestion call into a decision card that expires with its timeout, answering the call only once a pinned key signed the pick of every question (a multi-select card toggles options and sends them with one signature, and every such card also takes one signed line of "Other" text); the commit skills run `approval.py verify` on the staged tree before committing, else they ask in the terminal. With no key pinned, every executor refuses; review rejections and a decision a rule takes stay unsigned. A signed rule never covers a command holding `;`, `&`, `|`, a backtick, `$`, `<`, `>`, parentheses or a line break: such a command always asks. The hub page is trusted while it asks for a signature or shows the blob to pin: whoever controls the hub container can show one item and have another signed, or hand over a key of its own. Any local process, sandboxed agents included, can also send the unsigned operator actions (the bare decision choice `/api/decisions//choose`, which sends no answer, the priority order, settings that add no stream origin, review rejections, the bare ask denial `/api/asks//deny`, console dismissals) with the hub's guard headers, and the container reads the review pages from `pages/` of the council root, which every sandboxed agent can write; it mounts the council root at its host path and no longer reads the host `/tmp`. All three close with the agent VMs of core requirement 093, like the Docker-socket gap. Restart your agent afterwards so it loads the new skills. diff --git a/orchestrator/Dockerfile b/orchestrator/Dockerfile index 40cf9f7..1f0ac23 100644 --- a/orchestrator/Dockerfile +++ b/orchestrator/Dockerfile @@ -59,7 +59,7 @@ RUN chmod 0755 /opt/voices /opt/whisper COPY server.py /app/server.py COPY kvb_orchestrator /app/kvb_orchestrator -COPY client/hub_limits.py client/signing.py client/emoji-variation.json client/passkey.py client/verifier.py client/queue_live.py client/sandbox_paths.py /app/client/ +COPY client/hub_limits.py client/signing.py client/emoji-variation.json client/passkey.py client/verifier.py client/pruning.py client/queue_live.py client/sandbox_paths.py /app/client/ COPY templates /app/templates COPY vendor /app/vendor diff --git a/orchestrator/client/permission_hook.py b/orchestrator/client/permission_hook.py index 297078d..71c25ba 100755 --- a/orchestrator/client/permission_hook.py +++ b/orchestrator/client/permission_hook.py @@ -7,7 +7,9 @@ --approvers: the pinned passkeys, e.g. ~/.config/kvb-orchestrator/approvers.json. --replay: this hook's replay store, outside the hub's reach, e.g. ~/.local/state/kvb-orchestrator-approvals/hook.json. - stdin: the Claude Code PermissionRequest hook input. + stdin: the Claude Code PermissionRequest hook input, or the PostToolUse + input of a call that ran, which report_ran() tells the hub and which + prints nothing. Returns: stdout: the PermissionRequest decision JSON: allow only when a pinned @@ -70,6 +72,8 @@ QUESTION_TOOL = "AskUserQuestion" SHELL = "Bash" SHELL_KEYS = frozenset({"command", "description", "timeout", "run_in_background"}) OPTION_KEYS = ("label", "description", "preview") +RAN_EVENT = "PostToolUse" +RAN_TIMEOUT = 2.0 def summary(tool: str, tool_input: object) -> str: @@ -196,11 +200,41 @@ def encoded(payload: dict) -> bytes: return json.dumps(payload).encode() -def create(base: str, ask: dict, timeout: float, shown: dict) -> str: - data = encoded({**ask, "timeout": timeout, **shown}) +def call_key_of(hook: dict) -> str: + """Returns: + signing.call_key() of the hook input's tool_name and tool_input, the + same for the PermissionRequest and the PostToolUse input of one call; + empty when they cannot be encoded, so the ask goes without it and + never becomes an expired Match card. + """ + try: + return signing.call_key(hook.get("tool_name"), hook.get("tool_input")) + except (TypeError, ValueError): + return "" + + +def report_ran(base: str, hook: dict) -> None: + """Args: + hook: the PostToolUse input of a call that ran; the hub closes the + oldest still pending ask of that session and call_key_of() as + answered in the terminal. The report approves and denies nothing. + """ + key, session = call_key_of(hook), str(hook.get("session_id") or "") + if not key or not session or len(session) > NAME_LIMIT: + return + request = urllib.request.Request(f"{base}/api/asks/ran", data=encoded({"call_key": key, "session": session}), headers={"Content-Type": "application/json", **hub_api.GUARD}, method="POST") + hub_api.call(request, RAN_TIMEOUT) + + +def create(base: str, ask: dict, timeout: float, shown: dict, key: str) -> str: + """Args: + key: the call's call_key_of(), sent only when not empty. + """ + called = {"call_key": key} if key else {} + data = encoded({**ask, "timeout": timeout, **called, **shown}) if len(data) > hub_limits.DIFF_BODY_LIMIT: print(f"kvb-orchestrator: the ask goes without its diff, its {len(data)} bytes pass the hub's {hub_limits.DIFF_BODY_LIMIT}", file=sys.stderr) - data = encoded({**ask, "timeout": timeout}) + data = encoded({**ask, "timeout": timeout, **called}) headers = {"Content-Type": "application/json", **hub_api.GUARD} request = urllib.request.Request(f"{base}/api/asks", data=data, headers=headers, method="POST") ask_id = hub_api.call(request, hub_api.SLACK)["id"] @@ -350,6 +384,9 @@ def main() -> int: deadline = time.monotonic() + args.timeout try: hook = json.load(sys.stdin) + if hook.get("hook_event_name") == RAN_EVENT: + report_ran(base, hook) + return 0 questions = asked_questions(hook) if questions is not None: chosen = answers_of(base, hook, questions, args.timeout, trust, deadline) @@ -365,7 +402,7 @@ def main() -> int: print(f"kvb-orchestrator: {WORKTREE}", file=sys.stderr) return 0 pinned, shown = commit_diff(ask, staged_diff.rules_root()) - ask_id = create(base, ask, args.timeout, shown) + ask_id = create(base, ask, args.timeout, shown, call_key_of(hook)) answer = {"status": "pending"} while answer["status"] == "pending" and (left := deadline - time.monotonic()) > 0: answer = status(base, ask_id, min(left, POLL)) diff --git a/orchestrator/client/pruning.py b/orchestrator/client/pruning.py new file mode 100644 index 0000000..e474f0c --- /dev/null +++ b/orchestrator/client/pruning.py @@ -0,0 +1,120 @@ +from __future__ import annotations + +import datetime +import re + +import signing + +ANNOUNCE = "announce" +APPLY = "prune" +TASKS_LIMIT = 50 +WINDOW_MIN = 60 +SKEW = 300 +SENDER = "Operator" +RECORDS = ("operator/", "hotfix/") +DAYS = re.compile(r"[1-9][0-9]{0,2}") +EPOCH = re.compile(r"[1-9][0-9]{9}") + + +def whole(value: object) -> bool: + return isinstance(value, int) and not isinstance(value, bool) + + +def checked_tasks(tasks: list[str]) -> list[str]: + """Returns: + tasks: 1 to TASKS_LIMIT distinct register slugs signing.TASK matches, + none an operator/ or hotfix/ record. + + Raises: + signing.Refused for any other list. + """ + if not 1 <= len(tasks) <= TASKS_LIMIT or len(set(tasks)) != len(tasks): + raise signing.Refused(f"a prune names 1 to {TASKS_LIMIT} distinct tasks") + if not all(signing.TASK.fullmatch(task) and not task.startswith(RECORDS) for task in tasks): + raise signing.Refused("a pruned task is no register task slug outside operator/ and hotfix/") + return tasks + + +def announced(argv: list[str]) -> bool: + return len(argv) >= 6 and argv[0] == ANNOUNCE and argv[1] == "--days" and argv[3] == "--deadline" and bool(DAYS.fullmatch(argv[2]) and EPOCH.fullmatch(argv[4])) + + +def applied(argv: list[str], not_before: object) -> bool: + if len(argv) < 4 or argv[:2] != [APPLY, "--since"] or not EPOCH.fullmatch(argv[2]) or not whole(not_before): + return False + return WINDOW_MIN <= not_before - int(argv[2]) <= signing.PRUNE_WINDOW + + +def prune_argv(argv: object, not_before: object) -> list[str]: + """Args: + argv: the announce job's `announce --days --deadline + ...` (N 1 to 999 DAYS, an EPOCH) with not_before None, or + the apply job's rasci.py arguments `prune --since + ...` with not_before the deadline, WINDOW_MIN to + signing.PRUNE_WINDOW seconds after since; the tasks as + checked_tasks() takes them. + not_before: the epoch the runner holds the job back until, signed + with it. + + Returns: + argv, the hub and the runner check it the same way. + + Raises: + signing.Refused for every other argv or not_before. + """ + if not isinstance(argv, list) or not all(isinstance(part, str) for part in argv): + raise signing.Refused("the argv is no list of texts") + if not_before is None and announced(argv): + checked_tasks(argv[5:]) + return argv + if applied(argv, not_before): + checked_tasks(argv[3:]) + return argv + raise signing.Refused(f"the argv is no prune announce with --days and --deadline, nor rasci.py prune --since with a deadline {WINDOW_MIN} to {signing.PRUNE_WINDOW} s later") + + +def prune_item(argv: list[str], not_before: int | None) -> dict: + item = {"kind": signing.PRUNE_KIND, "argv": argv} + return item if not_before is None else {**item, "not_before": not_before} + + +def tasks_of(argv: list[str]) -> list[str]: + return argv[5:] if argv[0] == ANNOUNCE else argv[3:] + + +def deadline_of(argv: list[str]) -> int: + return int(argv[4]) + + +def timely(argv: list[str], not_before: int | None, now: float) -> None: + """Raises: + signing.Refused for an announce whose deadline passed or lies over + signing.PRUNE_WINDOW + SKEW seconds ahead, and for an apply job + before its not_before. + """ + if not_before is not None and not_before > now: + raise signing.Refused(f"the prune is not due before {stamp(not_before)}") + if not_before is None and not now < deadline_of(argv) <= now + signing.PRUNE_WINDOW + SKEW: + raise signing.Refused(f"the prune deadline {stamp(deadline_of(argv))} passed or lies over {signing.PRUNE_WINDOW} s ahead") + + +def stamp(epoch: int) -> str: + return datetime.datetime.fromtimestamp(epoch).astimezone().isoformat(timespec="seconds") + + +def announcement(argv: list[str]) -> str: + """Returns: + The Securite text of an announce argv: every task, the deadline in + local HH:MM and ISO 8601, and how an agent keeps a task. + """ + deadline = datetime.datetime.fromtimestamp(deadline_of(argv)).astimezone() + names = ", ".join(tasks_of(argv)) + return ( + f"Stale task prune at {deadline:%H:%M} ({deadline.isoformat(timespec='seconds')}): {names}. " + f"Each had no register change for {argv[2]} days; at the deadline the hub runner sets every one still unchanged to stopped. " + "Keep a task with rasci.py keep ; any register change of it keeps it too." + ) + + +def radio_argv(argv: list[str]) -> list[str]: + return ["send", "security", announcement(argv), "--session", SENDER] diff --git a/orchestrator/client/resources.py b/orchestrator/client/resources.py index 597d1f5..dfbed68 100755 --- a/orchestrator/client/resources.py +++ b/orchestrator/client/resources.py @@ -33,14 +33,32 @@ is the name the council claim of the session carries, else the session id's first 8 characters; account is the email the SessionStart hook mapped the session to in the council's - session-accounts.jsonl, left out for an unmapped session. A message counts once by its message id and - request id, also when written over several lines or copied into a - fork's transcript. /offsets.json holds {files: {path: offset}, - seen: {hour: [key digest]}}, seen keeping the hours this run read and - the last two, and is replaced only when it changes. In the first - minute of an hour, rows of the same hour, agent and model merge and - the rows of a day that ended more than 90 days ago fold into one row - per day, agent and model with width: 86400, kept forever. + session-accounts.jsonl, left out for an unmapped session. The same + tokens go to /usage.jsonl as those rows plus skill?, tool?, + subagent? and repo?: skill the last Skill call of the session (main + thread and sidechains) before the message; tool the sorted, + comma-joined tool names of the message; subagent the agentType of a + sidechain transcript's agent-.meta.json; repo the base name of + the git top-level of the message's cwd; a tag is left out while "" + (none, the main thread, text only). Per usage row t and width each of + agent, model, account and the tags keeps its 50 values of the most + tokens and folds the rest into "(other)". A message counts once by + its message id and request id, also when written over several lines + (its tools joined over the lines one run reads) or copied into a + fork's transcript. Only names and counts are stored, never prompt + text, tool inputs or outputs. /context.jsonl gets per day and + agent {t, agent, turns: {kilo: count}, compactions}: the main thread's + context per turn (input plus cache read) in thousands of tokens, + rounded down, and its compact boundaries. /offsets.json holds + {files: {path: offset}, seen: {hour: [key digest]}, skills?: {session: + [[t, skill]]}}, seen keeping the hours this run read and the last two, + skills the calls from the last two hours and the one before, and is + replaced only when it changes. In the first minute of an hour, token + rows of the same hour, agent and model merge and the rows of a day + that ended more than 90 days ago fold into one row per day, agent and + model with width: 86400, kept forever; usage.jsonl is rewritten line + by line the same way by usage_tags.trimmed(); context rows merge per + day and agent. --state: the directory of these files, the unit passes ~/.local/state/agents-council/resources. --council: the council directory with queue.json and the claims. @@ -74,15 +92,15 @@ import stat import subprocess import sys import time -from collections.abc import Callable +from collections.abc import Callable, Iterator from pathlib import Path import queue_live +import usage_tags as tags +from usage_tags import COUNTS, DAY, HOUR, NAMES, add, token_rows INTERVAL = 60 BUCKET = 900 -HOUR = 3600 -DAY = 86400 FINE = 7 * DAY COARSE = 90 * DAY COMMAND_SECONDS = 10 @@ -95,12 +113,13 @@ NVIDIA = "0x10de" DISPLAY = "0x03" NVIDIA_QUERY = "pci.bus_id,utilization.gpu,memory.used,memory.total" UNREAD = {"util": None, "vram_used": None, "vram_total": None} -COUNTS = (("input", "input_tokens"), ("output", "output_tokens"), ("cache_read", "cache_read_input_tokens"), ("cache_write", "cache_creation_input_tokens")) -NAMES = tuple(name for name, _ in COUNTS) HOST_DIGITS = (("cpu", 1), ("ram", 1), ("swap", 1), ("load", 2), ("psi_some", 2), ("psi_full", 2), ("swap_out_mb_min", 1)) CLAIMS = ("*/claim.json", "*/*/claim.json") SAMPLES = "samples.jsonl" TOKENS = "tokens.jsonl" +CONTEXT = "context.jsonl" +USAGE = "usage.jsonl" +COMPACTION = "compact" SESSION_ACCOUNTS = "session-accounts.jsonl" EMAIL_CHARS = 254 OFFSETS = "offsets.json" @@ -609,6 +628,34 @@ def replace(path: Path, text: str) -> None: os.close(parent) +def stream_rewrite(path: Path, produce: Callable[[Iterator[bytes]], Iterator[str]]) -> None: + """Args: + path: the file, read line by line without following a link and + replaced through a fresh temp file beside it, so its size meets + no read limit; a missing file stays missing, a link at its + directory or a file that is not regular raises OSError. + produce: the new file's lines from the old file's lines. + """ + parent = folder(path) + temp = f".{path.name}.{os.urandom(8).hex()}" + try: + try: + source = os.open(path.name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC, dir_fd=parent) + except FileNotFoundError: + return + with open(source, "rb") as old, open(os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC, 0o600, dir_fd=parent), "w", encoding="utf-8") as new: + if not stat.S_ISREG(os.fstat(old.fileno()).st_mode): + raise OSError(errno.EINVAL, "not a regular file", str(path)) + new.writelines(produce(old)) + os.replace(temp, path.name, src_dir_fd=parent, dst_dir_fd=parent) + except BaseException: + with contextlib.suppress(OSError): + os.unlink(temp, dir_fd=parent) + raise + finally: + os.close(parent) + + def rewrite(path: Path, keep: Callable[[list[dict], float], list[dict]], now: float) -> None: rows = read_rows(path) kept = keep(rows, now) @@ -661,18 +708,27 @@ def count(value: object) -> int: return value if isinstance(value, int) and not isinstance(value, bool) and value > 0 else 0 -def assistant(raw: bytes) -> tuple[dict, dict, dict] | None: - """Returns: - (row, message, usage) of an assistant transcript line whose message - carries a usage map and whose row a session id, else None. - """ +def parsed(raw: bytes) -> dict | None: try: row = json.loads(raw) except (ValueError, RecursionError): return None - message = row.get("message") if isinstance(row, dict) and row.get("type") == "assistant" else None + return row if isinstance(row, dict) and isinstance(row.get("sessionId"), str) else None + + +def turn_of(row: dict) -> tags.Turn | None: + """Returns: + The turn of an assistant transcript line whose message carries a + usage map and a model and whose row a time, else None; of the + message only its id, model, usage and tool names are kept. + """ + message = row.get("message") if row.get("type") == "assistant" else None fields = message.get("usage") if isinstance(message, dict) else None - return (row, message, fields) if isinstance(fields, dict) and isinstance(row.get("sessionId"), str) else None + ts = epoch(row.get("timestamp")) + if not isinstance(fields, dict) or ts is None or not isinstance(message.get("model"), str): + return None + counts = tuple(count(fields.get(field)) for _, field in COUNTS) + return tags.Turn(message_key(message.get("id"), row.get("requestId")), ts, row["sessionId"], message["model"], counts, tags.tool_names(message), row.get("isSidechain") is True, string_of(row.get("cwd"))) def message_key(ident: object, request: object) -> str: @@ -685,22 +741,6 @@ def message_key(ident: object, request: object) -> str: return base64.urlsafe_b64encode(hashlib.blake2b(text.encode("utf-8"), digest_size=KEY_BYTES).digest()).decode("ascii") -def usage(raw: bytes) -> tuple[str, float, str, str, tuple[int, ...]] | None: - """Returns: - (message key, time, session, model, counts in COUNTS order) of an - assistant transcript line with a usage field, a time and a model, - else None. - """ - found = assistant(raw) - if found is None: - return None - row, message, fields = found - ts, model = epoch(row.get("timestamp")), message.get("model") - if ts is None or not isinstance(model, str): - return None - return message_key(message.get("id"), row.get("requestId")), ts, row["sessionId"], model, tuple(count(fields.get(field)) for _, field in COUNTS) - - def first_sight(key: str, ts: float, seen: dict[int, set[str]], keys: dict[int, set[str]]) -> bool: """Returns: Whether the message key at ts is in neither seen nor keys at its hour @@ -716,13 +756,39 @@ def first_sight(key: str, ts: float, seen: dict[int, set[str]], keys: dict[int, return not known -def scan(path: Path, start: int, budget: int, seen: dict[int, set[str]]) -> tuple[int, list[tuple[float, str, str, tuple[int, ...]]], dict[int, set[str]]]: +def take(row: dict, found: tags.Read, turns: dict[str, tags.Turn], seen: dict[int, set[str]], keys: dict[int, set[str]]) -> None: + """Args: + row: one parsed transcript line. + found: gets its first-seen turn, its skill calls and its compaction. + turns: this scan's turns by message key; a later line of the same + message adds its tool names to the turn. + seen: the keys of earlier runs and files per hour. + keys: the keys this scan read per hour. + """ + if tags.is_compaction(row): + ts = epoch(row.get("timestamp")) + if ts is not None and first_sight(message_key(row.get("uuid"), COMPACTION), ts, seen, keys): + found.compactions.append((row["sessionId"], ts)) + return + turn = turn_of(row) + if turn is None: + return + found.skills += [(turn.session, turn.ts, name) for name in tags.skill_calls(row["message"])] + if turn.key and turn.key in turns: + turns[turn.key].tools |= turn.tools + elif first_sight(turn.key, turn.ts, seen, keys) and any(turn.counts): + found.turns.append(turn) + turns[turn.key] = turn + + +def scan(path: Path, start: int, budget: int, seen: dict[int, set[str]]) -> tuple[int, tags.Read, dict[int, set[str]]]: """Returns: The offset after the last complete line read from start, at most - about budget bytes on, the usage of every message seen holds no key - of, and per hour the keys of every message read. + about budget bytes on, what take() found in the lines, and per hour + the keys of every message read. """ - found = [] + found = tags.Read() + turns: dict[str, tags.Turn] = {} keys: dict[int, set[str]] = {} position = start with path.open("rb") as handle: @@ -731,27 +797,12 @@ def scan(path: Path, start: int, budget: int, seen: dict[int, set[str]]) -> tupl if not raw.endswith(b"\n") or position - start >= budget: break position += len(raw) - read = usage(raw) if b'"usage"' in raw else None - if read is not None and first_sight(read[0], read[1], seen, keys) and any(read[4]): - found.append(read[1:]) + row = parsed(raw) if b'"usage"' in raw or tags.COMPACT in raw else None + if row is not None: + take(row, found, turns, seen, keys) return position, found, keys -def token_rows(sums: dict[tuple, list[int]]) -> list[dict]: - """Args: - sums: per (t, agent, model, width, account) the counts in COUNTS - order, account "" for a session the hook mapped to none. - - Returns: - One token row per key in key order; a row other than hourly names - its width, a row of a mapped session its account. - """ - return [ - {"t": t, "agent": agent, "model": model, **dict(zip(NAMES, counts, strict=True)), **({} if width == HOUR else {"width": width}), **({"account": account} if account else {})} - for (t, agent, model, width, account), counts in sorted(sums.items()) - ] - - def token_key(row: dict, line: float) -> tuple: """Returns: (t, agent, model, width, account) of the row a token row merges @@ -765,12 +816,6 @@ def token_key(row: dict, line: float) -> tuple: return row["t"], row["agent"], row["model"], HOUR, account -def add(sums: dict[tuple, list[int]], key: tuple, counts: tuple[int, ...]) -> None: - total = sums.setdefault(key, [0] * len(COUNTS)) - for index, value in enumerate(counts): - total[index] += value - - def compact(rows: list[dict], now: float) -> list[dict]: """Returns: The token rows merged per token_key(), every day that ended more than @@ -789,15 +834,15 @@ def start_of(entry: object, info: os.stat_result, now: float) -> int: return info.st_size if info.st_mtime < now - COARSE else 0 -def read_transcript(path: Path, entry: object, budget: int, now: float, seen: dict[int, set[str]]) -> tuple[int, int, list, dict[int, set[str]]]: +def read_transcript(path: Path, entry: object, budget: int, now: float, seen: dict[int, set[str]]) -> tuple[int, int, tags.Read, dict[int, set[str]]]: """Returns: - (start, end, usages, keys per hour) of path read from the offset + (start, end, read, keys per hour) of path read from the offset entry records, without reading once budget is spent. """ info = path.stat() start = start_of(entry, info, now) if budget <= 0 or start >= info.st_size: - return start, start, [], {} + return start, start, tags.Read(), {} return start, *scan(path, start, budget, seen) @@ -807,44 +852,65 @@ def seen_of(value: object) -> dict[int, set[str]]: return {int(hour): {key for key in keys if isinstance(key, str)} for hour, keys in value.items() if hour.isdigit() and isinstance(keys, list)} +def seen_floor(now: float) -> float: + return now // HOUR * HOUR - HOUR + + def kept_seen(seen: dict[int, set[str]], touched: set[int], now: float) -> dict[str, list[str]]: - floor = now // HOUR * HOUR - HOUR + floor = seen_floor(now) return {str(hour): sorted(keys) for hour, keys in sorted(seen.items()) if hour in touched or hour >= floor} +def read_all(transcripts: Path, offsets: dict, seen: dict[int, set[str]], budget: int, now: float) -> tuple[dict, set[int], tags.Read]: + """Returns: + (files, touched, read): the offset per transcript after this run, + the hours whose keys it read, and what the transcripts held, each + sidechain turn tagged with its transcript's agent type. + """ + found = tags.Read() + files, touched = {}, set() + for path in sorted(transcripts.rglob("*.jsonl")): + key = path.relative_to(transcripts).as_posix() + try: + start, end, read, keys = read_transcript(path, offsets.get(key), budget, now, seen) + except OSError: + if key in offsets: + files[key] = offsets[key] + continue + files[key] = end + budget -= end - start + for hour, ids in keys.items(): + seen.setdefault(hour, set()).update(ids) + touched.add(hour) + found.extend(read, tags.agent_type(path, read_json) if any(turn.sidechain for turn in read.turns) else "") + return files, touched, found + + def count_tokens(transcripts: Path, council: Path, state: Path, now: float, budget: int) -> list[dict]: """Returns: The rows appended to /tokens.jsonl by this run. """ stored = read_json(state / OFFSETS) - offsets = stored.get("files") if isinstance(stored, dict) and isinstance(stored.get("files"), dict) else {} - seen = seen_of(stored.get("seen") if isinstance(stored, dict) else None) - names = claim_names(council) - accounts = session_accounts(council) - sums: dict[tuple, list[int]] = {} - files, touched = {}, set() - for path in sorted(transcripts.rglob("*.jsonl")): - key = path.relative_to(transcripts).as_posix() - try: - start, end, found, keys = read_transcript(path, offsets.get(key), budget, now, seen) - except OSError: - if key in offsets: - files[key] = offsets[key] - continue - files[key] = end - budget -= end - start - for hour, read in keys.items(): - seen.setdefault(hour, set()).update(read) - touched.add(hour) - for ts, session, model, counts in found: - add(sums, (int(ts // HOUR * HOUR), names.get(session) or session[:8], model, HOUR, accounts.get(session, "")), counts) - rows = token_rows(sums) + kept_before = stored if isinstance(stored, dict) else {} + offsets = kept_before.get("files") if isinstance(kept_before.get("files"), dict) else {} + seen = seen_of(kept_before.get("seen")) + files, touched, found = read_all(transcripts, offsets, seen, budget, now) + history = tags.history_of(kept_before.get("skills")) + tags.add_calls(history, found.skills) + names, accounts = claim_names(council), session_accounts(council) + sums, context = tags.tally(found, history, lambda session: names.get(session) or session[:8], lambda session: accounts.get(session, "")) + rows = token_rows(tags.untagged(sums)) append_rows(state / TOKENS, rows) - kept = {"files": files, "seen": kept_seen(seen, touched, now)} + append_rows(state / USAGE, token_rows(tags.fold(sums))) + append_rows(state / CONTEXT, tags.context_rows(context)) + skills = tags.kept_history(history, seen_floor(now), now - COARSE) + kept = {"files": files, "seen": kept_seen(seen, touched, now), **({"skills": skills} if skills else {})} if kept != stored: replace(state / OFFSETS, json.dumps(kept, sort_keys=True, separators=(",", ":"))) if now % HOUR < INTERVAL: rewrite(state / TOKENS, compact, now) + stream_rewrite(state / USAGE, functools.partial(tags.trimmed, now=now, line=now - COARSE)) + rewrite(state / CONTEXT, tags.compact_context, now) return rows diff --git a/orchestrator/client/runner.py b/orchestrator/client/runner.py index 2c6ace0..746d7a6 100755 --- a/orchestrator/client/runner.py +++ b/orchestrator/client/runner.py @@ -15,6 +15,15 @@ --gates: the installed gates script, e.g. ~/.claude/skills/kvb-check-gate/scripts/gates.py; optional, gate changes need it. + --queue: the installed queue script, e.g. + ~/.agents/skills/kvb-org-queue/scripts/queue.py; optional, queue + changes need it and --council. + --schedules: the installed schedules script, e.g. + ~/.claude/skills/kvb-org-organize/scripts/schedules.py; optional, + schedule changes need it and --council. + --radio: the installed radio script, e.g. + ~/.claude/skills/kvb-org-radio/scripts/radio.py; optional, stale + task prunes need it, --rasci and --council. --operator: the installed operator script, e.g. ~/.claude/skills/kvb-org-operator/scripts/operator.py; optional, without it no row closes done after exit 0. @@ -38,15 +47,38 @@ Returns: refuses a cycle or a done with an open key result, and its reason is the job's output. Runs every signed gate change (rule set|drop, parents add|drop) the same way as `python3 -I -B ` with the - operator's HOME, so gates.py writes its default gates.db. Refuses task + operator's HOME, so gates.py writes its default gates.db. Runs every + signed queue change (`override ` or `config set `, + signing.queue_argv()) the same way as `python3 -I -B ` + with the operator's HOME and the council, so queue.py marks the entry + in its queue and writes the operator's queue config. Runs every + signed schedule change of a System timer or a Claude task + (`timer ...` or `cron ...`, + signing.schedule_argv()) the same way as + `python3 -I -B ` with the operator's HOME and the + council, so schedules.py writes the timer's drop-in or the task's cron + and refreshes schedules-view.json. Runs a signed stale task prune + (pruning.prune_argv()) as two jobs of one signature: the announce job + as `python3 -I -B send security --session Operator`, + naming every task and the deadline, and the apply job as + `python3 -I -B prune --since ...`; every job + whose not_before lies ahead stays queued, unclaimed, until a later + cycle. Refuses task changes without --rasci and --council or into a council that is a - symlink or another uid's, gate changes without --gates, and every other - job. Posts the last 200 output lines + symlink or another uid's, gate changes without --gates, queue changes + without --queue and --council or into such a council, schedule changes + without --schedules and --council or into such a council, prunes + without --radio, --rasci and --council or into such a council, and every + other job. Posts the last 200 output lines back while it runs and the exit code at its end. Before a poll, at most every PREVIEW_SECONDS, it posts, for each open operator row that is a git merge of a full commit id (staged_diff.merge_of) whose HEAD differs from the preview the hub holds, staged_diff.merge_preview, which its Match card shows; such a merge whose job names the previewed HEAD is refused once HEAD moved. + For each open operator row and each pending Bash ask that shipped no + diff that is a git commit-tree with a parent (staged_diff.commit_tree_of) + and has no preview of that parent at the hub, it posts + staged_diff.commit_tree_preview, or the git error line that kept it. At start, before its first cycle, it removes a leftover runner-job.json and posts /api/runner/restart once, so the hub fails every job an earlier runner left running; a failed post is printed to stderr. While @@ -80,6 +112,7 @@ from typing import NamedTuple import hub_api import hub_limits +import pruning import signing import staged_diff import verifier @@ -92,14 +125,21 @@ ERROR_LIMIT = 500 PREVIEW_FAILURES = (OSError, ValueError, staged_diff.DiffError) BEAT = 2.0 PREVIEW_SECONDS = 10.0 +TREE_KIND = "commit-tree" SAFE_PATH = "/usr/bin:/bin" TASK_JOB = "task" TASK_LIMIT = 30.0 GATE_JOB = "gate" +QUEUE_JOB = "queue" +SCHEDULE_JOB = "schedule" +PRUNE_JOB = signing.PRUNE_KIND OPERATOR = "operator/" REFUSED = "refused: no valid operator signature for this command" UNREGISTERED = "refused: this runner was started without --rasci and --council; reinstall its unit with make orchestrator-runner" UNGATED = "refused: this runner was started without --gates; reinstall its unit with make orchestrator-runner" +UNQUEUED = "refused: this runner was started without --queue and --council; reinstall its unit with make orchestrator-runner" +UNSCHEDULED = "refused: this runner was started without --schedules and --council; reinstall its unit with make orchestrator-runner" +UNPRUNED = "refused: this runner was started without --radio, --rasci and --council; reinstall its unit with make orchestrator-runner" class Register(NamedTuple): @@ -107,6 +147,14 @@ class Register(NamedTuple): council: Path +class Scripts(NamedTuple): + register: Register | None + gates: Path | None + queue: Path | None + schedules: Path | None + radio: Path | None + + class Host(NamedTuple): shell: str operator: Path | None @@ -176,14 +224,86 @@ def gate_refusal(job: dict, trust: verifier.Trust, now: float) -> str | None: Why the change must not run, or None when signing.gate_argv() accepts its argv and a pinned key signed it. """ + return argv_refusal(job, trust, now, signing.gate_argv, signing.gate_item) + + +def argv_refusal(job: dict, trust: verifier.Trust, now: float, shape: Callable[[object], list[str]], + item: Callable[[list[str]], dict]) -> str | None: + """Args: + job: the claimed change with argv and proof. + trust: the pinned keys, the runner's replay store and the origin. + now: the current time in epoch seconds. + shape: the signing check of its argv, raising signing.Refused. + item: the signed item of that argv. + + Returns: + Why the change must not run, or None when shape accepts its argv + and a pinned key signed its item. + """ try: - argv = signing.gate_argv(job["argv"]) - verifier.check(job.get("proof"), signing.gate_item(argv), "", trust, now) + argv = shape(job["argv"]) + verifier.check(job.get("proof"), item(argv), "", trust, now) except (signing.Refused, OSError) as error: return f"{REFUSED}: {error}" return None +def queue_refusal(job: dict, trust: verifier.Trust, now: float) -> str | None: + """Args: + job: the claimed queue change with argv and proof. + trust: the pinned keys, the runner's replay store and the origin. + now: the current time in epoch seconds. + + Returns: + Why the change must not run, or None when signing.queue_argv() + accepts its argv and a pinned key signed it. + """ + return argv_refusal(job, trust, now, signing.queue_argv, signing.queue_item) + + +def schedule_refusal(job: dict, trust: verifier.Trust, now: float) -> str | None: + """Args: + job: the claimed schedule change with argv and proof. + trust: the pinned keys, the runner's replay store and the origin. + now: the current time in epoch seconds. + + Returns: + Why the change must not run, or None when signing.schedule_argv() + accepts its argv and a pinned key signed it. + """ + return argv_refusal(job, trust, now, signing.schedule_argv, signing.schedule_item) + + +def prune_refusal(job: dict, trust: verifier.Trust, now: float) -> str | None: + """Args: + job: the claimed prune job with argv, not_before and proof. + trust: the pinned keys, the runner's replay store and the origin. + now: the current time in epoch seconds. + + Returns: + Why the job must not run, or None when pruning.prune_argv() accepts + its argv with its not_before, it is due (pruning.timely()) and a + pinned key signed its item, not_before included. + """ + try: + not_before = job.get("not_before") + argv = pruning.prune_argv(job["argv"], not_before) + pruning.timely(argv, not_before, now) + verifier.check(job.get("proof"), pruning.prune_item(argv, not_before), "", trust, now) + except (signing.Refused, OSError) as error: + return f"{REFUSED}: {error}" + return None + + +def not_due(job: dict, now: float) -> bool: + """Returns: + Whether a listed job carries a not_before after now; the cycle + leaves it queued and unclaimed until then instead of waiting on it. + """ + not_before = job.get("not_before") + return pruning.whole(not_before) and not_before > now + + def moved(job: dict) -> str | None: """Args: job: a claimed operator command; head, when set, is the HEAD its @@ -212,11 +332,14 @@ def preview(row: dict, rules: Path | None) -> dict | None: Returns: The preview to post for a git merge row whose HEAD differs from the hub's: staged_diff.merge_preview, or {head, error} when it cannot be - built; None for every other row. + built; for a git commit-tree row, with kind TREE_KIND, + tree_preview() once head is not its parent; None for every other + row. """ found = staged_diff.merge_of(row["command"], row["directory"]) if found is None: - return None + tree = staged_diff.commit_tree_of(row["command"], row["directory"]) + return None if tree is None or tree[2] == row["head"] else {"task": row["task"], "command": row["command"], "kind": TREE_KIND, **tree_preview(tree, rules)} try: head = staged_diff.head_of(found[0]) except PREVIEW_FAILURES as error: @@ -233,6 +356,36 @@ def preview(row: dict, rules: Path | None) -> dict | None: return {"task": row["task"], "command": row["command"], "head": head, **shown} +def tree_preview(found: tuple[Path, str, str], rules: Path | None) -> dict: + """Args: + found: the directory, tree and parent staged_diff.commit_tree_of + read from a git commit-tree. + rules: the MEDUSA rules directory. + + Returns: + staged_diff.commit_tree_preview, or {head, error} with the parent + as head and the git error line that kept it. + """ + try: + return staged_diff.commit_tree_preview(*found, rules) + except PREVIEW_FAILURES as error: + return {"head": found[2], "error": str(error)[:ERROR_LIMIT]} + + +def ask_preview(ask: dict, rules: Path | None) -> dict | None: + """Args: + ask: a pending Bash ask that shipped no diff, with id, command, cwd + and head, the parent of the preview the hub holds, None for none. + rules: the MEDUSA rules directory. + + Returns: + {ask, ...tree_preview()} for a git commit-tree with a parent whose + preview the hub lacks; None for every other ask. + """ + found = staged_diff.commit_tree_of(ask["command"], ask["cwd"]) + return None if found is None or found[2] == ask["head"] else {"ask": ask["id"], **tree_preview(found, rules)} + + def review_preview(row: dict, rules: Path | None) -> dict | None: """Args: row: a pending review that shipped no diff, with id, worktree, tree @@ -271,11 +424,15 @@ def previews(base: str, rules: Path | None) -> None: for row in listed["rows"]: shown = preview(row, rules) if shown is not None: - call(base, PREVIEWS, oversized(shown, ("task", "command", "head"))) + call(base, PREVIEWS, oversized(shown, tuple(key for key in ("task", "command", "kind", "head") if key in shown))) for row in listed["reviews"]: shown = review_preview(row, rules) if shown is not None: call(base, PREVIEWS, oversized(shown, ("id", "head"))) + for ask in listed["asks"]: + shown = ask_preview(ask, rules) + if shown is not None: + call(base, PREVIEWS, oversized(shown, ("ask", "head"))) def council_refusal(council: Path) -> str | None: @@ -371,6 +528,77 @@ def gate(job: dict, gates: Path, report: Callable[[dict], None]) -> int: return spawn([sys.executable, "-I", "-B", str(gates), *argv], "/", env, report, TASK_LIMIT) +def queue(job: dict, scripts: Scripts, report: Callable[[dict], None]) -> int: + """Args: + job: the claimed and verified queue change with argv. + scripts: the runner's scripts; queue and the register's council set. + report: called with {"output", "code", "refused"}. + + Returns: + The exit code of queue.py, run from / on the argv queue_argv() + checked, with the operator's HOME and the council as its + AGENTS_COUNCIL_ROOT. + + Raises: + signing.Refused for an argv of any other shape. + """ + return council_script(scripts.queue, signing.queue_argv(job["argv"]), scripts, report) + + +def schedule(job: dict, scripts: Scripts, report: Callable[[dict], None]) -> int: + """Args: + job: the claimed and verified schedule change with argv. + scripts: the runner's scripts; schedules and the register's council + set. + report: called with {"output", "code", "refused"}. + + Returns: + The exit code of schedules.py, run from / on the argv + schedule_argv() checked, with the operator's HOME and the council as + its AGENTS_COUNCIL_ROOT. + + Raises: + signing.Refused for an argv of any other shape. + """ + return council_script(scripts.schedules, signing.schedule_argv(job["argv"]), scripts, report) + + +def prune(job: dict, scripts: Scripts, report: Callable[[dict], None]) -> int: + """Args: + job: the claimed and verified prune job with argv and not_before. + scripts: the runner's scripts; radio and the register set. + report: called with {"output", "code", "refused"}. + + Returns: + The exit code of radio.py sending the announcement for the announce + job, else of rasci.py prune on the apply job's argv. + + Raises: + signing.Refused for an argv of any other shape. + """ + not_before = job.get("not_before") + argv = pruning.prune_argv(job["argv"], not_before) + if not_before is None: + return council_script(scripts.radio, pruning.radio_argv(argv), scripts, report) + return council_script(scripts.register.rasci, argv, scripts, report) + + +def council_script(script: Path, argv: list[str], scripts: Scripts, report: Callable[[dict], None]) -> int: + """Args: + script: the skill script to run. + argv: its arguments, already checked against their signing shape. + scripts: the runner's scripts; the register's council set. + report: called with {"output", "code", "refused"}. + + Returns: + The exit code of `python3 -I -B