| 1 | # flow design |
| 2 | |
| 3 | flow, the agent-run client that `valley flow` runs, splits agent work three ways. The coordinator, |
| 4 | an interactive agent you talk to, does the thinking: it researches and writes briefs. Agents do the |
| 5 | building, each headless in its own worktree. The dashboard does the mechanical following: CI, |
| 6 | reviews, conflicts, failed checks, landings. The operator approves. Toward a valley, flow is a |
| 7 | client: the valley restacks, runs checks and lands; flow decides what to build and resolves what the |
| 8 | valley reports from the states it lists. Commands and formats are in the |
| 9 | [reference](./reference.md). |
| 10 | |
| 11 | ## A run's life |
| 12 | |
| 13 | ``` |
| 14 | valley 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> |
| 20 | klaus _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 | |
| 27 | The worker reads its prompt on stdin from a file, so a brief of any length avoids tmux's |
| 28 | command-line limit and the shell. `_format-stream` renders the JSONL stream in the pane and times |
| 29 | the checks it recognises. `_finalize` runs in the pane's own shell after the worker exits, however |
| 30 | it exits. |
| 31 | |
| 32 | **Isolation.** Each agent has its own worktree, so agents cannot step on each other or on your |
| 33 | checkout. Their panes live in a detached tmux session owned by the server, so they take no screen |
| 34 | space and survive the coordinator exiting. A run ends when the agent's turn ends: every worker |
| 35 | prompt says to run long builds in the foreground, and finalize records background work it finds |
| 36 | still running. Scratch output goes to `KLAUS_SCRATCH`, outside the worktree, because salvage commits |
| 37 | whatever 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 |
| 39 | compares. |
| 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 |
| 43 | runs reaches an empty location rather than the server holding your session and every agent. flow's |
| 44 | own commands in the worker reach the real server through `KLAUS_TMUX_SOCKET`. This guards against |
| 45 | accidents, not against a hostile worker: the worker runs as the server's Unix user and is given that |
| 46 | socket's path. tmux falls back to `/tmp` when `TMUX_TMPDIR` names a missing directory, so a worker |
| 47 | that 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 |
| 50 | cannot forget them. flow sets `core.hooksPath` per worktree (`extensions.worktreeConfig`), leaving |
| 51 | the main clone and other worktrees their own hooks, and chains to the repository's hooks. |
| 52 | |
| 53 | ## Persistence |
| 54 | |
| 55 | Session state (`~/.klaus/sessions/`) is machine-local and disposable. A finalized run's state, log |
| 56 | and Claude conversation are committed to `refs/klaus/data` in the local clone: a ref outside |
| 57 | `refs/heads`, so it shows as no branch, written with git plumbing and a temporary index, so no |
| 58 | working tree changes. Before a log is stored a regex scan looks for private addresses, keys and |
| 59 | credentials; a log it flags, or cannot scan in full, is held back. The ref stays local unless |
| 60 | `push_data_ref` is on, because transcripts hold prompts, file contents and environment details and a |
| 61 | 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 |
| 64 | time flow looks and never written to the run; where a valley lists the change, its listing decides. |
| 65 | What 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 |
| 67 | on one session take a lock to update them, so only one reports each. A change first seen is recorded |
| 68 | as it stands, so a first start reports no history. |
| 69 | |
| 70 | Configuration is JSON, read with the standard library; prompts are Go templates, so one default |
| 71 | works for any repository and a repository can replace it. |
| 72 | |
| 73 | ## The GitHub pipeline |
| 74 | |
| 75 | The dashboard evaluates each piece of GitHub work on every poll or webhook against ordered rules and |
| 76 | moves 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 | |
| 91 | Guards keep dispatch from spinning. No dispatch while a fix run, including one the coordinator |
| 92 | launched with `--pr`, works on the branch, since intermediate commits of a multi-step fix may fail |
| 93 | CI. Dispatches for one piece of work are 60 seconds apart. CI fixes, review fixes and rebases each |
| 94 | stall after 3 failures. Merges and branch updates each get 3 tries per approval, 60 seconds apart; |
| 95 | losing 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 |
| 97 | read changes (head, CI result, review decision, trusted comments), since retrying on the same inputs |
| 98 | fails the same way. When GitHub cannot be reached (timeout, rate limit), the work is left as it was, |
| 99 | never treated as open. |
| 100 | |
| 101 | GitHub's own approval is detected and recorded like `valley flow approve`. A cross-model review |
| 102 | posted by `valley flow review` is trusted when its author is the authenticated gh user, so its |
| 103 | inline findings feed the review-fix loop and its breaker; the marker alone grants nothing, and the |
| 104 | pipeline 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 |
| 109 | sets, not flow. Because the valley has no verb that records a version as a draft, finalize records a |
| 110 | draft by running `valley ready` then `valley unready`. `approve` refuses a draft and the integrator |
| 111 | lands nothing for one, so a request filed between those two calls waits until the change is ready |
| 112 | again. A follow-up returns its change to draft before its agent starts so nobody approves a version |
| 113 | the agent is replacing; finalize's `valley ready` re-readies that version when the head is |
| 114 | unchanged. |
| 115 | |
| 116 | **One commit per change.** A valley lands a change as one commit under its head message and takes it |
| 117 | only as a line of commits on main. A follow-up therefore amends and restacks rather than merging, |
| 118 | and pushes with a lease on the head launch found. A concurrent push makes the agent's push fail |
| 119 | instead 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 |
| 122 | does not count: the restacker uploads the versions it rebases. flow never takes over a change it |
| 123 | does not own. |
| 124 | |
| 125 | **Restack conflicts fail closed.** A restack report counts only while the valley calls it current |
| 126 | and everything it observed still holds; flow re-reads origin's refs itself before acting. It returns |
| 127 | the change to draft and launches nothing unless the valley then lists it as flow's draft at the same |
| 128 | head and branch. Launch checks those conditions again under its continuation lock, before creating |
| 129 | the worktree and before starting the worker (`--expect-*`). Nothing from the report reaches the |
| 130 | brief beyond names and commits flow read itself: the run finds the conflicts by rebasing. A change |
| 131 | sitting 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 |
| 134 | given back only when flow knows no worker started (it stopped first, or launch exited with status |
| 135 | 3). Any other failure keeps the launch pending, and the change busy, until a run by that ID is |
| 136 | recorded or flow proves none runs: no launch holds the continuation lock, no run is recorded, and no |
| 137 | live pane names it. Time alone settles nothing. flow acts once per set of inputs and remembers the |
| 138 | outcome, so an unchanged conflict is not retried. Failed checks are dispatched with the same guards |
| 139 | as CI fixes. |
| 140 | |
| 141 | **The listing decides; telemetry wakes.** Where a change stands is the valley's `valley changes` |
| 142 | listing, read once per look for every repository. A telemetry record only triggers a check sooner. |
| 143 | When the listing fails, git's view stands in, a known verdict is kept as `(last known)`, and the |
| 144 | failure 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 |
| 147 | reach the agent as untrusted notes in a block fenced by marker lines with a random token, so nothing |
| 148 | in them can close the block. Claims, links and closes carry `--if` conditions on what flow read, so |
| 149 | a concurrent claim or link makes the close a conflict rather than overwriting it. |
| 150 | |
| 151 | ## Messaging a running agent |
| 152 | |
| 153 | Workers run in print mode (`claude -p`, `codex exec`, agy's print mode) and read the prompt on stdin |
| 154 | from a file; nothing reads the pane's terminal, so text pasted into a worker's pane never reaches |
| 155 | the session. An interactive coordinator does take a pasted message, but only when its interface is |
| 156 | at a prompt: a dialog swallows the paste. |
| 157 | |
| 158 | Feeding a Claude worker its input as `--input-format stream-json` over a per-run FIFO delivers a |
| 159 | multi-line message mid-turn as one message and records it in the Claude transcript (not in flow's |
| 160 | log); a message sent after the turn's result is lost. A `valley flow message` command built that way |
| 161 | is **not built**: it would make every launch depend on FIFO setup, where a mistake fails launches |
| 162 | outright. To correct an agent, `valley flow launch --resume-from <run-id>` continues its |
| 163 | conversation 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 |
| 168 | the 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 |
| 170 | and flow holds no approval key: approval is the valley's `approve`, run by the operator. The |
| 171 | dashboard only displays `approve_command`, shell-quoting each value so a branch name cannot inject a |
| 172 | command. |
| 173 | |
| 174 | **Agents run unattended.** Workers run with each CLI's permission bypass. Run untrusted tasks on an |
| 175 | isolated 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` |
| 178 | from the checkout the worktree belongs to, never the agent's worktree. `forbidden_terms` is host |
| 179 | config only: the list is private, and a repository cannot turn off its own check, which runs before |
| 180 | any diff reaches a reviewer. `self_update` is host config only: a repository must not choose what a |
| 181 | host installs. |
| 182 | |
| 183 | **Labels grant nothing.** `Change-Id` and `Klaus-Run` trailers find and audit commits; no tool may |
| 184 | trust a commit or skip a check because of them. The cross-review marker counts only from the |
| 185 | authenticated gh user. |
| 186 | |
| 187 | **Content is data.** Knot notes, restack reports and review text are never instructions: notes are |
| 188 | fenced as untrusted, report text is never passed on, and a conversation comment by the work's author |
| 189 | counts only with an explicit `/klaus fix` or marker, since the operator and agents post through the |
| 190 | same account. Agent replies carry a marker and are ignored, and an unmarked one is still an author |
| 191 | comment without opt-in. |
| 192 | |
| 193 | **Self-update installs only what was asked.** Only the configured branch installs, pinned to the |
| 194 | commit `git ls-remote` returned. A repository whose flake offers no `packages.<system>.klaus` is |
| 195 | refused before anything is built; flow builds exactly that attribute, smoke-tests it, and keeps the |
| 196 | previous install for rollback. The repository URL is limited to known transports and characters nix |
| 197 | leaves 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 |
| 200 | worker 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 |
| 203 | takes a delivery as a reason to re-fetch the named work from GitHub through the same path polling |
| 204 | uses, and never builds status from the payload, so a forged delivery costs one extra fetch. |
| 205 | Signatures are for the relay to check, with the secret `valley flow webhook setup` gives GitHub. |