gunk-dev/the-valley

design.md

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