gunk-dev/the-valley

reference.md

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