gunk-dev/the-valley

reference.md

source88a5a486b52fmain's published tip history
82.6 KiB · Rendered
1# klaus reference
2
3The complete surface of klaus: commands and flags, configuration, environment, files, trailers, the
4data ref, events, and the constraints the code enforces. The [guide](./guide.md) tells the everyday
5story; the [design](./design.md) explains the mechanisms.
6
7In this reference, **GitHub work** is a GitHub pull request <!-- prose-allow: vocabulary --> that an
8agent opened or that klaus tracks, and `<pr>` names one by number, URL or `owner/repo#N`. A
9**change** is a valley change; its **handle** is the shortest unique prefix of its change ID.
10
11## Commands
12
13| Command | Purpose |
14| ------------------------------------- | ------------------------------------------------------------- |
15| `klaus`, `klaus session`, `klaus new` | Resume or start an interactive coordinator session |
16| `klaus launch` | Launch an autonomous agent run |
17| `klaus status` | Every run of the session, then running and recent jobs |
18| `klaus dashboard` | Live TUI of runs, changes and jobs; runs the pipeline |
19| `klaus logs <run-id>` | A run's output |
20| `klaus watch` | Stream the session's events, or wait for the next ones |
21| `klaus notifications` | Events since the last check, summarised (alias `notif`) |
22| `klaus jobs [show <id>]` | Consults, reviews and prose passes |
23| `klaus consult` | Ask another model a read-only question |
24| `klaus review <pr>` | Second-opinion review of GitHub work by another model family |
25| `klaus approve`, `klaus merge` | Approve GitHub work; merge it in order |
26| `klaus ready <run-id\|handle>` | Mark a valley change ready once its review passes |
27| `klaus track`, `klaus untrack` | Follow work no agent of the session made |
28| `klaus failed-checks` | Dispatch fixes for failed valley checks, once |
29| `klaus restack-conflicts` | Dispatch runs for valley restack conflicts, once |
30| `klaus cleanup` | Remove runs' worktrees, panes and state |
31| `klaus push-log <run-id>` | Store a log held back for sensitivity on the data ref |
32| `klaus report time` | Where agent wall-clock time went |
33| `klaus target` | Set or show the session's default repository |
34| `klaus project`, `klaus sync` | The project registry; fetch every registered project |
35| `klaus scaffold <name>` | Create a GitHub repository and have an agent scaffold it |
36| `klaus init` | Write default configuration |
37| `klaus webhook check\|setup` | GitHub webhooks for registered projects |
38| `klaus self-update` | Install the tip of the configured branch into the nix profile |
39
40`klaus --version` prints `klaus version <v>`.
41
42### klaus, klaus session, klaus new
43
44`klaus` and `klaus session` resume the most recent coordinator session or create one; `klaus new`
45creates a fresh one. They must run inside tmux. In a repository the coordinator works in a worktree
46of `origin/<default branch>` under `worktree_base`, with klaus's hooks but no trailers; elsewhere in
47`~/.klaus/sessions/<id>/workspace`, configured by `~/.klaus/config.json` alone. Each creates the
48session's `events.jsonl` and syncs registered projects in the background (`~/.klaus/sync.log`).
49
50| Flag | Meaning |
51| ------------------------ | --------------------------------------------------------------------- |
52| `--backend <kind>` | Coordinator backend: `claude`, `codex` or `agy`; saved on the session |
53| `--agent-backend <kind>` | The session's default worker backend |
54| `--continue` | (`session`) resume the most recent session |
55| `--resume <id>` | (`session`) resume the given session |
56
57A resumed coordinator keeps its saved backend. A Claude coordinator's project memory directory
58(`~/.claude/projects/<encoded path>/memory`) is a symlink to `~/.klaus/memory`, shared by every
59session; older memory files migrate into it on resume.
60
61### klaus launch
62
63`klaus launch "<prompt>" | --prompt-file <path> [flags]`. The positional prompt and `--prompt-file`
64are mutually exclusive, and one is required.
65
66| Flag | Meaning |
67| ---------------------------- | ------------------------------------------------------------------------- |
68| `--prompt-file <path>` | Read the brief from a file, verbatim |
69| `--repo <r>` | Registered project name, `owner/repo` or URL |
70| `--issue <n\|knot>` | GitHub issue to reference; on a valley project, a [knot](#knots) to work |
71| `--pr <n>` | Work on existing GitHub work's branch; also resumes a budget-paused one |
72| `--change <ref>` | Continue a change in a repository without GitHub on its branch |
73| `--resume-from <run-id>` | Continue a previous run's conversation |
74| `--branch <name>` | Name the new branch; not with `--pr` or `--change` |
75| `--backend <kind>` | Worker backend |
76| `--model`, `--effort` | Model and reasoning effort for the backend |
77| `--budget <usd>` | Claude only: spending cap (default `default_budget`) |
78| `--replay`, `--no-replay` | Force or disable [trajectory replay](#trajectory-replay) |
79| `--replay-threshold-kb <n>` | Largest trajectory replayed; 0 uses `replay_threshold_kb` |
80| `--reason <reason>` | Dispatch reason recorded on the run and its events |
81| `--force-takeover` | Launch past a run still on the branch or change; reset the local branch |
82| `--local`, `--host <name>` | Run locally, or on this [sandbox host](#sandbox-hosts) |
83| `--run-id <id>` | Use this run ID (`YYYYMMDD-HHMM-` and 8 hex digits); refused if taken |
84| `--expect-owner <principal>` | With `--change <change-id>`: require this record owner |
85| `--expect-branch <branch>` | ... the active version, and the launch, on this branch |
86| `--expect-head <sha>` | ... the active version, origin's branch and the worktree at this full SHA |
87| `--expect-draft` | ... the change listed as a draft |
88
89**Target repository**, in order: `--repo` naming a registered project; `--repo` as `owner/repo` or a
90URL (cloned or fetched under `<worktree_base>/.repos/<owner>/<repo>`); the current repository; the
91session target (`klaus target`); else an error.
92
93**Prompt storage.** However given, the brief is written to `prompts/<run-id>.md` in the session
94directory, kept as the record, and every worker reads it on stdin. A local Claude worker reads its
95system prompt from `prompts/<run-id>.system.md`; an agy worker reads system prompt and brief
96together from `prompts/<run-id>.input.md`. What still goes on the pane command line (the Codex
97system prompt, a sandbox Claude system prompt) is checked first: a pane command over 12000 bytes
98fails the launch before any worktree exists, naming the part that is too large.
99
100**Branch names.** Without `--pr` or `--change`, the branch is `<slug>-<tail>`, the tail being the
101run ID's last 8 hex digits. The slug comes from the `--issue` title (GitHub issue or knot), else the
102brief's first `# ` heading outside code fences, else its first non-empty line: a leading
103`<repo-name>:` is dropped, the text is lowercased, each run of characters outside `[a-z0-9]` becomes
104one `-`, and it is cut at a word boundary to at most 40 characters. With no slug, or a name git
105rejects, the branch is `agent/<run-id>`. `--branch` must pass `git check-ref-format --branch` and
106exist neither locally nor on origin.
107
108**Setup.** Launch fetches the default branch, makes the worktree, snapshots the clone's shared git
109files (config, `info/attributes`, hooks), installs [the hooks](#commit-hooks-and-trailers), runs
110`nix develop --command true` when the worktree has a `flake.nix`, and starts the worker in a window
111of the detached tmux session `klaus-agents-<session-id>` (or a split of the coordinator's window
112with `agent_display: "pane"`). The pane runs the worker piped through `tee` to the run's log and
113`klaus _format-stream`, then `klaus _finalize <run-id>`. A local worker needs `bash` and its own CLI
114on the `PATH` launch runs with; launch fails, naming the command and the `PATH`, when either is
115missing. Launch prints `delivery:`, `change:`, `replay:`, `resume:` and `takes on:` lines saying
116what it decided.
117
118#### Change IDs of follow-ups
119
120A fresh launch mints a change ID; a follow-up keeps the one it continues. `--pr` takes the change ID
121of the run that opened the GitHub work, in any session on the machine, else the `Change-Id` of its
122head commit. `--change` takes the named change's, even with `--resume-from`. `--resume-from` alone
123takes its run's. A follow-up to a run recorded without a change ID gets a new one, and the `change:`
124line says so. Dispatch reasons follow: `launch`, `pr-follow-up`, `budget-resume`,
125`change-follow-up`, `resume`.
126
127#### Resolving `--change`
128
129`<ref>` is resolved in order: a run ID names its run's change; a change ID, a prefix of one, or a
130recorded handle is matched against runs of the target repository in any session; failing that, in a
131repository that delivers to a valley, `valley changes --json` names it. A run belongs to the target
132repository when its [repository name](#repository-names) is the target's last component. A ref
133naming several changes is an error listing them. `--change` refuses a GitHub repository, and `--pr`
134or `--branch` beside it. The worktree tracks the change's branch on origin: the valley's active
135version's branch, else the branch the change's newest run pushed; launch fails when none is known or
136origin lacks it.
137
138In a valley repository the worker prompt has the agent amend the change's head commit (or end with a
139commit whose message describes the whole change), never merge another branch in, rebase onto
140`origin/main` when asked or when it conflicts, and push with
141`git push --force-with-lease=refs/heads/<branch>:<head> origin HEAD:refs/heads/<branch>`, where
142`<head>` is the tip launch found. Elsewhere it commits on top and pushes fast-forward, without
143rebasing or force-pushing.
144
145#### `--resume-from` on its run's branch
146
147Combined with `--pr` or `--change`, `--resume-from` supplies the conversation and they supply the
148branch. Alone, it continues the branch its run pushed without GitHub work, as `--change` does, only
149when all of these hold: the run is in the target repository (by name, and by GitHub owner where
150known); no run of the change has GitHub work; origin has the branch; no run of another change worked
151on it and origin's tip carries no other `Change-Id`; the change's branch (the valley's active
152version's, else its newest push's) is still that branch; the branch holds that run's push, or a
153later head of the change (a later run's push on it, or the active version's head); and on GitHub, no
154GitHub work of any state has the branch as its head. Otherwise the follow-up gets a new branch and
155the `resume:` line says why.
156
157#### A run still working on the branch
158
159`--pr`, `--change`, and `--resume-from` continuing its run's branch refuse while a run in any
160session is running on that branch or change in the target repository, naming it. They also refuse,
161with or without `--force-takeover`, while any worktree has the branch checked out (naming it, its
162run, and whether it holds uncommitted changes or commits origin lacks), and while the local branch
163holds commits `origin/<branch>` lacks. `--force-takeover` passes the running-run check and resets
164the local branch to origin's tip, discarding such commits. In one clone these launches hold
165`klaus-continue.lock` from the check through the new run's registration; a second waits up to 5
166minutes, then refuses. `klaus ready` takes the same lock.
167
168#### Dispatcher launches
169
170`--run-id` lets a dispatcher record the run before launching; a launch with it that fails before the
171worker starts exits with status 3. With `--change <full change ID>`, the `--expect-*` flags make
172launch ask the valley, under the continuation lock, before creating the worktree and again after
173returning the change to draft, just before the worker starts; a valley or origin it cannot ask, a
174change not as expected, or a failed `valley unready` fails the launch. Launch stops a worker whose
175run it could not record.
176
177#### Trajectory replay
178
179At finalize, klaus commits a Claude run's resumable conversation to the data ref at
180`sessions/<run-id>.jsonl`. `--pr` on budget-paused work, and `--change` on any change, fetch the ref
181from origin (best effort), restore the newest run's conversation into the new worktree and run
182`claude --resume <uuid>`. Only the most recent run is replayed; otherwise the agent starts fresh,
183and the `replay:` line names the run and the reason, when: that run used another backend; nothing
184was stored (sensitive content, or work older than replay); it ran on another machine and
185`push_data_ref` was off there; the trajectory exceeds the threshold (default 300 KB; `--replay`
186bypasses it); no Claude session ID is known; it ran on a sandbox host; or `--no-replay` is given. A
187Codex follow-up of a Codex run forks its thread (`codex exec fork`) on the same machine; agy always
188starts fresh. A replayed conversation mentions the old worktree path and holds tool results from the
189time it stopped. With `--resume-from`, that run's conversation is used instead; when it cannot be
190resumed the agent starts fresh rather than replaying another run's.
191
192#### Backends
193
194| Capability | Claude | Codex | agy |
195| -------------------------------- | ------------------------ | -------------------------------- | ------------------------- |
196| Coordinator resume | saved conversation ID | newest conversation in workspace | workspace conversation ID |
197| `--resume-from` | staged transcript | local thread, same machine | fresh, with a warning |
198| `--pr`/`--change` conversation | replay from the data ref | fork, same machine | fresh |
199| Budget, budget pause, `--replay` | yes | refused | refused |
200| Shared coordinator memory | `~/.klaus/memory` | the CLI's own | the CLI's own |
201
202Worker backend precedence: `--backend`, the session's saved worker default, `KLAUS_AGENT_BACKEND`,
203`default_agent_backend`, then `claude`. Model and effort: the flag, else `backends.<kind>`, else for
204Claude only `default_agent_model`/`default_agent_effort`; a `backends.<kind>` entry replaces the
205legacy defaults even with empty fields, and with nothing set the CLI's own default applies. Model
206names pass through unchanged. Claude efforts are `low`, `medium`, `high`, `xhigh`, `max`. Workers
207run with each CLI's permission bypass; agy runs with a 24-hour print timeout. `klaus status` shows
208the model the worker reported, else the one launched with, else `(default model)`.
209
210### klaus status
211
212Prints the runs table; a line for each run that changed its clone's shared git files; the failed
213valley checks and the restack conflicts on changes klaus owns; a `Session cost` line that includes
214removed runs; then the session's jobs (running, and finished in the last 3 hours).
215
216| Column | Values |
217| ----------------- | ---------------------------------------------------------------------------- |
218| RUN ID | the run's ID |
219| STATUS | where the run stands (below) |
220| MODEL, COST | backend and model; the run's cost |
221| ISSUE, REPO, HOST | the `--issue`; the target repository; where the agent ran |
222| CHANGE | `#N`, else the change's handle, else the first 8 characters of its change ID |
223| CI | `passing`, `failing`, `pending`, `unknown`; valley checks for a ready change |
224| CONFLICTS | `none`, `yes`, `unknown`, `restack` |
225| BEHIND | commits the base has that the head lacks |
226| MERGE | `ready`, `behind N`, `blocked`, `pending` |
227| PROMPT | the prompt, or the change's title, cut at 40 characters |
228
229STATUS is `running`, `needs-attention`, `superseded`, `pr-created`, `merged`, `closed`, `no-access`,
230`awaiting-integration`, `integrated`, `branch-gone`, a [valley state](#valley-change-states),
231`working`, `tracking` or `exited`. `running` means the pane is running the run (a dead pane, or one
232idle at a shell after finalize, is not). `working`: another run of its change is running.
233`superseded`: a run needing attention whose pushed work a later run of its change took on, and that
234run is running or finished. `no-access`: GitHub will not show the work with the current credentials.
235`tracking`: added by `klaus track` and not yet settled.
236
237### klaus dashboard
238
239| Key | Action |
240| --------------------- | ------------------------------------------------------------------------------------------------ |
241| `j`/`k`, `↑`/`↓` | move the selection |
242| `PgUp`/`PgDn` | move a page |
243| `g`/`G`, `Home`/`End` | top, bottom |
244| `h` | show or hide done rows older than `hide_finished_after_minutes` |
245| `a` | approve the selected GitHub work |
246| `d` | pre-fill `WRT PR#<num>:` in the coordinator's pane and focus it <!-- prose-allow: vocabulary --> |
247| `o` | open the selected GitHub work in a browser (`xdg-open`, or `open`) |
248| `x` | after `y`: remove what `klaus cleanup --done` would; hide finished jobs |
249| `tab` | select a job, or back to the runs |
250| `enter` | read the selected job's record and answer (`esc` back) |
251| `r` | refresh and redraw |
252| `q`, `ctrl+c` | quit |
253
254**Rows.** Runs on one GitHub work share its row (named by the owner and repository in its URL and
255its number); runs without GitHub work on one change (same change ID, same repository) share the
256change's row. A change's row shows the handle (else the change ID's first 8 characters), the
257valley's title (else the pushed head's subject), and where the active version stands, with its head;
258earlier versions fold into it. A newer push the valley holds no version of is noted in the footer
259(`a newer push 1a2b3c4 isn't ready`). While an agent runs on a row, the row names it, sorts with the
260agents and offers no approve command. Rows are grouped yours, agents, pipeline, done, newest first;
261the line above the list counts groups and shows the position and hidden count. Done rows older than
262`hide_finished_after_minutes` (default 60) are hidden; a row the dashboard watched finish stays the
263full period. A repository column appears when the session spans repositories or shows a change.
264
265**Sources.** File-system watching of run state, GitHub polling every 30 seconds (one GraphQL query
266per repository for all its tracked work, plus a compare when a head or base moved), or
267[webhooks](#webhook-receiver). Work seen merged or closed is not asked about again
268(`pr-transitions.json`); reopened work stays closed to klaus. Work the account cannot read (404, a
269non-rate-limit 403, an unresolvable reference) shows `NO ACCESS`, skips CI, conflict and review
270queries, and is asked again every 30 minutes. When GitHub rate-limits, polling stops until the time
271GitHub gives (or 2 minutes), the header says `GitHub rate-limited until HH:MM`, and rows keep their
272status. Pushed branches and valley changes are checked every minute, with at most one
273`valley changes` per check. While it shows changes, the dashboard follows each valley host's
274telemetry with one `valley telemetry --json follow` per host (one of the principal's follow slots);
275a decision, stored evidence or a batch's end triggers an extra check. Where telemetry cannot be
276followed, it logs that once, keeps to the minute and retries every 10 minutes.
277
278**Footer commands.** `dashboard.approve_command` is expanded for a selected `READY` row (`approve:`)
279or `SUBMIT` row (`submit:`): `{repo}` (the repository as the row names it), `{branch}`, `{change}`
280(full change ID), `{handle}`, `{head}`. Values other than `[A-Za-z0-9._/-]` are shell-quoted, so
281placeholders go unquoted. A row lacking a placeholder's value, a `DRAFT` row, or a row with an agent
282running shows none.
283
284**Jobs.** Below the rows, the session's jobs: `RUNNING`, and those finished in the last 3 hours
285(`SUCCEEDED`, `FAILED`, `TIMED OUT`, `INTERRUPTED`, `DIED`), re-read every 30 seconds.
286
287**Restart.** Every 30 seconds the dashboard resolves `klaus` on `PATH`; when it names a different
288file that runs `--version`, the footer says `klaus updated to <version>; restarting`, and after 10
289seconds without a key press the dashboard shuts down as on `q` and execs the new klaus with the same
290arguments and environment. A failed exec is shown and that file is not tried again.
291
292Notes go to `dashboard.log` in the session directory, never to the screen. A narrow or short pane
293drops spacing, status, job and help lines before rows.
294
295### klaus logs
296
297`klaus logs <run-id>` shows the live pane while the run runs, else replays the saved log through the
298formatter. `--replay` re-formats the saved JSONL log; `--raw` prints it as is.
299
300### klaus watch
301
302| Flag | Meaning |
303| --------------------- | ----------------------------------------------------------------------------------------- |
304| `--filter <type>` | Include this type (repeatable); replaces the default filter |
305| `--filter-out <type>` | Exclude this type (repeatable), after `--filter` |
306| `--run <id>` | Only this run's events (a number for pipeline events, a handle for a change's) |
307| `--since-start` | Emit the file's existing events first |
308| `--once` | Wait for at least one matching event, print all that arrived, then a `next:` line, exit 0 |
309| `--after <offset>` | With `--once`: the byte offset to read from |
310| `--json` | Raw JSONL lines |
311| `--list-types` | Print live and reserved types and the default filter |
312| `--session-id <id>` | Override `KLAUS_SESSION_ID` |
313
314`--after` is a byte offset into `events.jsonl` at the start of a line. The `next:` line repeats the
315other flags given, for example `next: klaus watch --once --after 18342`; with `--json` it is
316`{"after":18342,"next":"klaus watch --once --after 18342 --json"}`. Without `--after`, `--once`
317starts at the end of the file (the start with `--since-start`). Interrupted before any event, it
318prints only its `next:` line. An offset past the end or inside a line is an error, as is an events
319file replaced or removed while a watch waits. A watch on a session without an events file waits for
320it while the session directory exists; an unknown session fails at once.
321
322### klaus notifications
323
324Shows events since the last run (marker `notifications-marker` in the session directory), grouped
325into summaries; `--all` shows every event, `--json` lists them. A superseded run's
326`agent:needs-attention` is left out of the summary.
327
328### klaus jobs
329
330`klaus jobs` lists running jobs and those finished in the last 3 hours (`--all`: every record kept).
331`klaus jobs show <id>` prints a record and its answer (`--answer`: only the answer); `<id>` is a job
332ID, a unique ending of one, or a panel ID. A job record (`jobs/<run_id>.json`) holds `kind`
333(`consult`, `review` or `prose`), `thread`, `turn`, `role`, `backend`, `model`, `effort`, `dir`,
334`repo`, `commit` (or a review's `pr`), the `prompt` excerpt, `started_at`, `finished_at`, the klaus
335`pid` and its start time from `/proc/<pid>/stat`, `panel`, and `status`: `running`, `succeeded`,
336`failed`, `timed out` or `interrupted`, with a short `error`. A `running` record whose process is
337gone reads `died`. A one-shot consult's answer is `<run_id>.answer` beside the record, a failed
338one's raw output `<run_id>.raw`; a thread's answer is in its log. Records finished over 7 days ago
339are removed when a job starts.
340
341### klaus consult
342
343`klaus consult [flags] ("<question>" | --prompt-file PATH)`.
344
345| Flag | Meaning |
346| --------------------- | -------------------------------------------------------------------------------------------- |
347| `--backend <kind>` | Model family (default: first installed in `consult.order` other than `KLAUS_BACKEND`) |
348| `--model`, `--effort` | Default `backends.<kind>` |
349| `--role <r>` | `partner`, `critic`, `reviewer` or a verbatim system prompt (default `consult.default_role`) |
350| `--thread NAME` | Continue a named conversation in the current or most recent session |
351| `--dir <path>` | Workspace, read as it stands (default: current directory or the thread's) |
352| `--repo NAME` | A registered project, as a snapshot of origin's default branch |
353| `--file <path>` | Inline a file (repeatable, 200 KB total) |
354| `--prompt-file` | Read the question from a file |
355| `--timeout <d>` | Deadline per backend call (default `10m`) |
356| `--panel` | Ask every installed family other than the caller, concurrently |
357| `--list` | List threads with backend, successful turns and last use |
358
359`--dir`/`--repo`, `--panel`/`--thread` and `--panel`/`--backend` are exclusive. Paths resolve from
360the invoking directory; each attachment sits under a header with its path (for agy, between BEGIN
361and END lines). The question goes on stdin.
362
363**`--repo`** fetches origin's default branch (the project's `default_branch`, else `main`) at the
364start of each turn and checks it out, detached, in a snapshot worktree of the clone. The prompt's
365first line is `Workspace: <project> at origin/<branch> <commit>`, and the commit is kept in the
366thread, the `consult:started` event and the job record. A one-shot snapshot (shared by a panel)
367lives in `~/.klaus/consult-snapshots/` and goes when the consult ends; a thread's lives at
368`consults/NAME.workspace` and moves to the current origin branch every turn. When the fetch fails, a
369thread reads its last snapshot with a warning; a first turn fails. `klaus cleanup --all` removes
370thread snapshots, and a missing one is made again.
371
372**Threads** keep backend, model, effort, role and workspace; conflicting overrides are refused.
373`consults/NAME.json` holds metadata and `consults/NAME.log` the transcript: JSON lines, each turn
374written `pending` before the backend starts and updated to `ok` or `error: <message>`, recording
375backend, model, resume ID, the snapshot commit, and how the session ID was found (`stderr`,
376`stdout-json`, `diagnostic-log`, `text`, `assigned`, `resume`). A failed turn keeps its output in
377`NAME.<turn>.raw`. Outside a pane, threads use the most recent session; one-shot questions need
378none.
379
380**Panels** print each answer whole as it finishes, under a backend/model heading; a timed-out member
381prints `timed out`; any failed member fails the command after the others print.
382
383**Isolation.** Codex runs in its read-only sandbox with `--ignore-user-config` (no MCP servers from
384`$CODEX_HOME/config.toml`; authentication still uses `CODEX_HOME`) and apps, plugins, hooks and
385subagents disabled. Claude runs in safe mode with only Read, Grep and Glob. agy runs in plan mode
386with a temporary agent definition exposing only file reads and search, removed after the call.
387Consults never create run state.
388
389### klaus review
390
391`klaus review <pr>` has a model family other than the author's review GitHub work. The author's
392family is that of the klaus run that opened it, else Claude.
393
394| Flag | Meaning |
395| --------------------- | ------------------------------------------------------------------------- |
396| `--repo <r>` | Repository of a bare number |
397| `--backend <kind>` | Reviewer family (default: the [cross-review choice](#configuration-keys)) |
398| `--model <m>` | Default `backends.<reviewer>.review_model` |
399| `--post` | Submit one `COMMENT` review (default `cross_review.post`) |
400| `--allow-same-family` | With `--backend`, allow the author's own family |
401
402The reviewer sees only `gh pr diff`, the title and the description, with consult isolation, and
403returns findings and a verdict on whether the change matches its stated intent. A posted review has
404event `COMMENT`, never `APPROVE` or `REQUEST_CHANGES`: findings on diff lines become inline
405comments, the rest go in the body, which ends with
406`<!-- klaus-cross-review backend=<kind> model=<model> sha=<head-sha> -->`. Posting is refused when
407the same reviewer already reviewed the head commit, or when `cross_review.max_rounds` marker reviews
408from your gh account exist; both checks, and a check that the head has not moved, run again just
409before posting. `locks/review-<owner>-<repo>-<n>.lock` makes a concurrent `--post` in the session
410fail at once. In a session it emits `review:started`/`review:completed` and leaves a job record;
411SIGINT and SIGTERM end it as `interrupted`.
412
413### klaus approve, klaus merge
414
415`klaus approve <n>...` (`--run <run-id>`, `--all` for every merge-ready one) marks GitHub work
416approved in run state and emits `pr:approval-changed`.
417
418`klaus merge <n>...` merges in order, stopping at the first that fails and reporting the rest. For
419each: check readiness; wait for CI (polling every 30 seconds, up to 10 minutes); if it conflicts,
420rebase it onto main in a temporary worktree, run the verification (`merge_verify_command`, else
421`go build ./...` when there is a `go.mod`, else nothing) and push with `--force-with-lease`; merge
422with `gh pr merge`; mark the run merged. Work merely behind is merged as is; if GitHub demands an
423up-to-date branch, klaus runs GitHub's branch update (a merge from main, which keeps the head and
424its approval), waits for CI and merges again. Merge never removes a worktree that has the branch
425checked out. Without a clone it resolves one (current repository, registered project, or a clone
426under `<worktree_base>/.repos`), and the target repository's `.klaus/config.json` applies.
427
428| Flag | Meaning |
429| --------------------- | -------------------------------------------------------- |
430| `--dry-run` | Print the plan |
431| `--merge-method <m>` | `squash` (default), `merge` or `rebase` |
432| `--no-delete-branch` | Omit `--delete-branch` |
433| `--repo <owner/repo>` | Repository for every number |
434| `--force` | Bypass the approval check |
435| `--yes`, `-y` | Skip unapproved work with a warning instead of prompting |
436
437### klaus ready
438
439`klaus ready <run-id|handle> [--head <sha>]` marks a change's current head ready
440(`valley ready --change <change-id> --head <head> <branch>`, in the run's clone): the active
441version's head when the valley lists the change, else the head its newest run in any session pushed.
442`<run-id|handle>` is a run ID, or a handle, change ID or prefix as this session's runs record them.
443With `--head` (full, or at least 7 hex digits) it marks exactly that head and refuses, naming the
444current head, when the change has moved on; the current head is then origin's tip of the change's
445branch when it differs from the active version, and an unreachable origin is a refusal. It refuses
446while an agent in any session runs on the change, and for a repository that does not deliver to a
447valley. It clears `valley.draft` on this session's run that pushed the head, emits
448`agent:change-ready` with `"via": "klaus ready"`, and prints
449`<repo> <handle> v<n> ready at <head> (run <id>)`.
450
451### klaus track, klaus untrack
452
453`klaus track <ref>...` and `klaus untrack <ref>...`, with `--repo` naming the repository of a bare
454number or the project of a bare handle or change ID. GitHub work is a number (in `--repo`, else the
455session target), a URL or `owner/repo#N`; it reads `tracking` until GitHub says merged or closed. A
456change is a handle, a change ID or `<project>:<handle>`; the project is the one before the colon,
457else `--repo`, else the session target, else the current directory's repository, and klaus runs
458`valley changes --json` in its checkout and records the change ID, repository, handle, and the
459active version's title, branch and head. A change already followed is not added again; a landed or
460withdrawn one is added with a warning. Untrack removes only what track added, and a ref naming
461tracked changes in several projects removes none.
462
463### klaus failed-checks, klaus restack-conflicts
464
465One pass of what the dashboard does every minute: dispatch fix runs for
466[failed valley checks](#failed-check-dispatch), and runs for
467[restack conflicts](#restack-conflict-dispatch), on changes klaus owns.
468
469### klaus cleanup
470
471`klaus cleanup <run-id> | --done | --all [--force]` kills a run's pane, removes its worktree and
472scratch directory, deletes its local branch and its state, keeping its cost and duration in the
473session's ledger (`cleared.jsonl`). `--done` removes the runs of work that is merged, closed,
474integrated, withdrawn or gone, and the older runs of open work, keeping each open item's latest run,
475runs needing attention and running runs, with a line for each. `--all` removes every run and the
476session's unused consult thread snapshots, and the detached agents session once no run holds a pane
477in it and no pane runs a command. Running runs are skipped unless `--force`.
478
479### klaus push-log, klaus report time
480
481`klaus push-log <run-id> [--push]` commits a log held back by the [sensitivity scan](#the-data-ref)
482to the data ref after you reviewed it; `--push` also pushes the ref once.
483
484`klaus report time [--since 7d] [--repo <r>] [--current] [--json]` reads every session's event log
485(`--current`: this one) and reports, per repository and overall, for runs started in the window
486(`0`: all time): runs by dispatch reason, time by phase, checks by kind, idle time between a
487change's runs, time from the last run to the first approval, follow-ups per change, consult and
488review time, and cost. Runs sharing a change ID in a repository, or GitHub work, are one change.
489`--repo` takes a key, valley name or short name; `--json` gives durations in milliseconds. Runs
490without phase events count from `agent:started` to their last event; a run without a reason counts
491as `unknown`.
492
493### klaus target, klaus project, klaus sync
494
495`klaus target [name | owner/repo]` sets the session's default repository (`target.json`); without an
496argument it shows it, and `--clear` removes it.
497
498`klaus project add <owner/repo | name> [--path <dir>] [-d <description>]` clones into the projects
499directory (or registers an existing checkout) and records it in `~/.klaus/projects.json`; a bare
500name searches your GitHub repositories, and without `-d` the description comes from `gh repo view`.
501`project list`, `project remove <name>` (keeps the clone), `project describe <name> <text>` (empty
502clears) and `project set-dir <path>` complete it. Descriptions appear in the coordinator's
503`## Registered projects` block. `klaus sync` fetches and fast-forwards every registered project.
504
505### klaus scaffold, klaus init
506
507`klaus scaffold <project-name> [--description <d>] [--type web|cli] [--budget <usd>] [--backend <kind>]`
508creates a GitHub repository, registers it, and launches an agent that scaffolds it from
509`.klaus/principles.md` in the current directory (else built-in principles), without templates. It
510must run inside tmux.
511
512`klaus init` writes `.klaus/config.json` (the defaults) and `.klaus/prompt.md` in a repository, or
513`~/.klaus/config.json` outside one.
514
515### klaus webhook
516
517`klaus webhook check` shows each registered project's webhook state; `klaus webhook setup [project]`
518creates missing ones. Both need `webhook.relay_url`; `setup` also needs `webhook.secret_file`. Hooks
519subscribe to `push`, `check_run`, `check_suite`, `pull_request`, `pull_request_review` and
520`issue_comment`.
521
522### klaus self-update
523
524Off until the host config has `self_update` (`repo`, and `branch`, default `main`); a repository's
525`.klaus/config.json` cannot set it. `repo` is an `https://`, `ssh://`, `git://` or `file:///` URL,
526an absolute path, or `user@host:path` (read as `ssh://user@host/path`; write `user@host:~/path` for
527a home-relative path). Other transports (`ext::`, `fd::`) and characters outside
528`[A-Za-z0-9._~/:@-]` are refused; git and nix read the same URL, with
529`GIT_ALLOW_PROTOCOL=https:ssh:git:file`. A `git://` repository needs a nix that accepts `git+git://`
530flake references; nix 2.31 refuses them. A run:
531
5321. takes a lock under `$XDG_STATE_HOME/klaus/` (a run finding another exits 0, saying so); a pinned
533 install exits 0 with a note;
5342. resolves the branch with `git ls-remote <repo> refs/heads/<branch>`;
5353. exits 0 when the installed klaus was built from that commit (`-v` says so);
5364. reads the packages the flake offers at that commit and, unless it offers
537 `packages.<system>.klaus`, refuses with nothing built or changed. The refusal asks for
538 `self_update.repo` to name a repository whose flake offers it, such as the-valley's; the next run
539 then builds, smoke-tests and installs from there, whatever the state file remembers of the
540 repository before;
5415. exits 0 when that commit already failed (retried when the branch moves, or with `--retry`);
5426. builds exactly `git+<repo>?ref=refs/heads/<branch>&rev=<sha>#packages.<system>.klaus`, never a
543 default package;
5447. smoke-tests it: `klaus --version` must report the commit and `klaus status` must exit 0; a
545 failure records the commit as failed, installs nothing and exits non-zero;
5468. replaces the nix profile element `klaus`, leaving other elements and the system klaus alone;
5479. records current and previous store paths and commits, the time and any failure in
548 `$XDG_STATE_HOME/klaus/self-update.json`.
549
550`--rollback` reinstalls the previous store path (again to return); `--pin` holds the current install
551until `--unpin`; `--retry`, `--rollback`, `--pin` and `--unpin` are exclusive.
552
553### Internal commands
554
555| Command | Use |
556| ------------------------------------------------------- | -------------------------------------------------------- |
557| `klaus _finalize <run-id>` | Finalize a run; the pane runs it after the worker |
558| `klaus _format-stream [--sandbox]` | Format a worker's JSONL stream; time its checks |
559| `klaus _pre-review [--dir <worktree>]` | Forbidden terms, linters, peer review and prose rewrites |
560| `klaus _forbidden-terms [--repo <r>] [<base>] [<head>]` | Check a range for forbidden terms; exit 1 on a match |
561| `klaus _event --run-id <id> --type <t> --data <json>` | Append an event to the session's log |
562
563`_pre-review` runs [forbidden terms](#forbidden-terms) first, even with `pre_review.enabled` false,
564then the linters (`pre_review.linters`, else detected), then the peer review with the
565[cross-review choice](#configuration-keys) (printing the reviewer), then the
566[prose pass](#configuration-keys). It exits 1, saying the delivery should be blocked, on a forbidden
567term, a lint failure, or findings at or above `pre_review.block_on`.
568
569## Configuration
570
571Configuration layers: built-in defaults, then the host config `~/.klaus/config.json`, then the
572repository's `.klaus/config.json`. Two keys are read from the host config only: `forbidden_terms` (a
573repository's value is ignored) and `self_update`. Finalize reads `ready_at_finalize` and
574`push_data_ref` from the checkout the run's worktree belongs to, never from the agent's worktree.
575
576### Configuration keys
577
578| Key | Default | Meaning |
579| --------------------------------------------------- | ---------------------------------------- | ------------------------------------------------------------- |
580| `worktree_base` | `$TMPDIR/klaus-sessions` | Where worktrees and `.repos/` clones go |
581| `default_branch` | `main` | The repository's default branch |
582| `default_budget` | `5.00` | Claude spending cap in USD |
583| `data_ref` | `refs/klaus/data` | The [data ref](#the-data-ref) |
584| `push_data_ref` | `false` | Push the data ref to origin after every run |
585| `replay_threshold_kb` | `300` | Largest trajectory replayed |
586| `default_coordinator_backend` | `claude` | Coordinator backend |
587| `default_agent_backend` | `claude` | Worker backend |
588| `backends.<kind>.model`, `.effort` | unset | Per-backend model and effort for workers and consults |
589| `backends.<kind>.review_backend` | unset | Reviewer family for work this family wrote |
590| `backends.<kind>.review_model` | unset | Model when this family reviews |
591| `default_agent_model`, `default_agent_effort` | unset | Legacy Claude worker defaults |
592| `agent_display` | `detached` | `detached` session windows, or `pane` splits |
593| `sandbox_host` | unset | SSH host for agent runs |
594| `format` | `nix fmt` if the flake has a `formatter` | Formatter command line for the pre-commit hook |
595| `house_rules.repo`, `.path` | unset | [House rules](#prompts-and-house-rules) file |
596| `forbidden_terms` | unset | Host only: [forbidden terms](#forbidden-terms) |
597| `trusted_reviewers` | `["gemini-code-assist[bot]"]` | Logins whose comments dispatch fix agents |
598| `pr_reviewer` | picked at launch | Login an agent requests review from |
599| `require_approval` | `true` | `klaus merge` requires approval |
600| `auto_merge_on_approval` | `false` | The pipeline merges approved, green, conflict-free work |
601| `merge_verify_command` | `go build ./...` with `go.mod` | Verification before a merge's force-push |
602| `ready_at_finalize` | `true` | Mark a valley change ready at finalize, or leave a draft |
603| `pre_review.enabled` | `true` | Run linters and peer review |
604| `pre_review.linters` | detected | Linter commands |
605| `pre_review.review_model` | `haiku` | Claude reviewer model |
606| `pre_review.max_fix_rounds` | `2` | Review fix rounds |
607| `pre_review.block_on` | `high` | Lowest finding severity that blocks |
608| `pre_review.prose.enabled` | `true` | Run the prose pass |
609| `pre_review.prose.order` | `agy`, `codex`, `claude` | Writer preference |
610| `pre_review.prose.paths` | none | Files beyond Markdown and READMEs whose added lines are prose |
611| `pre_review.prose.timeout_seconds` | `600` | Per model call |
612| `pre_review.prose.max_input_bytes` | `40000` | Diff sent to the models |
613| `pre_review.prose.writer.<kind>`, `.checker.<kind>` | backend defaults | `model` and `effort` for the writer and checker |
614| `cross_review.enabled` | `true` | `false` keeps the author's family |
615| `cross_review.order` | `codex`, `claude`, `agy` | Reviewer preference |
616| `cross_review.post` | `false` | Default for `klaus review --post` |
617| `cross_review.max_rounds` | `2` | Posted cross-reviews per GitHub work |
618| `consult.order` | `codex`, `claude`, `agy` | Consult family preference |
619| `consult.default_role` | `partner` | Consult role |
620| `dashboard.hide_finished_after_minutes` | `60` | Hide older done rows; negative never hides |
621| `dashboard.approve_command` | empty | Footer approve template (`submit_command`: deprecated name) |
622| `webhook.*` | absent | [Webhook receiver](#webhook-receiver) |
623| `self_update.repo`, `.branch` | absent, `main` | Host only: [self-update](#klaus-self-update) source |
624
625**Cross-review choice.** The reviewer family is `backends.<author>.review_backend`, else the first
626`cross_review.order` entry that is not the author and whose CLI is on `PATH`, else the author's own;
627`enabled: false` skips the order. The model is `backends.<reviewer>.review_model`, else
628`pre_review.review_model` for Claude, else the CLI default.
629
630**Prose pass.** Prose is the added lines of Markdown files and READMEs and of files `paths` matches
631(a pattern without `/` matches a file name anywhere; `dir/**` a tree), plus the head commit message;
632a change with no prose beyond a short commit message is skipped. The writer is the first installed
633family in `order` other than the author's, the checker the next (else the author's); each runs at
634`writer.<kind>`/`checker.<kind>`, else backend defaults, except that an agy writer's model defaults
635to `gemini-4-hydrogen-high`. The writer lists each passage's claims in a ledger before rewriting,
636following the writing sections of the repository's `AGENTS.md` and `CLAUDE.md` and the house rules;
637the checker reports each rewrite that changes the meaning.
638
639**`pr_reviewer`.** Used as given. Unset, launch lists the repository's collaborators with push
640access, drops bots and the `gh` user, and picks the owner if present, else the only one left; with
641several left or a failed `gh` call it warns and requests no review. Runs that open nothing new skip
642it.
643
644**`trusted_reviewers`.** Inline review comments and conversation comments both count; a comment
645stops counting once a newer commit is pushed, and an edit counts as new. A conversation comment by
646the work's author counts only if its first non-blank line is `/klaus fix` or it holds
647`<!-- klaus-actionable -->` on a line of its own; quoted lines do not count. Agent replies carry
648`<!-- klaus-agent-reply -->` and are ignored. A review carrying the cross-review marker counts as
649trusted when its author is the authenticated gh user.
650
651### Prompts and house rules
652
653`.klaus/prompt.md` is the worker system prompt template, `.klaus/session-prompt.md` the
654coordinator's and `.klaus/pr-fix-prompt.md` the fix agents'. They are Go templates:
655
656| Variable | Value |
657| ----------------- | -------------------------------------------------------------------------------- |
658| `{{.RunID}}` | the run ID |
659| `{{.Issue}}` | the GitHub issue, if any |
660| `{{.Branch}}` | the agent's branch |
661| `{{.RepoName}}` | the repository's name |
662| `{{.Reviewer}}` | the login to request review from; empty when none, and for direct push |
663| `{{.DirectPush}}` | true when origin is not on github.com |
664| `{{.PR}}` | (fix prompt) the number of the work being fixed <!-- prose-allow: vocabulary --> |
665
666klaus appends its worker rules to every worker prompt: the run ends with the agent's turn, so long
667builds run in the foreground; the test guidance; scratch output stays out of the worktree; a broken
668environment is reported, not worked around; work whose cost is out of proportion stops and reports
669what it taught; and the final report has the headings Intent, Decisions, Shape, What the
670implementation taught us, Checks, Diff summary.
671
672`house_rules` (`{"repo": "<registered project>", "path": "guidance/house-rules.md"}`) is read at
673launch with `git show` from the project's freshly fetched origin default branch, never a working
674tree, and appended after the worker rules, and to the context of `klaus consult --repo`, the
675`_pre-review` reviewer, and the prose writer and checker. The run records its source, commit and
676sha256, and launch prints them. An unreadable file is warned about once, recorded as missing, and
677skipped. A repository's config may name other rules.
678
679### Forbidden terms
680
681```json
682"forbidden_terms": {
683 "site": {"terms": ["internal-host", "corp.example.org", "10.0.2."], "allow_paths": ["docs/hosts.md"]}
684}
685```
686
687A key is a registered project name (its checkout, worktrees, and clones with the same GitHub origin)
688or `owner/repo` (any checkout with that GitHub origin); both apply when both match. The check fails
689when a term appears, case-insensitively as a literal substring, in a line the change adds since its
690merge base with `origin/<default_branch>` (binary files too), in an added or renamed file's name, or
691in a new commit's message. Deleted lines do not count; a moved file's lines count at the new path.
692Files equal to or under an `allow_paths` entry are skipped. The report lists `file:line: term` or
693`commit <sha>: term`, naming only the terms found.
694
695## Environment variables
696
697| Variable | Set by | Meaning |
698| --------------------- | --------------------- | ------------------------------------------------------------------------------------------------- |
699| `KLAUS_SESSION_ID` | session, agent panes | The session; without it, commands use the most recent session |
700| `KLAUS_BACKEND` | session, launch | The running agent's backend: consults pick another family; `_pre-review` takes it as the author's |
701| `KLAUS_AGENT_BACKEND` | session | The session's worker backend default |
702| `KLAUS_RUN_ID` | launch | The run, in the agent's pane (and on a sandbox host) |
703| `KLAUS_RUN_EVENTS` | launch, sandbox runs | `output`: `_pre-review` prints its check as a stream line |
704| `KLAUS_SCRATCH` | launch, local workers | The run's scratch directory |
705| `KLAUS_TMUX_SOCKET` | launch, local workers | The real tmux server's socket, for klaus's own commands |
706| `TMUX_TMPDIR` | launch, local workers | The run's own empty tmux directory; `TMUX`, `TMUX_PANE` unset |
707| `XDG_STATE_HOME` | user | Self-update's lock and state go in `$XDG_STATE_HOME/klaus` (default `~/.local/state/klaus`) |
708| `CODEX_HOME` | user | Codex authentication, also for consults |
709
710## Files and state
711
712| Path | Holds |
713| ------------------------------------------------- | ----------------------------------------------- |
714| `~/.klaus/config.json` | Host config |
715| `~/.klaus/projects.json` | The project registry |
716| `~/.klaus/memory/` | Shared Claude coordinator memory |
717| `~/.klaus/sync.log` | Background project syncs |
718| `~/.klaus/consult-snapshots/` | One-shot consult snapshots |
719| `~/.klaus/sessions/<id>/` | A session (below); machine-local |
720| `<worktree_base>/` | Run and coordinator worktrees; `.repos/` clones |
721| `<clone's git common dir>/klaus-continue.lock` | The continuation lock |
722| `$XDG_STATE_HOME/klaus/self-update.json`, `.lock` | Self-update state and lock |
723
724In a session directory:
725
726| Path | Holds |
727| ------------------------------------------------------------ | ------------------------------------------------------- |
728| `runs/<run-id>.json` | Run state (the coordinator's too) |
729| `logs/<run-id>.jsonl` | The worker's raw stream |
730| `prompts/<run-id>.md`, `.system.md`, `.input.md` | The brief and the prompts workers read |
731| `tmux/<run-id>/`, `scratch/<run-id>/` | The run's `TMUX_TMPDIR` and `KLAUS_SCRATCH` (mode 0700) |
732| `events.jsonl` | The [event log](#events) |
733| `jobs/`, `consults/` | Job records; consult threads |
734| `locks/` | Per-review posting locks |
735| `pr-transitions.json`, `change-transitions.json` (+ `.lock`) | Transitions already reported |
736| `checks-dispatches.json`, `restack-dispatches.json` | What the dispatchers did |
737| `cleared.jsonl` | Cost and duration of removed runs |
738| `target.json`, `notifications-marker` | Session target; last notifications check |
739| `dashboard.log` | Dashboard notes |
740| `workspace/` | The coordinator's workspace outside a repository |
741
742Run state records, among others: `id`, `prompt`, `issue`, `pr`, `pr_url`, `branch`, `worktree`,
743`tmux_pane`, `budget`, `log_file`, `created_at`, `cost_usd`, `duration_ms`, `backend`, `model`,
744`resolved_model`, `effort`, `target_repo`, `clone_dir`, `host`, `approved`, `merged_at`,
745`failure_reason`, `needs_attention`, `pushed_branch`, `pushed_sha`, `pushed_subject`, `change_id`,
746`delivery` (`pr` or `push`), `valley`, `unready`, `change_repo`, `knot`, `dispatch_reason`,
747`repo_key`, `head_sha`, `took_over`, `house_rules` and `shared_git`.
748
749## The data ref
750
751At finalize klaus commits, with a temporary index and without touching any working tree, to
752`data_ref` (default `refs/klaus/data`) in the local clone: `runs/<run-id>.json`,
753`logs/<run-id>.jsonl` and the Claude conversation `sessions/<run-id>.jsonl`. Before a log is stored,
754a scan looks for private IP addresses, SSH keys, credential patterns and `.age` secret references
755(the repository's own remote hosts are exempt); a log that matches, or cannot be scanned in full, is
756held back, only the state is stored, and `klaus push-log` stores it after review. A trajectory with
757sensitive content is not stored. The ref is pushed to origin only when `push_data_ref` is true; a
758push sends its whole history, and anyone who can read the repository can read it.
759
760## Commit hooks and trailers
761
762Every commit an agent makes ends with:
763
764```
765Change-Id: <change id>
766Klaus-Run: <run id>
767```
768
769`Change-Id` is in jj's change-id form (32 characters from `k` to `z`); `Klaus-Run` leads to the run
770and its prompt, log, cost and trajectory. They label commits for finding and auditing; they grant
771nothing, and no tool may trust a commit or skip a check because of them.
772
773Launch installs, for the agent's worktree only (`core.hooksPath` set with `git config --worktree`,
774enabling `extensions.worktreeConfig` once on the clone):
775
776- **commit-msg**: strips Claude/Anthropic attribution, adds `Change-Id` unless present and
777 `Klaus-Run` unless that run is listed (an amend by a later run keeps the change ID and lists both
778 runs), then runs the repository's own `commit-msg` hook. A message empty or made only of `#` lines
779 is left alone.
780- **pre-commit**: runs `format` from the worktree root, re-stages the files that were staged, then
781 runs the repository's own `pre-commit` hook; unstaged changes stay unstaged, and a failing
782 formatter stops the commit.
783
784A shared `core.hooksPath` pointing inside `.git/worktrees/` is removed; any other shared value is
785the repository's, and its hooks run. The coordinator's worktree gets the hooks without trailers.
786Finalize's own salvage and budget-pause commits skip hooks and add the trailers themselves.
787
788## Delivery and finalize
789
790`delivery` is decided at launch from the clone's `origin`: a github.com URL
791(`git@github.com:o/r.git`, `https://github.com/o/r`, `ssh://git@github.com/o/r.git`) is `pr`,
792anything else `push`; a `--pr` fix is always `pr`. A `push` run never records GitHub work, whatever
793URLs its log holds.
794
795Finalize parses the log for cost, duration, session ID and, for `pr` runs, the URL; checks the
796clone's shared git files against the launch snapshot (a difference beyond `git push -u` tracking
797emits `agent:shared-git-changed` and marks the run needing attention); on Linux records processes
798still running in the worktree as `failure_reason` (`background work still running (<commands>)`);
799stores the run on the data ref; and removes the worktree and scratch directory. It deletes the local
800branch only when its work is on the default branch or origin's live tip (`git ls-remote`) matches.
801
802**Pushed branches.** A clean run whose branch is on origin records `pushed_branch` and `pushed_sha`
803and emits `agent:completed` and `agent:branch-pushed` (`repo`, `branch`, `sha`); the local branch is
804deleted. Of the branches the worktree ends on and launch made (not the default branch), a head on
805origin counts as pushed when the local branch holds it. The run's change is the pushed head whose
806`Change-Id` matches the final head's, else the head of the branch the worktree ends on; when that
807differs from launch's, `agent:change-recorded` (`change_id`, `branch`, `head`, `launch_change_id`,
808`launch_branch`, and `pushed` when several changes were pushed) precedes `agent:completed`, and runs
809recorded as taken over are dropped.
810
811**Integration checks** (each look, never written to the run): one `git ls-remote` per repository, a
812fetch of the default branch and pushed branches, then per run: `integrated` when the pushed SHA or
813the branch's tip is an ancestor of the default branch; integrated by content (`INTEGRATED~`) when a
814first-parent commit made after the run started has the same `git patch-id --stable` as the branch's
815diff from the merge base (searching at most 500 commits); `branch-gone` when the branch was deleted
816and neither matched; else `awaiting-integration`. A missing clone, an unreachable origin, a pruned
817SHA, a too-shallow history or the 500-commit cap leave it awaiting.
818
819**Salvage.** A run that ends without delivering, or crashes, gets a commit of everything uncommitted
820that `.gitignore` does not exclude (`wip: klaus finalize salvage <id>`), a plain `git push -u`
821unless origin's live tip already matches (not for runs with GitHub work), keeps its local branch,
822and emits `agent:needs-attention` with `branch`, `pushed` and `reason` (`no_pr`, `session_limit`,
823background work, or the crash). The worktree stays if the commit failed. The attention passes to a
824later run of the change once it records `took_over` (at launch, when it continues a branch holding
825the salvaged head; at finalize, when its head contains it) and is running or finished. A run with no
826commits beyond the default branch and no background work finishes as `agent:completed`.
827
828**Budget pause.** A Claude run stopped at its budget gets `WIP from klaus run <id> (budget paused)`,
829a `--force-with-lease` push, a draft opened or updated with the label `klaus:budget-paused` and a
830one-line comment, and cleanup. The label is the persisted state; a follow-up's finalize removes it
831and emits `agent:resumed`. Claude's structured result is authoritative when the CLI exits non-zero
832at its budget or turn limit.
833
834## Valley delivery
835
836A repository delivers to a valley when its origin is not GitHub, the pushed head (at launch: the
837commit the worktree starts from) has `policy/valley` or a `policy/instance/` directory, and
838`valley help` lists `ready` and `changes`. `valley ready`, `valley unready` and every knot call are
839bounded by 30 seconds; `valley changes` gets three minutes.
840
841- **Finalize** runs `valley ready --change <change_id> --head <pushed_sha> <branch>`, expecting
842 `<repo> <handle> v<n> ready`, records `valley` (repo, handle, version, title) and emits
843 `agent:change-ready` (`repo`, `change_id`, `handle`, `version`, `title`, `head`). Any other
844 outcome is recorded as `valley.error` and warned about; the run shows `SUBMIT` with the reason.
845- With `ready_at_finalize` false, it then runs `valley unready <change_id>`, records `valley.draft`
846 and emits `agent:change-draft` instead. A valley without `unready` gets no ready at all; a failed
847 unready leaves the change ready and emits `agent:change-ready`.
848- **Follow-up launches** return an inherited change to draft first (`valley unready <change_id>`,
849 expecting `<repo> <handle> v<N> draft` or `<repo> <handle> draft`) and record `unready`; a change
850 that was not ready is left alone, and a failure is recorded as `unready.error` and the launch goes
851 on (unless `--expect-draft`).
852
853### Repository names
854
855A run's valley repository is the one `valley ready` reported; else, for a follow-up, the repository
856of the run it continues (`change_repo`); else the one `valley unready` reported; else the last
857component of the target repository without `.git`. Runs share a change when they share a change ID
858and repository name. `repo_key` is `valley:<name>` for these, `owner/repo` on GitHub, else the short
859name.
860
861### Valley change states
862
863`klaus status` and the dashboard read `valley changes --all --json` once per look (the
864`valley-changes/v1` view; other schemas are refused) and match a run to the version, in its
865repository and change, whose head is its pushed SHA.
866
867| Dashboard | `klaus status` | Group | Meaning |
868| ----------------------------- | ----------------------------- | -------- | ----------------------------------------------------------------------------------------- |
869| `REVIEW` | `awaiting-review` | pipeline | a draft left by finalize for review; approve refuses it |
870| `READY` | `awaiting-approval` | yours | the active version, ready, awaiting approval |
871| `APPROVED` | `approved` | pipeline | an integration request is filed and undecided, or stale only because checks are `pending` |
872| `INTEGRATED` | `integrated` | done | the change landed (every version shows it) |
873| `UNCERTAIN` | `uncertain` | yours | a request consumed or failed without landing evidence, or an unknown value |
874| `CHECKS FAILED` | `checks-failed` | yours | stale, and the version's checks failed |
875| `CONFLICTING` | `conflicting` | yours | stale, and the current restack report says `conflict` |
876| `STALE`, `REJECTED`, `FAILED` | `stale`, `rejected`, `failed` | yours | the integrator's decision |
877| `WITHDRAWN` | `withdrawn` | done | the change was withdrawn |
878| `OLDER VERSION` | `older-version` | done | a newer version exists and the change has not landed |
879| `DRAFT` | `draft` | yours | returned to draft with no run of it running |
880
881Landing is the change's `landed_version`, else any version `landed` or `landed-recorded`. A run the
882listing lacks, or a failed listing, falls back to the git integration check, reading `READY` (or
883`REVIEW`) rather than `GONE`. A row the dashboard has seen keeps its last verdict marked
884`(last known)`. While a listing fails, the dashboard shows
885`valley unreachable: <reason>; showing git's view` and `klaus status` prints it on stderr.
886`valley changes --checks` adds checks; a valley refusing the flag is listed without it, and the
887refusal is remembered for 10 minutes.
888
889### Restack-conflict dispatch
890
891klaus owns a change when its record's owner is the clone's `valley.principal`. A report
892(`refs/the-valley/restack/main/<change-id>`) counts while the valley calls it current and the
893change's record, active version, head and branch match it; klaus re-reads origin's refs before
894acting. The dispatch is `valley unready`, then
895`klaus launch [--repo <project>] --change <change-id> --run-id <id> --expect-owner <principal> --expect-branch <branch> --expect-head <head> --expect-draft --reason restack-conflict "<brief>"`.
896The brief names the change, version, head, branch and main's tip, never the report's paths or text.
897Limits: no second run on a change, 60 seconds between dispatches, at most 3 runs until a clean
898report, once per input set (head, main's tip), 16 input sets remembered per change. An attempt is
899given back only when no worker started (stopped before launching, or exit status 3). Events:
900`change:restack-dispatched`, and `change:restack-stalled` with a `reason` once per input set.
901`klaus status` shows `restack` in CONFLICTS.
902
903### Failed-check dispatch
904
905For each failed head of a ready change klaus owns, the dispatch is
906`klaus launch --change <change-id> --run-id <id> --expect-owner <principal> --expect-branch <branch> --expect-head <head> --reason checks-failed <brief>`.
907Once per failed head, never while a run works on the change, and at most 3 failed attempts (a fix
908whose next version still fails counts) until the checks pass; recorded in `checks-dispatches.json`.
909
910### Knots
911
912`--issue` is a knot when its form is `oc-`, `bd-`, `ida-` or `qn-` with 7 hex digits, optionally
913`<project>:` first. Launch refuses it with `--pr`, outside a valley repository, without
914`valley knot`, and for a knot that is not an active outcome or bug, or that a running or unknown run
915claims; a claim left by a run klaus knows has ended is released (`--if claimed_by=<run>`) and taken
916over. The knot, parents and comments go into the brief in a `## Project notes (untrusted)` block
917between marker lines carrying a random token. Just before the worker starts,
918`valley knot claim <id> --run <run-id>` (a refusal fails the launch). Finalize, once the head is
919ready, runs `valley knot link <id> --change valley:<repo>/<change-id>` and
920`valley knot unclaim <id> --if claimed_by=<run-id>`; a failed run comments (`valley knot comment`)
921and releases instead. When the change lands, the dashboard comments with the version and commit and
922sets the knot `done` (outcome) or `closed` (bug) only if every linked change landed, no child is
923active and nobody claims it, with `--if` conditions on status, claim and links. Recorded as
924`knot.landed`, `knot.closed`, `knot.error`.
925
926## Events
927
928Each line of `events.jsonl` is
929`{"timestamp": <RFC3339>, "run_id": ..., "type": ..., "data": {...}}`.
930
931| Type | When |
932| ----------------------------------------------------- | ------------------------------------------------------------------ |
933| `agent:started`, `agent:completed` | A run started; finished |
934| `agent:pr-created` | A run opened GitHub work |
935| `agent:branch-pushed` | A run finished with its branch on origin, no GitHub work |
936| `agent:change-recorded` | Finalize recorded another change or branch than launch |
937| `agent:change-ready`, `agent:change-draft` | A pushed head became a ready, or draft, version |
938| `agent:needs-attention` | Salvaged or failed; needs the operator |
939| `agent:shared-git-changed` | The clone's shared git files changed during the run |
940| `agent:paused`, `agent:resumed` | Budget pause; its follow-up finalized |
941| `agent:ci-passed`, `agent:ci-failed` | CI on an agent's GitHub work |
942| `pr:awaiting-approval`, `pr:approved`, `pr:merged` | GitHub work ready for approval; approved; merged (once each) |
943| `pr:approval-changed` | `klaus approve` changed klaus's approval |
944| `pipeline:stalled` | The pipeline gave up on GitHub work |
945| `change:approved`, `change:integrated` | A ready version got a request; the change landed (`landed_commit`) |
946| `change:stale`, `change:rejected`, `change:failed` | The integrator's decision on the active version |
947| `change:withdrawn` | The change was withdrawn |
948| `change:new-version` | A version this session did not record (`uploader`) |
949| `change:checks-failed`, `change:checks-passed` | The host's verdict on a ready version's checks (`failed`) |
950| `change:restack-dispatched`, `change:restack-stalled` | A restack run launched; klaus stops short |
951| `consult:started`, `consult:completed` | A consult backend call |
952| `review:started`, `review:completed` | A `klaus review` |
953| `phase:started`, `phase:completed` | A run phase (`setup`, `agent`, `finalize`) |
954| `check:started`, `check:completed` | A check an agent ran |
955
956The default `klaus watch` filter is every type above except `agent:started`, `agent:completed`,
957`agent:paused`, `agent:resumed`, `agent:ci-*`, `agent:change-recorded`, `agent:shared-git-changed`,
958`pr:awaiting-approval`, `pr:approval-changed`, `phase:*` and `check:*`, plus the reserved types
959`agent:error`, `ci:failed`, `ci:passed` and `pr:comment`, which nothing emits.
960
961`pr:approved` and `pr:merged` fire once per piece of GitHub work across restarts; work already
962merged when first seen emits neither. Change transitions fire once per mark, under the change's
963handle, from the dashboard's minute check; each carries `repo`, `handle`, `change_id`, `version`,
964`head`, `title`, `repo_key` and `key`. A change first seen is recorded as it stands, without events.
965Dashboards on one session share the transition files under their `.lock`. `klaus status` emits
966nothing.
967
968**Consult events** share a `run_id` `consult-YYYYMMDD-HHMM-xxxxxxxx` (one pair per panel member) and
969carry `backend`, `model`, `effort`, `role`, `thread`, `dir`, `repo`, `commit`, `panel`, `prompt`
970(first line, up to 120 characters) and `prompt_file`; `consult:completed` adds `duration_ms`,
971`success` and on failure a short `error` (`timeout after 10m0s`, `interrupted`), never model output.
972**Review events** carry `backend`, `model`, `repo`, `pr_number`, `author`, `post`, then
973`duration_ms`, `success`, `findings`, `review_url` or `error`. SIGINT and SIGTERM still emit the
974completion; outside a session nothing is emitted.
975
976### Run fields on events
977
978Run events (`agent:*`, `phase:*`, `check:*`, `pr:approval-changed`) also carry:
979
980| Field | Meaning |
981| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
982| `repo_key` | `owner/repo`, `valley:<name>`, else the repository's short name |
983| `change_id`, `pr_number` | The run's change; its GitHub number once it has one |
984| `key` | `owner/repo#12`, else `<repo_key>@<change_id>` |
985| `dispatch_reason` | `launch`, `pr-follow-up`, `budget-resume`, `change-follow-up`, `resume`, `ci-fix`, `review-fix`, `review-comment-fix`, `conflict-fix`, `restack-conflict`, `checks-failed`, or a `--reason` |
986| `head_sha` | The tip finalize found on origin, else the worktree's `HEAD` at the end or start |
987
988Pipeline and change events carry `repo_key` and `key` when known; consult events carry `repo_key`.
989Unknown fields are left out.
990
991`phase:completed` carries `phase`, `started_at`, `ended_at`, `duration_ms` (and `cost_usd` for
992`agent` where known): `setup` is launch's work before the agent; `agent` runs from pane start to
993finalize; `finalize` up to killing the pane. `check:*` carry `kind` (`pre-review`, `build`, `test`,
994`lint`), `command`, `source`, `duration_ms` and `success`; `_pre-review` adds `lint_ms`,
995`review_ms`, `findings`, `blocking`, `lint_failed`. `_format-stream` times the build, test and lint
996commands it recognises in the stream (`go test`, `go vet`, `cargo build`, `npm test`,
997`make <target>`, `nix build`, `nix flake check`, ...); a command line that also runs
998`klaus _pre-review` is marked `includes_pre_review`. On a sandbox host `_pre-review` prints
999`klaus-check-completed: {...}` and the pane's `_format-stream` records it (`via: stream`).
1000
1001## Sandbox hosts
1002
1003With `sandbox_host` set (or `--host`), launch checks the host
1004(`ssh -o ConnectTimeout=3 -o BatchMode=yes <host> true`), creates the worktree path there and syncs
1005the worktree with `rsync -az --delete`; the agent runs over SSH and its stream, formatting and
1006finalize stay local. An unreachable host falls back to local execution. A sandbox worker gets no
1007`KLAUS_SCRATCH` or private `TMUX_TMPDIR`; its prompt says to keep scratch files in a `mktemp -d`
1008directory, and nothing removes the worktree copy. The dashboard tags such runs `[sandbox]` and shows
1009reachability; `klaus status` shows HOST. Claude conversations stay on the sandbox host, so its runs
1010are never replayed.
1011
1012## Webhook receiver
1013
1014| Key | Default | Meaning |
1015| ------------------------------------ | ----------------- | --------------------------------------------------------------- |
1016| `webhook.port` | `9800` | Port the dashboard listens on |
1017| `webhook.path` | `/webhook/github` | Path of deliveries |
1018| `webhook.relay_url` | none | Public URL of the relay |
1019| `webhook.secret_file` | none | File holding the secret `setup` gives GitHub to sign deliveries |
1020| `webhook.poll_fallback` | `false` | Also poll every 30 seconds |
1021| `webhook.reconcile_interval_seconds` | `300` | Full re-fetch interval when not polling; negative disables |
1022
1023A delivery names the work or repository to re-fetch from GitHub; the receiver builds no status from
1024it and checks no signature. Only one dashboard per user holds the port; another polls as if no
1025webhook were configured, and its source line says so. The source line shows the age of the last
1026delivery (`· last event 5m`), dim under 30 minutes, yellow under 2 hours, red beyond; a long silence
1027may be a quiet repository or a broken path.
1028
1029## Constraints
1030
1031- Sessions, launches and `klaus scaffold` run inside tmux; agents are headless and take no input.
1032- A run ends with its agent's turn; background work still running is interrupted and recorded.
1033- No approval is automated: klaus posts no approving review, and `klaus ready` never approves.
1034- The pipeline dispatches nothing on work a fix run is on, spaces dispatches 60 seconds apart, and
1035 stalls work after 3 failed attempts of a kind.
1036- Briefs of any length go through files; inline pane content is capped at 12000 bytes.
1037- Budgets, budget pause and `--replay` are Claude-only; `--resume-from` never moves a conversation
1038 between backends or machines.
1039- Consult attachments total at most 200 KB; each consult call has a deadline (default 10 minutes);
1040 `klaus merge` waits at most 10 minutes for CI; the continuation lock waits at most 5 minutes.
1041- `valley ready`, `valley unready` and knot calls are bounded by 30 seconds, `valley changes` by
1042 three minutes; the dashboard holds one telemetry follow slot per valley host.