gunk-dev/the-valley

reference.md

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