gunk-dev/the-valley

design.md

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