| 1 | # klaus design |
| 2 | |
| 3 | klaus splits agent work three ways. The coordinator, an interactive agent you talk to, does the |
| 4 | thinking: it researches and writes briefs. Agents do the building, each headless in its own |
| 5 | worktree. The dashboard does the mechanical following: CI, reviews, conflicts, failed checks, |
| 6 | landings. The operator approves. Toward a valley, klaus is a client: the valley restacks, runs |
| 7 | checks and lands; klaus decides what to build and resolves what the valley reports from the states |
| 8 | it lists. Commands and formats are in the [reference](./reference.md). |
| 9 | |
| 10 | ## A run's life |
| 11 | |
| 12 | ``` |
| 13 | klaus launch |
| 14 | → run ID (YYYYMMDD-HHMM-<8 hex>), branch name, change ID |
| 15 | → git fetch origin <default>; git worktree add <worktree_base>/<run-id> -b <branch> |
| 16 | → hooks, shared-git snapshot, runs/<run-id>.json, prompts/<run-id>.md |
| 17 | → a window of tmux session klaus-agents-<session-id> runs: |
| 18 | <worker> < prompt | tee logs/<run-id>.jsonl | klaus _format-stream; klaus _finalize <run-id> |
| 19 | klaus _finalize |
| 20 | → cost, duration, session ID and outcome from the log |
| 21 | → deliver: record GitHub work, or the pushed branch (and valley ready), or salvage, or pause |
| 22 | → scan, then commit state, log and conversation to the data ref |
| 23 | → remove the worktree, the scratch directory and the pane |
| 24 | ``` |
| 25 | |
| 26 | The worker reads its prompt on stdin from a file, so a brief of any length avoids tmux's |
| 27 | command-line limit and the shell. `_format-stream` renders the JSONL stream in the pane and times |
| 28 | the checks it recognises. `_finalize` runs in the pane's own shell after the worker exits, however |
| 29 | it exits. |
| 30 | |
| 31 | **Isolation.** Each agent has its own worktree, so agents cannot step on each other or on your |
| 32 | checkout. Their panes live in a detached tmux session owned by the server, so they take no screen |
| 33 | space and survive the coordinator exiting. A run ends when the agent's turn ends: every worker |
| 34 | prompt says to run long builds in the foreground, and finalize records background work it finds |
| 35 | still running. Scratch output goes to `KLAUS_SCRATCH`, outside the worktree, because salvage commits |
| 36 | whatever the worktree holds uncommitted. A worker's writes to its clone's git config, |
| 37 | `info/attributes` or hooks reach every worktree of the clone, so launch snapshots them and finalize |
| 38 | compares. |
| 39 | |
| 40 | **Workers do not reach the tmux server by accident.** A local worker starts without `TMUX` and |
| 41 | `TMUX_PANE`, and with `TMUX_TMPDIR` set to its run's own empty directory, so a `tmux kill-server` it |
| 42 | runs reaches an empty location rather than the server holding your session and every agent. klaus's |
| 43 | own commands in the worker reach the real server through `KLAUS_TMUX_SOCKET`. This guards against |
| 44 | accidents, not against a hostile worker: the worker runs as the server's Unix user and is given that |
| 45 | socket's path. tmux falls back to `/tmp` when `TMUX_TMPDIR` names a missing directory, so a worker |
| 46 | that points it at one can still reach a server on tmux's default socket. |
| 47 | |
| 48 | **Hooks per worktree.** Trailers and formatting are added by hooks, never by the prompt, so an agent |
| 49 | cannot forget them. klaus sets `core.hooksPath` per worktree (`extensions.worktreeConfig`), leaving |
| 50 | the main clone and other worktrees their own hooks, and chains to the repository's hooks. |
| 51 | |
| 52 | ## Persistence |
| 53 | |
| 54 | Session state (`~/.klaus/sessions/`) is machine-local and disposable. A finalized run's state, log |
| 55 | and Claude conversation are committed to `refs/klaus/data` in the local clone: a ref outside |
| 56 | `refs/heads`, so it shows as no branch, written with git plumbing and a temporary index, so no |
| 57 | working tree changes. Before a log is stored a regex scan looks for private addresses, keys and |
| 58 | credentials; a log it flags, or cannot scan in full, is held back. The ref stays local unless |
| 59 | `push_data_ref` is on, because transcripts hold prompts, file contents and environment details and a |
| 60 | pushed ref is readable by anyone who can read the repository. |
| 61 | |
| 62 | **Observed, not recorded.** Whether a pushed branch landed is checked against the run's clone each |
| 63 | time klaus looks and never written to the run; where a valley lists the change, its listing decides. |
| 64 | What the dashboard records is what it has reported: `pr-transitions.json` and |
| 65 | `change-transitions.json` make each transition an event exactly once across restarts, and dashboards |
| 66 | on one session take a lock to update them, so only one reports each. A change first seen is recorded |
| 67 | as it stands, so a first start reports no history. |
| 68 | |
| 69 | Configuration is JSON, read with the standard library; prompts are Go templates, so one default |
| 70 | works for any repository and a repository can replace it. |
| 71 | |
| 72 | ## The GitHub pipeline |
| 73 | |
| 74 | The dashboard evaluates each piece of GitHub work on every poll or webhook against ordered rules and |
| 75 | moves it through the stages `ci_pending`, `ci_failed`, `ci_passed`, `review_pending`, `approved`, |
| 76 | `needs_rebase`, `merging` and `merged`, with `budget_paused` and `stalled` beside them. |
| 77 | |
| 78 | - **Budget paused** comes first: a draft labelled `klaus:budget-paused` with no agent running waits |
| 79 | for the operator, whatever CI says. |
| 80 | - **CI failed**: a fix agent (`klaus launch --pr`) is told to read `gh pr checks` and |
| 81 | `gh run view --log-failed`. A fix whose agent finished while CI still fails counts as failed. |
| 82 | - **Changes requested**, or new trusted comments: a fix agent addresses them, and the pipeline then |
| 83 | resolves the review threads. |
| 84 | - **Conflicts** with passing CI: a rebase agent rebases onto main, resolves, tests and pushes; |
| 85 | approval is not required. |
| 86 | - **Behind** and approved: `gh pr update-branch` satisfies an up-to-date rule; the merge follows on |
| 87 | a later poll once CI re-ran. |
| 88 | - **Approved**, green, conflict-free, with `auto_merge_on_approval`: `klaus merge --yes`. |
| 89 | |
| 90 | Guards keep dispatch from spinning. No dispatch while a fix run, including one the coordinator |
| 91 | launched with `--pr`, works on the branch, since intermediate commits of a multi-step fix may fail |
| 92 | CI. Dispatches for one piece of work are 60 seconds apart. CI fixes, review fixes and rebases each |
| 93 | stall after 3 failures. Merges and branch updates each get 3 tries per approval, 60 seconds apart; |
| 94 | losing and regaining approval resets them. A failed dispatch stalls the work with one |
| 95 | `pipeline:stalled` naming the error, and nothing is dispatched again until an input the dispatch |
| 96 | read changes (head, CI result, review decision, trusted comments), since retrying on the same inputs |
| 97 | fails the same way. When GitHub cannot be reached (timeout, rate limit), the work is left as it was, |
| 98 | never treated as open. |
| 99 | |
| 100 | GitHub's own approval is detected and recorded like `klaus approve`. A cross-model review posted by |
| 101 | `klaus review` is trusted when its author is the authenticated gh user, so its inline findings feed |
| 102 | the review-fix loop and its breaker; the marker alone grants nothing, and the pipeline does not |
| 103 | start cross-reviews itself. |
| 104 | |
| 105 | ## Delivery to a valley |
| 106 | |
| 107 | **Ready at finalize.** The valley identifies the uploader from `valley.principal`, which the host |
| 108 | sets, not klaus. Because the valley has no verb that records a version as a draft, finalize records |
| 109 | a draft by running `valley ready` then `valley unready`. `approve` refuses a draft and the |
| 110 | integrator lands nothing for one, so a request filed between those two calls waits until the change |
| 111 | is ready again. A follow-up returns its change to draft before its agent starts so nobody approves a |
| 112 | version the agent is replacing; finalize's `valley ready` re-readies that version when the head is |
| 113 | unchanged. |
| 114 | |
| 115 | **One commit per change.** A valley lands a change as one commit under its head message and takes it |
| 116 | only as a line of commits on main. A follow-up therefore amends and restacks rather than merging, |
| 117 | and pushes with a lease on the head launch found. A concurrent push makes the agent's push fail |
| 118 | instead of overwriting it, and the valley keeps every version's head so rewriting loses nothing. |
| 119 | |
| 120 | **Ownership.** A change is klaus's when its record's owner is klaus's principal. The latest uploader |
| 121 | does not count: the restacker uploads the versions it rebases. klaus never takes over a change it |
| 122 | does not own. |
| 123 | |
| 124 | **Restack conflicts fail closed.** A restack report counts only while the valley calls it current |
| 125 | and everything it observed still holds; klaus re-reads origin's refs itself before acting. It |
| 126 | returns the change to draft and launches nothing unless the valley then lists it as klaus's draft at |
| 127 | the same head and branch. Launch checks those conditions again under its continuation lock, before |
| 128 | creating the worktree and before starting the worker (`--expect-*`). Nothing from the report reaches |
| 129 | the brief beyond names and commits klaus read itself: the run finds the conflicts by rebasing. A |
| 130 | change sitting on other changes, or a conflict in a change below, is left to the coordinator. |
| 131 | |
| 132 | **Accounting is conservative.** The attempt and run ID are recorded before launch; the attempt is |
| 133 | given back only when klaus knows no worker started (it stopped first, or launch exited with status |
| 134 | 3). Any other failure keeps the launch pending, and the change busy, until a run by that ID is |
| 135 | recorded or klaus proves none runs: no launch holds the continuation lock, no run is recorded, and |
| 136 | no live pane names it. Time alone settles nothing. klaus acts once per set of inputs and remembers |
| 137 | the outcome, so an unchanged conflict is not retried. Failed checks are dispatched with the same |
| 138 | guards as CI fixes. |
| 139 | |
| 140 | **The listing decides; telemetry wakes.** Where a change stands is the valley's `valley changes` |
| 141 | listing, read once per look for every repository. A telemetry record only triggers a check sooner. |
| 142 | When the listing fails, git's view stands in, a known verdict is kept as `(last known)`, and the |
| 143 | failure is shown, never read as "no change". |
| 144 | |
| 145 | **Knots** are read and written only through the `valley` CLI. A knot's text, parents and comments |
| 146 | reach the agent as untrusted notes in a block fenced by marker lines with a random token, so nothing |
| 147 | in them can close the block. Claims, links and closes carry `--if` conditions on what klaus read, so |
| 148 | a concurrent claim or link makes the close a conflict rather than overwriting it. |
| 149 | |
| 150 | ## Messaging a running agent |
| 151 | |
| 152 | Workers run in print mode (`claude -p`, `codex exec`, agy's print mode) and read the prompt on stdin |
| 153 | from a file; nothing reads the pane's terminal, so text pasted into a worker's pane never reaches |
| 154 | the session. An interactive coordinator does take a pasted message, but only when its interface is |
| 155 | at a prompt: a dialog swallows the paste. |
| 156 | |
| 157 | Feeding a Claude worker its input as `--input-format stream-json` over a per-run FIFO delivers a |
| 158 | multi-line message mid-turn as one message and records it in the Claude transcript (not in klaus's |
| 159 | log); a message sent after the turn's result is lost. A `klaus message` command built that way is |
| 160 | **not built**: it would make every launch depend on FIFO setup, where a mistake fails launches |
| 161 | outright. To correct an agent, `klaus launch --resume-from <run-id>` continues its conversation in a |
| 162 | fresh run, losing only the turn in flight. |
| 163 | |
| 164 | ## Trust boundaries |
| 165 | |
| 166 | **Only the operator approves.** `klaus approve` and `klaus merge`'s approval check are the human |
| 167 | gate for GitHub work; the coordinator prompt forbids approving. Cross-model reviews are `COMMENT` |
| 168 | reviews, never approvals. For a valley, `klaus ready` marks a reviewed head ready and klaus holds no |
| 169 | approval key: approval is the valley's `approve`, run by the operator. The dashboard only displays |
| 170 | `approve_command`, shell-quoting each value so a branch name cannot inject a command. |
| 171 | |
| 172 | **Agents run unattended.** Workers run with each CLI's permission bypass. Run untrusted tasks on an |
| 173 | isolated sandbox host; the gates above hold whatever an agent does. |
| 174 | |
| 175 | **The agent cannot steer its own finalize.** Finalize reads `ready_at_finalize` and `push_data_ref` |
| 176 | from the checkout the worktree belongs to, never the agent's worktree. `forbidden_terms` is host |
| 177 | config only: the list is private, and a repository cannot turn off its own check, which runs before |
| 178 | any diff reaches a reviewer. `self_update` is host config only: a repository must not choose what a |
| 179 | host installs. |
| 180 | |
| 181 | **Labels grant nothing.** `Change-Id` and `Klaus-Run` trailers find and audit commits; no tool may |
| 182 | trust a commit or skip a check because of them. The cross-review marker counts only from the |
| 183 | authenticated gh user. |
| 184 | |
| 185 | **Content is data.** Knot notes, restack reports and review text are never instructions: notes are |
| 186 | fenced as untrusted, report text is never passed on, and a conversation comment by the work's author |
| 187 | counts only with an explicit `/klaus fix` or marker, since the operator and agents post through the |
| 188 | same account. Agent replies carry a marker and are ignored, and an unmarked one is still an author |
| 189 | comment without opt-in. |
| 190 | |
| 191 | **Self-update installs only what was asked.** Only the configured branch installs, pinned to the |
| 192 | commit `git ls-remote` returned. A repository whose flake offers no `packages.<system>.klaus` is |
| 193 | refused before anything is built; klaus builds exactly that attribute, smoke-tests it, and keeps the |
| 194 | previous install for rollback. The repository URL is limited to known transports and characters nix |
| 195 | leaves unchanged, so git and nix read the same source. |
| 196 | |
| 197 | **Dispatchers fail closed.** A dispatched launch checks the valley and origin again just before the |
| 198 | worker starts and refuses on anything it cannot confirm. |
| 199 | |
| 200 | **A webhook delivery is only a signal.** The dashboard's receiver does not check signatures; it |
| 201 | takes a delivery as a reason to re-fetch the named work from GitHub through the same path polling |
| 202 | uses, and never builds status from the payload, so a forged delivery costs one extra fetch. |
| 203 | Signatures are for the relay to check, with the secret `klaus webhook setup` gives GitHub. |