gunk-dev/the-valley

architecture.md

source34d12a6791c4main's published tip history
324.7 KiB · Rendered
1# Architecture as deployed
2
3This document describes what the-valley runs today, read from the code, and the architectural
4principles its design follows. It makes four kinds of statement. A principle is a rule the design
5follows, with the reason for it; the code that carries it out is cited like any other behaviour.
6Behaviour is what the code does, cited to the files that do it. A deployment choice is what a host's
7configuration decides, rather than the code. It is labelled **deployment choice**. A guarantee names
8the flake check (`checks.x86_64-linux.<name>`) or test that demonstrates it; a statement of
9behaviour with no named check is unchecked. Security and rollouts are in
10[security.md](./security.md), planned work lives in
11[the plan graph](./concepts.md#records-project-storage-the-plan-graph-and-knots) (`valley plan`),
12and the project's purpose and principles are in [purpose.md](./purpose.md).
13
14## Overview
15
16A valley host keeps bare git repositories and accepts changes to them over ssh. Anyone with a key
17may push a topic branch. A protected branch such as `main` accepts a push only from the principals
18the project names as its writers. The integrator moves it by landing an integration request. The
19integrator lands a request when every check the project's policy requires is covered by a signed
20statement that the check passed.
21
22The parts are:
23
24- the host module, which installs everything below (`nix/valley-host.nix`);
25- the push hook, which decides what a push may write (`valleyhook/`);
26- the integrator, one controller per protected project (`integrator/`);
27- `attest`, which runs checks and signs the evidence (`attest/`, `note/`);
28- the identity compiler, which turns a registry into keys and grants (`identity/`);
29- the `valley` command line tool (`bin/valley`);
30- `valley-worker`, the check worker, which builds and publishes pure check evidence for ready
31 changes before approval (`status/worker.go`);
32- `valley-web-publish`, `valley-web-receive`, `valley-web`, and the web export (`web/`). The
33 publisher builds a signed export of the projects that have an effective reader and uploads it; a
34 valley host can run it on a timer. `valley-web-receive` receives the uploads into a state
35 directory, where `web/export` stages and activates them. `valley-web` serves the active export's
36 plan, knots, and `main` source over HTTP (`GET` and `HEAD`). An edge runs the receiver and
37 `valley-web` side by side from a NixOS module or a container image;
38- read access, which reads and evaluates the two consents for reading a project (`readaccess/`);
39- `valley-restacker`, the restacker, which rebases ready changes onto `main` as its own principal,
40 one controller for each project a host lists (`restack/`);
41- the review record and its history, which nothing writes or admits yet (`review/`);
42- `sigverify`, a hardware-key signature verifier that nothing calls yet (`sigverify/`).
43
44## The source and project storage
45
46A project keeps its data in one of two places. The source is the project's tree: its code,
47configuration, policy, schemas and docs. Project storage sits beside the source, in the same store,
48and holds what is about the project rather than part of it. This section states which data belongs
49where. The principles hold for any store. How this deployment realises them in git comes last.
50
51**Data that is true of a version of the project belongs in the source.** Code, configuration,
52policy, schemas and docs are each true of the version that holds them. They fork when the source
53forks, so a release's docs describe that release. A change governs them. This is why the integrator
54reads a change's policy from the target's tip: policy is true of the version it governs
55(`integrator/policy.go`).
56
57**Data about the project, rather than of one version, belongs in project storage.** Any one of these
58reasons puts it there:
59
60- It needs one truth across every line of the source, as the plan does.
61- It describes a version, so it cannot live inside that version. An approval or a check's evidence
62 for a tree cannot be part of that tree. Change records, attestations, integration requests and
63 their outcomes are kept beside the source for this reason.
64- A write to it has no effect to gate, as with a knot's status.
65
66**Project storage shares the source's substrate, not its governance.** It uses the project's store,
67transport and backup, the one policy point at the host, and the project's principals. Each kind of
68data in it is held to rules that match what a write to it can do. This deployment shows the range:
69
70- An attestation can let a change land. So the hook admits one only when each of its notes verifies
71 under a known signer and is about the tree the ref names, and never lets it be rewritten
72 (`valleyhook/attestation.go`).
73- A change record can only refuse. So the hook allows only the transitions in
74 [Change records](#change-records), and the integrator reads records only to refuse
75 (`valleyhook/record.go`, `integrator/records.go`).
76- A knot informs and decides nothing. So any named principal may write one, and the hook checks the
77 graph's shape and its history: one commit on the old tip, and never a rewind
78 (`valleyhook/knots.go`).
79
80A change to the source has effects. So it lands only when it is approved and every check it requires
81has passed (see [The integrator](#the-integrator)).
82
83**Knots can direct work but never authorize it.** A knot can ask for work. That work reaches the
84source only as a change, under the source's rules. Nothing that decides a change reads a knot.
85
86**A settled answer crosses over.** While a question is open, it lives in project storage as a knot.
87When its answer settles something about the design, the answer enters the source's docs through a
88change, and the knot links that change.
89
90**Project storage shares the project's readers.** Whoever can read the source can read project
91storage, and the reverse. Data that needs different readers belongs to a different project.
92
93The source says what is; its history, how it came to be; the knots, where it goes.
94
95In this deployment, project storage is the refs under `refs/the-valley/` in the project's git
96repository, beside the source's `refs/heads/`. [What a push may write](#what-a-push-may-write) says
97which namespace holds what and who may write it, and [The plan graph](#the-plan-graph) describes the
98knots. A plain `git clone` fetches branches and tags, so it carries the source and no project
99storage. The tools that read project storage fetch it by name: `valley knot` and `valley plan` list
100`refs/the-valley/knots` with `ls-remote` and fetch the commit it names, and `valley changes` and
101`valley status` read change records the same way (`status/knot.go`, `status/changes.go`). The
102mirrors receive `main` and tags only, so no project storage reaches a mirror
103(`nix/valley-host.nix`). The host's backup copies the whole data directory, `/srv/git` by default,
104so it holds project storage too. The readers follow from git. Anyone who can read a repository can
105fetch the objects of every ref in it, and git's own documentation says that even its namespaces are
106not effective for read access control (`gitnamespaces(7)`, SECURITY).
107
108## The host module
109
110The NixOS module `services.valley` reads one CUE file, `services.valley.config`. The build vets it
111against `schema/valley.cue` and fails on any error (`nix/valley-host.nix`). The file declares the
112projects, their mirrors, their protection and the backup policy. Checked by `module-eval` and
113`cue-vet`.
114
115### Repositories and the git user
116
117Each project is a bare repository at `/srv/git/<name>.git`. All ssh git traffic logs in as one Unix
118user, `git`. The git user's login shell runs `valleyhook shell` (`nix/valley-host.nix`,
119`valleyhook/shell.go`). For each session, `valleyhook shell` does three things:
120
1211. For a push only, it refuses the session when the hold file `/srv/git/.valley-hold` exists, or
122 when the converged record `/srv/git/.valley-converged` does not match the running configuration.
123 Fetches stay open. Both are checked when the session starts, so a push already past this check is
124 not stopped by a hold created later.
1252. It drops every `GIT_*` variable and any `VALLEY_PRINCIPAL` the client sent. It sets
126 `VALLEY_PRINCIPAL` from the tag on the authorized-keys entry of the key that logged in. An
127 untagged or ambiguous key gets no principal.
1283. It runs `git-shell` with the same arguments. `git-shell` limits the session to git's own
129 commands.
130
131The sshd `Match User git` block turns off TCP, agent and X11 forwarding and tunnels, and sets
132`ExposeAuthInfo` so the shell can see which key logged in. It leaves stream-local (Unix socket)
133forwarding on. A host's configuration can add its own block with `DisableForwarding yes` and
134`PermitTTY no` (**deployment choice**). Build-time assertions refuse an sshd config that would let a
135client set `VALLEY_PRINCIPAL` or `GIT_*` (`nix/valley-host.nix`). Checked by `ssh-e2e` (a real sshd
136in a VM), `module-eval` and `valleyhook-unit`.
137
138### valley-init and the push hold
139
140`valley-init` is a oneshot service that runs as git (`nix/valley-host.nix`). It first deletes the
141converged record, so pushes are refused while it runs. It then creates any missing repository and
142links each repository's hooks. A foreign `pre-receive` hook or any `core.hooksPath` setting is a
143conflict. When there is no conflict, it writes the converged record. The record is the first 32 hex
144characters of a SHA-256 of the init script. So pushes resume only when every repository's
145`pre-receive` hook is this configuration's. A hand-written `post-receive` hook is left in place and
146is not a conflict. Checked by `init-e2e` and `ssh-e2e`.
147
148A host with an instance repository also publishes its project list there. `valley-init` writes a
149blob at `refs/the-valley/projects` that names every enabled git project, one per line, sorted, and
150nothing else. Clients read it to find the host's projects (`valley changes --all`). It discloses
151every project name to whoever can read the instance repository. A host without an instance
152repository publishes nothing. A list that cannot be written is a warning, not a conflict. Checked by
153`init-e2e` and `valley-changes`.
154
155The hold file belongs to the operator, who creates it to pause all pushes. `valley-init` never
156touches it.
157
158### The signers publication
159
160The host publishes what a client verifies the integrator's transfer statements with. The publication
161is a tree at `refs/the-valley/signers` in the instance repository. It holds two files:
162`known-signers`, the known-signers file the controllers read, and `integrator-name`, the name they
163sign under, on one line. Both are in one tree under one ref, so a client reads both values or
164neither. A host that restricts signers to projects (see
165[Evidence: attest and notes](#evidence-attest-and-notes)) adds a third file, `signer-projects`, the
166signer projects file the controllers read. A signer that file names, a worker or another controller,
167is never this host's integrator. So while it names the integrator name a client uses, the client
168verifies no transfer statement, and a publication whose `signer-projects` does not read is not used
169(`status/signers.go`, `rebase/snapshot.go`). The restacker applies the same rule to the file it is
170given as `--signer-projects`. Approval reads the published file too: it reuses a note only when one
171of its signers counts in the project (`status/coverage.go`).
172
173The publisher is `integrator publish-signers` (`integrator/signers.go`). The oneshot service
174`valley-signers` runs it as git (`nix/valley-host.nix`). A host renders the service when the
175integrator is enabled and the host serves the instance repository (`integrator.instanceProject`).
176The publisher is given the same signers file, the same `--name` and the same `--signer-projects` as
177the controllers. When `integrator.signingName` is unset, neither is given a name. Both then take the
178integrator's default, `<hostname>/attestations`, computed by the same code on the same host. The
179service's sandbox lets it write the instance repository and nothing else.
180
181The service runs at boot and on activation, after `valley-init` and after the registry compiler when
182there is one. The signer projects file is rendered into the Nix store, so a changed list is a
183changed command for the service, which activation runs again. A path unit, `valley-signers.path`,
184runs it again whenever the signers file changes, as it does when a compilation replaces the file. A
185run that would publish what is already there writes nothing. A run that changes the publication
186moves the ref with a compare-and-swap.
187
188Two runs at once take turns. Each run holds a lock in the instance repository from reading the
189signers file to moving the ref. So the later run reads the file after the earlier one has published,
190and a run that read an older file cannot publish it over a newer one.
191
192A run that cannot read the signers file, or reads one that is not a list of verifier keys, fails and
193leaves the last publication in place. A file that holds no key under the signing name is published
194anyway, because it is what the controllers use. That includes a file with no key at all, which is
195what the registry compiles to once every signing key is revoked. Clients then stop verifying with
196the revoked keys. The run warns that no client can verify a statement with the file.
197
198Only the host's machinery writes the ref, never a push. The hook refuses every push to a
199`refs/the-valley/*` ref it does not name. On the host, the publisher writes the ref. The integrator
200can write it too: the instance repository is group-writable, and the integrator is in that group
201because it lands code there. Checked by `module-eval`, `signers-e2e` and `publish-e2e`.
202
203### The build slice
204
205The build slice caps the total CPU and memory that all Nix daemon builds on a host can use at once.
206It keeps a runaway build from starving the host's other services (knot oc-03b6f8c). A host turns it
207on with `services.valley.buildSlice.enable` (`nix/valley-host.nix`). It is off by default, and
208turning it on is a **deployment choice**. The check worker cannot be enabled without it
209(`implemented`).
210
211Every user who builds through the Nix daemon shares one pool of CPU and memory. That pool covers the
212check worker's builds and evaluation, the daemon itself, and local builds through the daemon, such
213as those an operator runs with `valley approve`. The Nix daemon runs every build as its own child
214process inside the daemon's cgroup, no matter which user asked for the build. To cap those builds,
215the module places `nix-daemon.service` in `valley-builds.slice` (`implemented`). By default, the
216slice sets `CPUQuota` to `400%` (`buildSlice.cpuQuota`, four CPUs' worth), `MemoryMax` to `8G`
217(`buildSlice.memoryMax`), and `MemorySwapMax=0` (no swap).
218
219When the slice hits its memory cap, the kernel's OOM killer kills the single process in the slice
220using the most memory. That is usually the build that pushed the slice over the cap, but it can be
221an unrelated build in the slice that happens to hold more memory at that moment. Nothing exempts the
222daemon's own processes from being chosen. When a child build is killed, `nix-daemon.service` stays
223up because its unit delegates its cgroup, which sets systemd's `OOMPolicy` to `continue`. Services
224outside the slice are unaffected.
225
226Checked by `worker-e2e` and `module-eval`. In `worker-e2e`, a build that tries to use six CPUs is
227throttled to four. The test then runs two unrelated builds alongside a worker check that allocates
228memory without bound. Once the larger unrelated build has settled, the test sets the slice's memory
229cap at runtime to the anonymous and shared memory the slice already holds plus half of that build's
230resident memory, then starts the worker. The kernel kills at least two processes. The worker's
231runaway build fails, the larger unrelated build fails, and the smaller unrelated build finishes.
232`sshd`, `nix-daemon`, and the integrator controllers stay up, and no other unit fails. `module-eval`
233checks that the slice renders the quota and memory cap the host configures.
234
235The slice does not cap:
236
237- Nix commands that bypass the daemon, such as a build `root` runs directly on the store, which run
238 outside the slice and are uncapped.
239- Disk space, scratch directories, `/nix/store` growth, or disk I/O.
240- Exploits against shared host components. The slice limits CPU and memory use only; builds still
241 share the Nix evaluator, the daemon, the kernel, and `/dev/kvm` with the host.
242- Device access. The slice sets no device policy, so the daemon can still hand `/dev/kvm` to NixOS
243 VM tests, whose virtual machines must fit within the slice's memory cap alongside everything else
244 in the slice.
245
246## What a push may write
247
248Every repository's `pre-receive` hook runs `valleyhook pre-receive` (`valleyhook/main.go`,
249`valleyhook/policy.go`). The hook is default-deny. If any one ref update is refused, the whole push
250is refused. The hook reads the project's push policy with every key spelled exactly as its field
251(`exactjson/`). A policy that holds any other key, or a key twice in one object, refuses the whole
252push. A push may update at most 1000 refs, and the hook refuses one that updates more before it
253decides any ref. It asks `git symbolic-ref` whether each pushed ref is symbolic, so it reads a
254symbolic ref exactly as git does. Checked by `protect-e2e`, `ssh-e2e` and `valleyhook-unit`, and for
255the plan graph by `knots-e2e`.
256
257| Ref namespace | Who may push | Rule |
258| ----------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
259| `refs/heads/*` (topic branches) | Any key | Create, update and delete. |
260| Protected refs (default `refs/heads/main`) | Principals in `protection.writers` (default empty) | The integrator moves them on disk, so it needs no place in `protection.writers`. |
261| `refs/the-valley/attestations/<tree>/<key-hash>` | Any key | Create only. The ref must name a tree of notes within size bounds, and each note must verify under a known signer and be about that tree (`valleyhook/attestation.go`). |
262| `refs/the-valley/integration-requests/<target>/<c>` | Principals with the `approve` grant (also accepted as `request`) | Create, update and delete. A change with a record is requested as `c-<change-id>` (see [The integrator](#the-integrator)). |
263| `refs/the-valley/changes/main/<change-id>` | Any named principal creates; the owner, `approve` or `restack` holders update; `approve` deletes | A change record. The hook allows only the transitions in [Change records](#change-records) (`valleyhook/record.go`). The integrator reads it to refuse. |
264| `refs/the-valley/restack/main/<change-id>` | Principals with the `restack` grant | A restack report about a change the repository records. Created and extended, never deleted (see [Restack reports](#restack-reports), `valleyhook/report.go`). |
265| `refs/the-valley/knots` | Any named principal | The plan graph, that name exactly. One commit on the tip that keeps the graph valid; never deleted (see [The plan graph](#the-plan-graph), `valleyhook/knots.go`). |
266| `refs/the-valley/projects` (instance repository) | Nobody | `valley-init` writes it on disk: the host's project list (see [valley-init](#valley-init-and-the-push-hold)). |
267| `refs/the-valley/signers` (instance repository) | Nobody | `valley-signers` writes it on disk, and the integrator can: what clients verify transfer statements with (see [The signers publication](#the-signers-publication)). |
268| Every other `refs/the-valley/*` | Nobody | This covers the integrator's outcome records, `refs/the-valley/integration-outcomes/<target>/<c>`, its landing records, `refs/the-valley/integration-landings/<target>/<head>`, and review histories (see [Reviews](#reviews)). |
269| `refs/replace/*`, `refs/notes/*` | Nobody | A replace ref would let git show other content under a watched name. |
270| Symbolic refs | Nobody | |
271| `refs/refs/*`, `refs/heads/refs/*`, `refs/tags/refs/*`, `refs/remotes/refs/*` | Nobody creates or updates one | A ref named like another ref. When that ref is missing, git reads, fetches and pushes to this one in its place. A delete follows the rule of its namespace. |
272| Tags and every other ref | Principals named in a project grant: `grants.<name>: {refs, writers}` (`schema/valley.cue`) | Grant patterns cannot name `heads`, `replace`, `notes` or `the-valley`. |
273
274Branches and tags hold the source. The namespaces under `refs/the-valley/` are project storage, as
275[The source and project storage](#the-source-and-project-storage) describes.
276
277The `approve` and `restack` grants each come from two places: the host's declared
278`services.valley.grants.approve` and `services.valley.grants.restack`, and the identity compiler's
279`grants` file. The two sources add up. The `approve` grant is also accepted as `request`, and the
280two names are one grant. Its holders are the principals named under either name, in
281`services.valley.grants.approve`, in `services.valley.grants.request`, or in the registry. Both
282writers write each holder as a `request <principal>` line, and the hook reads a line naming either
283name as the `approve` grant (`valleyhook/grants.go`). The `restack` grant is the host restacker's.
284It authorises two writes and nothing else: one version added to another principal's ready change,
285and the change's restack report. It grants nothing on integration requests. Why replace refs are
286closed is recorded in
287[bd-75c8721](../archive/.the-valley/bugs/bd-75c8721-pushes-could-write-any-namespace.md).
288
289### Change records
290
291A change is one piece of work aimed at `main`. Its ID is stable across rebases, in jj's form: 32
292letters from `k` to `z`. Each time a head of the change is marked ready, the change gains a version.
293The change's record lists the versions, and the hook guards every write to it. A record grants
294nothing: the integration request is still the only way a change reaches `main`. The integrator reads
295records only to refuse. It lands no request that would bring a version of a change that is not
296`ready` (see [The integrator](#the-integrator)).
297
298A change is in one of three states:
299
300- `ready`: the change is offered for landing. A change is created ready.
301- `draft`: the change is paused, by `valley unready`. A draft voids nothing. When it is readied
302 again, the approvals of its active version still stand.
303- `withdrawn`: the change is given up. Withdrawing voids everything outstanding on the change: its
304 integration requests, and the approvals and reviews of every version. A change brought back from
305 withdrawn always needs fresh approvals.
306
307The integrator enforces the pause. It refuses a request that would bring a version of a draft or a
308withdrawn change, so a request filed before the change was paused or withdrawn stays where it is and
309does not land. A draft's request lands once the change is ready again, which is what a pause means.
310
311The integrator also voids a withdrawn change's requests. On each pass it deletes the request named
312`c-<change-id>`, and every request whose head is one of the change's version heads. So readying the
313change again needs a fresh approval. A withdrawal followed by a ready within one pass is not seen,
314and can leave an old request in place. So `valley withdraw` warns when origin holds a request for
315the change, and `valley unready` notes one. The request is looked for under `c-<change-id>`, and
316under the name a branch's request has, for the branch of each of the change's versions. Only an
317`approve` holder may touch a request ref, so the warning says the operator must drop it if the
318change is readied first. Approvals have no records of their own: signed approval statements are
319**not built**.
320
321The ref `refs/the-valley/changes/main/<change-id>` points at a record commit. The commit's tree
322holds one entry, `record.json`, as a plain file. Its schema is `valley-change-record/v1`, read by
323one strict parser that the hook and the CLI share (`change/record.go`):
324
325```json
326{
327 "schema": "valley-change-record/v1",
328 "change_id": "<32 letters from k to z>",
329 "target": "main",
330 "owner": "<principal>",
331 "state": "ready",
332 "seq": 3,
333 "versions": [
334 {
335 "n": 1,
336 "head": "git-sha1:<40 lowercase hex>",
337 "title": "<the head's subject>",
338 "branch": "<branch, or empty>",
339 "uploader": "<principal>"
340 }
341 ],
342 "active": 1
343}
344```
345
346The parser refuses anything that is not valid UTF-8. It also refuses a duplicate key at any depth,
347an unknown field, and data after the object. Every field must have the type shown. `seq` runs from 1
348to 100000, and `n` and `active` from 1 to 1000. Versions are numbered 1, 2, 3 with no gap. A title
349is 1 to 200 bytes with no control characters. `state` is `ready`, `draft` or `withdrawn`.
350
351The record commit's parents tie it to what it records. In the table, `P` is the record commit's
352parents, `old` is the ref's value before the push, and `h` is the head of the version being added.
353
354| Transition | Who | `P` | What the record must say |
355| ------------------------- | -------------------------------- | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
356| Create | Any named principal | `[h]` | One version: `n` 1, `head` `h`, and the pusher as `uploader`. The pusher as `owner`, `seq` 1, `active` 1, `state` `ready`. `target` and `change_id` are the ref's. |
357| New version | The owner or an `approve` holder | `[old, h]` | `old`'s versions unchanged, plus one with the next `n`, `head` `h` other than the active head, and the pusher as `uploader`. `active` is the new `n`, `state` `ready`, `seq` one more than `old`'s. |
358| Unready | The owner or an `approve` holder | `[old]` | Everything as in `old`, except `state` goes from `ready` to `draft` and `seq` goes up by one. `active` stays. |
359| Withdraw | The owner or an `approve` holder | `[old]` | Everything as in `old`, except `state` goes from `ready` or `draft` to `withdrawn` and `seq` goes up by one. `active` stays. |
360| Ready again, same version | The owner or an `approve` holder | `[old]` | Everything as in `old`, except `state` goes from `draft` or `withdrawn` to `ready` and `seq` goes up by one. `active` stays. |
361| Ready again, new version | The owner or an `approve` holder | `[old, h]` | As for a new version, from `draft` or `withdrawn`. |
362| Restack | A `restack` holder | `[old, h]` | As for a new version, from `ready` only. The new version keeps the `branch` and `title` of the version that was active. |
363| Delete | An `approve` holder | — | Allowed, to keep storage tidy. |
364
365The restack row applies only when the `restack` grant is what authorises the write: the pusher
366neither owns the change nor holds `approve`. Such a pusher may write that row and no other. The hook
367refuses its write when the change is `draft` or `withdrawn`, when the record changes the state with
368one parent, and when it adds more than one version. It also refuses a changed earlier version,
369owner, target, change ID, branch or title, and an uploader other than the pusher. A `restack` holder
370may not delete a record. A `restack` holder that owns the change, or also holds `approve`, writes by
371the other rows. The hook cannot tell a submitted change from a ready one, because a landed change
372can stay `ready`; leaving submitted changes alone is the restacker's own selection.
373
374The hook refuses every other write. That includes a key that names no principal, extra parents,
375parents in another order, a head that is not a commit, and a tree of another shape. It also includes
376a record with one parent that leaves the state as it was, such as `ready` to `ready` without a new
377version, and `withdrawn` to `draft`. A withdrawn change comes back ready, never as a draft. The
378owner, the target and the change ID never change.
379
380Each record commit is at most 4 KiB, its tree at most 1 KiB, and its `record.json` at most 64 KiB. A
381push may update at most 32 records. The hook checks each of these bounds before it reads anything
382past it, and the integrator reads records under the same bounds (`change/record.go`).
383
384A repository may hold at most 2000 records, counted with one `for-each-ref`. This bound is soft. A
385pre-receive hook runs before git installs any ref, and nothing serializes two pushes' hooks. So
386pushes that run at the same time can each count the same records and each create more. The count can
387then pass 2000 by at most the record updates those pushes had in flight, which is 32 per push. Once
388the count is past 2000, every later create is refused. The integrator reads at most 4000 records,
389twice this bound. A repository that holds more lands nothing until records are deleted, because the
390integrator could not tell which heads are versions of changes that are not `ready`. Each project has
391its own integrator, so no other repository is held up.
392
393The writer numbers versions, and the hook holds them to append-only and gap-free. The integrator
394takes this numbering as it is. A change is owned by the principal whose key pushed its first record,
395so an agent's principal owns every change the agent starts.
396
397A record keeps every head it names reachable, because each head is a parent of a record commit. So
398records retain source objects the way topic branches do, and the hook restricts them no further.
399
400Checked by `valleyhook-unit`, with a case for each rule of each transition against real git objects,
401by `change-unit`, which runs the parser's tests and its fuzz target's seed corpus, by
402`valley-ready`, which drives the transitions through real pushes, and for the restack row by
403`protect-e2e` and `identity-e2e`.
404
405### Restack reports
406
407A restack report is what the host restacker observed when it tried to rebase a ready change onto
408`main`. It records the inputs it read, what came of the attempt, and what it published. A report is
409an observation. It grants nothing, and it is not evidence that a version's content is unchanged or
410approved.
411
412The ref `refs/the-valley/restack/main/<change-id>` points at the change's latest report commit. The
413commit's tree holds one entry, `report.json`, as a plain file. The first report commit has no
414parent. Each later one has the report it replaces as its one parent, so the ref keeps the change's
415whole history of reports. Its schema is `valley-restack-report/v1`, read by one strict parser that
416the hook and the CLI share (`change/report.go`):
417
418```json
419{
420 "schema": "valley-restack-report/v1",
421 "change_id": "<32 letters from k to z>",
422 "target": "main",
423 "target_tip": "git-sha1:<main as the attempt read it>",
424 "operation": "<the restacker's name for the attempt>",
425 "result": "conflict",
426 "layers": [
427 {
428 "change_id": "<32 letters from k to z>",
429 "record": "git-sha1:<the record commit read>",
430 "version": 2,
431 "head": "git-sha1:<the active version's head>",
432 "branch": "topic",
433 "branch_tip": "git-sha1:<origin's topic as read>",
434 "published": null
435 }
436 ],
437 "failing_layer": "<change id, or null>",
438 "conflict_paths": ["src/main.go"],
439 "blocking_requests": [
440 {
441 "ref": "refs/the-valley/integration-requests/main/<name>",
442 "tip": "git-sha1:<the request as read>"
443 }
444 ],
445 "refusal": null
446}
447```
448
449- `layers` are the changes the attempt rebased together, bottom first: 1 to 64, each change once,
450 and the report's own change among them.
451- A layer's `head` and `branch` are its active version's, as the record names them. `branch` is
452 empty for a version that names no branch.
453- A layer's `branch_tip` is where origin's branch was when the attempt read it. It is `null` when
454 origin had no such branch, and always `null` when `branch` is empty. It is recorded apart from
455 `head` because the two can differ: the branch can be missing, or somewhere other than the head its
456 version names.
457- `result` is `conflict`, `blocked`, `partial`, `complete` or `superseded`. A conflict names its
458 `failing_layer`. A conflict and a block publish nothing. `partial` means the branches moved and
459 not every version was added; `complete` means every layer gained a version. `superseded` means the
460 attempt was given up because its inputs moved while it ran.
461- `published` is `null` for a layer whose branch did not move. Otherwise it is
462 `{"head", "version", "record"}`: the head the branch moved to, and the version and record commit
463 that recorded it, both `null` when no version was added. A layer with no branch publishes nothing.
464- `blocking_requests` are the integration requests that held the attempt back. Each is the request's
465 ref, which is on `main`, and `tip`, the object the ref pointed at when the attempt read it. There
466 are at most 64, each ref once.
467- `conflict_paths` holds at most 100 paths of 1 to 1024 bytes. `refusal` is `null` or 1 to 2048
468 bytes. `operation` is 1 to 64 letters, digits, dots, colons, dashes and underscores. No string
469 holds a control character.
470
471A report is current while every ref it observed still holds what the report says it held. Those refs
472are `main`, each layer's record ref and branch, and each blocking request. The comparison is exact,
473and absence counts: a branch the report saw missing must still be missing. A layer with no branch
474has no branch to compare. For a layer the attempt published, the branch must be at the published
475head, and the record ref at the published record when a version was added. Each comparison uses what
476the report recorded of that ref: a branch is compared with its `branch_tip`, never with the
477version's `head`. A report that is not current is historical (`rebase/report.go`).
478
479The parser refuses what the record parser refuses: invalid UTF-8, a duplicate key, an unknown field,
480a field of another type, and data after the object.
481
482Only a `restack` holder may write a report. The hook refuses a report for any target but `main`, a
483ref whose last part is not a change ID, and a change the repository holds no record of. It refuses a
484first report with a parent, a later one whose one parent is not the ref's old value, and every
485delete. Each report commit is at most 4 KiB, its tree at most 1 KiB, and its `report.json` at most
48664 KiB. A push may update at most 64 reports. The hook checks each bound before it reads anything
487past it.
488
489Checked by `protect-e2e` and `identity-e2e`, which push reports through the rendered hook, by
490`valleyhook-unit`, and by `change-unit`, which runs the parser's tests and its fuzz target's seed
491corpus. `valley-status` reads reports through the CLI and checks when each one is current.
492
493## After a push: events and mirrors
494
495Each repository's `post-receive` hook runs every program in `hooks/post-receive.d/`
496(`nix/valley-host.nix`). There are two:
497
498- **The bus publisher**, when the bus is on. It publishes one `ref-updated` event for every ref the
499 push updated, on the subject `valley.git.<repo>.ref-updated`. Checked by `bus-e2e`.
500- **The mirror hook**, when the project declares mirrors. It does not push. It writes the push's ref
501 moves, one `<old> <new> <ref>` line each, as a file in the repository's publish queue,
502 `valley-publish-queue/`, and returns. A dead mirror therefore never slows or fails a push.
503
504The integrator moves refs with `git update-ref`, which runs no `post-receive` hook. So it does both
505jobs itself for each landing (`integrator/bus.go`). It writes the move to the same publish queue. It
506also publishes the `ref-updated` event straight to the bus, with the same payload the bus publisher
507would send. It publishes only after the landing is fully recorded: the queue entry written, the
508evidence stored and the request consumed. Each publish is stopped after 10 seconds, so a bus that
509hangs cannot hold up a landing. Checked by `integrator-e2e`.
510
511One unit pushes the mirrors: `valley-publish@<project>`, a service that runs as git. A systemd path
512unit starts it whenever the project's queue is not empty. Mirrors are a list of URLs
513(`schema/valley.cue`). The service lists the queued files and then runs `git push --prune` of `main`
514and all tags to each URL. Tags are copied whether or not `main` reaches them. Because of `--prune`,
515a tag deleted on the primary is deleted on the mirror. Nothing else on the mirror is changed. A
516mirror holds refs that other writers put there, such as a forge's own namespaces or a bot's
517branches, and those are theirs. Deleting a ref that a public mirror has already served would not
518unpublish it anyway, because forges keep its objects fetchable by SHA. The push uses the git user's
519own ssh identity, which the host provides. Checked by `mirror-e2e`.
520
521A repository that becomes a mirror keeps every ref it already holds. So the operator deletes what
522should not be published when declaring the mirror:
523
524```sh
525git ls-remote <url> # list every ref the mirror holds
526git push <url> --delete <ref>... # delete each one that should not be published
527```
528
529The service deletes the files it listed only after every mirror push succeeds. When a push or a
530deletion fails, the service fails and the files stay. systemd then runs the service again after a
531delay that grows from 30 seconds to 15 minutes. A run that lasts 15 minutes is stopped with
532everything it started. Checked by `publish-e2e`. Because the integrator publishes its events itself,
533a mirror outage never delays an event on the bus.
534
535Having one publisher is what keeps a mirror from being rewound. git reads the local refs before it
536contacts the mirror. So when two pushes run at once, one can read an old `main`, stall, and then
537force-push that old `main` over a newer one the other pushed meanwhile. systemd never runs two
538instances of one unit at the same time, and nothing else pushes the mirrors. A move queued while a
539push runs stays in the queue, so the next run pushes the newer `main`. `mirror-e2e` stalls a push in
540that window: two pushers at once rewind the mirror, and the service ends at the newer `main`.
541
542The bus is NATS with JetStream, listening on `127.0.0.1:4222`. `valley-bus-init` creates one stream,
543`valley`, over the subjects `valley.>`, with file storage and NATS defaults. The events are defined
544in `schema/events.cue`: `ref-updated`, `integration-succeeded` and `request-stale`. The bus has no
545authentication, so nothing treats an event as authoritative
546([bd-d853d9c](../archive/.the-valley/bugs/bd-d853d9c-bus-unauthenticated.md)). The integrator reads
547git directly.
548
549## The integrator
550
551Each protected project has one controller, `valley-integrator@<project>`, running as the
552`valley-integrator` user in group git (`nix/valley-host.nix`). It makes one pass over the open
553requests in order, then sleeps 15 seconds and starts again (`integrator/main.go`,
554`integrator/refs.go`). No bound on how long a request waits is checked.
555
5561. **Find requests.** A request is a ref `refs/the-valley/integration-requests/<target>/<change>`
557 that points at the change's head commit. A change with a record is requested as `c-<change-id>`.
558 Every name of that form is reserved for the change with that ID. Any other name is a branch's:
559 the branch with each `/` replaced by `-`.
5602. **Void what a withdrawal voids.** The records are read once per pass (see below). A request named
561 for a withdrawn change, or whose head is one of a withdrawn change's version heads, is deleted
562 with the outcome `voided-withdrawn`. The record is read again just before each deletion, and the
563 request is deleted only while the change is still withdrawn. The deletion is leased on the head
564 the pass found, so a request filed again since stands.
5653. **Skip what is decided.** The outcome record
566 `refs/the-valley/integration-outcomes/<target>/<change>` holds the head, the target tip, a hash
567 of all attestation refs, and the outcome. If the first three still match, the request is skipped.
568 A `failed` outcome is retried after 10 minutes. A refusal from step 4 is never skipped this way.
5694. **Refuse what the records refuse.** A request is refused with the outcome `refused-not-ready`
570 when either of these holds:
571 - it is named `c-<change-id>`, and the record `refs/the-valley/changes/<target>/<change-id>` is
572 missing, is not `ready`, or does not list the request's head as one of its version heads;
573 - whatever its name, a commit it would bring to the target, from the merge base to the head, is a
574 version head of a record that is not `ready`. The outcome names that change. So a child of a
575 draft's head, approved under another name, does not land the draft.
576
577 A request whose commits from the merge base with the target to the head include a merge is
578 refused with the outcome `refused-merge`. A merge could make other work look landed by ancestry.
579 A refused request stays where it is, and no event is published. A refusal is decided again on
580 every pass, and reported only when it is new, so a draft readied again is judged on the next
581 pass.
582
5835. **Build the candidate.** Every change lands as one commit that the integrator writes, with the
584 tip as its only parent. None of the head's own commits reaches the target, so the target's
585 history holds only the trees that review showed. The base is `git merge-base` of the tip and the
586 head. If the base is the tip, the candidate's tree is the head's tree. Otherwise
587 `git merge-tree --write-tree` builds the tree, and a conflict makes the request stale. The commit
588 keeps the head's author and message. Its committer is the integrator at
589 `integrator@the-valley.invalid`. A stack approved at its top lands as one commit, with landing
590 evidence for its top alone.
5916. **Derive the required checks** (see Policy below).
5927. **Judge the evidence** (see Evidence below). The outcome is `land`, `stale` or `reject`. A stale
593 request publishes `request-stale`.
5948. **Land.** The integrator signs a transfer statement that records the policy digest and the checks
595 it relied on. Then, as the last thing before the commit point, it reads every record again into a
596 fresh index and applies step 4 once more, since judging and signing can take minutes. Then it
597 lands and records the landing in one ref transaction, as described below. Then it queues the
598 landing for the publisher and publishes `ref-updated` and `integration-succeeded`.
599
600A landing is published in this order (`integrator/refs.go`):
601
6021. **Build every object.** The integrator writes the landing commit, then the evidence: each
603 attestation ref's new tree, with the countersigned notes and the transfer statement added to what
604 the ref already holds. It writes the landing record for the head (see
605 [Landing records](#landing-records)) and the outcome record that says `land`. Each ref but the
606 target is read here, and the value read is kept.
6072. **Apply them in one transaction.** One `git update-ref --stdin` transaction (`start`, `update`
608 and `delete` lines, `prepare`, `commit`) moves the target from the judged tip to the landing
609 commit, moves each evidence and record ref from the value it was read at, and deletes the request
610 while it still names the head that lands. git locks and compares every ref before it moves any,
611 so all of them change or none does. This is the commit point.
6123. **On a conflict, nothing changed.** When the target moved, nothing lands, and the request is
613 judged again next pass. When another ref moved, as when a push created an attestation ref the
614 landing adds to, the integrator reads the refs again, builds the objects again, and retries,
615 three times in all.
6164. **Notices last.** The publisher's queue and the bus events follow the transaction, as best
617 effort. A failure of either is reported and changes nothing the transaction recorded.
618
619A request that was replaced while the pass worked is a new approval. The transaction leaves it
620standing, and the integrator says so. One window remains: a crash inside git's commit phase. With
621the files ref backend, git renames each ref's lock file into place one ref at a time, so a crash
622there can leave some refs moved and others not. A landing cut short this way can read `uncertain`.
623Checked by `integrator-e2e` (scenarios for a change on the tip, merge, conflict, stale evidence,
624tampered notes, retries, a moved target, a request approved again during a landing, requests named
625for changes, drafts under either kind of name, a child of a draft's head, merges, a request voided
626by a withdrawal, a landing record that outlasts the next version's landing, and a tree that lands
627twice) and `integrator-unit`.
628
629### Landing records
630
631A landing record says that one head landed. The integrator writes one for each head it lands, at
632`refs/the-valley/integration-landings/<target>/<head>`, in the landing's transaction
633(`change/landing.go`). It names the commit the head landed as and the request name it landed under.
634An outcome record is kept per request name, so the next version of a change to land under the same
635name replaces it. A landing record is kept per head, so that later landing leaves it in place. No
636push may write the namespace (see [What a push may write](#what-a-push-may-write)). Clients read it
637to bind a transfer statement to the exact head that landed (see
638[Listing changes](#listing-changes)). Its format is in
639[the reference](./reference.md#integrator-landing-record-refsthe-valleyintegration-landingstargethead).
640
641Each decision the integrator reports is followed by one timing line in its output, which the unit's
642journal keeps (`integrator/timing.go`). The line is the label `timing` and a JSON object:
643
644```text
645$ journalctl -u valley-integrator@the-valley -o cat | sed -n 's/^ timing //p' | tail -n 1
646{"time":"2026-10-20T12:00:00.000Z","project":"the-valley","request":"refs/the-valley/integration-requests/main/c1","change":"c1","head":"4ae651e56c34b79b324aca341508cf35c3aaae8e","target":"refs/heads/main","tip":"9d1c0e2b7a6f5e4d3c2b1a0f9e8d7c6b5a4f3e2d","outcome":"land","duration_ms":2310,"stages_ms":{"checkout":40,"evidence":350,"land":3,"policy":1500,"publish":10,"record":30,"refusal":20,"sign":300}}
647```
648
649It names the request, the change, its head, the target and its tip, and the outcome. A decision that
650fails has the outcome `failed`. `duration_ms` is the whole decision. `stages_ms` divides it among
651the stages the decision reached: `refusal` (step 4, and the second reading of the records in step
6528), `checkout` (the worktree of the tip), `evidence` (verifying the notes), `policy` (step 6),
653`apply` (step 5's merge), `closures` (recomputing input closures for a moved tree), `sign` (the
654transfer statement), `record` (building the landing's evidence trees, landing record and outcome
655record), `land` (the commit point's ref transaction), and `publish` (the publisher's queue and the
656bus). A voided request gets a timing line too. A refusal that repeats is not reported again, so it
657is not timed again either. The line is output only: no ref, record or event carries it. The line is
658printed after the decision's outcome is recorded. It is dropped when it cannot be written within a
659second, so a journal that stalls or goes away cannot keep an outcome from being recorded. Checked by
660`integrator-unit` and `integrator-e2e`.
661
662The security invariant is the operator's approval: only content the operator approved lands. The
663request names the exact head that was approved, and the integrator lands only what a request names.
664So a record that moves after the request is filed cannot change what lands.
665
666Readiness is the author's workflow signal, and the integrator enforces it as closely as refs allow.
667It does not enforce it atomically. The integrator reads the records last just before it moves the
668target, and a record written between that read and the move is not seen. So a head the operator
669approved can still land after its author has paused it. Content the operator did not approve can
670never land this way. The race-free design binds each approval to the record's withdraw generation in
671a signed approval statement (**not built**).
672
673The records are read with the parser the hook and the CLI share (`change/`), under the bounds the
674hook admits them under (`integrator/records.go`). Each pass reads every ref under
675`refs/the-valley/changes/` into an index by version head, with one `for-each-ref` and two batched
676`cat-file` reads, and step 8 reads them all again. A `c-<change-id>` request's own record is read
677fresh each time. A repository that holds more than 4000 records lands nothing, as
678[Change records](#change-records) describes.
679
680A stored record that does not read is isolated. It names no head the integrator can see, so it
681refuses nothing, and a head it names can land. Every pass that reads records reports it with a
682`WARNING` line. The pass also warns with each request that brings a commit the record may name: one
683its record commit reaches, since a record names its version heads as parents of its record commits.
684`valley status` warns the same way for the change's request. The hook refuses a record that does not
685read, so corrupt storage is the only way to get one.
686
687## The restacker
688
689The restacker rebases ready changes onto `main` when `main` moves under them, as its own principal,
690so their evidence stays fresh without their owners rebasing and approving again.
691`valley-restacker run` (`restack/`) runs a write pass at startup and then waits `--interval`
692(default 15 seconds) after each pass before starting the next, until stopped.
693`valley-restacker once` runs a single write pass. Every pass reads origin whether or not `main` has
694moved, so a change readied after the last landing is picked up without waiting for another landing.
695If the state directory holds an open journal from earlier operations, a write pass settles that
696journal first. It then plans each family, builds the pass's writes, adds them to the journal, and
697pushes them (see [Publishing](#publishing)). `valley-restacker once --report-only` plans and builds
698the same writes and evaluates any existing journal, without writing a journal or pushing to origin.
699On a host, `services.valley.restacker` runs one controller for each configured project (see
700[The restacker on the host](#the-restacker-on-the-host)).
701
702It is a git client of origin. It reads origin into a scratch repository under `--state`, with hooks
703off and no system or user git configuration, so no filter driver is defined. Nothing is ever checked
704out in the scratch repository's work tree. The work tree exists because `attest`, which verifies the
705integrator's transfer statements, reads only a repository that has one. Its flags name origin
706(`--repo`), the principal it pushes as (`--principal`), the landing verifier (`--known-signers`,
707`--integrator-name`, `--attest`), and the floor, which it finds as the integrator does:
708`--instance-repo` with `--instance-ref` and `--instance-policy`, or a materialized `--instance`. The
709project layer is read from `main`'s tip.
710
711git in the scratch repository commits under the identity that `--commit-name` and `--commit-email`
712give. By default that is the principal's name and `restacker@the-valley.invalid`. The restacker sets
713that identity as git's author and committer explicitly. It never takes an identity from
714`GIT_AUTHOR_*`, `GIT_COMMITTER_*` or `EMAIL` in its environment, and git is told not to guess one.
715git there also inherits no configuration from the environment: `GIT_CONFIG_COUNT` with its
716`GIT_CONFIG_KEY_<n>` and `GIT_CONFIG_VALUE_<n>`, `GIT_CONFIG_PARAMETERS`, and the other
717`GIT_CONFIG*` variables are dropped. Such configuration would beat the scratch repository's own, so
718an inherited `author.name` would replace the restacker's identity. A commit the restacker rebases
719keeps its author, and the restacker is its committer. A `--report-only` pass writes commits only in
720its scratch repository: the rebased commits, and the record and report commits it builds.
721
722No git variable that points git somewhere else reaches anything a pass runs. That covers another
723repository (`GIT_DIR`, `GIT_WORK_TREE`, `GIT_COMMON_DIR`, `GIT_INDEX_FILE`, `GIT_OBJECT_DIRECTORY`,
724`GIT_ALTERNATE_OBJECT_DIRECTORIES`, `GIT_NAMESPACE`, `GIT_GRAFT_FILE`), other programs
725(`GIT_EXEC_PATH`, `GIT_TEMPLATE_DIR`), other attributes (`GIT_ATTR_SOURCE`) and another object
726format (`GIT_DEFAULT_HASH`). A pass removes every `GIT_*` variable from its own environment as it
727starts, except `GIT_SSH`, `GIT_SSH_COMMAND` and `GIT_SSH_VARIANT`, so cue, attest and the git that
728composes the policy run without them too. The scratch repository's `core.attributesFile` is
729`/dev/null`. git would otherwise read the user's own attributes file under `XDG_CONFIG_HOME` or
730`HOME`, and an attribute such as `merge=union` there would change how a rebase merges.
731
732A pass locks its state directory from start to end, so a second pass on the same directory fails at
733once while one runs. `run` holds the lock for its entire lifetime, so only one controller can use a
734state directory at a time. When a pass fails, `run` writes the error to stderr and doubles the wait
735before the next pass, from `--interval` up to 5 minutes, until a pass succeeds. The directory
736belongs to the repository, target and principal of the first pass that used it, recorded in its
737`binding.json`. A pass for any other is refused, and needs its own `--state`. A pass runs for at
738most `--timeout`, 10 minutes by default. When the timeout passes, or the pass is interrupted or
739stopped, every git, cue and attest it started is killed, with whatever each of them started, ssh
740included. Writing the plan is bounded the same way. A pass whose output nobody reads ends at its
741timeout. Under `once`, the program then lets go of the lock, so the next pass can take it. Under
742`run`, the program keeps the lock and starts its next pass after the wait. A message of the
743program's own, such as the error it ends with, is given up on after 5 seconds, so a stderr nobody
744reads cannot hold the process either. Checked by `restack-unit` and `restack-e2e`.
745
746To read a snapshot of origin, a pass lists origin's refs and then fetches the objects they name. If
747a ref moves between the listing and the fetch and origin has pruned the old object (for example,
748when `main` is rewritten), the fetch fails. `ReadSnapshot` then lists origin and fetches again, up
749to three attempts in total, before returning the error (`rebase/snapshot.go`). Checked by
750`rebase-unit`.
751
752A family is the connected layers of one snapshot, as the rebase engine captures them
753(`rebase.Capture`). Two stacks on a shared lower layer are one family. The planner gives each family
754one of five answers:
755
756- **leave**: no layer is a ready change: drafts, withdrawn changes and uncertain landings alone. A
757 plain branch is never planned on its own, and a submitted change is no layer.
758- **current**: the family already descends from `main`'s tip.
759- **hold**: something stops it, and each reason is listed. A layer that is not a ready change holds
760 its family, as does any refusal of the engine's `Family.Check`.
761- **restack**: nothing holds it.
762- **wait**: the family shares a change or a branch with a family still held in the journal. A family
763 that this pass would otherwise mark `restack` or `hold` also waits when it shares a change or a
764 branch with another such family. The pass builds no writes for a waiting family until that overlap
765 clears (see [Publishing](#publishing)). For example, two ready changes that name the same branch
766 are captured as two separate families when neither head descends from the other and no shared
767 lower layer joins them. Because the journal never holds two families that share a branch, both
768 families wait, each naming the other in its reason, while unrelated families are planned as usual.
769
770A family is also held while a related integration request might still land. A request is related by
771its name (`c-<change-id>`, or the branch-derived name of any version the change has had), by a head
772equal to any version head a layer's change has had, or by an incoming range (what the request's head
773reaches and `main`'s tip does not) that contains such a head. A request filed for an older version
774therefore holds the family whatever its name. The snapshot lists request heads without fetching
775them, so the planner fetches them before it reads any ancestry. A request whose relation cannot be
776determined holds every family it might be about. A related request releases the family only with a
777current outcome of `stale` or `reject`; a `reject` is noted. Current means the outcome's head,
778target tip and evidence fingerprint all equal what the planner sees. The fingerprint is
779`change.EvidenceFingerprint`, which the integrator writes and `valley status` reads. The planner
780judges requests in name order. One snapshot therefore gives the same reasons, notes and reports
781every time it is planned.
782
783A family is held when any record it would change is over a limit, counted with the version the
784restack would add:
785
786- `restack.maxAutomaticVersions` versions uploaded by the restacker's principal, from the composed
787 policy at `main`'s tip;
788- 900 versions;
789- 99,000 record updates;
790- 48 KiB of encoded record JSON.
791
792The cap is read through `composed/`, the composed-policy reader the integrator reads its checks and
793policy digest through. Both run `cue export` of the floor, the template the policy's type selects,
794and the project layer, under the packaged schema.
795
796The schema puts no upper bound on the cap. `composed/` keeps the cap as cue writes it, so the
797integrator, which does not read the cap, composes any policy the schema admits. The planner counts a
798cap larger than a Go `int` holds as the largest `int`. That is no practical cap, since no record
799holds that many versions. Checked by `integrator-unit`, `restack-unit` and `restack-e2e`.
800
801The plan prints as a summary, or with `--json`. The JSON is not a published format. `restack-unit`
802covers request association, outcome currency and the capacity arithmetic. `restack-e2e` runs the
803planner over a repository wired with the rendered hook and checks that no ref on origin moves.
804
805### What a pass builds
806
807For each family it would restack, a pass prepares the family in a throwaway worktree and builds its
808writes in the scratch repository (`restack/build.go`):
809
8101. the one atomic branch push, each branch leased on the tip the capture read;
8112. each change's next version, lower layers first, built from the record the capture read and leased
812 on that record commit. It keeps the active version's branch and title, and names the restacker's
813 principal as its uploader. Its push reads origin's branch first, and pushes nothing unless the
814 branch is at the prepared head;
8153. a report for each recorded change in the family, saying `complete`.
816
817A family whose rebase conflicts gets reports that say `conflict` and name the failing layer. A
818family the engine refuses to prepare, or that the planner holds, gets reports that say `blocked`,
819with the refusal or the planner's reasons. Neither gets a branch push or a version. A family left
820alone or already current gets nothing. A plain branch is no report layer. A report that says what
821the change's current report on origin says is not built again: two reports are the same when their
822observations and result are, whatever operation wrote each. `--json` shows each family's writes
823under `writes`.
824
825A conflict keeps every path that conflicted, whatever bytes the name holds (`rebase/prepare.go`). A
826report holds what the report format allows, and when the observation holds more, the report is a
827fallback (`restack/report.go`):
828
829- With more than 64 recorded changes in the family, it keeps the change's own layer and the failing
830 one.
831- It keeps each conflict path and each blocking request that fits on its own, up to 100 paths and 64
832 requests. A path fits at up to 1,024 bytes of UTF-8 with no control character. A request fits when
833 its ref is at most 256 bytes and its name is a branch name.
834- Its refusal has each run of control characters made one space, and is cut to fit 2,048 bytes.
835- Its refusal ends with a note stating what the report omitted and naming
836 `observations/<digest>.json` in the state directory, where `<digest>` is the digest of the full
837 observation. That digest distinguishes two fallback reports whose truncated fields look the same.
838- If the report is still over 64 KiB, it sheds its conflict paths, then its blocking requests, then
839 every layer but the two it keeps.
840- If the change's own layer alone is still over 64 KiB, no report of that change is built, and the
841 pass's writes say why.
842
843A family with more than 64 recorded changes still proceeds: each change's report keeps that change's
844own layer. A replacement report's result describes the whole family, whichever layers it keeps. It
845says `complete` when every version of the family was added, and `partial` when any was not. So a
846replacement that keeps only its own layer can say `partial` because of another layer's version, and
847the journal accepts it (see [The journal](#the-journal)). Checked by `restack-unit` and
848`restack-e2e`.
849
850Before saving a journal that contains a truncated report, the restacker writes the full observation
851to `observations/<digest>.json` in the state directory. The file stores the exact JSON bytes that
852were hashed to form `<digest>`, so its SHA-256 prefix matches `<digest>`. The restacker never
853deletes observation files, so omitted details (such as conflict paths beyond the 100-path report
854limit) remain on disk after the journal closes. Checked by `restack-unit`. Because these files
855accumulate without bound, an operator reclaims space by removing old files manually (see
856[Helper and host commands](reference.md#helper-and-host-commands)).
857
858The restacker skips rebasing a family when every recorded change in it already has a current report
859with result `conflict`. A conflict report remains current only while `main`, and each change record,
860branch, and blocking request the report lists, stay at the commits the report observed. Currency
861checks only the refs listed in each report. When any of those refs moves, the report becomes
862historical, and a later pass tries the rebase again. A new recorded layer that joins the family does
863not make the existing reports historical. That layer has no current conflict report of its own, so
864the family does not qualify for the skip, and the pass tries the rebase. Any omitted conflict paths
865remain in the observation file named by the report. Checked by `restack-unit`.
866
867### The journal
868
869The journal records every pending write in `journal.json` in the state directory before the
870restacker pushes anything (`restack/journal.go`). Its format is `valley-restack-journal/v1`, which
871is internal to the restacker. The journal header names the repository, target, and principal. An
872open family stays in the journal across passes while later passes append newly built families, so
873one journal can hold families from multiple operations. For each family, the journal stores:
874
875- the operation ID that built it, along with `main`'s tip and the evidence fingerprint captured by
876 that operation;
877- the full observation: every layer (including plain branches), related integration requests, all
878 conflict paths, and the full refusal text;
879- the pending branch push, version updates, and initial reports in the serialized forms defined by
880 the rebase engine (`rebase/pending.go`);
881- any replacement reports built later to record what actually happened after the branches moved (see
882 [Publishing](#publishing));
883- the writes confirmed on origin (`accepted`): whether a read saw the branch push on origin, and the
884 change IDs whose new versions a read saw on origin (see [Publishing](#publishing)).
885
886Each conflict path is base64-encoded so file names with non-UTF-8 bytes survive JSON serialization
887byte for byte. Every object those writes would push is kept reachable in the scratch repository
888under `refs/valley-restack/<operation>/<object>` for as long as the journal names it: each prepared
889head, each record commit, and each report and replacement commit. An object that a report's JSON
890only names is not kept by these refs. The scratch repository fsyncs every object and ref it writes,
891and the restacker writes `journal.json` via an fsynced temporary file renamed into place.
892
893A journal is read as strictly as it is written. A field missing, unknown or named twice, a form that
894does not agree with itself, and a journal for another repository, target or principal are refused,
895and nothing in a refused journal is decided. A refused journal is an error that recovery reports,
896never a crash. A family's writes must agree with each other:
897
898- A family that would restack adds exactly one version of each of its changes.
899- Each report gives the family's result: complete, conflict or blocked.
900- A report says a version was published exactly when the family adds that version, and then names
901 that version's head, number and record commit.
902- A replacement report is stored only after origin is recorded as having accepted the family's
903 branch push. Every layer in a replacement reports that change's prepared head as published, and
904 includes version and record fields only when they match the version the family adds.
905- A replacement report that says `complete` gives every layer it lists a published version. One that
906 says `partial` lists a layer with no version, or leaves out a change of the family. A fallback
907 report that leaves out layers may say either, because its result describes the whole family: the
908 version that was not added may belong to a layer it leaves out.
909- A version can be recorded as accepted by origin only when the family's branch push is also
910 recorded as accepted, and only for a change whose version the family adds, in bottom-up layer
911 order without duplicates.
912- No two families in the journal may share a change or a branch.
913
914The restacker does not keep a journal that would not read back as written. A lost journal is never
915inferred. A change whose branch a pass moved with no journal to say so is held by the planner,
916because its branch is not at its recorded head. Checked by `restack-unit`.
917
918### Recovery
919
920Recovery reads origin and the journal, and decides each write in the order a pass makes them: the
921branch push, then the versions, lower layers first, then the reports and replacements
922(`restack/recover.go`). Each write is `done` when origin holds it or has moved on from it, `finish`
923when it is still valid to push, or `stop` when it must not be pushed. A stop is final when no later
924pass could push it, and terminal when it is also a local failure the journal keeps the diagnostics
925of. Any write recorded in the journal as accepted by origin is treated as `done` on every subsequent
926read, even if the branch or record on origin moves afterward (see [Publishing](#publishing)).
927
928| Write | `finish` while | `stop` (final) on |
929| --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
930| The branch push | `main` is at the tip the family was rebased onto, every branch is at its lease, every record is at the record commit read, and nothing has been submitted | a branch moved, `main` moved, a record moved (an unready, a withdrawal, a new version), a submission, or a prepared head missing from the scratch repository |
931| A version | its branch is at the prepared head, or the branch push is still to finish, and its record is the record commit read | the author moving the branch or the record, a withdrawal, an unready, a submission, a deleted branch, or a `main` that does not descend from the captured tip |
932| A report | origin's report is the one it was built on, and what it says was published is on origin or is still to finish | a version it says was added stopped, or origin's report moved |
933| A replacement | origin's report is still the commit it was built on, and its content still matches the current version decisions | origin's report moved, or the replacement does not match the current version decisions (a new replacement is built in its place) |
934
935A related integration request that might still land is a stop that is not final: the branch push
936waits, and the versions pause. Requests are related as the planner relates them, by every version
937head the changes have had, the prepared heads included. A deleted change record is a terminal stop
938for its version and its report, since the hook takes no report about a change the repository does
939not record. A family whose writes stop does not stop another's. A `main` that has moved on, and
940still descends from the captured tip, does not stop a version whose branch was pushed.
941
942In `--report-only` mode recovery decides and pushes nothing, and leaves the journal as it is. The
943decisions are printed, and under `recovery` with `--json`. A write pass pushes what recovery decides
944to finish (see [Publishing](#publishing)). Checked by `restack-unit`.
945
946### Publishing
947
948A write pass executes its journal using the same decision rules as crash recovery
949(`restack/publish.go`). In each step, it reads a fresh snapshot of origin, evaluates every write in
950the journal as described in [Recovery](#recovery), and pushes the next phase of writes marked
951`finish`. Each family advances one phase per step: first the atomic branch push, then the version
952updates from bottom layer to top, and finally the reports and replacement reports. The pass reads a
953full snapshot of origin again before every phase. So an integration request filed after a family's
954branch push pauses its version updates when the snapshot read for that phase shows the request. A
955request filed after that snapshot was read does not pause that phase. Each version push also reads
956its branch on origin once more, and pushes nothing unless the branch is still at the prepared head
957(`rebase/record.go`). If a push succeeds on origin but the reply to the client is lost, the next
958read sees the new ref on origin and marks the write `done`, so a version is never appended twice.
959One `settle` call runs at most eight read-and-push steps; any write still marked `finish` after the
960eighth step stays in the journal for the next pass.
961
962Once origin accepts a family's branch push, the pass works to give each recorded change in that
963family a report on origin that describes what happened. The initial reports built during planning
964say `complete`, which remains accurate when every change's new version is added. If any version is
965stopped or paused, the pass builds a replacement report for each change in the family. A
966replacement's result describes the whole family's versions: `partial` while any version of the
967family is not added, and `complete` once every one is. A replacement records the versions that were
968added on origin, and states in its refusal why each remaining version was not added. The restacker
969builds replacements from the journal's observation and the latest snapshot of origin, and saves them
970to the journal before pushing them. Recovery evaluates replacements like any other write, so a
971replacement whose push fails or loses its reply stays in the journal for the next step. The
972restacker skips building a replacement when origin's current report for that change already has the
973same content.
974
975Two kinds of change get no replacement:
976
977- a change whose record was deleted from origin, since the hook takes no report about a change it
978 does not record. Recovery stops that change's pending report for good, and its decision quotes the
979 report it did not push (`restack/recover.go`);
980- a change no report of which fits the report format, even with its own layer alone (see
981 [What a pass builds](#what-a-pass-builds)).
982
983If a family's branch push stops before moving any branch, the journal pushes no report for it. The
984restacker's planning reports on that family instead: in the same pass, when the family settles
985before the pass plans, or in the next pass. The restacker never writes the `superseded` result.
986
987Before pushing or building replacements in a step, the pass records in `journal.json` any branch
988push or version update that the latest read saw on origin (`accepted`). From then on, recovery
989treats those writes as `done` regardless of what happens to the branches or change records on origin
990later. Even if an author rewrites or deletes every branch the family moved, the journal remembers
991that the branches moved and which versions were added, and continues pushing the family's reports or
992replacements until origin accepts them.
993
994Families in the journal advance independently. At each step, every family with a write marked
995`finish` pushes its next phase, while any other family whose branches moved builds replacements if
996needed. A write that origin repeatedly refuses therefore delays only its own family. The pass
997retires finished families from the journal as soon as a read shows no writes to push and no
998replacements to build across any family, or on the eighth and final step of `settle` for the
999families that have nothing left to push or build then. A family is retired only when it was idle
1000during that step and is closed. A family remains open in two cases:
1001
1002- at least one of its writes is still marked `finish`;
1003- origin accepted its branch push, and at least one of its version updates is neither `done` nor
1004 finally stopped (`stop (final)`). For example, a version paused by a pending integration request
1005 keeps its family open, and its replacement reports say `partial` until that request resolves.
1006
1007A pending report or replacement is marked `finish` until a read sees it on origin, so a family with
1008a report still to push stays open. A family can still be retired without a report of each of its
1009changes on origin. That happens when a change's record was deleted from origin, and when no report
1010of a change fits; in both cases no write is left to finish. When all families have been retired, the
1011pass removes `journal.json` and deletes all `refs/valley-restack/*` retention refs from the scratch
1012repository.
1013
1014Any family that remains open stays in `journal.json` for the next pass. When a write pass plans new
1015work while a journal is still open, any family in the new snapshot that shares a change or a branch
1016with a journaled family is marked `wait`, and the pass builds no writes for it so its refs cannot
1017race the open family. Unrelated families are planned, built, and appended to the same journal. A
1018family paused by an integration request therefore holds back only its own changes and branches. A
1019family whose branch push stopped without moving any branch is retired from the journal and planned
1020again: by the same pass when the family settles before the pass plans, or by the next pass. If
1021`journal.json` cannot be read or validated, or belongs to a different repository, target, or
1022principal, every write pass refuses to proceed until the operator fixes or moves the file,
1023preventing a new journal from overwriting an unrecovered one.
1024
1025Checked by `restack-unit`, through the rendered hook:
1026
1027- after a landing, a two-owner stack is restacked once, each layer onto the new layer below it,
1028 while a conflicting change beside it is reported as `conflict` and skipped on the next pass;
1029- an integration request holds its family until the request has a current `stale` outcome;
1030- a journal interrupted after any step finishes on the next pass with one version per change;
1031- an owner's push to a restacked branch stops that change's version update and produces a `partial`
1032 replacement report;
1033- a replacement report refused by origin stays in the journal until a later pass pushes it, and one
1034 whose push reply is lost is seen on origin by the next read without being pushed twice;
1035- a replacement report refused by origin is still pushed after the author rewrites or deletes every
1036 branch the family moved;
1037- a report that origin keeps refusing holds only its own family in the journal, while a family
1038 restacked beside it is retired and restacked again after the next landing;
1039- two ready changes that name the same branch both wait while an unrelated change beside them is
1040 restacked;
1041- an integration request filed between the branch push and version updates pauses the versions and
1042 keeps the family open until released, while an unrelated change readied beside it is restacked;
1043- the project's `maxAutomaticVersions` cap holds a change that has reached the limit;
1044- `run` converges on a change readied after the landing and exits cleanly when stopped.
1045
1046Checked by `restack-e2e` as well: after the real integrator lands a change, write passes over an SSH
1047stand-in restack two owners' changes once each, including when the reply to the first record push is
1048dropped.
1049
1050### The restacker on the host
1051
1052`services.valley.restacker` runs one systemd service, `valley-restacker@<project>.service`, for each
1053project in `projects` (`nix/valley-host.nix`). Each service runs `valley-restacker run` as the
1054system user `valley-restacker` in its own group `valley-restacker`. That user belongs to no other
1055group and cannot read or write the bare repositories under `services.valley.dataDir` (`/srv/git` by
1056default) or the integrator's and worker's keys. Each project gets its own `0700` state directory at
1057`/var/lib/valley-restacker/<project>`, which is the only persistent path the sandboxed unit can
1058write (`ProtectSystem=strict`). The unit's private temporary directories (`PrivateTmp`) are writable
1059too, and do not outlive the service.
1060
1061The controller connects to the host's repositories over `localhost` SSH as its own principal. It
1062authenticates with the private key at `sshKeyFile`, which systemd reads as root and passes to the
1063service via `LoadCredential`, so the key file on disk can be readable by root alone. Before each
1064start, `ExecStartPre` writes the host's own SSH public keys into `<state>/known_hosts`, and the
1065controller's SSH client accepts only those host keys. The controller reads the instance floor from
1066`integrator.instanceProject` over the same local SSH connection, or from the local directory
1067`integrator.instancePolicy`. It verifies transfer statements using the same `known-signers` file,
1068`signer-projects` file, and `--integrator-name` as the integrator controllers.
1069
1070Enabling `services.valley.restacker` configures the local systemd units and creates the
1071`valley-restacker` Unix user and group. Enrolling the restacker's public key under its principal
1072(`restacker.principal`, default `valley-restacker`), granting that principal `restack`, and
1073provisioning the private key at `sshKeyFile` are each a **deployment choice**. Until the key is
1074enrolled and granted `restack`, `valleyhook` refuses the controller's version updates and reports.
1075
1076Checked by `restack-host-e2e` in a NixOS VM with the principal enrolled and the key provisioned:
1077
1078- after `main` advances, the service restacks a ready change as `valley-restacker`;
1079- the `valley-restacker` Unix user is denied access to `/srv/git`, the integrator's key and state,
1080 and the root-owned key file under `/run/valley-keys`;
1081- over SSH, the restacker's key can push a topic branch like any named principal, and the hook
1082 refuses its pushes to `main`, integration requests, integration outcomes, and change record
1083 deletions.
1084
1085## The check worker
1086
1087The check worker builds the checks a ready change requires before anyone approves it. It publishes
1088the evidence on `origin`, where approval reuses it instead of building it (see
1089[The valley command](#the-valley-command)). `valley-worker` runs one pass of it. It is
1090`valley-go work` (`status/worker.go`), packaged with this flake's git, cue and `attest` and the
1091verification schema (`nix/packages.nix`). It keeps no queue, lease or schedule, and nothing connects
1092to it. A host that turns the worker on runs a pass on a timer (see
1093[The worker on the host](#the-worker-on-the-host)).
1094
1095A pass builds evidence only for the projects named with `--repo`. It reads each project as
1096`valley pending --repo` does, so it can run from a clone of any project the host serves. To find a
1097project other than its clone's own, it also reads `policy/valley` on `main` of `origin` to find the
1098instance repository, then reads `refs/the-valley/projects` there. When that `main` holds
1099`policy/instance` and no `policy/valley`, `origin` is itself the instance repository. To load a
1100project's policy floor, it can fetch `main` of the owning valley that the project's `policy/valley`
1101names. For each project it follows approval's steps:
1102
11031. It lists the ready changes whose active version has not landed, and pins each one's active head.
11042. It derives the checks the head requires with the Go deriver, as `valley-go checks` does, over the
1105 head's merge base with `main`. Both policy layers come from `main`'s tip on `origin`, as approval
1106 reads them, never from the change.
11073. It reads the evidence `origin` holds for the head's tree, with the coverage rules approval uses.
1108 It leaves `command` checks to approval.
11094. It runs every `nix` check that is not covered in one batch, with `attest run --rev <head>` under
1110 the worker's own key. Then it pushes the one ref `attest` stored,
1111 `refs/the-valley/attestations/<tree>/<key-hash>`, and nothing else.
1112
1113The hook admits that ref as it admits any evidence. Every note must verify under the host's known
1114signers and name the ref's tree and key hash, whoever pushes it. The integrator then judges the
1115worker's notes like any other. Where the host restricts the worker's key to projects (see
1116[Evidence: attest and notes](#evidence-attest-and-notes)), `--repo` names those projects and no
1117others (**deployment choice**). The controllers count the worker's evidence nowhere else. The host
1118module refuses a host that runs the worker without that restriction.
1119
1120The evidence is about the head's tree, so it stays true if the change moves on while the batch runs.
1121The pass does not read the change's record again before it publishes. A superseded head's evidence
1122is published, and the next pass builds the new version.
1123
1124The attestation namespace admits creations only, so the worker never builds what it could not
1125publish. When `origin` already holds the worker's own ref for the tree and that ref lacks a required
1126check, the pass says so and builds nothing. Approval builds the rest under the operator's key
1127([bd-7b7d58f](../archive/.the-valley/bugs/bd-7b7d58f-same-tree-re-attestation-cannot-be-published.md)).
1128
1129A push whose reply is lost is not built again. If the push landed, the next pass finds the evidence
1130on `origin`. If it did not land, the ref is still stored in the worker's clone, and a later pass
1131pushes that same object again.
1132
1133After a failure, the same thing waits before it is tried again. A batch that fails waits 15 minutes
1134at first, and a push that fails waits one minute. Each failure in a row doubles the wait, up to 24
1135hours. A wait is measured from when the attempt ended, so a long build does not use up its own wait.
1136The waits are kept in `failures.json` in the worker's state directory, project by project. A batch's
1137key is its tree and the names of the checks it runs, the ones `origin` holds no evidence for. A new
1138key escapes the previous key's wait. A batch with the same key keeps the earlier wait, whichever
1139change it belongs to. A push is known by the object it publishes, so changes whose heads hold the
1140same tree wait together.
1141
1142A pass forgets the waits it did not meet in a project, but only for a project it read whole: every
1143ready change's checks derived and its evidence read. A pass over other projects, or one that could
1144not read this project, leaves its waits as they are.
1145
1146Passes that share a state directory take turns. Each holds an `flock` on the `lock` file there for
1147the whole pass. The pass also hands that open file to `attest`, so the lock stays held while a batch
1148runs, even when the pass that started the batch is killed. A second pass waits for all of it. Then
1149it reads `origin` after the first has published, or finds the ref the batch stored and publishes it.
1150
1151A read of `origin` that fails stops the pass, because a read that did not happen must not read as no
1152changes or no evidence. Anything else that goes wrong with one change is reported, and the pass goes
1153on to the next. The pass exits 1 when anything went wrong, with one exception. When `failures.json`
1154cannot be read or does not parse, the pass prints a warning on `stderr`, starts the record empty,
1155and goes on, and that alone does not make it exit 1.
1156
1157Checked by `valley-request`, which runs the packaged worker through the protected host's hook and
1158lands its evidence with the real integrator.
1159
1160### The worker's wakeups
1161
1162A move of a ref the worker reads starts a pass at once, without waiting for the timer. The host does
1163this with a wake directory, `worker.wakeDir` (`/var/lib/valley-worker-wake` by default). A writer
1164that moves such a ref creates the empty file `due` there, and `valley-worker.path` starts a pass
1165while `due` exists (`implemented`, `status/wake.go`, `nix/valley-host.nix`).
1166
1167The writers are these:
1168
1169- a push to one of `worker.projects` or to `integrator.instanceProject`, through the
1170 `post-receive.d/valley-wake` hook. A push that moves only `refs/the-valley/knots`,
1171 `refs/the-valley/integration-outcomes/*` or `refs/the-valley/integration-landings/*` marks
1172 nothing. Every other ref marks, the worker's own evidence included.
1173- the integrator, after a landing in one of those projects. A local landing runs no hook, so the
1174 controller marks `due` itself, right after the landing commits and before the mirror queue and the
1175 bus.
1176- `integrator publish-signers`, when it moves `refs/the-valley/signers`. A run that publishes
1177 nothing new marks nothing.
1178
1179A mark is created with `O_CREAT|O_EXCL`. A `due` that already exists is a mark already made, so any
1180number of moves leave one file. The directory never holds more than `due`, `claimed` and `lock`, and
1181none of them is a temporary file.
1182
1183A pass claims the mark before it reads any ref. It takes `lock` in the wake directory and renames
1184`due` to `claimed`. A move marked after the rename leaves a new `due` beside `claimed`. When the
1185pass ends, the path unit sees that `due` and starts the next pass. A mark made while a pass builds
1186is therefore never absorbed by that pass. The pass then reads the refs as they are, as a pass the
1187timer starts does.
1188
1189A pass acknowledges its claim by removing `claimed`, and only when it has handled what it read. It
1190has handled it when it read every project and every failure it met is a failed batch or push whose
1191wait it recorded. A policy that did not read, checks that did not derive, a read of `origin` that
1192failed, or a record that was not written leaves `claimed` in place. So does a pass that is killed.
1193Nothing watches `claimed`. It records that the last claim was not handled, and the next pass that
1194handles everything removes it. A pass never removes `due`.
1195
1196`due` is a prompt and nothing more. It carries no content, and nothing reads it as code, a path or a
1197ref. What a pass builds still comes from the change records, `main`, the floor and the evidence it
1198reads, and the pushes it makes still pass the pre-receive hook. A pass that a stale or duplicate
1199mark starts finds nothing to build and pushes nothing. It still reads every project's records,
1200policy and coverage. The worker's own evidence push marks `due` once, and the pass that follows
1201finds the evidence and builds nothing, so it stops there.
1202
1203The worker's timer remains the recovery scan (`implemented`):
1204
1205- A ref can move and its writer can fail to mark, for example when the writer is killed between the
1206 two. The timer's first pass after activation, and every later one, reads everything.
1207- A failed batch or push waits out its recorded wait (`firstBuildWait`, `firstPushWait`, doubled for
1208 each failure in a row). A mark does not retry it sooner: the pass finds it still waiting. It runs
1209 again in the first pass that starts after its wait is over. That pass starts at most
1210 `worker.interval` plus the timer's accuracy after the pass before it ended, so a retry comes
1211 within one interval, one accuracy window and one pass's runtime of its deadline.
1212- A pass that could not read `origin`, or its policy, is not retried at once either. The service has
1213 no `Restart=`, so the next pass is the timer's, or one a new mark starts.
1214
1215A pass that cannot claim `due` still reads and builds, and then exits `75`. The service restarts on
1216that status alone (`RestartForceExitStatus=75`), after `RestartSec` set to `worker.interval`. While
1217the service waits to restart, the path unit starts nothing. A wake directory that cannot be renamed
1218in therefore runs one pass per interval, rather than one pass after another.
1219`StartLimitIntervalSec=0` keeps a burst of passes from leaving the service refusing to start.
1220
1221The directory is `0770`, owned by `valley-worker` and the `valley-worker-wake` group, whose members
1222are `services.valley.user` and `integrator.user`. It has no sticky bit, so the worker can rename a
1223`due` made by either writer. It sits outside the worker's own `0700` state directory and outside the
1224repository directory, and the worker stays out of the repository group. The worker, the integrator
1225and the signer publisher each name it in `ReadWritePaths`.
1226
1227Where the timer still does the work (`not built`):
1228
1229- A worker project's `policy/valley` can name an instance on another host, or another instance
1230 project. A move there marks nothing on this host, and the timer's pass reads it.
1231- A mark made by a hand-written `post-receive.d` hook that fails before `valley-wake` runs, since
1232 the dispatcher stops at the first hook that fails.
1233- The integrator, the restacker and the identity compiler keep their own polling loops and timers.
1234 Their memos and caches do not wake on these marks.
1235
1236Checked by `worker-e2e`, which runs the real units on a host, and by `module-eval`. In `worker-e2e`,
1237with the timer stopped, a ready push starts a pass. So does a landing by the integrator's own
1238service while the project's mirror and the bus hang, and so does a floor landing in the instance
1239project, which is not a worker project. With the timer at its minute, a pass killed during a build
1240leaves its claim, and so does a pass that cannot reach the repositories over SSH. In both cases the
1241timer's next pass builds the change with no new mark. A failed batch is not built again before its
1242wait, however many marks and timer passes arrive. The claim and acknowledgement under concurrent
1243writers is checked by `TestWakeLosesNoMark` (`status/wake_test.go`), and the landing's mark ahead of
1244a hung bus by `integrator-e2e`.
1245
1246### The worker on the host
1247
1248`services.valley.worker.enable` runs `valley-worker` on a timer so ready changes have their Nix
1249checks built and signed before an operator approves them (`nix/valley-host.nix`). It is off by
1250default, and turning it on is a **deployment choice**. When enabled, the module creates
1251(`implemented`):
1252
1253- the `valley-worker` system user and group, with a `0700` state directory at `worker.stateDir`
1254 (`/var/lib/valley-worker` by default);
1255- `valley-worker.service`, a oneshot unit that runs one pass of `valley-worker` over
1256 `worker.projects` as `valley-worker`, inside `valley-builds.slice`;
1257- `valley-worker.timer`, which starts `valley-worker.service` 1 second after activation and waits
1258 `worker.interval` (`1m` by default, plus up to 1 minute of systemd timer slack) after each pass
1259 finishes before starting the next;
1260- `valley-worker.path`, which starts `valley-worker.service` whenever the wake directory holds `due`
1261 (see [The worker's wakeups](#the-workers-wakeups)).
1262
1263No target waits for `valley-worker.service`: boot and a switch never wait for a build
1264(`implemented`). A pass can start while a switch runs.
1265
1266Two passes that use the same state directory never overlap. systemd only starts the oneshot unit
1267while it is inactive, and the worker's own `flock` on `<stateDir>/lock` serializes any pass run by
1268hand with `--state <stateDir>`. A pass run with a different state directory takes a different lock.
1269
1270In the default configuration, the `valley-worker` user cannot read or write the repository directory
1271(`services.valley.dataDir`, `/srv/git` by default) on disk. The module makes that directory `0750`,
1272owned by `services.valley.user` and the repository group (`services.valley.group`, `git` by
1273default). It gives the worker its own primary group, `valley-worker` (`implemented`). This keeps the
1274worker out only while it is not a member of the repository group, as its primary group or as a
1275supplementary one. The module does not stop a host's configuration from adding that membership
1276(**deployment choice**). Instead of reading the directory, the worker connects to the host's own
1277`sshd` as the repository account (`services.valley.user`, `git` by default) over `localhost`, using
1278its own SSH key. Every push from the worker goes through `valleyhook shell` and
1279`valleyhook pre-receive` like any external client's push. The service runs in a git repository
1280without a checkout at `<stateDir>/origin` whose `origin` remote points at the local instance
1281repository (`<user>@localhost:<instanceProject>.git`, where `<user>` is `services.valley.user`).
1282From there, `valley-worker` discovers each project in `worker.projects` through
1283`refs/the-valley/projects`, just as `valley pending --repo` does.
1284
1285The service pins the worker's SSH connections to the local host. It writes the host's own SSH host
1286keys to `<stateDir>/known_hosts` under `localhost` and passes `HostKeyAlias=localhost` and
1287`StrictHostKeyChecking=yes` in `GIT_SSH_COMMAND`. If a project's `policy/valley` names this host by
1288its public hostname, such as `git@valley-host:valley.git`, SSH still verifies it against the local
1289host key. A server presenting an unrecognized host key fails verification. This host-key pin
1290restricts SSH connections only; it does not cut the worker off from the network. When the worker
1291fetches an instance floor named in `policy/valley`, `valley-go` sets
1292`GIT_ALLOW_PROTOCOL=ssh:git:https:file` in its own child environment (`status/list.go`), so the host
1293module cannot narrow that list, and `git://` and `https://` URLs still reach other hosts without
1294using SSH. Similarly, when Nix builds a check, it can fetch flake inputs over the network from the
1295URLs in `flake.lock`.
1296
1297The worker uses one Ed25519 key to sign check attestations under `worker.signerName` and to
1298authenticate its SSH connections (`implemented`). On its first start, `valley-worker.service`
1299generates `<stateDir>/key` (mode `0400`, owned by `valley-worker` inside the `0700` state
1300directory). It writes the key to `<stateDir>/key.new` first and renames `key.new.pub` and `key.new`
1301into place, so an interrupted start never leaves a half-written key. Alongside `<stateDir>/key`, the
1302service writes `<stateDir>/key.pub` (the OpenSSH public key) and `<stateDir>/verifier` (the
1303`known-signers` line for `worker.signerName`). Whenever `<stateDir>/verifier` is created or changes,
1304the service prints both public lines to the systemd journal. In normal operation, the service never
1305prints or copies the private key, and it does not place the key in a git repository or the Nix
1306store. Other unprivileged users on the host (`git`, `valley-integrator`, `nobody`) cannot read
1307`<stateDir>`. However, any process running as `valley-worker` — including the `git` and `nix`
1308commands a pass invokes — can read `<stateDir>/key`, and can replace `key` or `key.pub` in
1309`<stateDir>` (which the journal prints as it finds on disk). Checked by `worker-e2e`.
1310
1311A newly generated key has no access until the operator enrolls it (**deployment choice**). Until
1312then, `sshd` rejects the worker's connection and each pass stops at its first read of `origin`
1313(`implemented`).
1314
13151. Enable the build slice and the worker on the host, restrict `worker.signerName` in
1316 `integrator.signerProjects` to the exact list in `worker.projects`, and deploy the host
1317 configuration:
1318
1319 ```nix
1320 services.valley.buildSlice.enable = true;
1321 services.valley.worker = {
1322 enable = true;
1323 projects = [ "the-valley" ];
1324 signerName = "worker/attestations";
1325 };
1326 services.valley.integrator.signerProjects."worker/attestations" = [ "the-valley" ];
1327 ```
1328
13292. After `valley-worker.service` has run once, read the worker's public key and verifier line:
1330
1331 ```sh
1332 journalctl -u valley-worker -g "the worker's"
1333 sudo cat /var/lib/valley-worker/key.pub /var/lib/valley-worker/verifier
1334 ```
1335
13363. Enroll the key in the identity registry as its own `machine` principal with `signs` set to
1337 `worker.signerName` and a `git-push` grant, then land that change. On the next compilation,
1338 `valley-identity` adds the key to `known-signers` and to the repository account's
1339 `authorized_keys`:
1340
1341 ```cue
1342 "worker": {
1343 kind: "machine"
1344 keys: [{
1345 class: "ssh-ed25519"
1346 bound: "host"
1347 public: "ssh-ed25519 AAAA..."
1348 signs: "worker/attestations"
1349 }]
1350 grants: push: boundary: "valley-host-push"
1351 expires: "2027-06-01"
1352 }
1353 ```
1354
1355 On a host that does not use `services.valley.identity`, add `key.pub` to
1356 `services.valley.authorizedKeys` as an untagged string and add the `verifier` line to the file at
1357 `integrator.knownSignersFile`.
1358
13594. If other hosts share the same identity registry, add `worker.signerName` to
1360 `services.valley.integrator.signerProjects` on those hosts as well. Without an entry in
1361 `signerProjects`, a controller accepts a known signer's evidence in every project it serves.
1362
1363At NixOS evaluation time, `services.valley.worker` refuses to build unless all of the following hold
1364(`implemented`; checked by `module-eval`):
1365
1366- `services.valley.buildSlice.enable` is `true`.
1367- `services.valley.integrator.enable` is `true` and `services.valley.integrator.instanceProject` is
1368 set.
1369- `worker.projects` is non-empty and names only repositories this host serves.
1370- `worker.signerName` differs from the integrator's signing name.
1371- `integrator.signerProjects.<signerName>` lists the exact projects in `worker.projects`.
1372
1373Once enrolled in the identity registry with a `git-push` grant (**deployment choice**), the worker's
1374key authenticates as a named principal (`VALLEY_PRINCIPAL=worker`) on every repository the host
1375serves. `valleyhook pre-receive` allows a named principal without `approve` or `restack` grants to
1376push (`implemented`):
1377
1378- attestation refs (`refs/the-valley/attestations/<tree>/<key-hash>`), which are all the worker
1379 writes in normal operation;
1380- topic branches (`refs/heads/*`), which it can create, update, or delete;
1381- change records (`refs/the-valley/changes/main/<change-id>`) that name it as the owner;
1382- new commits on the plan graph (`refs/the-valley/knots`).
1383
1384A host that leaves the worker out of `protection.writers` keeps it from writing protected refs such
1385as `main`, and the hook enforces that deployment choice (`implemented`). The hook also stops the
1386worker from filing integration requests or updating another principal's change records.
1387`integrator.signerProjects` restricts which projects count the worker's signed notes; it does not
1388restrict which repositories the key can push to. An untagged key in `services.valley.authorizedKeys`
1389has no principal name, because its session leaves `VALLEY_PRINCIPAL` unset. So the hook allows it to
1390push only attestation refs and topic branches. A registry key can push to topic branches, its own
1391change records, and the plan graph, which a worker does not need. A permission that limits a key to
1392attestation pushes is **not built** (knot oc-6da5273). It must exist before a worker runs on more
1393than one host.
1394
1395The worker's builds are capped at one check build at a time, 4 CPUs, and 8 GiB of memory
1396(**deployment choice**). `valley-builds.slice` enforces the 4-CPU and 8-GiB limits across the Nix
1397daemon and the worker (see [The build slice](#the-build-slice)), and `valley-worker.service`
1398configures how the worker invokes Nix (`implemented`):
1399
1400- `valley-worker.service` runs inside `valley-builds.slice`, so the worker's own flake evaluation
1401 shares the slice's CPU and memory caps with the daemon's builds.
1402- `attest run` starts one `nix build` process per CPU available to it (`runtime.NumCPU()`).
1403 `valley-worker.service` pins the worker to a single CPU (`CPUAffinity=0`), so `attest` runs one
1404 check build at a time.
1405- `NIX_CONFIG` sets `max-jobs = 1` and `cores = 4`. The Nix daemon applies both settings per client
1406 connection, including connections from untrusted users. Each `nix build` therefore builds one
1407 derivation at a time and passes `NIX_BUILD_CORES=4` to the builder. `NIX_BUILD_CORES` is only a
1408 hint; the slice's `CPUQuota` is what enforces the CPU cap.
1409- `NIX_CONFIG` sets `builders =` and `accept-flake-config = false`, so the worker never delegates
1410 builds to remote machines and ignores `nixConfig` blocks in candidate flakes.
1411
1412Individual builds have no timeout. A check build that hangs holds the worker lock and blocks further
1413passes until an operator stops `valley-worker.service`.
1414
1415Checked by `worker-e2e` and `module-eval`. On a six-CPU VM, `worker-e2e` runs the worker against a
1416ready change with two required Nix checks and verifies that they build one at a time inside
1417`valley-builds.slice` with `NIX_BUILD_CORES=4`. `module-eval` checks the rendered systemd units and
1418`NIX_CONFIG`.
1419
1420## Policy
1421
1422A project's required checks come from three CUE layers, unified as
1423`floor & templates[type] & project` (`schema/verification.cue`):
1424
1425- **The schema**, `schema/verification.cue`, ships inside the `valley`, integrator and
1426 `valley-restacker` packages (`nix/packages.nix`).
1427- **The floor and templates** come from the owning valley's instance repository, at
1428 `policy/instance/*.cue` on its `main`. `policy/valley` names that repository. A value the floor
1429 writes as `true` is mandatory. A template value written `bool | *true` is a default a project may
1430 turn off. Every `*.cue` document directly in that directory is read, from a NUL-separated tree
1431 listing so git never quotes a non-ASCII name such as `naïve.cue` (`composed/composed.go`). Checked
1432 by `integrator-unit`.
1433- **The project layer** is `policy/project/*.cue`, read at the tip of the target branch.
1434
1435Both layers are read from integrated tips, never from the change being judged
1436(`integrator/policy.go`, `composed/composed.go`). A path class maps path globs to checks. A change
1437requires the union of the checks of every class one of its paths matches. A path no class matches
1438requires the `unclassified` checks. The integrator gets this answer by running `valley checks`,
1439which diffs with renames counted on both sides. Checked by `policy-deriver` and `cue-vet`.
1440
1441A layer's documents are the entries bash's glob `"$dir"/*.cue` names. The directory is a name and
1442never a pattern, so a directory named `policy[1]` is read, and `policy1` is not. A name beginning
1443with a dot is not a document. Checked by `derive-unit`.
1444
1445A glob matches bytes. `valley checks` derives in the C locale, whatever locale it is run in. So `?`
1446matches one byte, and `?.md` does not match `é.md`, whose `é` is two bytes. A path holding a byte
1447that is not UTF-8 matches a glob like any other path. Under a UTF-8 locale, bash's regular
1448expressions would match characters, and such a path would match no glob, not even `**`. The checks a
1449change requires would then depend on the locale of the operator's shell or the integrator's unit.
1450Checked by `derive-unit`.
1451
1452The derivation fails closed. A failed read of the diff, the target, a policy layer or the composed
1453policy makes `valley checks` exit non-zero and print no report. Without that, the failure would read
1454as an empty list, and an empty list derives a change that requires nothing. The integrator also
1455refuses output that is not a whole report: no header, no required-checks section, or a
1456required-checks heading with no checks under it. It believes a report of no changed paths only when
1457git agrees that the two trees are the same. Checked by `policy-deriver`, `valley-request` and
1458`integrator-unit`.
1459
1460A policy cannot forge a line of what it renders. `valley checks` reads the composed policy as lines
1461of tab-separated fields, and the policy's own strings are fields of those lines. A newline in one
1462would end its line and start a forged one, such as a looser carry mode for a class the floor pinned.
1463So the schema refuses control characters in path globs, and its name shape already keeps them out of
1464class and check names. `valley checks` also refuses a rendered line holding one. It refuses a second
1465line for anything the policy states once, such as a class's carry mode or a class's requirement of a
1466check. The integrator refuses a report that states one thing twice, such as two carry modes or two
1467rows for one check. Checked by `cue-vet`, `policy-deriver` and `integrator-unit`.
1468
1469A second deriver is written in Go (`derive/`). The check worker runs it, while `valley checks`,
1470approval and the integrator use the one in `bin/valley`. It reads the whole composed policy through
1471`composed.Read` (`composed/model.go`): every class's paths, requirements and carry mode, the
1472`unclassified` set, and each check's runner, cost and validity. It asks cue whether each requirement
1473is mandatory the way `valley checks` asks: it vets the layers with a document setting that
1474requirement to `false`. It reads a diff as `valley checks` does, with renames counted on both sides,
1475and keeps every path whole, whatever bytes it holds. It matches globs byte by byte, as
1476`valley checks` does. It reads a layer's documents as `valley checks` does. Checked by
1477`derive-unit`.
1478
1479`derive-unit` holds the two derivers to the same answer. It runs both over this repository's own
1480policy, the example policies under `examples/policy/`, and paths drawn from a fixed seed. It runs
1481`valley checks` under the C, `C.UTF-8` and `en_US.UTF-8` locales, with the layers in directories
1482named like glob patterns. Every global of the Bash derivation must equal the Go answer: the
1483documents composed, the changed paths, the classes matched, the carry mode, the unclassified paths,
1484and each required check's classes, pin, runner, attribute, command and cost. The two derivers differ
1485in three places, where `valley checks` is wrong:
1486
1487- `valley checks` splits a path holding a newline into two paths.
1488- A class added by refining `policy` may require a check no layer defines, because the schema's
1489 cross-check reads only the layers. `valley checks` derives under it, and fails on an unbound
1490 variable when a change touches that class. The Go deriver refuses the policy.
1491- `valley checks` merges a class named `unclassified` with the `unclassified` set, so each requires
1492 the other's checks. When both require one check, it refuses every derivation. The Go deriver keeps
1493 them apart.
1494
1495`valley-go checks` prints the Go deriver's answer as the `valley-checks/v1` JSON document. It takes
1496the schema, the floor's directory and the project layer's directory, and two commits:
1497
1498```sh
1499valley-go checks --schema schema/verification.cue \
1500 --instance policy/instance --project policy/project <base> <head>
1501```
1502
1503```json
1504{
1505 "schema": "valley-checks/v1",
1506 "base": "<sha>",
1507 "head": "<sha>",
1508 "policy_digest": "<sha256>",
1509 "paths": [{ "path": "docs/guide.md" }, { "base64": "c3JjL2NhZukucnM=" }],
1510 "classes": ["docs"],
1511 "unclassified_paths": [],
1512 "carry": "same-paths",
1513 "required": [
1514 {
1515 "name": "prose-format",
1516 "classes": ["docs"],
1517 "unclassified": false,
1518 "pin": "mandatory",
1519 "cost": "quick",
1520 "runner": "nix",
1521 "attribute": "prose-format"
1522 }
1523 ]
1524}
1525```
1526
1527- `paths` is every side of the diff, sorted bytewise. A path that is UTF-8 is `{"path": ...}`. Any
1528 other is `{"base64": ...}`, in standard base64, because JSON holds only UTF-8.
1529- `classes` is the classes a path matched. `unclassified_paths` is the paths no class covers.
1530- `policy_digest` is the integrator's policy digest of the same layers.
1531- Each required check lists the classes requiring it. `unclassified` is `true` when the
1532 `unclassified` set requires it. `pin` is `mandatory` or `default`. `attribute` is given for the
1533 `nix` runner, `command` for the `command` runner, and `validity` when the policy declares one.
1534
1535A failure prints nothing on stdout and exits 1. The document is a contract with a version, so a
1536change to the name or meaning of any field is a new version. Checked by `valley-go-unit`.
1537
1538A check also declares a `cost`, `quick` by default. A `slow` check takes minutes, or needs special
1539hardware such as KVM. `valley checks` reads the cost from the composition it derives from. After the
1540report it prints two lines, `quick:` and `slow:`, each listing the required checks of that cost.
1541`valley checks --names` prints the required check names alone, one per line, and `--cost quick` or
1542`--cost slow` keeps one set. The integration gate does not read the cost. Approving runs every
1543required check, and the integrator requires evidence for every required check, whatever its cost.
1544The cost changes neither which checks a change requires nor what the integrator accepts. Checked by
1545`policy-deriver` and `integrator-unit`.
1546
1547Each class also declares a carry mode. The mode says how far an approval of a change touching the
1548class carries when the change is rebased onto a target that has moved. An approval carries only when
1549the rebased change has exactly the files the approval saw. The mode adds a condition on the landings
1550since the approval:
1551
1552- `exact`: there were none, so the target has not moved.
1553- `same-class`: none of them touched a path in any class the change touches.
1554- `same-paths`: no further condition.
1555
1556A class writes its modes as a set of keys, such as `carry: {"same-class": true}`, in the same form
1557as `requires`. The class's mode is the strictest mode whose key is `true`, and `same-paths` when no
1558key is `true`. The layers compose as they do for checks. A floor's `true` cannot be turned off, a
1559template's `bool | *true` is a default a project may turn off, and a project may always add a
1560stricter mode. A change's carry mode is the strictest among the classes its paths match, and a path
1561no class matches is `same-paths`. `valley checks` prints the mode on a `carry mode:` line, and the
1562integrator refuses a report without a valid one. Checked by `cue-vet`, `policy-deriver` and
1563`integrator-unit`.
1564
1565A policy also sets `restack.maxAutomaticVersions`, a whole number of at least 1. It is 64 unless a
1566layer sets it. The restacker rebases a ready change when its target moves, and adds each result to
1567the change as a new version. The cap is how many versions of one change may have been uploaded by
1568the principal the restacker is configured to push as. The planner counts every version of the change
1569with that uploader, and holds a change whose next version would go over the cap. A host may impose a
1570lower ceiling of its own, outside the policy. The carry modes and the cap are part of the composed
1571policy, so the integrator's policy digest, a SHA-256 of the whole composition, changes when either
1572does. Approval carry reads the carry modes, and is not built yet, so nothing acts on them. The
1573restacker's planner reads the cap (`composed/composed.go`, `restack/plan.go`). Checked by `cue-vet`,
1574`integrator-unit`, `restack-unit` and `restack-e2e`.
1575
1576the-valley's own project layer is `policy/project/policy.cue`. It gives each part of this repository
1577a class that requires the checks reading that part. A Go module requires its unit tests, and its
1578end-to-end check where it has one. The CLI requires its script and status checks. The Nix, the
1579schemas and the policy require their evaluations and vets. The NixOS module also requires the
1580end-to-end checks that run what it renders, and two of those boot NixOS machines. A change to
1581`flake.nix` or `flake.lock` does not require them, so a nixpkgs bump boots no machine. A check's own
1582files, such as its script under `nix/checks/`, require that check. A change to documentation alone
1583requires the floor's `prose-format` and nothing else, which checks Markdown formatting and relative
1584links and heading anchors across `README.md`, `AGENTS.md` and `docs/*.md`
1585(`nix/checks/prose-format.sh`). A project layer that stopped composing would stop every derivation
1586once it landed, including the derivation of its own fix. So the `own-policy` check composes the
1587layer with the example floor before it lands. It fails if the layer names a check this flake does
1588not define, if a script under `nix/checks/` requires no check of its own, or if a docs-only change
1589would require more than `prose-format`.
1590
1591In the-valley's layer, four parts are `same-class`: the hook, the integrator, the signature
1592verifier, and the identity compiler with `schema/identity.cue`. The policy is `exact`: `policy/` and
1593`schema/verification.cue`. Everything else is `same-paths`. The tree holds no registry, grant or
1594secret data of its own. The ones under `examples/` and `attest/conformance/` are test fixtures. Two
1595classes exist only to set a mode, `identity-compiler` and `policy-authority`. They require no
1596checks, so the paths they cover require the checks of their other classes. `schema/verification.cue`
1597also requires the integrator's checks, because both compose a policy under it. The layer leaves the
1598restacker's cap at 64. `own-policy` holds each scope to its mode, holds the paths the two mode
1599classes cover to the checks of their other classes, and holds the cap to 64.
1600
1601The reasons for CUE here, and for the mandatory-versus-default encoding, are in
1602[dcr-0f5d9b1](../archive/.the-valley/decisions/dcr-0f5d9b1-cue-config-host-module.md) and
1603[dcr-f41f718](../archive/.the-valley/decisions/dcr-f41f718-declared-verification-policy.md).
1604
1605## Evidence: attest and notes
1606
1607`attest run` runs checks against a commit exported with `git archive` (`attest/run.go`,
1608`attest/check.go`). A `nix` check builds the flake check's derivation. A `command` check runs a
1609shell command in the exported tree. If every check passes, `attest` writes a statement per check,
1610signs it, and stores it under `refs/the-valley/attestations/<tree>/<key-hash>`.
1611
1612The `nix` checks build side by side instead of one after another. One nix evaluation names every
1613check's derivation. Each derivation is then built by a `nix build` of its own, with up to one build
1614per CPU running at once. Nix applies `max-jobs` and `cores` within each build, so that bound is how
1615many checks build at once. Each check's outcome is its own build's exit status, and a check that
1616failed keeps its own build's `stderr` as its log. So a failed build stays failed even when another
1617derivation produces the same output path, as two fixed-output derivations can. A check that does not
1618evaluate is an error for that check alone, and the others are still built. The `command` checks run
1619after the `nix` checks, one at a time. The statements are the ones a check built alone would get,
1620and nothing is published unless every check passed. Checked by `attest-e2e`, through
1621integrator-e2e's stand-in for nix, and against a real nix by the tests in `attest/run_test.go`. A
1622nix build has no daemon to build with, so those tests run under `go test` on a machine with nix, and
1623skip elsewhere.
1624
1625A statement is line-based text that opens with `the-valley/attestation/v1` (`attest/text.go`,
1626`schema/attestation.cue`). Its subject is the tree digest. A pure statement records the derivation,
1627its inputs digest and the output. An effectful statement records the environment and the time of the
1628observation. The envelope is a signed note: the `sumdb/note` format with Ed25519, implemented in
1629`note/note.go`. Checked by `attest-e2e`, `attest-conformance`, `attest-schema` and `note-unit`.
1630
1631The integrator reads evidence at the head's tree and verifies each note with `attest verify`
1632(`integrator/evidence.go`). It does not run the checks itself. A tree may hold several notes about
1633one check, one per signer. The integrator judges the check by one of them: the first note that
1634verifies, with the refs in byte order, whatever that note records. Until a note verifies, the last
1635one read stands, so a refusal is reported. This choice is `change.SelectNotes`
1636(`change/evidence.go`), and approval makes the same choice. A required check is met when its note is
1637signed by a known signer, says the check `passed`, and one of these holds
1638(`integrator/verdict/verdict.go`):
1639
1640- **A pure check, unmoved tree.** The landed tree is the attested tree. No inputs are compared.
1641- **A pure check, same inputs.** `attest inputs` on the candidate gives the same inputs digest and
1642 derivation hash. `attest inputs` evaluates the derivation and does not build it; evaluation can
1643 still build anything the flake imports from a derivation.
1644- **An effectful check.** No class that requires it changed between the base and the tip, and the
1645 evidence is younger than the check's `validity` window.
1646
1647Checked by `integrator-unit` (the verdict tests) and `integrator-e2e`.
1648
1649The integrator recomputes inputs only when the landed tree is not the attested tree. Then it asks
1650one `attest inputs` for every required pure check, which exports the tree once and evaluates the
1651checks together (`integrator/evidence.go`). It takes that answer only when the command exited `0`
1652and printed exactly the checks asked for, each in the expected form. Otherwise it drops the whole
1653answer and asks for each check alone, so a check that does not evaluate is stale alone and the
1654others still transfer. A single check is never asked for twice. The retry has a cost: when the
1655shared evaluation stops at an error nix cannot catch, a pass makes up to 2N+1 evaluations for N
1656checks, where asking for each alone makes N.
1657
1658Checked by `integrator-unit` (the closures tests) and `integrator-e2e` (scenarios 1, 2, 2b and 2d).
1659
1660The flake gives each check only the files it reads, and gives each package only the files its build
1661reads (`nix/checks.nix`, `nix/packages.nix`). An edit to any other file leaves a check's derivation
1662and inputs digest unchanged, so its evidence transfers. Building a package does not run tests. Each
1663Go module's unit tests run in its `*-unit` check, which builds the package again with its test files
1664and the files they read. Editing a test therefore changes only that `*-unit` check. Four checks test
1665what the NixOS host module renders without running the integrator, the identity compiler, or
1666valleyhook: `module-eval`, `mirror-e2e`, `bus-e2e`, and `init-e2e`. Those checks render the module
1667with stand-in scripts for the integrator, the identity compiler, and `valleyhook`
1668(`nix/checks/hosts.nix`), so editing one of those programs leaves the four checks unchanged.
1669`nix/tools/drv-churn.sh` measures which checks a representative edit changes.
1670
1671A signer can be restricted to projects. This is how a check worker's key can sit in the
1672known-signers file that every controller on a host shares, while its evidence counts only in the
1673projects it builds for. The controllers are given a signer projects file (`--signer-projects`,
1674rendered from `integrator.signerProjects`) that names each restricted signer and its projects
1675(`note/signerprojects.go`). In a project not listed for it, the controller classifies a note whose
1676only verified signers are restricted elsewhere as signed by an unknown signer, as it classifies a
1677stranger's note (`integrator/evidence.go`). A signer the file does not name is not restricted. The
1678push hook does not read the file, so it admits a restricted signer's evidence in every project, and
1679only the controllers refuse it. Approval reads the file the host publishes, so it does not skip a
1680check on such a note, and builds that check instead (see [The valley command](#the-valley-command)).
1681
1682A controller's own signature never makes a check's attestation count (`implemented`). When a change
1683lands, the controller countersigns the attestations it carried (`integrator/transfer.go`). That
1684countersignature vouches for the landing in the controller's own project, not for the check.
1685
1686Another controller's signature is known to be an integrator's only by declaration. Nothing in a note
1687marks a signature as a countersignature, and anyone can drop or reorder a note's signature lines. So
1688a host declares each other controller whose key its known-signers file holds, by listing that
1689controller's name in `integrator.signerProjects` with no project (`deployment choice`). A listed
1690name counts nowhere. A countersigned attestation copied in from that controller's project then
1691counts only through the signer who made the check claim. A host that leaves another controller's key
1692undeclared lets that controller's signature count as check evidence.
1693
1694A controller reads the file once, at start. Every name and project in it is printable ASCII with no
1695space, and the host module holds the list it renders to the same rule. A file that cannot be read,
1696names a signer twice, holds a word that is not printable ASCII, names a signer no verifier key can
1697carry, or names the controller's own `--name` stops the controller before it judges anything. The
1698last is refused because a restricted signer under the integrator's own name could also sign transfer
1699statements, which clients believe in every project. The publisher refuses the same files. A changed
1700list does not by itself re-judge a request whose answer is recorded: a request a narrower list held
1701back waits until its head, the target's tip or the stored evidence moves. Checked by
1702`integrator-e2e`, `integrator-unit`, `note-unit`, `module-eval`, `signers-e2e` and `restack-e2e`.
1703
1704Check definitions come from the change being judged. `attest` builds the flake checks of the
1705exported tree, so a change can edit the check it is judged by
1706([bd-eaefe82](../archive/.the-valley/bugs/bd-eaefe82-check-definitions-come-from-the-branch.md),
1707[ida-a9e274c](../archive/.the-valley/ideas/ida-a9e274c-mandated-checks-come-from-the-instance.md)).
1708
1709## Reviews
1710
1711A review is a reviewer's judgment of one version of a change. It approves the version or requests
1712changes to it, with a summary and notes on the files the reviewer read. Human and agent reviewers
1713write the same record. An agent's review also records how its judgment was produced. A review grants
1714nothing: only an integration request lands a change.
1715
1716The `review/` module defines the record, how a review is bound to what its reviewer read, and the
1717history reviews are kept in. Host admission is **not built**. The push hook has no rule for
1718`refs/the-valley/reviews/`, so it refuses every push there, and no `valley` verb writes or reads a
1719review. Checked by `review-unit`.
1720
1721**The record.** A review is one JSON file, `review.json`, in the schema `the-valley/review/v1`
1722(`review/review.go`). It holds:
1723
1724- `review_id`, 32 lowercase hex digits. The reviewer makes it once and keeps it through every retry
1725 of publishing the review.
1726- The change ID, the target, the review's name, such as `docs-style` or `operator`, and the
1727 reviewer, a principal.
1728- The `verdict`: `approve`, `request-changes` or `withdraw`.
1729- The binding, below, a summary, and notes.
1730- For an agent, its provenance: the harness, the model, digests of the generation settings and of
1731 the inputs, and the tokens the run reported.
1732
1733A note is anchored to a file the reviewer read. The anchor is the side (`before` for the base,
1734`after` for the head), the path, the blob the path held on that side, and an optional range of
1735lines, numbered from 1. A note on deleted lines is anchored to the before side.
1736
1737A `withdraw` review takes back an earlier review of the same change, named by its ID. It judges no
1738version, so it has no binding and no notes, and its summary gives the reason. Only the review's
1739reviewer or an operator may withdraw it. The project's rule for a blocking review is that a request
1740for changes stops counting only when it is withdrawn, or when a version with a different delta needs
1741a fresh review. A later approval does not clear it. Evaluating reviews by that rule is **not
1742built**.
1743
1744The parser is as strict as the change record's. It refuses invalid UTF-8, a key given twice, a field
1745the schema does not have (a key in another case among them), a field of another type, a string or
1746list past its bound, and anything after the object. A review is at most 64 KiB.
1747
1748**The binding.** A review records exactly what its reviewer read, so anyone with the objects can
1749recompute it (`review/binding.go`). It names:
1750
1751- the change record commit the reviewer read, and the version number and head that commit names;
1752- the target tip the version was judged against;
1753- the merge base of that tip and the head;
1754- the digest of the `valley-delta-v1` delta from the base to the head: the files the version
1755 changes, whole.
1756
1757When the tip and the head have no merge base, or more than one, there is no single base to compare
1758from. Then there is no binding, and so no review. `review.Bind` refuses to make one, and
1759`review.Verify` refuses a binding that names a base there.
1760
1761`review.Verify` recomputes every part. The record commit must name the version with the head. Given
1762the change's record ref, the record commit must be the record of its own `seq` on that ref's
1763first-parent history, so a review cannot bind a record written to look like one. Given the target's
1764tip, the bound tip must be on its history. The base must be the one merge base, and the delta must
1765have the bound digest. Each note's path must hold its blob on its side, with its lines inside the
1766file.
1767
1768Recomputing reads trees a pusher chose, so it runs within a budget of bytes, tree entries and time.
1769`delta.BetweenWithin` is the bounded form of `delta.Between`, which is unbounded. It asks git for
1770each object's type and size before its content. It counts every entry it visits, so a subtree that
1771two directories name counts twice, and it counts the bytes of every path it builds. git is killed at
1772the deadline. The first bound crossed ends the reading with an error that wraps `delta.ErrBudget`,
1773so a caller can tell a version too large to recompute from a binding that is wrong.
1774`delta.BetweenWithin`, `review.Bind` and `review.Verify` check the deadline once more before they
1775succeed, so none of them returns a result finished after it. A note's file has no size bound of its
1776own. It is read within the budget's bytes, and a file too large for them is the budget's refusal,
1777not the note's.
1778
1779**The history.** A change's reviews are kept at `refs/the-valley/reviews/<target>/<change-id>`
1780(`review/history.go`). Each commit holds one review, as the single file `review.json`, with these
1781parents:
1782
1783| Review | Parents |
1784| ------------------------------------ | ------------------------------------------------------------------- |
1785| The first review | The change record commit it binds |
1786| A later review that judges a version | The review commit before it, then the change record commit it binds |
1787| A withdrawal | The review commit before it |
1788
1789The first-parent chain lists every review in order. The last parent keeps each judged record
1790reachable, with the heads it names, after the change's record ref is deleted and the repository
1791pruned.
1792
1793A history is append-only. Each review ID in it is unique. A withdrawal names an earlier review of
1794the history, under the same review name, that is not itself a withdrawal and is not withdrawn
1795already. A history holds at most 512 reviews. Each review commit is at most 4 KiB and its tree at
1796most 1 KiB.
1797
1798An append is a compare-and-swap. `review.Build` writes the commit that appends a review to the head
1799the client read. `review.Publish` pushes it with `--force-with-lease`, so the push fails if another
1800review arrived first. The client then reads the new head and builds again, with the same review.
1801`review.Build` reports a review the history holds already, so a retry after an unconfirmed push
1802publishes nothing twice.
1803
1804`review.CheckAppend` decides one update of a history's ref, for the push hook to call; the hook does
1805not call it. It refuses a delete, and any update that is not one new review commit on the old head
1806by the table above. The review must name the pusher as its reviewer. The caller says, from its
1807grants, which review names the pusher may write under, and whether the pusher is an operator. A
1808review that judges a version under any other name is refused before its binding is read. A
1809withdrawal needs no grant of its name. It must be of the pusher's own review, unless the pusher is
1810an operator, who may withdraw any review. So a reviewer whose grant is revoked can still take back
1811their own judgment. A review that judges a version must be about a change the repository records,
1812and its binding must verify.
1813
1814## Identity
1815
1816The identity registry is CUE under `identity/` in the instance repository, read from a single commit
1817of its `main` (`identity/registry.go`, `schema/identity.cue`). It declares principals and
1818boundaries.
1819
1820- A principal has a kind (`human`, `machine` or `service`), one or more `ssh-ed25519` keys, and
1821 grants. A key may also sign attestations, under a name it declares, and may carry a YubiKey PIV
1822 attestation that the compiler verifies (`identity/attestation.go`).
1823- A grant names a boundary. A boundary has a kind: `git-push`, `registry`, `approve`, `restack` or
1824 `edge-read`. The kind `approve` is also accepted as `request`. A registry using either name
1825 compiles the same files. A grant at an `edge-read` boundary is a read grant and names the projects
1826 it covers. The identity compiler ignores read grants when writing its output files; the web
1827 publisher and `valley-read-coverage` read them directly from the registry (see
1828 [Read access](#read-access)).
1829- `anyone`, the reader who presents no credential, has its own top-level entry beside `principals`.
1830 It holds only read grants and has no keys.
1831- A machine, service or external principal must declare `expires`. From that day on, a successful
1832 compile leaves the principal out of every file. A compile that is refused keeps the previous
1833 files, expired entries included. Keys the host declares statically are outside the registry and do
1834 not expire.
1835
1836`valley-identity` compiles the registry every 5 minutes, as git (`nix/valley-host.nix`,
1837`identity/compile.go`, `identity/render.go`). It writes three files under
1838`/var/lib/valley-identity/`:
1839
1840- `authorized_keys.git`: one line per key of a principal with a `git-push` grant, tagged
1841 `environment="VALLEY_PRINCIPAL=<principal>"`. sshd reads it after the host's declared keys.
1842- `known-signers`: the keys that may sign attestations, for the hook and the integrator. The host
1843 also publishes it for clients (see [The signers publication](#the-signers-publication)).
1844- `grants`: one `request <principal>` line per holder of an `approve` grant, at a boundary of kind
1845 `approve` or `request`, and one `restack <principal>` line per holder of a `restack` grant. A
1846 principal holding both kinds is written once. The line keeps the name `request`, and the hook
1847 reads it as the `approve` grant.
1848
1849When asked, the compiler also writes the approval keys and the touch-always hardware approval keys
1850of human principals holding an `approve` grant (see
1851[Approval signers files](reference.md#approval-signers-files)). The host module does not write them,
1852and no gate reads them.
1853
1854The compiler refuses a registry where no principal holds a registry grant, where a key's hardware
1855attestation does not verify, where one key pushes for two principals, where a pushing key matches a
1856host-declared key under a different tag or none, or where a key that approves is also held by
1857another unexpired principal. Keys that neither push nor approve are not checked for collisions.
1858
1859The compiler reads every key of the registry's export spelled exactly as the schema spells its field
1860(`exactjson/`). A registry may reopen a schema definition and add a field to it, such as `Grants`
1861beside `grants`. Go's JSON decoder alone would read that field as `grants`. So the compiler refuses
1862a registry whose export holds a key that is not a field of the schema, spelled exactly. It also
1863refuses an export that holds a key twice in one object.
1864
1865The compiler reads the registry at `--ref` by that exact name, and reads the commit the ref held
1866from then on. An instance repository with no such ref fails the compilation, whatever other ref git
1867would take the name for (see
1868[Refs are read by their exact names](security.md#refs-are-read-by-their-exact-names)).
1869
1870The compiler computes everything before it writes anything, so a refused registry leaves the last
1871good files in place. Checked by `identity-e2e`, `identity-schema` and `exactjson-unit`, and by the
1872Go tests in `identity/identity_test.go`. Why identity is a governed registry, and why machine keys
1873expire, is in
1874[dcr-b87f6e8](../archive/.the-valley/decisions/dcr-b87f6e8-identity-is-a-governed-registry.md) and
1875[bd-8a591dc](../archive/.the-valley/bugs/bd-8a591dc-machine-credentials-never-expire.md).
1876
1877## sigverify
1878
1879`sigverify` verifies OpenSSH SSHSIG signatures and signed git tags against an `allowed_signers` file
1880(`sigverify/`). It exists because `ssh-keygen -Y verify` and `git verify-tag` never check the
1881hardware key's flags. A key file edited with `ssh-keygen -p -O no-touch-required` signs without a
1882touch, and those tools accept the signature.
1883
1884- The default class, `fido-sk`, takes only security-key signatures. It requires the user-presence
1885 bit. It also requires user verification under `--require-uv` or a `verify-required` signer line.
1886- The `tkey-signer` class takes an `ssh-ed25519` key marked as a TKey key in `allowed_signers`. The
1887 verifier cannot tell a TKey key from any other ed25519 key, so the mark is trusted at enrollment.
1888- Plain software keys pass only with `--allow-non-sk` or `--allow-class software`.
1889
1890Checked by `sigverify-unit` and `sigverify-e2e`, including a touchless-signature negative test.
1891Nothing in the-valley calls `sigverify` yet.
1892
1893## The valley command
1894
1895`bin/valley` is a shell script, also packaged with its schema (`nix/packages.nix`). Its `status`,
1896`ready`, `unready`, `withdraw`, `rebase`, `changes`, `pending`, `knot`, `plan` and `self-update`
1897verbs are a Go program, `valley-go` (`status/`), which the package puts on the script's `PATH`.
1898`valley-go` rebases with the rebase engine, a Go module of its own (`rebase/`), which also reads how
1899far each version has landed for its listings. The package stamps its version on the script, and
1900`valley self-update` keeps a user's `valley` at the tip of a branch (see
1901[Version and self-update](#version-and-self-update)).
1902
1903| Command | What it does |
1904| ---------------------------- | ----------------------------------------------------------------------------------------------------- |
1905| `valley pending` | Lists the ready changes not yet landed, then the branches no change is on, then the drafts. |
1906| `valley changes --json` | Prints every change in every state, across the host with `--all`, as `valley-changes/v1`. |
1907| `valley review <change>` | Shows a change, then offers `[a]pprove`, `[v]iew full diff`, `[r]eject`, `[s]kip`, `[b]ase` if stale. |
1908| `valley approve <change>` | Approves one head of the change, as `[a]pprove` does. `--head <sha>` names the head. |
1909| `valley rebase <change>` | Rebases the change's whole stack, as `[b]ase` does, and adds each rebased head as a new version. |
1910| `valley checks` | Reports the checks the policy requires of a change, grouped by declared cost. It runs nothing. |
1911| `valley status [--json] <c>` | Reads the request and outcome record for a change. `--json` prints the `valley-status/v1` object. |
1912| `valley ready [<branch>]` | Marks a head of the branch ready as a new version of its change, in the change's record. |
1913| `valley unready <change>` | Makes a ready change a draft, as its owner or the operator. |
1914| `valley withdraw <change>` | Marks a ready change or a draft withdrawn, as its owner or the operator. |
1915| `valley knot <verb>` | Reads and writes the project's plan graph (see [The plan graph](#the-plan-graph)). |
1916| `valley plan` | Shows the plan graph as a tree, and what waits on the operator (see [The plan view](#the-plan-view)). |
1917| `valley tail [subj]` | Subscribes to bus events. |
1918| `valley replay [dir]` | Publishes one `ref-updated` event per current ref. |
1919| `valley self-update` | Installs the tip of a branch of the-valley into the user's nix profile, once it passes a smoke test. |
1920| `valley --version` | Prints the version stamp: the CLI's version and the commit its package was built from. |
1921
1922`[a]pprove` is the operator's approval of a change. It reuses the evidence `origin` already holds
1923for the head's tree, and runs the other required checks with `attest` in a worktree of the head it
1924approves. Then one atomic push carries the new evidence refs and the integration request, with a
1925lease on the request ref. When the request already names this head, the push leaves the request ref
1926out. When there is no new evidence as well, there is no push. `[b]ase` rebases the change's whole
1927stack in a temporary worktree, and pushes every layer's branch in one atomic push, with a lease on
1928each. `[r]eject` deletes the remote branch after a prompt.
1929
1930Evidence on `origin` comes from a check worker (see [The check worker](#the-check-worker)) or from
1931an earlier approval. Approval skips a check only when the integrator will accept the same evidence.
1932Approval reads the evidence with `valley-go coverage` (`status/coverage.go`). It lists `origin`'s
1933attestation refs for the head's tree and fetches the objects they name. It reads the notes from
1934those objects byte for byte, as the integrator reads them. A local ref that was never published does
1935not count. A listing or a fetch that fails ends the approval, and nothing runs.
1936
1937Approval judges each required `nix` check by the note the integrator judges it by: the first note
1938for the check that verifies under the `known-signers` file the host publishes (see
1939[The signers publication](#the-signers-publication)). With no publication, nothing is reused.
1940
1941A note verifies here only when one of the signers `attest verify` accepts counts in this project, by
1942the rule the controllers apply (see [Evidence: attest and notes](#evidence-attest-and-notes)). The
1943publication's `signer-projects` file must let that signer count in the project. The signer must not
1944be the publication's integrator name, since the integrator's signature on a note is its
1945countersignature. Approval names the project after `origin`'s URL. The host's controllers name it
1946after their repository's directory, so the two agree when the URL ends in that directory's name. A
1947publication whose `signer-projects` is not a file, or does not read, is not used, so nothing is
1948reused.
1949
1950The check is covered when that note also meets all of these:
1951
1952- It is pure evidence for the check's name and its flake attribute.
1953- It records the check as `passed`.
1954- When `VALLEY_KNOWN_SIGNERS` is set, `attest verify` accepts it under that file too, by a signer
1955 that counts in this project. A local file can narrow what approval reuses, never widen it beyond
1956 what the host publishes.
1957
1958Comparing the attribute is stricter than the integrator's rule for an unmoved tree, which compares
1959none. Coverage decides only what approval runs. The integrator judges every note again when it
1960decides the request.
1961
1962A `command` check is never covered, so approval runs it again. Every check that is not covered runs
1963under the operator's own key, so its evidence goes to a ref of its own beside the worker's. When
1964every required check is covered, nothing runs and no key is needed. When `origin` already holds the
1965operator's own ref for the tree and a check still has to run, approval refuses before running
1966anything. The namespace is create-only, so the new evidence would have nowhere to go
1967([bd-7b7d58f](../archive/.the-valley/bugs/bd-7b7d58f-same-tree-re-attestation-cannot-be-published.md)).
1968Checked by `valley-request`, which also lands a fully covered approval and a partly covered one with
1969the real integrator.
1970
1971Approval also measures how long each required check took. `attest run` prints a `time` line after
1972each check, with its result, its duration, and whether nix found its output already built.
1973`[a]pprove` passes `attest run --timings`, which appends one JSON line per check to
1974`$XDG_STATE_HOME/valley/timings.jsonl` on the operator's machine (`attest/timing.go`). The line
1975names the repository, the change and version, the head, the check, its runner and declared cost, its
1976result, and `duration_ms`. A `nix` check's line also gives its evaluation time, `eval_ms`, which is
1977part of its `duration_ms`. The `nix` checks share one evaluation and build at the same time, so the
1978sum of a run's `duration_ms` is more than the run took. The log stays local and is not evidence:
1979nothing signs it or pushes it. A log that cannot be written is a warning, and approval continues.
1980Timing never holds approval up: anything at the log's path that is not a regular file is refused at
1981once, and a `time` line, warning or log line that cannot be written within a second is dropped. The
1982reference describes [the timing log](reference.md#the-timing-log) field by field.
1983
1984A change with a record is requested as `refs/the-valley/integration-requests/main/c-<change-id>`. A
1985branch no record is on is requested under its name with each `/` replaced by `-`. A branch whose
1986name maps to `c-<change-id>` is refused, by `approve` and by `status`: that name is the change's.
1987
1988When the checks fail under `[a]pprove`, approving the same head again can only fail again. So the
1989prompt then says approving needs a new head. It offers only `[r]eject` and `[s]kip`, plus `[b]ase`
1990where it is offered. `[a]pprove` comes back once the change is at another head, as it is after
1991`[b]ase`. A refusal that is not a check failure, such as a lost lease race, keeps the prompt as it
1992was.
1993
1994`review` reads the change's state from its record before it shows the change. A change that is not
1995ready says so on the first line shown, above its diff, and again in place of the usual prompt:
1996
1997- A draft:
1998 `nxvp v2 is a draft: its owner (alice) hasn't marked it ready, so it can't be approved yet.`
1999- A withdrawn change: `nxvp is withdrawn: there is nothing to approve.`
2000
2001The prompt then offers only `[v]iew full diff` and `[s]kip`. A change is often a draft because an
2002agent is working on it: an agent runner unreadies a change while its run works, and readies the new
2003head when the run finishes. `[a]pprove` would be refused. `[b]ase` is not offered either, since
2004adding the rebased head as a version would ready the change behind its owner's back. `[r]eject` is
2005not offered, because it records nothing on the change. It only deletes the branch, which the owner
2006may still be working on. The state can change while the review is open, so `[a]pprove` and `[b]ase`
2007still read the record again when they act, and refuse a change that is not ready. A branch no record
2008is on has no state, and is offered the usual prompt.
2009
2010`review` also shows the knots a change does. These are the knots in the project's plan graph whose
2011`changes` lists `valley:<project>/<change ID>` (see [The plan graph](#the-plan-graph)). The project
2012is origin's repository name, as `valley knot` reads it. The plan graph holds these links in project
2013storage; the change record tracks only the change's versions and state. `review` prints one line per
2014knot above the change's diff:
2015
2016```text
2017does oc-6335749 (open): Ready changes stay landable as main moves
2018```
2019
2020For a single change, these lines follow the first line of the comparison or diff, or the draft or
2021withdrawn notice when the change is not ready. In a stack, each layer's page shows that layer's
2022knots under its heading. Active knots come first, then terminal ones, each group in ID order.
2023`valley-go does` reads the graph once per review for every change in it (`status/does.go`). A
2024missing or unreadable graph shows no knots. `valley review -v` says why on stderr. Checked by
2025`valley-ready`.
2026
2027A change with a stack under it is reviewed one layer at a time, bottom first, each against the layer
2028below it. The layers are what `valley pending` lists under the change: the changes whose active
2029version has not landed, and the branches no record is on, whose heads the change's head contains.
2030`valley-go stack` lists them (`status/stack.go`). A withdrawn change under the change is a layer
2031too.
2032
2033- `review` first lists the layers. It warns of each lower layer that is a draft or withdrawn, since
2034 the integrator refuses to land it or anything above it. Its last line says how the review goes:
2035 read each layer and go on with `[n]`, and approving the top lands every layer.
2036- When the bottom does not fast-forward from `main`, the summary ends with a prompt, before any
2037 layer is paged, such as
2038 `one, at the bottom, does not fast-forward from main: [b]ase all 3 onto main, [s]top?`.
2039 - `[b]ase` rebases the whole stack, as `valley rebase` does. `review` then reads the stack again,
2040 lists it again, and pages the rebased layers. So the heads paged are the heads approved.
2041 - `[s]top` ends the review, and nothing is done.
2042 - When the rebase is refused or left unfinished, `review` says what happened and offers only
2043 `[s]top`.
2044- Each layer's page is headed `change <k> of <n>: <name> on <below>`. The page shows the layer's log
2045 and its diff from the layer below. Notes taken on it are kept under its own branch.
2046- After each lower layer, `review` asks a prompt that names the layer and its place, such as
2047 `two, 2 of 3: [n]ext layer, [a]pprove one and two, [v]iew full diff, [s]top?`.
2048 - `[n]ext layer` goes on to the layer above. It is the usual answer.
2049 - `[a]pprove` approves that layer at the head shown, exactly as reviewing it alone would. That
2050 lands it and every layer under it, and ends the review. The prompt names what it lands:
2051 `one alone` at the bottom, `one and two` at the second layer, and `the <k> up to <name>` from
2052 the third layer up.
2053 - `[v]iew full diff` pages the layer's log and diff against the layer below it, and asks again.
2054 - `[s]top` ends the review, and nothing is done.
2055- After the top, the prompt names the change and says that approving it lands every layer, such as
2056 `three, 3 of 3: [a]pprove all 3, [v]iew full diff, [r]eject three, [s]top?`. Only the top is
2057 offered `[r]eject`.
2058- When a layer's checks fail, its prompt says approving needs a new head and stops offering
2059 `[a]pprove`, as for a change alone.
2060- A layer that is not ready says so under its heading and in its prompt, as a change alone does.
2061 `[a]pprove` is not offered at that layer or at any layer above it, since approving one would land
2062 it. Each prompt above it says why in its place, such as
2063 `three, 3 of 3: it would bring two, change 2 of 3, which is a draft, so it can't be approved yet. [v]iew full diff, [r]eject three, [s]top?`.
2064 A top that is not ready is not offered `[r]eject` either.
2065- Every layer's notes are printed at the end, whatever the verdict.
2066
2067A change with nothing under it is reviewed against `main`.
2068
2069`valley approve` and `valley rebase` are for front ends, such as an agent runner's dashboard, that
2070show a change their own way. Each runs the same code as its key, so the checks, the request write
2071and the refusals are the same. `approve` exits non-zero when it refuses. `rebase` does not re-review
2072the result, and it leaves a stack that already fast-forwards from `main` alone. Checked by
2073`valley-cli`, `valley-request`, `valley-status`, `valley-ready`, `valley-changes`, `review-notes`
2074and `integrator-e2e`.
2075
2076`approve`, and so `[a]pprove`, refuses a head before any check runs when two things hold:
2077
2078- the head does not fast-forward from `main`;
2079- the commits it would bring, from its merge base with `main` to the head, include a version head of
2080 another change that has not landed.
2081
2082Such a head is a layer above the bottom of a stale stack. The refusal gives the command that rebases
2083the stack: `valley rebase <change>`. This is the project's choice, not a rule the integrator needs.
2084The integrator could land the head, as one commit recorded against its request alone. The changes
2085under it would then have no landing record of their own (see [Listing changes](#listing-changes)).
2086The checks would also run over a head that has to be rebased anyway. A stale head with no change
2087under it is approved as it is: the bottom layer of a stack, or a change alone. The integrator merges
2088it onto `main`.
2089
2090An approval of a change with a record binds one head, and the request names exactly that head:
2091
2092- `valley approve <change> --head <sha>` approves `<sha>`. It refuses unless `<sha>` is one of the
2093 record's version heads, active or not. A front end passes the head it showed, so what is approved
2094 is what was seen.
2095- Without `--head`, `approve` prints the active version's head and title and asks for confirmation.
2096 It does this only on a terminal, and refuses when it is not on one.
2097- `valley review <change>` shows the active version's head, and `[a]pprove` approves that head.
2098- A version may name no branch. `approve --head` files its head all the same, since the request
2099 names the head. `review` refuses such a change, because its notes and `[r]eject` act on a branch.
2100
2101`valley approve` approves a branch no record is on at its tip on origin, as the fetch left it.
2102`--head`, when given, must be that tip. `valley review` approves such a branch at the head it
2103showed. Just before it publishes, it reads the branch on origin, and refuses when it has moved off
2104that head, naming both heads. The operator reviewed the branch, and the commits it has moved to have
2105not been read.
2106
2107`valley rebase <change>`, and `[b]ase` in a review, rebase the change's whole stack. The verb is
2108`status/rebase.go`, and the rebase engine (`rebase/`) does the work. The stack is the change and the
2109layers `valley-go stack` lists under it. A change with nothing under it is a stack of one. In a
2110throwaway worktree, bottom first, each layer's own commits are rebased onto the rebased layer below
2111it, and the bottom's onto `main`. So each layer keeps its own delta. Commits under the bottom that a
2112lower change landed drop out, since the integrator landed them as one new commit and their content
2113is on `main`. So does a branch below such a change: it is no layer. The rebase reads that landing as
2114`valley changes` does, and verifies the transfer statement with the same signers (see
2115[Listing changes](#listing-changes)).
2116
2117The rebase refuses, and changes nothing, when the stack cannot move whole:
2118
2119- a change in it is not `ready`, records no branch, or has a branch that is missing on origin or not
2120 at its recorded head;
2121- a plain branch in it is the branch of a change that is not in the stack;
2122- two layers are on one branch;
2123- the commits to be rebased hold a merge, or a version head of a change that is not `ready` or is
2124 not in the stack. A rebase gives every commit a new ID, so without this check a draft's commits
2125 could enter the stack under IDs no record names. This is the integrator's rule for what a request
2126 may bring, applied before the rebase;
2127- it holds a change, and `valley.principal` is unset. The refusal gives the command that sets it.
2128
2129A conflict in any layer pushes nothing and records nothing, and the error names the layer. Otherwise
2130the rebase publishes in two phases:
2131
21321. One atomic push moves every layer's branch, each leased on the tip the rebase read. Every branch
2133 moves, or none does.
21342. Bottom first, each change's rebased head is added to its record as a new version, as the
2135 principal `valley.principal` names. Each is added with `valley ready --if-active <head>`, which
2136 writes the version only while the change is still `ready` at the head the rebase began with. The
2137 record ref is leased on the record that check read, so a change unreadied in the meantime stays a
2138 draft at its old head. A failure for one change does not stop the others.
2139
2140A change alone prints its new head. A stack prints a manifest: one line for each layer, with its old
2141and new head, whether its branch was pushed, and whether a version was added. For each change left
2142unfinished, the manifest gives the exact `valley ready --head … --change … <branch>` command that
2143finishes it, and the rebase exits non-zero. Running the rebase again on a change whose branch holds
2144a head no version records is refused by the recorded-tip check, which prints the same command. When
2145the push's outcome is unknown, as after a transport error or when origin does not report it, the
2146rebase says so, prints the manifest, and says how to check: `git ls-remote origin <branches>`.
2147
2148After a rebase, any ready change or plain branch outside the stack whose head contains a layer's old
2149head is still on that old head. A second stack on a lower layer is one. The rebase names each, with
2150the `valley rebase` that moves it, and does not move it. After `[b]ase`, the review goes on at the
2151new heads. An interrupt or a SIGTERM while the stack is being prepared kills git and any hook it
2152started, removes the worktree, pushes nothing, and exits 130.
2153
2154The rebase engine is a Go package that a program imports, such as a service that keeps ready changes
2155based on `main`. It never exits the process: every step that runs git takes a `context.Context`.
2156Cancelling it kills git and, for local commands, the process group it runs in, including any hook or
2157filter it started; `ls-remote`, `fetch` and `push` stay in the caller's process group so ssh can
2158read the terminal, and git is killed alone. It works on a family of layers rather than one chain.
2159Linear history gives each layer at most one base, so the layers on one bottom layer form a tree: a
2160chain such as A → B → C, or a shared lower layer such as A → B and A → C. Its steps are:
2161
21621. **Capture.** From one snapshot of origin, read the family that a change or branch belongs to: the
2163 chain under it, as `valley rebase` takes, or every layer connected to it. Every layer keeps its
2164 captured head, branch tip and record commit. Each layer has a state: `ready`, `draft`,
2165 `withdrawn`, a plain branch, `submitted` or `uncertain`. The caller decides from the states
2166 whether to move the family.
21672. **Check.** Refuse what cannot be rebased whole, with the refusals listed above.
21683. **Prepare.** Rebase every layer in a throwaway worktree and publish nothing. A shared lower layer
2169 is rebased once, and each layer on it is rebased onto its new head. A conflict or an empty layer
2170 anywhere refuses the whole family. The prepared heads stay reachable under local refs until the
2171 caller releases them. A Prepare that fails or is cancelled leaves no worktree and no local ref
2172 behind.
21734. **Publish.** Read origin again, then move every branch of the family in one atomic leased push.
21745. **Append.** Add each change's prepared head as a version, lower layers first, one change at a
2175 time, with the `ready --if-active` rule. The caller may stop between appends.
2176
2177Each step returns Go values rather than prose: a refusal with its kind and layer, and for each layer
2178its prepared head, what became of its branch, and what became of its record. A push's outcome is
2179read from git's porcelain report. So a push that origin refused is told apart from one whose outcome
2180is unknown, and a record write keeps the commit it tried to push. Only an outright refusal counts as
2181refused: `[rejected]`, which git decides before it sends anything, or origin's own
2182`[remote rejected]`. A ref that origin sent no status for, or a status the engine does not
2183recognise, leaves the outcome unknown, since origin may have taken the update. `valley rebase` words
2184these results for the terminal. Checked by `rebase-unit`, over real repositories and real pushes.
2185
2186`valley ready [--head <sha>] [--change <id>] [--if-active <sha>] [--stamp] [<branch>]` writes a
2187change's record (`status/ready.go`). The branch is the current one unless named. The head is
2188`--head` when given, and otherwise the branch's head on origin. Either way the head must already be
2189on origin. An agent runner passes `--head` with the head it pushed, so the version names exactly
2190that head. ready reads the existing record, if there is one, and adds a version. For a ready change,
2191it refuses a head equal to the active version's. It pushes the record ref with a lease on the value
2192it read, and prints the handle and version, such as `app nxvp v2 ready`. A draft or a withdrawn
2193change comes back by `ready` too. At the head of its active version, it is ready again at that
2194version, and the record commit's one parent is the record before it. At another head, it gains the
2195next version. The record names the principal from `git config valley.principal`. The host derives
2196the pushing principal from the key, and the client cannot ask it, so the hook refuses a record that
2197names anyone else. `--if-active <sha>` adds the version only while the change is `ready` at an
2198active version whose head is `<sha>`.
2199
2200ready takes the change ID from the first of these that has one:
2201
22021. `--change <id>`;
22032. the head commit's `change-id` header, as jj writes it, read from the commit object itself;
22043. a `Change-Id:` trailer in the head's message;
22054. a new ID, which it prints.
2206
2207A header and a trailer that disagree are refused, and so are malformed values. IDs on other commits
2208of the change are not read. ready also refuses a change whose commits, from the merge base with
2209`main` to the head, include a merge, or that has more than one merge base. `--stamp` amends the
2210local branch's head to carry the ID as a trailer, and pushes the branch with a lease. It only starts
2211a new change. It refuses a change that already has a record, so it never decides whose a change is
2212from `valley.principal`, which is only what the checkout claims. It also refuses a head that is
2213already on origin.
2214
2215A change is named by its full ID or by its handle. The handle is the shortest prefix of the ID, at
2216least four letters, that no other change recorded on origin shares. A change can also be named by
2217its branch. Every verb that takes a change takes all three (`status/changes.go`). `valley pending`
2218and `valley changes` write a local handle cache at `valley/handles` under the common git directory,
2219ready changes before drafts, with each change's handle, state, branch and title
2220(`status/handles.go`). The zsh completion script (`completions/_valley`) offers those handles with
2221their titles and never fetches.
2222
2223`review`, `approve` and `rebase` read a branch name further, whether it is written as `<branch>` or
2224`origin/<branch>`. They read every record on origin and look for the ones whose active version is on
2225that branch:
2226
2227- If there are none, the name is a branch.
2228- If there is exactly one, the name is that record's change, exactly as if its ID had been given.
2229- If there is more than one, the verb refuses and lists their change IDs, so that one can be named.
2230
2231So whether a change's record is read never depends on how the change is named. These three verbs
2232need the `valley-go` helper for that reason.
2233
2234`review`, `approve` and `rebase` act on a change with a record at a head its record names. They
2235never act on the branch's tip. A record's branch is only where its head is expected to be, and
2236anyone who can push the branch can move it, even in the same push as the record. `review` shows the
2237active version's head. `approve` files the request at exactly the head bound to it, wherever the
2238branch is. `rebase` and `review`'s `[r]eject` act on the branch itself, so they refuse when the
2239branch's tip on origin is another commit than the active version's head, and the refusal names both
2240commits. `[r]eject` deletes the branch under a lease on the recorded head. `approve`, `rebase`, and
2241`review`'s `[a]pprove` and `[b]ase` refuse a change whose record is not `ready`, and the refusal
2242names its state. `review` does not offer them for a change that is not ready when it shows it.
2243`valley-go resolve` gives these verbs the change's ID, handle, active version, recorded head,
2244branch, state and owner on one line, and `valley-go versions` lists every version, for `approve`.
2245
2246The record can change while one of these verbs runs. Another principal may unready or withdraw the
2247change, or ready a new version, while a review is open or the checks run. So `approve` reads the
2248record again before it runs the checks, and again before it files the request. It refuses when the
2249change is not `ready`, or when the head it approves is not a version head. A new version does not
2250stop it, since the request names the head that was approved. `rebase` reads each change's record
2251before it starts, and again just before it pushes. It refuses when a record has changed at all in
2252between. These client checks save a run that would come to nothing. The integrator makes the same
2253check on origin.
2254
2255A name that read as a plain branch can come to name a change while the verb runs. For example,
2256someone readies the branch, and then unreadies it, while a review of it is open. So before `approve`
2257files, it reads the original name again. If it names a change by then, the change must be `ready`,
2258and its active version's head must be the head `approve` began with. Before `rebase` pushes, it
2259reads each plain branch in the stack again, and refuses when one names a change by then.
2260
2261`valley unready <change>` and `valley withdraw <change>` write a record that changes the state alone
2262(`status/ready.go`). Either may be run by the change's owner or by the operator, who holds the
2263`approve` grant; the hook refuses anyone else. They take a change by any of its names, and print the
2264handle, the active version and the new state, such as `app nxvp v2 draft`. Each says when a request
2265for the change is pending, and `withdraw` warns, as [Change records](#change-records) describes.
2266`valley pending` lists the changes whose record says they are drafts in a section of their own, at
2267the head of each active version. A branch whose tip is a draft's head is listed only there.
2268
2269`unready` and `withdraw` stop an approval that begins after them, on the client. They do not always
2270stop one already under way there. An approval reads the record one last time just before it files
2271the request, and a change unreadied or withdrawn after that read is filed all the same. No client
2272can close this window. git compares only the refs a push changes, and the record ref is not one of
2273them, so a push cannot be made conditional on the record. The integrator narrows it: it refuses to
2274land any request that would bring a version of a change that is not `ready`, whatever the request is
2275named. It reads the records last just before it moves the target, so only a record written in the
2276moment between that read and the move is missed (see [The integrator](#the-integrator)).
2277
2278`valley status` reads a name as `approve` does. A change with a record is read at its active
2279version's head, under its request name `c-<change-id>`. A branch no record is on is read at its head
2280on origin, under the branch's request name. It takes one `ls-remote` snapshot of origin for the
2281decision, and fetches the objects it names, without moving a local branch or writing `FETCH_HEAD`.
2282It reads ancestry first: a head already in `origin/main` is integrated, even if recording the
2283outcome failed. An outcome record it does not recognise is `unknown`, never a success.
2284
2285### Review against the approved version
2286
2287`review` sets each version it shows against the change's approved version, so that approving a
2288rebased change again is a short, informed step. `valley-go compare` (`status/compare.go`) makes the
2289comparison, and `bin/valley` prints what it says. It is information only: it files no request and
2290skips no check, and `[a]pprove` is the same act whatever it says. A plain branch is never compared.
2291
2292The approved version is the greatest version below the one shown whose exact head one of these
2293names:
2294
2295- an integration request on origin for the change;
2296- an outcome record on origin for the change that says `land`, `stale` or `reject` at that head. The
2297 integrator judges only requests that were filed, so each of these is an approval it judged.
2298
2299Both are read under `c-<change-id>` and under the request name of each branch the change's versions
2300have named. A branch's request name is lossy: `a/b` and `a-b` are both `a-b`. A branch named
2301`c/<ID>` or `c-<ID>` maps to `c-<ID>`, which is reserved for the change with that ID, so it adds no
2302name. Any other branch's name is ambiguous when anything else maps to it: a branch named by any
2303version of another change, or a branch on origin that is not one of this change's. A record on
2304origin that does not read makes every branch's name ambiguous, since it could name such a branch. A
2305request or outcome under an ambiguous name is not evidence of approval. When the greatest version
2306with any evidence has only ambiguous evidence, the approved version is not known, and `review` is
2307ordinary review. It never searches back for an older version instead.
2308
2309This is not a complete approval history. Outcome records are overwritten, and a version records
2310neither the base it was approved on nor when. "Approved" means filed through the request protocol;
2311it does not name who approved.
2312
2313**The comparison.** `review` freezes `main`'s tip T as its fetch left it, and the two heads: H₀, the
2314approved version's, and H₁, the one shown. Each head's base is its merge base with T, and each must
2315have exactly one: B₀ and B₁. B₀ must be B₁ or below it on T's first-parent history. Otherwise there
2316is no comparison, and `review` says why above the full diff. Then `valley-delta-v1` from B₀ to H₀ is
2317compared with `valley-delta-v1` from B₁ to H₁. For a layer of a stack, the comparison is the layer's
2318own change's: the layer's ID, version and head, so a lower layer is set against its own approval.
2319Its delta from its base includes the layers under it, which approving it would bring.
2320
2321**valley-delta-v1** (`delta/`) is the change between two git trees, as whole files. It is the set of
2322paths whose entries differ. Each path has a pre-image and a post-image: its entry in each tree, or
2323absent. An entry is a mode (`100644`, `100755` or `120000`) and the SHA-256 of the content, as in
2324`valley-tree-v1`; a symlink's content is its target. A rename is a deletion and an addition. So
2325binary content, the executable bit, symlink targets, CRLF and final newlines are all bound, and
2326nothing is positional. The encoding is a header line, `valley-delta-v1`, then one line per path,
2327sorted bytewise: `<len> <path> <pre> <post>`. `<len>` is the path's byte length in canonical
2328decimal, and `<path>` is its raw bytes, which a reader takes by that length. Each image is `-` or
2329`<mode> <sha256>`. The digest is the SHA-256 of the encoding.
2330
2331The trees are read straight from git's object store with `git cat-file`. No checkout, filter,
2332attribute, diff driver, rename detection or replacement ref is involved. A tree is refused when a
2333checkout on case-sensitive Linux could not hold it faithfully: a submodule or any other mode, a name
2334that is empty, `.`, `..`, `.git` in any case, holds a slash or is longer than Linux's limit of 255
2335bytes, two entries with one name (as a file and a directory at one path are), an empty subtree,
2336entries out of git's order, an entry whose object is not the type its mode says, or a symlink whose
2337target is empty, holds a NUL or is longer than Linux's limit of 4095 bytes. Every entry of both
2338trees is checked, including those the delta leaves out. The parser is strict. It accepts exactly the
2339encodings two such trees can give, and refuses anything else, such as a length with a leading zero,
2340a duplicate or unsorted path, an invalid mode or hash, a symlink with the hash of empty content, or
2341a line whose images are equal. The one exception is a symlink whose target holds a NUL or is too
2342long: an encoding holds only the target's hash, which shows neither. Conformance vectors under
2343`delta/testdata/` fix the encoding and digest. A Python script there computes their expected results
2344from the specification alone, independent of the Go code. Checked by `delta-unit`.
2345
2346**What review shows.** When the two deltas are equal, `review` prints, and pages nothing:
2347
2348```text
2349<change> v<N> at <head>: clean restack of approved v<M> at <old-head>.
2350File delta unchanged. Base <old-base> -> <new-base>.
2351Landings between bases:
2352 <commit> <subject>
2353```
2354
2355The landings are every commit on T's first-parent history in (B₀, B₁], oldest first.
2356
2357When they differ, `review` pages this, and then `git range-diff B₀..H₀ B₁..H₁`:
2358
2359```text
2360<change> v<N> at <head>: changed since approved v<M> at <old-head>.
2361Review the range-diff before approving.
2362Base <old-base> -> <new-base>.
2363Files whose change differs from v<M>'s, as mode and SHA-256 of the content:
2364 <path>
2365 v<M>: <pre> -> <post>
2366 v<N>: <pre> -> <post>
2367```
2368
2369range-diff compares patches, and a binary file's patch says only that it differs, so range-diff can
2370call two commits equal when a binary file or a mode differs between them. The list of files shows
2371every such difference.
2372
2373The page ends with the shown version's own diff of those files, from B₁ to H₁, in git's ordinary
2374form. range-diff's hunks carry no line numbers, so a note written beside them has no anchor. A note
2375written beside a line of that last diff keeps its file and line.
2376
2377Either way, the commits from each base to its head are compared for their messages and their author
2378fields (name, email and date), apart from the files. A difference is shown under its own heading,
2379`Commit messages changed since approved v<M>.` or `Commit authors changed since approved v<M>:`,
2380whatever the files say. Every prompt after a change is shown offers `[v]iew full diff`, which pages
2381the whole diff and asks again. Checked by `valley-go-unit`, `valley-ready` and `review-notes`.
2382
2383### The status object
2384
2385`valley status --json <change>` prints one JSON object on one line. Front ends read it, so it is a
2386contract with a version. A change to the name or meaning of any field is a new version.
2387
2388```json
2389{
2390 "schema": "valley-status/v1",
2391 "change": "topic/one",
2392 "request_name": "topic-one",
2393 "target": "main",
2394 "target_tip": "<sha>",
2395 "head": "<sha>",
2396 "request": {
2397 "ref": "refs/the-valley/integration-requests/main/topic-one",
2398 "commit": "<sha>"
2399 },
2400 "outcome": {
2401 "decision": "stale",
2402 "head": "<sha>",
2403 "tip": "<sha>",
2404 "failed_at": null
2405 },
2406 "state": "stale",
2407 "change_id": null,
2408 "handle": null,
2409 "version": null,
2410 "title": null,
2411 "owner": null,
2412 "landing": null,
2413 "restack": null,
2414 "knots": []
2415}
2416```
2417
2418- `change` is the branch as given, without `origin/`. `request_name` names its integration request:
2419 the branch with each `/` replaced by `-`. For a change with a record, `change` is the branch its
2420 active version names, or its handle when that names none, and `request_name` is `c-<change-id>`.
2421- `target_tip` is `main` on origin. `head` is the branch head on origin, or for a change with a
2422 record, the head its active version records. When the branch is gone, `head` is the request's
2423 commit, or else the outcome's head, or else `null`.
2424- `request` is `null` when origin holds no integration request for the change. `outcome` is `null`
2425 when origin holds no outcome record.
2426- `outcome.decision` is `land`, `stale`, `reject`, `refused-not-ready`, `refused-merge`,
2427 `voided-withdrawn`, `failed` or `unknown`. A record that does not parse is `unknown`.
2428 `outcome.head` and `outcome.tip` are `null` unless they are object ids, and `failed_at` is `null`
2429 unless the decision is `failed`.
2430- `change_id`, `handle`, `version`, `title`, `owner` and `landing` are `null` for a branch no record
2431 is on. For a change with a record they are its ID, its handle, its active version's number and
2432 title, its owner, and the active version's landing evidence as [Listing changes](#listing-changes)
2433 decides it.
2434- `restack` is `null` for a branch no record is on, and for a change with no restack report.
2435 Otherwise it is `{"ref", "commit", "current", "report"}`: the report's ref, its report commit,
2436 whether it is current, and the report as [Restack reports](#restack-reports) gives it. `current`
2437 is true only while every ref the report observed holds what it says it held, as
2438 [Restack reports](#restack-reports) defines it: `main`, each layer's record ref and branch, a
2439 branch it saw missing still missing, and each blocking request at its `tip`. A report that is not
2440 current is historical. The sentences say which it is, and name a current conflict's command to
2441 rebase by hand.
2442- `knots` lists the knots that link the change, as [Listing changes](#listing-changes) gives them,
2443 and is `[]` for a branch no record is on. When the plan graph is missing or unreadable, `knots` is
2444 `[]`, and `valley status --json -v` says why on stderr.
2445- A reader that meets a decision or a state it does not know should treat the status as unknown.
2446- `state` is one of these:
2447
2448| `state` | What it means |
2449| ----------------------- | ------------------------------------------------------------------------------------- |
2450| `integrated` | The head is in `origin/main`. |
2451| `integrated-recorded` | A `land` outcome names this head. The change landed as a different commit. |
2452| `outdated-request` | The request names a different commit from the active version's head, or the branch's. |
2453| `outcome-unreadable` | The outcome record does not parse. |
2454| `not-requested` | No request stands for the change. An outcome from an earlier head may remain. |
2455| `awaiting-decision` | A request stands for this head, and no outcome names it. |
2456| `awaiting-new-decision` | The outcome names this head, but `main` or the evidence has moved since it was made. |
2457| `stale` | The integrator reported the change stale against the current `main` and evidence. |
2458| `rejected` | The integrator rejected the evidence. |
2459| `refused-not-ready` | The integrator refused it: a record of its head is not `ready`. The request stands. |
2460| `refused-merge` | The integrator refused it: its commits from the merge base include a merge. |
2461| `voided-withdrawn` | The integrator deleted its request because the change was withdrawn. |
2462| `failed` | The integrator failed while processing the request. The change may still have landed. |
2463
2464An error prints no object. The message goes to stderr and the exit status is non-zero. The errors
2465are an unreadable origin, an origin without `main`, nothing on origin for the change, and a change
2466name that is not UTF-8, which JSON cannot carry exactly. Checked by `valley-status`, and by the Go
2467tests in `status/` for the outcome record's parser.
2468
2469### Listing changes
2470
2471`valley changes --json` prints every change a repository holds a record of, in every state, as the
2472`valley-changes/v1` object (`status/list.go`). Front ends read it, so it is a contract with a
2473version, like the status object. `valley pending` is the view a person reads (`status/pending.go`).
2474
2475Both read one snapshot of origin for each repository they list. For each version of each change,
2476they decide its landing evidence (`status/inventory.go`). The first rule that applies is the answer:
2477
24781. `landed`: the version's head is on `main`'s first-parent history, and no commit on that history
2479 between the head and `main`'s tip is a merge. That is, `git rev-list --first-parent` from `main`
2480 lists the head, and `git rev-list --first-parent --merges <head>..main` lists nothing. The
2481 integrator never writes a merge, and it never puts a change's own commits on `main`. This rule
2482 matches a head that reached `main` by a direct write, or through an earlier integrator that
2483 landed a head commit directly. Ancestry alone is not enough: a merge can drop the content of
2484 either of its parents, so a head below any merge has not landed by this rule.
24852. `landed-recorded`: every one of these holds.
2486 - A commit `L` on `main`'s first-parent history, with no merge above it, carries a transfer
2487 statement whose `change` is one of the version's request names. The request names are the
2488 version's branch with each `/` replaced by `-`, and `c-<change id>`.
2489 - `L` has one parent. Every commit that the integrator writes has one parent.
2490 - The statement's `base` is the `valley-tree-v1` digest of the version's tree, and its signature
2491 verifies as the integrator's.
2492 - The integrator recorded landing this version's head as `L` under that request name. A statement
2493 about trees cannot name the exact head that landed, and the integrator's records do. When
2494 origin holds a landing record for the head, it must name `L`, the request name and the head. A
2495 landing made before landing records were written has none, and then the outcome record for that
2496 request name must say `land` with this version's head. Only the integrator writes either
2497 record: the hook refuses a push to them.
2498 - The integrator's merge of the version's head onto `L`'s parent gives `L`'s tree. The client
2499 recomputes it as `integrator/git.go` makes it:
2500 `git merge-tree --write-tree --merge-base=<merge base> L^1 <head>`. When the change's base is
2501 `L`'s parent, the merge base is `L`'s parent and `merge-tree` gives the head's tree.
2502
2503 A head with a landed tree on another parent is another delta. These rules keep it from borrowing
2504 the landing's evidence.
2505
25063. `uncertain`: a request for the version was consumed, or its outcome record says `failed`, or a
2507 landing record names its head. The integrator records a landing in the transaction that moves
2508 `main`, so only a landing made before it did, or one cut short inside git's commit phase, exists
2509 without its evidence. A request is consumed when its outcome record says `land` for this head and
2510 the request ref does not point at it.
25114. `not-landed`: otherwise.
2512
2513Neither record alone is proof of a landing. A landing record is kept per head, so a later landing
2514under the same request name leaves the earlier one `landed-recorded`. An outcome record is kept per
2515request name, and a later pass overwrites it. Take a landing made before landing records were
2516written, whose head is not on `main`'s first-parent history. Only its outcome record bound it to its
2517head. When a newer version under the same request name replaces that outcome record, the version
2518reads `not-landed`, not `uncertain`, and the overwritten record cannot be recovered. Its commits can
2519then count as work in the listing of a change whose head descends from it. Rebasing that change does
2520not guarantee their removal: commits replayed by the rebase can still count as work.
2521
2522The client checks a transfer statement with `attest verify`. The signature must be by the
2523integrator's signing name, under a key in a known-signers file. The client takes each of these two
2524values from the first source that gives it (`status/signers.go`):
2525
25261. a flag: `--known-signers <file>` or `--integrator-name <name>`;
25272. the environment: `VALLEY_KNOWN_SIGNERS` or `VALLEY_INTEGRATOR_SIGNER`;
25283. the serving host's publication at `refs/the-valley/signers` in its instance repository (see
2529 [The signers publication](#the-signers-publication)). The client finds the instance repository
2530 the way `--all` does, below.
2531
2532The client reads the publication only when a statement needs verifying, and only for a value that no
2533flag or variable gives. A value from a flag or a variable is used whatever the host publishes.
2534Before the two values are used, the client checks that the file reads as verifier keys and holds a
2535key under the name. When it does not, the command says so on stderr, naming where each value came
2536from, and verifies no statement. Without both values, no transfer statement is believed: a version
2537that only a statement could show landed reads as `uncertain` or `not-landed`, and the command says
2538so on stderr. `status`, `stack`, `rebase`, `brings`, `pending` and `plan` read a landing the same
2539way. Checked by `signers-e2e`.
2540
2541Without `--all`, the commands list the current repository. With `--all`, they list every project the
2542serving host publishes at `refs/the-valley/projects`. The client reads the instance repository's URL
2543from `policy/valley` at `main`'s tip on origin, never from a checked-out or pushed tree. A
2544repository whose `main` carries `policy/instance` is its own instance. Each project's URL is the
2545instance's URL with its last path segment replaced, so the transport, user and host are kept. A
2546repository other than the current one is read through a clone under `$XDG_CACHE_HOME/valley/repos`.
2547A clone is made in a temporary directory beside its place and renamed into place once its origin is
2548set, so a run killed while making it, git included, leaves no clone behind. A clone already in place
2549is used as it is when its configuration names its origin. One that does not was left half made by an
2550older version, and is set aside and made again. When discovery is unavailable, `--all` says so and
2551lists the current repository alone. `--repo <name>` limits either command to one project.
2552
2553`policy/valley` is data that anyone who can land on `main` controls, so the client is careful with
2554the URL it names. It refuses a URL that starts with `-`, which git would read as an option. It
2555refuses git's `<transport>::<address>` form, such as `ext::`, which runs a command. It refuses any
2556scheme other than `ssh://`, `git://`, `https://` and `file://`. A scp-like URL and a local path are
2557allowed. Every git call that takes such a URL passes `--end-of-options` first, and runs with
2558`GIT_ALLOW_PROTOCOL=ssh:git:https:file`, which overrides any `protocol.*.allow` in the caller's own
2559configuration.
2560
2561```json
2562{
2563 "schema": "valley-changes/v1",
2564 "host": "valley-host",
2565 "repos": [
2566 {
2567 "repo": "app",
2568 "url": "git@valley-host:app.git",
2569 "error": null,
2570 "changes": [
2571 {
2572 "change_id": "nxvpwlkmqtsrzyoukklnpmqrstuvwxyz",
2573 "handle": "nxvp",
2574 "target": "main",
2575 "owner": "alice",
2576 "state": "ready",
2577 "record": "<record commit>",
2578 "seq": 3,
2579 "active": 2,
2580 "versions": [
2581 {
2582 "n": 1,
2583 "head": "<sha>",
2584 "title": "the head's subject",
2585 "branch": "topic",
2586 "uploader": "alice",
2587 "landing": "not-landed",
2588 "landed_commit": null,
2589 "request": {
2590 "ref": "refs/the-valley/integration-requests/main/topic",
2591 "commit": "<sha>"
2592 },
2593 "outcome": {
2594 "decision": "stale",
2595 "head": "<sha>",
2596 "tip": "<sha>"
2597 }
2598 }
2599 ],
2600 "includes": ["<change id>"],
2601 "restack": null,
2602 "knots": [
2603 {
2604 "id": "oc-6335749",
2605 "type": "outcome",
2606 "status": "open",
2607 "title": "Ready changes stay landable as main moves"
2608 }
2609 ]
2610 }
2611 ],
2612 "branches": [{ "branch": "loose", "head": "<sha>" }]
2613 }
2614 ]
2615}
2616```
2617
2618- The object is one line. `host` is the host the instance's URL reaches, or origin's without
2619 `--all`, with its port and without its user. A local path reaches `localhost`.
2620- A repository that cannot be read has its message in `error`, and empty `changes` and `branches`.
2621 The others are listed all the same.
2622- Changes are keyed by repository, target and change ID, in the order of their IDs. `state` is
2623 `ready`, `draft` or `withdrawn`. `record` is the record commit.
2624- A handle is unique among every change listed, in every repository. Every record of a listed
2625 repository counts, so a handle also names its change within that repository alone. When one change
2626 ID is recorded in more than one listed repository, each of those entries has the qualified handle
2627 `<repo>:<prefix>`, such as `app:nxvp`. git refuses a colon in a ref name, so a qualified handle is
2628 never also a branch, and never reads as `origin/<branch>`. Every verb that takes a handle accepts
2629 the qualified form, in the repository it names, and refuses one that names another repository.
2630- `landed_commit` is the commit on `main` the version landed as: its own head when `landed`, the
2631 transfer statement's commit when `landed-recorded`, and otherwise `null`.
2632- `request` is the request filed at the version's head under either of its request names, or `null`.
2633 `outcome` is the outcome record about the version's head, or `null`; its `tip` is `null` unless it
2634 is an object ID. Its `decision` takes the values `valley-status/v1` gives it, the refusals
2635 included.
2636- `includes` lists the changes whose active head is a strict ancestor of this one's, nearest only.
2637 It is ancestry alone: approving this change lands their content too.
2638- `restack` is the change's latest restack report, or `null`, with the shape and the meaning of
2639 `current` that `valley-status/v1` gives it.
2640- `knots` lists the knots the change does: every knot in its repository's plan graph whose `changes`
2641 lists `valley:<repo>/<change ID>`, with its ID, type, status and title. Active knots come first,
2642 then terminal ones, each group in ID order. Links to other projects or to GitHub are ignored. Each
2643 repository's graph is read once per command. When the graph is missing or unreadable, every change
2644 gets `[]`, and `-v` says why on stderr.
2645- `branches` lists each branch on origin, other than `main`, that `main` does not reach, that is no
2646 change's active head, and that no landed version's head reaches. A version lands as one new
2647 commit, so `main` reaches neither its own commits nor a branch below them, though their content is
2648 on `main`. A branch name that is not UTF-8 is left out, with a warning on stderr.
2649
2650`valley pending` prints three sections. `ready` holds the ready changes whose active version is
2651neither `landed` nor `landed-recorded`. `branches` holds the branches no change is on. `drafts`
2652holds the drafts. When no ready change is at the top of a stack, one line says so in place of
2653`ready`. That line also says where any ready change inside another section's stack is. With `--all`,
2654each repository is headed by its name.
2655
2656Each entry is a block. Its first line is its name, with the age and author of its head: the handle
2657and version for a change, the branch for a branch, and the handle and version on its branch for a
2658draft. The lines under it give the title and what the entry adds to its base, in commits and diff. A
2659change's title is its record's, for the active version. A branch's title is the subject of its first
2660own commit. When a knot links a change, the first knot's ID follows the title, as
2661`stack-c: build on stack-b · oc-6335749`. The title is cut short to make room; the knot ID is kept
2662whole.
2663
2664An entry's base is the nearest other entry its head strictly contains, or `main` when there is none.
2665That is the ancestry `includes` reads. Its commits and diff are counted from the nearer of its base
2666and the head of any landed version its head contains, since that version's commits are not on `main`
2667and its content is. A stack is an entry no other entry contains, the top, then every entry the top
2668contains. Those entries are listed under the top at one indentation, however deep the stack is. Each
2669entry is listed before the entries it contains. Approving the top lands everything listed under it,
2670and the top says how many entries that is.
2671
2672Each listed entry is on the entry listed right after it. Where it is not, it says `on <base>`. That
2673happens at a fork, where two entries are on one base: the base is listed under only one of them, and
2674the other says `on <base>`. A stack is printed in the section of its top entry. A listed entry from
2675another section is marked with it, as `(ready)` marks a ready change inside a branch.
2676
2677A change also says `includes <handle>` for a change its head contains that is not an entry, such as
2678a withdrawn one, and `uncertain` when that applies. It says `restack:` and what its restack report
2679says when that report is current. A historical report is left out. `--checks` adds the checks each
2680change requires, by cost, as `valley checks` derives them. Within a section, the stack with the
2681latest commit comes first. Every line fits the terminal's width, or 80 columns when stdout is not a
2682terminal. A title is cut short with `…`, and a handle or a branch never is. On a terminal, names are
2683bold, unless `NO_COLOR` is set.
2684
2685`valley pending --json` prints `valley-pending/v1`. It has the shape of `valley-changes/v1`, with
2686the human view's sections. `changes` holds only the ready changes that have not landed. Each
2687repository has a `drafts` array as well, holding the drafts, with the same entry shape, including
2688`knots`. `branches` is the same as in `valley-changes/v1`. Its `includes` counts only changes that
2689have not landed.
2690
2691```text
2692ready
2693pppp v1 1 minute ago · alice
2694 stack-c: build on stack-b · oc-6335749
2695 1 commit · 1 file +5 −0
2696 approving it lands the 2 below too
2697 ├ mmmm v1 2 minutes ago · alice
2698 │ stack-b: build on stack-a
2699 │ 1 commit · 1 file +12 −3
2700 └ nxvp v1 3 minutes ago · alice
2701 stack-a: the first layer
2702 2 commits · 4 files +80 −1
2703
2704vvvv v1 1 hour ago · alice
2705 lost: a change whose request was consumed
2706 1 commit · 1 file +1 −0
2707 uncertain: it may have landed without its evidence being stored
2708
2709branches
2710loose 6 seconds ago · alice
2711 loose: work no record is on
2712 1 commit · 1 file +1 −0
2713
2714drafts
2715qqqq v1 on paused 3 days ago · alice
2716 paused: not ready yet
2717 1 commit · 1 file +1 −0
2718```
2719
2720`review`, `approve`, `rebase`, `status`, `unready` and `withdraw` read a branch name as the change
2721whose active version is on it. A change whose active version is `landed` or `landed-recorded` is
2722skipped, so a branch name can be used again once its change has landed, whether or not the branch
2723has moved since. A landing read wrongly could make a draft's branch read as a plain branch. Nothing
2724lands from that: the integrator refuses a request at a draft's version head whatever it is named.
2725Checked by `valley-changes`, by `valley-status` for restack reports, and by the Go tests in
2726`status/` for handles, URLs and the JSON writer.
2727
2728### Version and self-update
2729
2730The installed `valley` package carries a version stamp: the CLI's version and the commit nix built
2731it from, such as `0.1.0-97db597` (`nix/packages.nix`). `valley --version` prints it. A build from a
2732tree with uncommitted changes ends in `-dirty`, and a build with no known commit ends in `-unknown`.
2733The stamp is on the package's outer wrapper and in its name only. So the packages that the checks
2734and the integrator use do not change with every commit. The script run straight from a checkout says
2735it is unstamped.
2736
2737`valley self-update` keeps a user's `valley` at the tip of a branch of the-valley, without a system
2738rebuild. It is for a machine where `valley` is a working tool, such as an agent's guest. The machine
2739the operator approves from, and the valley host, keep the version their system configuration pins.
2740So a commit on `main` never changes the tool that approves or admits the next one.
2741
2742Self-update is a Go module (`selfupdate/`) that `valley-go` runs. It installs only a commit it has
2743built and smoke-tested, and it keeps the previous install to roll back to. Each run:
2744
27451. resolves the branch with `git ls-remote`;
27462. stops if the installed `valley` was built from that commit. The state file says which commit
2747 self-update last installed. Before its first install, the running `valley`'s stamp says;
27483. builds exactly that commit with nix:
2749 `nix build 'git+<repo>?ref=refs/heads/<branch>&rev=<sha>#packages.<system>.valley'`;
27504. smoke-tests the build, in an environment that carries nothing of the running `valley`'s. Its
2751 `valley --version` must report the commit, and its `valley help` must exit 0. Its
2752 `valley checks --names` must derive two known checks from a tiny policy the package ships
2753 (`examples/policy/smoke/`), which shows that the schema the build carries composes a policy;
27545. installs the build into the user's default nix profile, in place of the element named `valley`.
2755 The `valley` the system installs stays underneath as the fallback.
2756
2757The state file, `$XDG_STATE_HOME/valley/self-update.json`, records the current install, the previous
2758one, and the last failure. A commit that fails to build or to pass the smoke test is skipped until
2759the branch moves, or until `--retry`. `--rollback` reinstalls the previous build, and `--pin` and
2760`--unpin` freeze and release the current one.
2761
2762The repository and branch come from `--repo` and `--branch`, or from the user's git config,
2763`valley.selfUpdate.repo` and `valley.selfUpdate.branch`. The branch defaults to `main`. No
2764repository's own config is read. A repository is refused unless it is an `https://`, `ssh://`,
2765`git://` or `file://` URL, an absolute path, or `user@host:path`, with no character that nix's
2766flake-ref parser would rewrite. `user@host:path` is read under the login's home, as git reads it, so
2767`git@valley-host:the-valley` is `ssh://git@valley-host/~/the-valley` to both git and nix. Nix
2768fetches the repository as the user who runs self-update, with that user's ssh keys and config.
2769
2770The flake's home-manager module, `homeManagerModules.valley` (`nix/home-module.nix`), runs
2771self-update on a timer. `programs.valley.selfUpdate.enable` adds the `valley-self-update` user
2772service and a timer that starts it two minutes after boot and every five minutes after. `.repo`
2773names the repository, and `.branch` the branch. The service runs the first `valley` on its `PATH`:
2774the one in the user's nix profile, then the one the user's home-manager profile installs.
2775
2776Checked by `selfupdate-unit`, over a real repository with a stand-in for nix, and by
2777`valley-self-update`, which runs the real package's smoke test with a stand-in for nix and holds the
2778units the home-manager module renders. No check runs a real nix build or profile install, because a
2779check's build has no nix daemon and no writable store.
2780
2781## The plan graph
2782
2783A project's plan is data kept with the project, in its
2784[project storage](#the-source-and-project-storage): a graph of knots at one ref,
2785`refs/the-valley/knots`, in the project's repository. A knot is an outcome, a bug, an idea or a
2786question, in the node format `schema/node.cue` states. A question is something work can wait on
2787until it is answered. Its `owner` names who has to answer. The ref is a cord and each knot is tied
2788on it, as people "return to knotting cords and using them" in the Tao Te Ching's chapter 80. The ref
2789never touches `main`, and nothing that decides a change reads it: no check, policy, build or
2790approval. A knot that says something was approved or landed is not evidence of it.
2791
2792The ref has its own root history. Its first commit has no parent, and each later commit has the
2793previous tip as its one parent. Each commit is one operation, and its tree is the whole graph:
2794`outcomes/`, `bugs/`, `ideas/` and `questions/` hold one file per knot, named `<id>-<slug>.md`, and
2795`comments/<id>/` holds one file per comment on that knot, named `<stamp>-<op>.md`. A knot's ID is
2796its type's prefix and the first 7 hex digits of the SHA-256 of its slug. When that ID is taken, the
2797slug gains a suffix, `-2`, `-3` and on, until the ID is free.
2798
2799The knot module (`knot/`) is the one reading of the graph, shared by the CLI and the push hook. A
2800knot's frontmatter is a strict subset of YAML that the module owns, because Go has no YAML parser.
2801Keys come in a fixed order, titles and other free text are JSON strings, and lists are sorted flow
2802lists. The module refuses any file that does not read back byte for byte as it would write it, so
2803there is one way to write each knot. The form is YAML, so the knowledge lint reads it too. The
2804module also fixes the graph's limits as named constants: 5,000 knots, 20,000 comments, 64 KiB a
2805knot, 16 KiB a comment, and 32 changed files a commit.
2806
2807The module holds a graph to its layout, its fields and its edges. `parent` names an outcome in the
2808graph. `blocked_by`, on outcomes and bugs, names knots in the graph, or another project's knot as
2809`<project>:<id>`, which only a reader resolves. Neither kind of edge forms a cycle.
2810`graduated_into`, on a graduated idea, names an outcome in the graph, when the idea is taken on as
2811work, or a question, when it needs settling. `changes`, on outcomes, bugs and questions, links
2812changes, each as `valley:<project>/<change ID>` or as `https://github.com/<owner>/<repo>/pull/<n>`.
2813On an outcome or a bug, they are the changes that do its work. On a question, it is the change that
2814records its answer in the source's docs. `valley review`, `valley pending`, `valley changes` and
2815`valley status --json` read these links to show the knots each change does (see
2816[Listing changes](#listing-changes)). A question may link none, when its answer is a comment or an
2817outcome that does the work. An idea links none, because it graduates into an outcome or a question.
2818A knot is never deleted, and its `id`, `type`, `created` and `created_by` never change. A comment
2819file is never moved or deleted, so its ID — the filename without `.md` — never changes either. A
2820comment's body can be edited in place. An edit keeps the comment's `author` and path, sets `edited`
2821to the edit timestamp, and sets `edited_by` to the editing principal. On a push, a new knot's
2822`created_by`, a new comment's `author`, and an edited comment's `edited_by` must match the pushing
2823principal. Because every write adds a commit to `refs/the-valley/knots`, the ref's commit history
2824preserves every earlier text of a knot and its comments. The module and the CUE schema with the
2825knowledge lint are two validators of one documented schema, and `knot-agree` runs both over shared
2826fixtures and generated graphs and fails on any disagreement about the rules they share. The
2827canonical form, the layout, cycles and transitions are the module's alone, and `knot-unit` covers
2828them.
2829
2830`valley knot` is the graph's API: `new`, `show`, `log`, `list`, `set`, `link`, `unlink`, `edit`,
2831`comment`, `claim`, `unclaim` and `schema`, each with `--json`, and each with `--project` for
2832another project on the same host. A write reads the tip with one `ls-remote`, one fetch and one
2833batched read of the tree. It builds the new commit with git plumbing on a private index, never
2834touching the worktree, and holds the result to the rules the hook applies. Then it pushes with
2835`--force-with-lease=refs/the-valley/knots:<old tip>`. When the lease fails, the operation is formed
2836again on the new tip, at most 5 tries in all, after a random pause. `set`, `edit`, `link --parent`,
2837`claim`, `unclaim` and `comment --edit` compare before they write: a field another write changed
2838meanwhile, a claim another run holds, a claim that changed before `unclaim` lands, or a comment file
2839another edit changed is reported as a conflict, with exit status 3, and is never overwritten. `--if`
2840adds a comparison of its own, and a field it names that no knot has is refused before anything is
2841read. Each operation carries a `Valley-Op` trailer whose ID it keeps across every try. After a push
2842whose outcome it cannot tell, the CLI looks for that ID among the ref's latest 64 commits before
2843trying again, so no operation is recorded twice. A push the hook refuses is not tried again, and the
2844CLI prints what the hook said. Checked by `valley-knot`, against bare repositories with no hook, and
2845by `knots-e2e` through the hook.
2846
2847`valley knot log` and `valley knot show --at` read a knot's history from `refs/the-valley/knots`.
2848`log` lists every commit that added, changed, or deleted the knot's file or a file under
2849`comments/<id>/`, newest first in topological order down to the root commit. For each commit, `log`
2850parses the UTC committer time, committer name, and `Valley-Op` operation ID with `knot.ParseCommit`,
2851the same parser the push hook uses. `show --at <commit>` loads the graph tree at `<commit>` and
2852displays the knot and its comments at that point in history. `<commit>` must be the fetched tip of
2853`refs/the-valley/knots` or one of its ancestors. Derived fields still use current state: claim age
2854is computed against the current clock, and cross-project `<project>:<id>` blockers resolve against
2855each target project's current tip.
2856
2857The host decides every push to the ref in `valleyhook` (`valleyhook/knots.go`), with the knot
2858module. It matches `refs/the-valley/knots` exactly, so a ref that only begins with that name stays
2859in the closed namespace. Any named principal may write the graph, and an untagged key may not. Every
2860writer can change every knot in every project's graph. That fits a deployment where the writers are
2861the operator and the operator's agents. Any principal added later gets the same reach. Comment edits
2862are the one exception: only the comment's `author` or a principal with the `approve` grant (also
2863accepted as `request`) may edit an existing comment. The knot module checks that an edit keeps
2864`author` and sets `edited` and `edited_by`, while `valleyhook` checks the host's grants file to
2865decide whether the pushing principal may edit another principal's comment. The CLI validates all
2866other graph rules before pushing, but it does not read host grants, so the hook enforces comment
2867edit authorization on push. A push that creates the ref brings one commit with no parent. An update
2868brings one commit whose only parent is the old tip, so a push is one operation and the ref never
2869rewinds. No push deletes the ref; a graph that must be recovered is recovered on the host, and its
2870history stays the record. The commit's committer is the pushing principal, and its message ends with
2871a `Valley-Op` trailer.
2872
2873The hook reads the old and new trees with the bounded walk attestations use, with the graph's own
2874budget: trees 3 deep, 20,000 entries in one tree and 30,005 in all, a shared subtree counted each
2875time a tree names it, 2 MiB a tree, 64 MiB read in all, and 5 seconds. When the 5 seconds pass, the
2876hook stops the git process it reads with, and refuses the push. It refuses one whose check ends late
2877as well, even if every read began in time. The walk refuses any tree entry git does not write, since
2878the host does not run git's fsck on what a push brings. An entry's name is not empty, `.` or `..`,
2879and holds no slash, so a root entry named `ideas/<id>-<slug>.md` is refused. Its mode is exactly one
2880of git's five, so `040000`, which git reads as a tree, is refused too. Attestations are walked the
2881same way. The hook then holds the push to the module's rules. The layout is checked exhaustively:
2882directories of mode `40000`, each an entry of its own, and plain files of mode `100644` at the
2883layout's paths and nowhere else, no empty directory, no repeated name, valid UTF-8 with no control
2884character but newline and tab. Every knot and comment the commit adds or changes is read and
2885checked, against the old tree for the transitions, as the pushing principal for `created_by`,
2886`author` and `edited_by`. Every tip the hook admitted was valid, so it reads only those files and
2887the knots their edges reach, but it checks the counts from the listing on every push, and a cycle is
2888looked for along the edges of every knot the push changes. A push that also carries an invalid
2889change record, attestation or integration request is refused whole, like any push with one refused
2890update.
2891
2892Measured at the limits, on the development VM: an update adding a comment to a graph of 5,000 knots
2893and 19,999 comments takes the hook 0.65 s when the comments are spread over every knot, so the walk
2894reads a directory of comments for each, and 0.1 s when they are all on one knot. One changing the
2895knot at the head of a 5,000-knot `blocked_by` chain of knots of about 250 bytes, so the cycle walk
2896reads every knot, takes 0.33 s. A typical update of a graph of 100 knots takes 13 ms. The cycle walk
2897counts against the 64 MiB budget, so a chain of more than about 4,000 knots of 16 KiB each cannot be
2898extended until it is shortened; knots of a few KiB never come near it. Reading the largest graph
2899with `valley knot list` takes 0.4 s.
2900
2901`valley knot list --ready` and `show` derive what the graph does not store. A knot is ready when it
2902is an outcome or a bug, is active and unclaimed, and every knot it is blocked by is terminal. An
2903idea is never ready. Nor is a question: it is answered, not picked up as work. A question clears the
2904work waiting on it when it is answered or dropped. A blocker that ended abandoned, discarded,
2905superseded or dropped still clears, and the view marks it. A parent's progress is its terminal
2906children that are not abandoned, out of its children that are not abandoned. A claim older than a
2907day is flagged as stale. A write that moves a knot to a terminal status clears its claim in the same
2908commit, and a claim left on a terminal knot is ignored. `show` escapes control characters and
2909characters that reorder text before printing, though the graph holds none.
2910
2911### The plan view
2912
2913`valley plan` shows a project's plan graph as a tree (`status/plan.go`). It is the view the operator
2914reads to see where things stand without asking anyone. It reads the graph as the knot verbs do: one
2915`ls-remote`, one fetch and one batched read.
2916
2917The roots of the tree are the outcomes with no parent: the milestones. Under each root come the
2918knots whose parent it is, indented, and their children under them, at every depth. Within a level,
2919knots are in the order they were created, then by title, then by ID. Active knots with no parent
2920that are not outcomes are listed after the roots, under `no milestone`.
2921
2922Each knot shows a glyph for its state, then its ID and its title. These are the states:
2923
2924| Glyph | State | What it means |
2925| ----- | ------------- | ------------------------------------------------------------------------------------------------ |
2926| ○ | `ready` | An active outcome or bug, unclaimed, whose blockers are all terminal. |
2927| ◐ | `in-progress` | An active knot that is claimed, or whose status is `in-progress`. |
2928| ⊘ | `blocked` | An active knot with a blocker that is not terminal, or that cannot be read. |
2929| ◇ | `active` | Any other active knot, such as an idea or an open question. |
2930| ✓ | `done` | A terminal knot that finished: `done`, `closed`, `answered` or `graduated`. |
2931| ✗ | `abandoned` | A terminal knot that ended without finishing: `abandoned`, `discarded`, `superseded`, `dropped`. |
2932
2933An active knot also shows its claim: the run and the claim's age, marked `stale` past a day. It
2934shows its owner, and its blockers by ID. A finished blocker is left out. A blocker that ended
2935abandoned, discarded, superseded or dropped clears the knot, and is shown with how it ended. A
2936reference to another project's knot, `<project>:<id>`, in `blocked_by` or `target`, is shown as
2937written. It is marked `dangling` when that project's graph cannot be read or holds no such knot.
2938
2939A root shows its progress at the right margin, as a count and a bar. Progress counts every
2940descendant, not only the children: those that are terminal and not abandoned, out of those that are
2941not abandoned. A knot under an abandoned knot still counts. A root whose descendants are all
2942terminal is shown as one line.
2943
2944Three sections follow the tree:
2945
29461. `waiting on you` lists the active outcomes and bugs, and the open questions, that the operator
2947 owns. Then it lists the changes ready for approval, as `valley pending` selects them: each one's
2948 handle, version, repository and title. The operator is the principal
2949 `git config valley.principal` names, or the one `--owner` names. When neither names one, the
2950 section says how to name one, and still lists the changes.
29512. `in flight` lists the active knots that are claimed, the oldest claim first.
29523. `open residuals` lists the open bugs. Bugs with no parent come first. The others are grouped
2953 under their parent.
2954
2955Without a flag, `plan` shows the current repository's project. `--project` names another project on
2956the same host. `--all` shows every project the host publishes at `refs/the-valley/projects`, found
2957as `valley pending --all` finds them, each under its name. A project that cannot be read is reported
2958in its own section, and the others are shown all the same. A project with no graph gets one line
2959saying so, with the command that starts one: `valley knot new outcome "<title>"`. Lines fit the
2960terminal as `valley pending`'s do. On a terminal each glyph has a colour and each root's title is
2961bold, unless `NO_COLOR` is set.
2962
2963```text
2964○ oc-65866d3 Slice one lands 2/2 ██████████
2965
2966○ oc-1b5d5fe Slice two lands 2/10 ██░░░░░░░░
2967 ✓ oc-7125815 Read the graph once
2968 ◇ qn-f10cc70 Choose the glyphs · owner operator
2969 ◇ ida-9c65fa3 Colour the glyphs · owner operator
2970 ○ oc-c9066f1 Document the schema · owner operator
2971 blocked by oc-23ebda7 (abandoned)
2972 lands in app:oc-7654321 (dangling)
2973 ◐ oc-c23db6f Draw the tree · claimed by run-7 11h ago · owner alice
2974 ⊘ oc-70947c5 Golden files · blocked by bd-6e27560
2975 ✓ bd-b198e52 The tree misses a level
2976 ○ bd-6e27560 Width is off by one
2977 ◐ oc-a7dff99 Old work · claimed by run-0 13d ago, stale
2978 ⊘ oc-f982ae7 Ship it · blocked by app:oc-2172d43,
2979 ghost:oc-0123456 (dangling), oc-70947c5
2980 ✗ oc-23ebda7 Use a tree widget
2981
2982○ oc-24df5c7 A late milestone 0/0 ░░░░░░░░░░
2983
2984no milestone
2985 ○ bd-bee76f4 A stray report
2986 ◇ ida-162ff1b The graph as a web page
2987
2988waiting on you (operator)
2989 ◇ qn-f10cc70 Choose the glyphs · owner operator
2990 ○ oc-c9066f1 Document the schema · owner operator
2991 blocked by oc-23ebda7 (abandoned)
2992 lands in app:oc-7654321 (dangling)
2993 ready for approval
2994 pqrs v1 the-valley plan: the plan graph as a view
2995
2996in flight
2997 ◐ oc-a7dff99 Old work · claimed by run-0 13d ago, stale
2998 ◐ oc-c23db6f Draw the tree · claimed by run-7 11h ago · owner alice
2999
3000open residuals
3001 ○ bd-bee76f4 A stray report
3002 under oc-c23db6f Draw the tree
3003 ○ bd-6e27560 Width is off by one
3004
3005○ ready ◐ in progress ⊘ blocked ◇ active ✓ done ✗ abandoned
3006```
3007
3008`VALLEY_NOW` stands in for the clock of the knot verbs and of `plan`. It holds an RFC 3339 time. A
3009knot's `created` date, a claim's `claimed_at`, a comment's stamp and an edit's `edited` are written
3010at that time, and a claim's age is read against it. The checks set it, so the dates and ages they
3011compare are the same on every run. It lets a writer do nothing new: the hook holds none of those
3012times to its own clock, so a writer could record any of them by writing the file.
3013
3014Checked by `valley-plan`, which builds a graph with the real knot verbs and compares the text and
3015the JSON with golden files in `status/testdata/plan/`, and by the Go tests in `status/` for progress
3016and ordering.
3017
3018`valley plan --json` prints `valley-plan/v1`, an indented JSON document. The web export reads it to
3019build the plan the web server shows, so it is a contract with a version, like the status object. A
3020change to the name or meaning of any field is a new version.
3021
3022```json
3023{
3024 "schema": "valley-plan/v1",
3025 "now": "2026-10-15T09:00:00Z",
3026 "operator": "operator",
3027 "projects": [
3028 {
3029 "project": "the-valley",
3030 "error": null,
3031 "tip": "<sha>",
3032 "roots": ["oc-65866d3", "oc-1b5d5fe", "oc-24df5c7"],
3033 "knots": [
3034 {
3035 "id": "oc-c23db6f",
3036 "type": "outcome",
3037 "status": "in-progress",
3038 "active": true,
3039 "title": "Draw the tree",
3040 "created": "2026-10-02",
3041 "created_by": "operator",
3042 "parent": "oc-1b5d5fe",
3043 "owner": "alice",
3044 "blocked_by": [],
3045 "claimed_by": "run-7",
3046 "claimed_at": "2026-10-14T21:30:00Z",
3047 "changes": [],
3048 "path": "outcomes/oc-c23db6f-draw-the-tree.md",
3049 "comment_count": 0,
3050 "ready": false,
3051 "waiting_on": [],
3052 "cleared_by_ending": [],
3053 "dangling": [],
3054 "unresolved": [],
3055 "children": ["oc-70947c5", "bd-b198e52", "bd-6e27560"],
3056 "blocks": [],
3057 "progress": { "done": 1, "of": 3 },
3058 "claim": {
3059 "by": "run-7",
3060 "at": "2026-10-14T21:30:00Z",
3061 "age_seconds": 41400,
3062 "stale": false
3063 },
3064 "state": "in-progress",
3065 "edges": []
3066 }
3067 ],
3068 "waiting_on_you": {
3069 "knots": ["qn-f10cc70", "oc-c9066f1"],
3070 "changes": [
3071 {
3072 "repo": "the-valley",
3073 "handle": "pqrs",
3074 "change_id": "pqrstuvwxyzkpqrstuvwxyzkpqrstuvw",
3075 "version": 1,
3076 "title": "plan: the plan graph as a view",
3077 "head": "<sha>"
3078 }
3079 ],
3080 "changes_error": null
3081 },
3082 "in_flight": ["oc-a7dff99", "oc-c23db6f"],
3083 "open_residuals": [
3084 { "parent": null, "bugs": ["bd-bee76f4"] },
3085 { "parent": "oc-c23db6f", "bugs": ["bd-6e27560"] }
3086 ]
3087 }
3088 ]
3089}
3090```
3091
3092- `now` is the time the view was derived at: the clock, or `VALLEY_NOW`. `operator` is the principal
3093 read as the operator, or `null` when none is named.
3094- `projects` holds one entry for each project read: the current one, the one `--project` names, or
3095 with `--all` every project the host publishes, in name order, with a graph or without one.
3096- `error` says why a project's graph could not be read, and is otherwise `null`. `tip` is the commit
3097 `refs/the-valley/knots` points at, or `""` when the project has no graph.
3098- `roots` lists the IDs of the root outcomes, in tree order. `knots` lists every knot, in the order
3099 the tree lists them, terminal knots included.
3100- Each knot has the fields a knot has in `valley knot list --json`, with two differences. Its
3101 `children` are in tree order. Its `progress` counts every descendant, where `valley knot`'s counts
3102 only children, and it is set for every knot with children.
3103- Each knot has two fields more. `state` is one of the six states above. `edges` lists the knot's
3104 references to another project's knot, from `blocked_by` and from `target`.
3105- An edge has the `field` it is in, the `ref` as written, and its `project` and `id`. Its `state` is
3106 `resolved` when that project's graph holds the knot, and then `status` and `title` are the knot's.
3107 It is `dangling` otherwise. `why` is then `missing` when the graph was read and holds no such
3108 knot, and `unreadable` when the graph could not be read. `why`, `status` and `title` are `null`
3109 where they do not apply.
3110- `waiting_on_you.knots` lists the IDs of the knots that wait on the operator, in tree order, or is
3111 `null` when no operator is named. `waiting_on_you.changes` lists the changes ready for approval.
3112 It is `null` when they could not be read, and `changes_error` then says why.
3113- `in_flight` lists the IDs of the claimed active knots, the oldest claim first. `open_residuals`
3114 lists the open bugs in groups. The group whose `parent` is `null` holds the bugs with no parent
3115 and comes first. Each other group's `parent` is the ID of the knot its bugs belong to.
3116- `waiting_on_you`, `in_flight` and `open_residuals` are `null` for a project with no graph, or
3117 whose graph could not be read.
3118
3119Without `--all`, a graph that cannot be read prints no document. The message goes to stderr and the
3120exit status is 1.
3121
3122## Read access
3123
3124`readaccess/` evaluates whether a principal is authorized to read a project at a destination
3125(`readaccess/`, `schema/read.cue`, `schema/identity.cue`). Authorization requires two consents, one
3126from the project and one from the instance. Both consents must match (`implemented`).
3127`valley-web-publish` exports every project that has an authorized reader at its destination, whether
3128`anyone` or a named principal. Its authorization names each project's readers (see
3129[What reaches the edge](#what-reaches-the-edge)).
3130
3131- **The project's consent** lives in `policy/read/*.cue` on the project's `main`. It declares the
3132 project's name, its 32-character hex publication identity, and the set of principals in `readers`.
3133 An empty `readers` set authorizes no one.
3134- **The instance's consent** is a read grant in the identity registry at a boundary of kind
3135 `edge-read`. The boundary names one `destination`, the web server that receives the export. The
3136 grant's `projects` field names what it covers: `"all"` for every project, or a map from project
3137 name to the publication identity declared in that project's `policy/read`.
3138
3139**`anyone`** represents a reader who presents no credential. The registry stores `anyone` in its own
3140top-level entry with no keys, no external identity, and no expiry. `anyone` can hold grants only at
3141`edge-read` boundaries, cannot be the `genesis` entry, and cannot be a principal name under
3142`principals`. A project is public at a destination when both consents authorize `anyone` there. An
3143SSH key admitted without a principal tag pushes as no principal (`VALLEY_PRINCIPAL` stays unset),
3144whereas `anyone` applies only to unauthenticated edge reads.
3145
3146Each project has a single reader set. A read grant covers a whole project; there are no grants for
3147individual refs, knots, or files. Instance membership, push access, approval grants, and restack
3148grants confer no read access.
3149
3150The schema and evaluator treat every named principal the same, including the operator
3151(`implemented`). For `readaccess/` and `valley-read-coverage` to count a project as authorized for
3152the operator, the project's `policy/read` must name the operator and an instance grant must cover
3153the project. An instance can grant the operator `projects: "all"` while each project names the
3154operator in its own `policy/read` (**deployment choice**). The starter policy for a new project,
3155`examples/policy/read/new-project/read.cue`, names only `operator`. `valley-read-coverage` reports
3156which projects lack either consent for a given principal without modifying anything
3157(`readaccess/cmd/valley-read-coverage/`).
3158
3159A grant for a specific project binds both the project's name and its publication identity. If a new
3160project reuses an old project's name with a different identity, the old grant does not cover it. A
3161grant with `projects: "all"` covers any identity, and still requires each project's own consent. A
3162`policy/read` whose `project` field does not match the repository it was read from is invalid and
3163consents to nothing.
3164
3165### Reading the two consents
3166
3167`readaccess.Reader` reads both consents from git commits (`readaccess/read.go`). It reads a
3168project's `policy/read` from `refs/heads/main`, and it reads the registry from the instance
3169repository's registry ref (`services.valley.identity.ref`, default `refs/heads/main`). Both
3170`valley-web-publish` and `valley-read-coverage` resolve the registry ref once with
3171`readaccess.ResolveRef`, which runs `git show-ref` on that exact full ref name, and then peel the
3172resulting object ID to a commit and read from that commit. To read a directory, the reader walks the
3173tree with `git ls-tree` and reads each regular `*.cue` file with `git cat-file`, without checking
3174out a worktree. If a directory entry's name contains a slash, is `.` or `..`, or appears more than
3175once, the document is invalid and no files are copied. Otherwise, the reader writes the files into a
3176temporary directory with no `cue.mod` and runs `cue export --out json` with the schema.
3177
3178In CUE, a document can redeclare a schema definition, and unification can reopen a closed struct to
3179extra fields. In `schema/read.cue`, `readers` is closed with `close()`, which a redeclaration cannot
3180reopen. After `cue export` succeeds, the Go reader checks the exported JSON in two separate ways
3181(`readaccess/read.go`).
3182
3183First, it checks the shape. It decodes the JSON with `exactjson`, which refuses a key that is not a
3184field of the Go struct it is read into, spelled exactly, and a key that appears twice in one object.
3185The decode also refuses a value of the wrong JSON type. So a registry that reopens `#Anyone` cannot
3186hold `Grants` beside an empty `grants` and have the reader take it for `grants`. The parts of the
3187registry that read grants do not use are kept as raw JSON, and are checked only for a key repeated
3188in one object: `keys`, `external`, `genesisGovernance`, `externalGovernance` and `readScopes`.
3189
3190Second, it checks again the values it acts on. For `policy/read`, it checks that the project name
3191matches the repository the policy was read from, the publication identity, and every reader name.
3192For the registry, it checks every principal name and every `expires` date. Then, for each grant of
3193an unexpired principal and of `anyone`, it checks that the grant's boundary is declared, that
3194`anyone` holds grants at `edge-read` boundaries alone, and that a grant at any other boundary names
3195no `projects`. For a grant at an `edge-read` boundary, it checks the boundary's `destination` and
3196every project name and identity in the grant's scope.
3197
3198The Go reader does not check boundary names, grant names, boundary kinds other than `edge-read`,
3199principal kinds, keys, or what `genesis` must be. Those rest on `cue export` under
3200`schema/identity.cue`, which refuses a registry that breaks them.
3201
3202A document that is missing, exceeds its size bounds, or fails schema or Go validation consents to
3203nothing. If `git` or `cue` fails to execute, crashes, or times out, the reader returns an execution
3204error so the caller aborts rather than treating the failure as a withdrawn consent. A principal
3205whose `expires` date has arrived receives no read grants, matching the identity compiler. Only
3206grants at `edge-read` boundaries for the target destination are collected.
3207
3208`Grants.May` reports whether a project's `Consent` names a principal and the principal's `Grants`
3209cover the project and its identity. `Grants.Readers` returns the sorted list of principals for whom
3210both consents match (`readaccess/access.go`).
3211
3212### What reaches the edge
3213
3214`valley-web-publish` exports every project that has an effective reader at `--destination` and a web
3215URL (`implemented`, `web/cmd/valley-web-publish/valley.go`). An effective reader is a principal that
3216the project's `policy/read` names and that a read grant at `--destination` covers for the project,
3217including `anyone` (`Grants.Readers`). The pass reads the registry's grants for `--destination`
3218first. It then reads `policy/read` only for the projects that the host declaration places in a group
3219and that some principal's grant selects, either by naming the project or with `projects: "all"`. A
3220project with no group has no web URL and is not exported. When a grant names such a project, the
3221pass logs a warning on `stderr` (see [Groups and web URLs](#groups-and-web-urls)). A project with no
3222effective reader is not exported either.
3223
3224The policy path signs an authorization that names each exported project with its effective readers
3225(`implemented`, `web/cmd/valley-web-publish/policy.go`). `anyone` is among them only when the
3226project's policy names `anyone` and a grant to `anyone` covers the project's identity. The content
3227pass exports the same projects into one shared export for all readers of the edge. For each exported
3228project, the export and its git bundle carry the project's reader view: every knot and comment in
3229its plan graph, its ready changes, and `main` with its commit history (see
3230[Web export](./reference.md#web-export-the-valleyweb-exportv2)). The export records no reader
3231access; the separate signed authorization names who may read each project, and the edge serves only
3232what that authorization allows (see [The authorization stream](#the-authorization-stream)). A
3233project leaves the edge when it loses its last effective reader. Removing one of several effective
3234readers drops that reader from the project's authorization and leaves the project on the edge for
3235the others.
3236
3237When building `export.json`, the publisher strips derived details about projects that are not
3238exported (`implemented`, `web/export/project.go`). A reference to a project that is not exported
3239keeps its identifying reference fields but loses its title, status, and other resolved details,
3240while a reference to an exported project keeps those details. The export's own projection is a
3241storage boundary. At request time, `valley-web` strips the derived details of any exported project
3242that the requesting reader may not see (see [Each reader's view](#each-readers-view)).
3243
3244`valley-web-publish` can write the authorization and the export to `--out` or send them over HTTP to
3245a receiver URL. `valley-web-receive` receives the upload into its store, staging it with
3246`Store.Stage` and activating it with `Store.Activate` (`web/export/store.go`; see
3247[The receiver](#the-receiver)). `valley-web` serves only `GET` and `HEAD` from the store
3248(`web/server/server.go`). A missing or invalid registry grants nothing, so the pass authorizes no
3249project and builds an empty export. A missing or invalid `policy/read` consents to nothing, so that
3250project is not exported. If the pass cannot read the instance repository or the schemas, it aborts
3251before signing anything. If it cannot read a selected project, the policy check is incomplete: the
3252pass sends the authorization and then fails before building or uploading an export.
3253
3254Checked by `readaccess-unit`, which reads both consents from real commits under the real schemas
3255(`readaccess/read_test.go`, and `TestCoverage` in `readaccess/cmd/valley-read-coverage/main_test.go`
3256for `valley-read-coverage`), by `web-unit` (`TestVisibilityNeedsBothConsents`, which checks each
3257authorization's readers, `TestAProjectMadePrivateLeavesTheReceiver`,
3258`TestAGrantSpelledAnotherWayIsRefused` and `TestPrivateSentinelsNeverLeave`), by `web-server-unit`
3259(`TestThePublishersOutputServesEachReader`, over the real publisher's output, which injects each
3260reader's principal and uses no link or session), by `web-push-e2e`, which exports a project two
3261named readers may read, keeps one with no effective reader off the edge, and signs a named reader in
3262with a link to read that project, by `cue-vet` and `identity-schema`, which test both schemas
3263against rejected examples, and by `identity-e2e`, which compiles the example registry containing
3264read grants and `anyone` against golden files. Unbuilt pieces are listed under
3265[Not deployed or not wired yet](#not-deployed-or-not-wired-yet).
3266
3267### The authorization stream
3268
3269Read access at the edge travels in a separate signed document, the authorization, independent of the
3270content export (`implemented`; see
3271[Web authorization](./reference.md#web-authorization-the-valleyweb-authorizationv1) for the format).
3272Authorizations and content exports are two streams that share one signing key, one receiver, and one
3273store. Each stream has its own sequence, its own locks on the publisher and the receiver, and its
3274own admission rules.
3275
3276- **Single writer.** Only the publisher's policy path signs authorizations
3277 (`web/cmd/valley-web-publish/policy.go`). Every pass runs the policy path before any content work,
3278 and `--policy-only` runs the policy path alone. While holding `<state>/authorization.lock`, the
3279 policy path reads the instance's read grants and each selected project's `policy/read`, allocates
3280 the next sequence number, and signs the authorization. Holding one lock across the check,
3281 allocation, and signing guarantees that an authorization with a larger sequence number always
3282 comes from a later policy check. The policy path releases the lock before sending the
3283 authorization to the receiver.
3284- **Monotonic sequence counter.** The authorization sequence comes from a counter in
3285 `<state>/authorization-sequence`, which the publisher syncs to disk before using it. Because the
3286 counter never reads a clock, a backward clock jump cannot give a new authorization an earlier
3287 sequence number. The receiver admits an authorization by its sequence number alone and ignores its
3288 age, so a valid withdrawal with a higher sequence number is always accepted. The receiver refuses
3289 any delayed or replayed authorization whose sequence number is at or below the stored sequence. If
3290 the receiver already holds a higher sequence number — for example, after the publisher's state is
3291 restored from an older backup — the policy path re-evaluates the policy and signs a new
3292 authorization above the receiver's sequence number instead of resending an earlier signature. A
3293 higher sequence alone does not make a check fresh, so the retry keeps no access that it could not
3294 check.
3295- **Kept access needs the receiver's agreement.** When a project's policy cannot be read, the policy
3296 path starts from the readers and publication identity that the last acknowledged authorization
3297 recorded for that project. It keeps only the readers that a current grant still covers for that
3298 identity, and it adds no reader without reading the project's consent. It names the acknowledged
3299 authorization's sequence as the new authorization's `basis`. The receiver stores an authorization
3300 with a `basis` only while its stored authorization has that exact sequence, and refuses it as
3301 `stale-basis` otherwise (`web/export/authorization.go`). After a `replayed` or `stale-basis`
3302 refusal, the publisher's record is out of date, and the retry keeps nothing it could not check. A
3303 publisher state restored from an old backup therefore cannot sign a withdrawn grant above the
3304 receiver's withdrawal.
3305- **Content uploads confer no access.** A content manifest records each project's publication
3306 identity, ref tips, and bundle digest, without any reader list. The receiver builds repositories
3307 in a generation only for projects named in the stored authorization, and `valley-web` serves a
3308 project only while the stored authorization names that project and its publication identity. A
3309 delayed content upload, whatever its sequence number, cannot grant access or restore a withdrawn
3310 project.
3311- **Independent receiver lock and slots.** The receiver stores an authorization under a dedicated
3312 lock and request-slot pool without running repository checks, plan-graph reads, or generation
3313 sweeps (`web/export/authorize.go`). A stalled content upload or a long commit cannot delay a
3314 withdrawal. When the receiver replies `200`, the authorization is already synced to disk.
3315- **Checked on every request.** `valley-web` reads the stored authorization at the start of every
3316 request and checks it again after rendering the response. If a new authorization arrived while the
3317 response was rendering, `valley-web` discards the response and renders it again. `valley-web`
3318 holds `serving.lock` shared across that last check and writing the response headers. The receiver
3319 takes `serving.lock` exclusively to rename a new authorization into place and replies only after
3320 releasing the lock (`web/export/authorize.go`, `web/server/server.go`). So a response whose
3321 headers are written after the receiver replies was checked against the new authorization, without
3322 restarting `valley-web`. Responses whose headers were written before finish normally. A request
3323 waits for `serving.lock` only until its deadline, or until its reader goes away, so a receiver
3324 stopped while it holds the lock makes requests answer `503` and writes nothing they rendered. When
3325 the authorization is missing or invalid, `valley-web` serves no projects.
3326- **Withdrawal and repository pruning.** A new authorization omits a project once the project has no
3327 effective reader left. `valley-web` then hides that project starting with the next request. Once
3328 no reader holds the active generation, the receiver deletes the project's git repository from that
3329 generation and omits it from future activations. The signed `export.json` file remains unchanged
3330 on disk, so the withdrawn project's plan text stays in the active generation until a later
3331 activation replaces and deletes that generation. Repository deletion runs in the background and
3332 retries on the next authorization, activation, or receiver startup without delaying the
3333 authorization reply. Under the authorization lock, each prune reads the stored authorization
3334 again, decides what to delete, and renames those repositories away, so a prune never deletes a
3335 repository that an acknowledged authorization names again.
3336- **Policy-check freshness.** Every pass sends an authorization, even when no content changed, and
3337 records in `checked` the time of the last complete policy check. Web pages display that timestamp
3338 as "Policy last checked …" alongside the export's collection time, and mark a page stale only when
3339 the policy check is old. An incomplete policy check reuses the previous authorization's `checked`
3340 time so the timestamp on the page does not advance. A recent `checked` time shows that the
3341 publisher can reach the edge, while `collected` shows the age of the exported content.
3342
3343Checked by `web-unit` (`TestVerifyAuthorizationSteps`, `TestAnAuthorizationWithABasisNeedsItStored`,
3344`TestStoreAuthorizesWhileTheActivationLockIsHeld`, `TestStorePrunesAWithdrawnRepository`,
3345`TestAPruneKeepsWhatAnAuthorizationNamesAgain`, `TestTheAuthorizationSequenceIsDurable`,
3346`TestTheAuthorizationCounterSurvivesFailedWrites`, `TestARestoredStateRestoresNoWithdrawnAccess`,
3347`TestAReceiverThatLostItsStateGetsTheReadableGrants`, and `TestUploadSkipsAnUnchangedDigest`), by
3348`web-receiver-unit` (`TestAnAuthorizationIsAdmittedBySequence` and
3349`TestASaturatedUploadLeavesValleyWebServing`), by `web-server-unit`
3350(`TestAuthorizationIsReadOnEveryRequest`, `TestAResponseIsHeldToTheAuthorizationWhenWritten`,
3351`TestAWithdrawalWaitsForAResponseItsCheckAdmitted` and `TestAServingLockWaitEndsWithTheRequest`),
3352and by `web-push-e2e`. That check uses `--policy-only` to withdraw both a public project and a
3353project readable only by named principals while a content upload is stalled on the receiver's
3354activation lock, and verifies that the stalled upload restores neither project's authorization or
3355repository. It also verifies that a policy check that cannot read a project's policy keeps only the
3356stored readers that a current grant still covers, and that removing one of two effective readers
3357leaves the project on the edge for the remaining reader.
3358
3359### One pass, one instance
3360
3361A publisher pass reads one instance: the instance repository at `--instance-repo`
3362(`web/cmd/valley-web-publish/valley.go`). At the start of the pass, the publisher fetches the
3363instance repository's `main` once into its cached bare repository (`origin.git`) and requires that
3364commit to carry `policy/instance` and no `policy/valley` (see the pass steps in
3365[Web export publisher](./reference.md#web-export-publisher)). If that fetched `main` carries
3366`policy/valley`, the pass fails because the repository points to another instance instead of
3367defining one.
3368
3369None of the `valley` commands that run later in the pass read `policy/valley` from the instance
3370repository's live `main`:
3371
3372- `valley plan` and `valley pending` run inside the staged pointer repository (`_pointer.git`), a
3373 bare repository whose `origin` is itself and whose `main` holds a single file, `policy/valley`,
3374 containing `--instance-repo`. The CLI reads `policy/valley` on its `origin`'s `main` and follows
3375 no further `policy/valley` in the target repository. Both commands therefore read the project list
3376 and signers from `--instance-repo` alone.
3377- `valley knot show --project` runs inside `origin.git`, whose `origin` is `--instance-repo`. It
3378 resolves the named project as a sibling of its `origin` and reads no `policy/valley`.
3379
3380Because neither command reads `policy/valley` from the instance repository's live `main`, a commit
3381that adds `policy/valley` to the instance repository during a pass cannot redirect the pass to
3382another instance, even when it is removed again before the pass finishes or when two instances serve
3383projects of the same name.
3384
3385Separate CLI invocations read the plan and each knot's detail, so a project's plan graph can advance
3386between commands. `export.Build` returns `export.ErrInconsistent` when a knot's detail was read at a
3387different graph tip than the plan. When that happens, the pass re-reads the plan and knot details
3388while reusing the instance commit, project list, and read grants fetched at the start of the pass,
3389for up to three attempts in total. If all three attempts are inconsistent, the pass fails.
3390
3391### Read links
3392
3393A read link is a bearer credential that lets its holder read what one registry principal may read at
3394the edge. The host issues and revokes links, and carries their verifiers to the edge in the
3395authorization (`implemented`). When started with `--origin`, `valley-web` redeems each link once
3396into a session for the link's principal (`implemented`; see [Readers' sessions](#readers-sessions)).
3397
3398- **The credential file:** `valley-web-publish link`, run as root through the `valley-web-link`
3399 wrapper, writes one record per link to a file outside every repository, cache and export. A record
3400 holds the link's ID, principal, note, verifier, issue time, revocation time and the file revision
3401 that set its state. The verifier is the SHA-256 of the link's 32-byte secret. The secret itself is
3402 printed once and kept nowhere. Because the edge also holds the verifiers, the credential file
3403 requires integrity rather than confidentiality: root alone writes it, and the publisher reads it
3404 through the group `valley-web-links` (`deployment choice`).
3405- **Bindings in the authorization:** Every time a pass signs an authorization, it holds the
3406 authorization lock from before it checks the policy until it has signed. After the policy check,
3407 it takes the links lock as well, reads the file, signs, and then releases the links lock. It signs
3408 one `binding` record per active link. A revoked link has no binding, and absence is revocation. A
3409 file that cannot be read sends an authorization with no bindings and fails the pass.
3410- **One links lock serializes changes and passes:** The links lock is the file `lock` in the
3411 credential file's directory. `issue`, `revoke` and `prune` hold it while they read and write the
3412 file, and take no lock in the publisher's state. A pass holds it from its read of the file until
3413 it has signed. So once a revoke has finished, no pass signs the revoked link. A pass takes the
3414 authorization lock first and the links lock second, and a change takes the links lock alone, so
3415 the two never wait for each other in a cycle. A change does not wait for a policy check, only for
3416 a pass that is reading the file and signing. Each side waits at most 60 seconds. If the wait runs
3417 out, a change fails and leaves the file unchanged, whereas a pass signs an authorization with no
3418 bindings and fails so that any withdrawal still reaches the edge (`implemented`).
3419- **Root follows no path the publisher controls:** Under the module, link commands run as root
3420 (`deployment choice`). Root owns the credential file's directory with mode 0750, and tmpfiles
3421 creates `lock` inside it, owned by root and the group `valley-web-links`, mode 0640. The publisher
3422 opens and locks `lock` through that group, and can make, replace or remove nothing there
3423 (`deployment choice`). Link commands open the lock without following a symbolic link or waiting on
3424 a FIFO, refuse anything but a regular file owned by root, and change the owner of nothing. The
3425 delivery record is the one file they read in the publisher's state, and they read it with the same
3426 checks (`implemented`).
3427- **The revision moves forward:** Every change writes a revision one past the greater of the file's
3428 revision and the greatest one a pass has signed from. So a change to a file restored from an older
3429 copy still writes past every revision already signed.
3430- **A restore restores the links:** A pass signs the credential file as it finds it. Restoring the
3431 host from a backup therefore restores the links as they were at the backup, and a link revoked
3432 after the backup is active again after the next pass. `valley-web-link revoke --all` cuts every
3433 link off ([security.md](./security.md#bearer-read-credentials)).
3434- **The file stays readable:** Reads and writes hold the file to 1 MiB. `issue` refuses to write it
3435 within 64 KiB of that limit, which always fits a revocation of every active link, so a revoke is
3436 never refused for size. `link prune` removes the revoked links whose revocation is enforced. A
3437 link absent from the file is as revoked as one recorded revoked, since the edge accepts only a
3438 link the stored authorization binds.
3439- **Why verifiers:** The edge receives verifiers and never secrets. A copy of the edge's store, or
3440 of the authorization, lets no one read: a verifier cannot be turned back into the link.
3441- **Delivery:** After every issue or revoke, the wrapper starts a policy-only pass. That pass takes
3442 the authorization lock and the links lock alone, so a stalled content upload does not hold up a
3443 revocation. The publisher records the file revision whose links the last acknowledged
3444 authorization carried. `link list` reports a link as `enforced` only when that revision is at
3445 least the one that set the link's state, and as `pending` otherwise. A pass already running when
3446 the change was made may have signed before it, so while a link is pending the wrapper starts the
3447 policy pass once more. It never repeats the change. The wrapper exits non-zero while a link is
3448 still pending, and running a revoke again retries the delivery.
3449- **Backup:** When the publisher is enabled, the host backup holds the credential file's directory
3450 and the publisher's state under `/var/lib/private`: its export key, its authorization counter and
3451 its delivery record (`deployment choice`).
3452
3453## The web server
3454
3455`valley-web` serves a receiver's store over HTTP (`web/server/`, `web/cmd/valley-web/`). It builds
3456each response for one reader (see [Each reader's view](#each-readers-view)). For the projects that
3457reader may see, it serves a projects page and a knots page of all of them. For each of those
3458projects, it serves the project's own knots page, each knot page, and a source browser for `main`
3459under the project's group, including a gzipped tar archive for each reachable commit. When started
3460with `--origin`, `valley-web` serves a request that carries a valid session cookie as that session's
3461principal, and serves every other request as `anyone` (`implemented`; see
3462[Readers' sessions](#readers-sessions)). Without `--origin`, it serves every request as `anyone`.
3463`valley-web` runs alongside the receiver as a separate process (see [The receiver](#the-receiver)).
3464It renders Markdown files and READMEs as documents with its own renderer, package `web/markdown`,
3465which uses the standard library alone. The renderer writes only a fixed set of elements and
3466attributes, and shows raw HTML as text. A relative link in a document is resolved to the target's
3467page at the same commit with no git call. Its flags, routes, and limits are in
3468[Web server (`valley-web`)](./reference.md#web-server-valley-web).
3469
3470### Each reader's view
3471
3472Each request is read as one principal, called its reader. A reader's view is the set of projects
3473that reader may see. The server builds every page, link, redirect, and source route from that view.
3474
3475**Which projects a reader sees.** The filter `visible` selects the projects in a reader's view
3476(`implemented`, `web/server/plan.go`). A reader sees a project when two conditions hold: the project
3477belongs to one of the export's groups, and the stored authorization allows either `anyone` or the
3478reader's principal to read it. `Authorization.Allows` checks one principal at a time against the
3479project's name and publication identity (`web/export/authorization.go`). `visible` checks `anyone`
3480and the reader's principal and takes the union of both results. A project without a group has no web
3481pages.
3482
3483**What a reader's view holds.** To build a view's lookup index and knots page, `projectForReader`
3484copies the projects in the reader's view and each of their knots (`implemented`,
3485`web/server/projection.go`). The decoded export stays unchanged, and all views of that generation
3486share it. Each copied knot keeps its own fields and the `state` and `ready` values that the host
3487derived. Hiding a project never recalculates the host's plan. `projectForReader` removes derived
3488information about projects outside the reader's view:
3489
3490- `waiting_on`, `cleared_by_ending`, `dangling`, and `unresolved` keep only references to knots in
3491 projects the reader sees.
3492- `waiting_on_hidden` is `true` when the export set it or when `projectForReader` removed a
3493 reference from `waiting_on`. It records only that a `waiting_on` reference was hidden, and says
3494 neither which knots nor how many.
3495- In those four lists, a valid entry is either a knot ID in the knot's own graph or
3496 `<project>:<id>`. Any entry that does not match one of those two shapes is also removed, even if
3497 it begins with the name of a visible project.
3498- In `edges`, an edge into a project the reader sees keeps its exported fields. An edge into any
3499 other project becomes a `hidden` edge, and its title, status, and reason are dropped regardless of
3500 its exported state.
3501
3502The authored reference fields — `blocked_by`, `target`, `graduated_into`, and change links — stay
3503unchanged in the copied knot. When rendering a page, the server resolves each reference through the
3504view's index after checking that the entire value matches a shape allowed for its field
3505(`knot/validate.go`, `web/server/knot.go`):
3506
3507- A `blocked_by` entry (or `waiting_on` entry on the knots page) is a knot ID in the knot's own
3508 graph (`knot.IsLocalID`), or `<project>:<id>` (`knot.IsQualifiedID`).
3509- A `target` is a project name (`knot.IsName`), or `<project>:<id>` (`knot.IsQualifiedID`). Because
3510 a single-segment `target` always names a project rather than a knot in the same graph, a project
3511 whose name looks like a knot ID is still checked as a project.
3512- `graduated_into` is the ID of an outcome or question in the knot's own graph (`knot.IsLocalID`).
3513- A change link is `valley:<project>/<change ID>` or `https://github.com/<owner>/<repo>/pull/<n>`
3514 (`knot.IsChangeLink`).
3515
3516Because the server validates the whole string before looking up a project or showing any text, a
3517malformed reference that begins with a visible project name — such as `app:site:oc-b000001` for
3518`<project>:<id>` or `valley:app/site/secret` for a change link — fails the shape check.
3519
3520When a reference names a project outside the reader's view, or fails its field's shape check, the
3521page shows a fixed placeholder with no link and none of the reference's text:
3522
3523- "an unpublished project" for a `target` that names a project or fails the shape check;
3524- "a knot in an unpublished project" for `blocked_by`, `waiting_on`, `graduated_into`, or a
3525 `<project>:<id>` entry in `target`;
3526- "a change in an unpublished project" for a change link.
3527
3528The server never infers whether a knot is waiting from `blocked_by`, because a blocker listed there
3529may already be done. Instead, it uses `waiting_on` and `waiting_on_hidden`. The server needs the
3530export's `waiting_on_hidden`, because the edge cannot reconstruct the blocker status of a project
3531that `export.json` omits. The export sets the flag when it hides a `waiting_on` reference into an
3532omitted project, and `projectForReader` sets it when it hides a `waiting_on` reference that is
3533malformed or names a project the reader may not see. Which references `waiting_on` holds is
3534described in [Unpublished blockers](#unpublished-blockers). As a result, a knot whose only blocker
3535is in a hidden project renders identically whether the export omits that project or includes it for
3536another reader. When the blocker is done, neither view shows the knot as waiting. When the blocker
3537is open, both views show once that it waits on "a knot in an unpublished project".
3538
3539A project outside the reader's view adds no entry on the projects page, navigation link, former
3540name, alias, redirect, target title or status, or source route. A group that contains no project in
3541the reader's view has no page and no group alias. Any request for a hidden project returns the same
3542static `404` page as a request for a project that does not exist.
3543
3544This filtering applies only to the export's structured fields. Authored prose in a visible project —
3545such as a knot body, a comment, a README, or an absolute link — is published as written.
3546
3547Checked by `web-server-unit`:
3548
3549- `TestNamedReadersSeeTheirOwnProjects` serves `anyone` and two named readers over signed fixtures
3550 that hold private projects across every route, alias, landing redirect, cross-project reference,
3551 Markdown page, and archive.
3552- `TestVisibilityIsTheUnionUnderThePublicationIdentity` checks that `visible` takes the union of
3553 `anyone` and the reader's principal and matches each project's publication identity.
3554- `TestAHiddenBlockerReadsAlikeInEitherExport` builds one export without a blocker's project and one
3555 holding it for another reader, and compares the projected fields and rendered pages byte for byte
3556 with the blocker done and open.
3557- `TestProjectionHidesOtherProjects` checks that `projectForReader` strips hidden projects from the
3558 derived lists and edges without changing the decoded export.
3559- `TestATargetNamesNoProjectTheReaderMayNotSee` gives a public knot a target in a private project
3560 whose name looks like a knot ID, checks that no page for an unauthorized reader names it while an
3561 authorized reader gets a link to its source, and checks the shape rules for `graduated_into`,
3562 `blocked_by`, `waiting_on`, and change links.
3563- `TestMalformedReferencesNameNothing` passes values that start with a visible project name yet
3564 match none of their field's shapes, checking that `projectForReader` removes them from the four
3565 derived lists and that every page shows them as unpublished with none of their text for all
3566 readers.
3567
3568### Requests, loads and indexes
3569
3570Every request runs through eight steps (`implemented`, `web/server/server.go`):
3571
35721. Check the HTTP method, read the stored authorization, and identify the request's reader.
35732. Obtain the active generation's decoded export and the index for the reader's view.
35743. Resolve the request path through that index.
35754. Answer redirects and `404` pages directly from the index without taking a `git` slot.
35765. For a source route that reads a repository, take a `git` slot and then open the generation from
3577 which the view was built.
35786. Render the complete response in memory.
35797. Release the generation and unpin the index.
35808. Re-read the authorization under the shared serving lock and write the response headers.
3581
3582A request holds no generation on disk while waiting for its view or for a `git` slot. If the active
3583generation advances before the request opens its generation in step 5, the request releases its
3584`git` slot, generation, and index, and starts again from step 2 within its 15-second deadline.
3585
3586**Decoded exports.** The server caches the decoded `export.json` of the newest generation it has
3587read. When a request needs a generation that has not been decoded yet, it waits for a load. Each
3588load runs in its own worker, which opens the active generation, reads and decodes `export.json`, and
3589releases the generation. Requests waiting for the same generation share one load. If all waiting
3590requests leave before the load finishes, the worker cancels the load and discards the partial read.
3591
3592At most 2 loads run at once (`server.MaxLoads`), using two loader slots: one general slot and one
3593slot reserved for anonymous requests. The reserved slot runs a load only while at least one
3594anonymous request waits for that load, so loads with only named waiters use the general slot alone.
3595When an anonymous request joins a load that is waiting to start, it can start that load on the
3596reserved slot, and named readers' requests for the same generation can join it there. If the last
3597anonymous waiter leaves a load on the reserved slot while named waiters remain:
3598
3599- **When the general slot is free:** the load moves to the general slot and continues running, so
3600 the named waiters lose no progress.
3601- **When the general slot is busy:** the server cancels the load and frees the reserved slot at
3602 once. The remaining named waiters wait for the general slot within their own deadlines. The
3603 cancelled worker holds no loader slot while it exits at its next cancellation check.
3604
3605Because a load with only named waiters never holds the reserved slot, an anonymous request never
3606waits for a loader behind named readers' loads. Concurrent requests for a generation share one read.
3607A read that every waiting request abandons is cancelled, so a later request may read that generation
3608again, as it may after the reserved slot's cancellation above.
3609
3610**Indexes.** Once a generation's export is decoded, the server builds an index for each view it
3611serves. An index is keyed by three values: the generation sequence number, the exact revision of the
3612authorization (its signed bytes), and the sorted names and publication identities of the view's
3613projects. Readers who see the same set of projects share one index, and a named reader who sees no
3614more than `anyone` shares the `anyone` index. The reader's identity never enters an index or any
3615page rendered from it. Each index is built in its own worker after the export is decoded; that
3616worker holds no loader slot, and no load waits for an index build.
3617
3618Cached and building indexes occupy places in two pools:
3619
3620- **Anonymous places (2 places):** Reserved for the `anyone` index — one for the current generation
3621 and one for a generation replacing it or being replaced. Named readers' requests never take an
3622 anonymous place.
3623- **Named places (8 places, `server.MaxViews`):** Shared by named readers' requests. Any view that
3624 includes projects beyond `anyone` takes a named place. A named reader whose view matches `anyone`
3625 serves from the shared `anyone` index object while occupying a named place for it.
3626
3627A request pins its index from step 2 until rendering finishes in step 7, before the response is
3628written. While an index is building or pinned by active requests, it occupies a place in each pool
3629that has at least one request waiting for or serving from it. As soon as no requests from one pool
3630pin the index, it releases that pool's place if requests from the other pool still pin it. For
3631example, when only named readers' requests pin the `anyone` index, it occupies a named place and no
3632anonymous place. When the last request unpins an index, the index remains cached in the single pool
3633of that last request. An index from an older generation or an older authorization stays counted in
3634its pool until the last request using it unpins it, and is then dropped.
3635
3636To free a place in a full pool, the server evicts only an index that no request is currently
3637pinning. If all waiting requests leave an index while it is still building, the server cancels the
3638build. The cancelled build keeps its pool place until its worker exits, and no new request can join
3639it. As a result, at most 10 workers (2 anonymous and 8 named) can build indexes at once.
3640
3641When a request must wait for a generation load, an index build, or a free place in its index pool,
3642it takes one of 64 view-waiting places (`server.MaxLoadWaiting`) and answers `503` if its 15-second
3643deadline expires first. Named readers' requests may take at most 48 of those 64 waiting places
3644(`server.MaxNamedWaiting`), including when waiting for the `anyone` index or for a named place to
3645hold it. Anonymous requests may take any of the 64 places. A request that finds no waiting place it
3646may take — all 64 full for an anonymous request, or 48 named places or all 64 places full for a
3647named request — answers `503` at once.
3648
3649Together, these reservations keep named readers from exhausting resources that anonymous requests
3650need. At least 16 waiting places, the reserved loader slot, and the 2 anonymous index places are
3651always available to anonymous traffic. The reservations do not isolate CPU or `git`: every other
3652limit is shared by all readers, and adding readers does not raise it. When all 8 named index places
3653are full, named readers' requests wait while anonymous requests do not, and an anonymous request for
3654the current generation always gets the current `anyone` index without waiting on any named reader's
3655request. Anonymous requests share their 16 reserved waiting places, reserved loader slot, and 2
3656index places among themselves. The limits shared by all readers are 8 `git` slots (`server.MaxGit`),
36572 Markdown rendering slots (`server.MaxRendering`), the 64 MiB response budget
3658(`server.MaxBuffered`) with its 48 MiB cap for large responses (`server.MaxLarge`), the 8 MiB
3659response size limit (`server.MaxResponse`), and the archive limits (see
3660[Web server (`valley-web`)](./reference.md#web-server-valley-web)).
3661
3662Checked by `web-server-unit`:
3663
3664- `TestIdenticalViewsShareAnIndex` checks that four readers across two distinct views build two
3665 indexes.
3666- `TestAnonymousViewsSurviveNamedSaturation` fills every named place with in-progress index builds
3667 and verifies that `anyone` is still served, that a new generation loads and indexes meanwhile,
3668 that a request waiting for room holds no loader, `git` slot, or generation and answers `503` at
3669 its deadline (or nothing if the client disconnects), and that a named reader whose view matches
3670 `anyone` still waits for a named place.
3671- `TestNamedRequestsTakeNoAnonymousPlace` has a named reader whose view matches `anyone` pin two
3672 generations' `anyone` indexes, activates a third generation, and checks that an anonymous request
3673 for the knots page is served at once, including when all other named places are full and that
3674 named reader's request for the third generation is waiting.
3675- `TestAnonymousRequestsKeepTheirWaitingPlaces` fills the 48 named waiting places, checks that the
3676 next named request answers `503` at once, and verifies that 16 anonymous requests can still wait
3677 for a new generation's load and be served.
3678- `TestAnonymousRequestsKeepALoader` checks the reserved loader slot.
3679- `TestALoadAnonymousRequestsLeaveMovesToTheOtherLoader` has the sole anonymous waiter leave a load
3680 on the reserved loader while a named reader still waits, checking that the load moves to the free
3681 general loader, that the reserved loader is immediately free for an anonymous request on a newer
3682 generation, and that the first export is read only once.
3683- `TestALoadAnonymousRequestsLeaveGivesBackTheKeptLoader` repeats that scenario while the general
3684 loader is busy with another named load, checking that the shared load is cancelled, that the
3685 reserved loader is freed at once so an anonymous request for a third generation succeeds while
3686 both named loads are held, and that the remaining named waiter is served from a second load of its
3687 generation once the general loader frees up.
3688- `TestIndexCancellationGivesBackItsPlace` cancels an index build at each step, and
3689 `TestProjectionStopsWhenCancelled` cancels `projectForReader` inside a knot's lists and edges.
3690- `TestAStoppedBuildKeepsItsPlace` cancels a build whose worker continues running, checking that
3691 requests for another view and for the same view wait for room and that at most 8 workers build
3692 named indexes at once.
3693- `TestSourceAdmission` checks that redirects, missing pages, and hidden projects take no `git` slot
3694 when all `git` slots are full.
3695
3696### Readers' sessions
3697
3698A reader signs in by redeeming a read link once to receive a session cookie (see
3699[Reader sessions](./reference.md#reader-sessions) for the routes and formats). `valley-web` tracks
3700redeemed links and active sessions in its browser state (`web/readerstate`), stored in `browser/`
3701beside the store descriptor (`implemented`). For each redeemed link, the browser state permanently
3702records the binding under which the link was redeemed, along with the SHA-256 hash of its session
3703token until the reader signs out.
3704
3705**One owner.** Only one `valley-web` process may open a `browser/` directory at a time. At startup,
3706`valley-web` acquires an exclusive `flock(2)` lock on `browser/owner.lock` and holds it until exit;
3707a second process pointed at the same directory refuses to start. `valley-web` also refuses to start
3708if `browser/` is accessible to any other user. Because a single process owns `browser/`, it can keep
3709the decoded state in memory knowing no other process modifies the files on disk. The deployment
3710provisions `browser/` owned by `valley-web`'s user with mode `0700`; neither `valley-web` nor the
3711receiver creates that directory or changes its owner.
3712
3713**Reads.** A request resolves its session under a read lock on the in-memory snapshot, without
3714taking a `flock(2)` lock or re-parsing `browser/state`. Waiting for the read lock stops if the
3715request's deadline expires or the client disconnects. Under the read lock, `valley-web` runs one
3716`lstat(2)` on `browser/state` to verify that the file on disk still matches the file it last read or
3717wrote. If `browser/state` is missing, replaced, or modified, `valley-web` marks the browser state
3718unavailable until the process restarts and never falls back to an earlier snapshot. While the
3719browser state is unavailable, requests carrying the session cookie answer `503` and requests without
3720the cookie are served as `anyone`.
3721
3722**Transactions.** Redemption and logout acquire three locks in fixed order and release them in
3723reverse order:
3724
37251. The in-memory snapshot's write lock.
37262. The transaction file lock (`flock(2)` on `browser/lock`).
37273. The receiver's serving lock (`v2/serving.lock`, shared), under which the transaction re-reads the
3728 stored authorization.
3729
3730A transaction never acquires a browser-state lock while holding `v2/serving.lock`. Waiting for any
3731lock stops if the request's deadline expires or the client disconnects. The transaction checks the
3732request context after acquiring each lock and checks again after encoding the new state document,
3733immediately before creating `browser/state.new`. If the deadline has expired at any of those checks,
3734the transaction aborts without writing anything, so a timed-out redemption consumes no link and a
3735timed-out logout ends no session.
3736
3737Once a transaction creates `browser/state.new`, it runs to completion. It writes the full next
3738document to `state.new`, syncs `state.new`, renames it over `state`, and syncs `browser/`. Only
3739after the directory sync succeeds does `valley-web` update the in-memory snapshot and send `204`
3740with `Set-Cookie`. If any step from writing `state.new` through syncing `browser/` fails, the
3741outcome is uncertain, and `valley-web` marks the browser state unavailable until the process
3742restarts. Because redemption marks the link consumed and records its session hash in a single
3743transaction, at most one concurrent redemption of the same link can commit. A crash before the
3744rename leaves the old `state` in place, so the link can still be redeemed on retry; a crash after
3745the rename leaves the link consumed even if the `204` response never reached the browser. At
3746startup, `valley-web` removes any leftover `state.new` without reading it, and syncs `state` and
3747`browser/` after loading `state` into memory.
3748
3749**Initializing `browser/state`.** When `browser/state` does not exist yet, `valley-web` creates an
3750empty `browser/state` only when `v2/authorization` is present, parses cleanly, and contains no
3751`binding` records. If `v2/authorization` is missing, unreadable, or binds any link, `valley-web`
3752leaves `browser/state` uncreated. Initialization takes the same three locks as a transaction,
3753re-reads `v2/authorization` under the shared `v2/serving.lock`, and holds `v2/serving.lock` until
3754the empty `browser/state` is synced on disk. Because the receiver needs an exclusive lock on
3755`v2/serving.lock` to rename a new authorization into place, no authorization carrying a binding can
3756land between that check and the commit. `valley-web` attempts initialization at startup and on every
3757request while `browser/state` is missing, so it creates the file as soon as an authorization with no
3758bindings arrives, without a restart. Any link bound before `browser/state` exists can never be
3759redeemed; the operator must revoke all links so the edge initializes `browser/state`, and then issue
3760new links.
3761
3762**Requests.** A `POST` to `/-/redeem` or `/-/logout` executes once under the request's 15-second
3763deadline and never reads the export. A `GET` or `HEAD` request resolves its session under the
3764browser state's read lock when it arrives and renders the page as that session's principal. Before
3765writing response headers, the server's final check acquires the browser state's read lock and then
3766the shared `v2/serving.lock`, re-reads the authorization, and resolves the session again. If either
3767the authorization or the session changed during rendering, the server discards the response and
3768renders again, up to three renders in total. If the request's deadline has expired by that final
3769check, the server answers `503` without renewing the cookie. Otherwise, while still holding both
3770locks, the server attaches the renewed `Set-Cookie` header and writes the response headers, then
3771releases both locks before writing the body. Any logout or revocation that commits before the final
3772check takes effect on that response; one that commits after the headers are written takes effect on
3773the next request.
3774
3775**Boundaries.** The stored authorization alone decides which projects a session's principal may
3776read; the browser state cannot grant access beyond that authorization. No authorization can make a
3777redeemed link redeemable again. A session remains valid only while the stored authorization binds
3778its credential ID to the exact principal and verifier under which the link was redeemed, so
3779re-binding the same credential ID to another principal or secret does not carry the session over.
3780The receiver's `Store.Authorize` never takes a browser-state lock, so a full or unavailable browser
3781state never delays storing a new authorization or revocation. Rolling `browser/state` back to an
3782older, internally valid copy is not detected.
3783
3784Checked by:
3785
3786- `web-server-unit`, which runs the browser-state unit tests (`web/readerstate/`) and the server's
3787 session tests (`web/server/session_test.go`): single-use redemption, identical `403` refusals, the
3788 `POST` header and body contract, cookie parsing and exact binding checks, the reader pages'
3789 `Content-Security-Policy`, unavailable and full states, initializing `browser/state` and its race
3790 against a new binding, concurrent redemptions, deadlines expiring while waiting on a stalled write
3791 or encoding a transaction, and revocation or logout during page, archive, or redirect rendering.
3792- `web-reader-state-crash`, which kills `valley-web` or injects filesystem errors at each step of
3793 redemption, logout, and initial state creation, then restarts `valley-web` on the resulting
3794 directory (`web/cmd/valley-web/crash_test.go`). It verifies that logout never answers `204` before
3795 its change is durable on disk, and that an initial state creation interrupted before its rename,
3796 followed by an authorization with link bindings leaves `browser/state` uncreated on restart.
3797- `web-reader-browser-e2e`, which drives `/-/redeem` in headless Chromium behind a TLS proxy in the
3798 build sandbox (`web/cmd/valley-web/browser_test.go`). It also spoils two redemption responses to
3799 verify that the page reports an unknown outcome and queries `/-/session` on retry before signing
3800 any session out.
3801- `web-push-e2e`, which redeems a link issued by the packaged publisher and exercises server
3802 restarts, link revocation, logout, and recovery from a missing or corrupted `browser/state`. It
3803 also redeems a link of a named reader of a project that `anyone` may not read. The session follows
3804 `/` to the projects page, finds that project there, and opens its tree page and its knots page
3805 from the page's links. It reads the project's knot, archive and the knots page of every project,
3806 and gets `404` for its tree page once a pass delivers the link's revocation.
3807- `web-receiver-unit`, which uploads a signed export with private projects through the real receiver
3808 to the packaged `valley-web` (`web/cmd/valley-web-receive/readers_test.go`). It verifies that two
3809 named principals and `anyone` each see the knots, source pages, and archives of their authorized
3810 projects alone, receive `404` for the rest, and lose access on the next request after a grant is
3811 withdrawn.
3812
3813### Reading the state directory
3814
3815`valley-web` only reads the receiver's store. Both programs take the path to the store's descriptor
3816file, and the store's payloads live in the `v2/` directory beside that file. `valley-web` opens the
3817store with `export.OpenReadOnly`, which creates no files and takes only shared `flock(2)` locks: on
3818the generation opened for a request, and on `serving.lock`, which it opens read-only, from its last
3819check of the authorization until the response's headers are written (`web/export/store.go`,
3820`web/export/authorize.go`). When the receiver opens the store with `export.OpenStore`, it recovers
3821any interrupted activation, sweeps old generations, and prunes withdrawn repositories. Until the
3822receiver finishes an interrupted activation, `valley-web` continues to serve the generation that
3823`current` points to.
3824
3825The store's entry point is a regular file so that binaries built for the v1 store layout, which
3826required a directory path for `--state`, refuse to open it. The `v2/` payload directory also omits
3827the `active` symlink and `exports/` directory that v1 binaries read, so pointing a v1 binary at
3828`v2/` serves nothing. Rolling the edge back to v1 binaries therefore serves no content from a v2
3829store, and no v1 binary ever reads the store without checking the authorization. The receiver writes
3830nothing outside the descriptor and `v2/`: state of the v1 layout beside the descriptor, which held
3831public projects only, stays until the operator deletes it by hand.
3832
3833Because `valley-web` writes nothing to the receiver's store, it can run as a separate Unix user with
3834read-only access to the store. The one place it writes is its own browser state in `browser/` beside
3835the descriptor (see [Readers' sessions](#readers-sessions)). The receiver keeps each staged upload
3836private to its own user until activation, and explicitly sets world-readable modes on `v2/`,
3837`generations/`, the descriptor, the authorization, and every directory and file of an activated
3838generation regardless of its umask (`web/export/store.go`; see
3839[Web export receiver state](./reference.md#web-export-receiver-state) for the file modes). The mode
3840of the descriptor's parent directory is a **deployment choice**. The receiver creates that directory
3841if it does not exist and leaves its mode unchanged, and the deployment grants the server's user read
3842and search access to it, for example through its group.
3843
3844Every `git` command that `valley-web` runs names the repository with `--git-dir`
3845(`web/export/bundle.go`). Passing `--git-dir` lets `git` read a repository owned by the receiver's
3846user without checking `safe.directory`, which the server's isolated `git` configuration cannot set.
3847
3848Checked by `web-unit` (`TestStoreModes`), which checks the staging and generation modes under umask
3849`0077`, and by `web-server-unit` (`TestServesAReadOnlyStateDirectory`), which runs `valley-web` on a
3850state directory written under umask `0077` with read-only permissions and repositories that `git`
3851treats as owned by another user.
3852
3853### Groups and web URLs
3854
3855Every project on the web belongs to a group. Project URLs begin with the group name followed by the
3856project's web name: `/<group>/<project>/…`, such as `/tools/app/knots/<id>`. `/<group>/` lists the
3857group's projects. The root path `/` redirects to the projects page at `/-/projects`, or to the
3858source tree of the reader's one project, and the knots page of every project is at `/-/knots`.
3859Because URLs appear in links, commits, and knots, renaming a group or a project redirects old URLs
3860only if the old name stays in the group's `aliases` or the project's `formerNames`. The lookup index
3861uses only declared names (`implemented`, `web/server/plan.go`).
3862
3863Groups and project placements are declared in `valley.cue` alongside each project's git store,
3864mirrors, ref protection, and push grants (`schema/valley.cue`). At build time, the NixOS modules
3865validate `valley.cue` with `cue vet` and export it to JSON with `cue export`. The web publisher
3866module passes that exported JSON file to `valley-web-publish` as `--host` (`nix/web-publisher.nix`).
3867Which groups exist and which group each project belongs to is a **deployment choice**.
3868
3869```cue
3870groups: core: {name: "tools", aliases: ["t"]}
3871groups: web: name: "docs"
3872projects: app: {group: "core", formerNames: ["tool"], aliases: ["app"]}
3873projects: "docs-app": {group: "web", name: "app"}
3874```
3875
3876- **Group:** Each group has a permanent identifier (`core` above) that projects reference in
3877 `group`. That identifier never appears in URLs. The group's `name` (`tools`) is the first segment
3878 of its projects' URLs. Each entry in `aliases` (`t`) is an alternate first segment that redirects
3879 to `name`. When a group changes its `name`, adding the old name to `aliases` keeps existing links
3880 working. Group members and stewards are **not built**.
3881- **Project identifier:** The key under `projects` (`app` and `docs-app` above) is the project's
3882 permanent identifier. It is unique across the host and names the project's repository, plan graph,
3883 `policy/read`, and read grants.
3884- **Project web name:** The project's `name` field is the second segment of its URLs, and defaults
3885 to the project's identifier when omitted. Above, `app` is served at `/tools/app/…` and `docs-app`
3886 is served at `/docs/app/…`. A web name must be unique only within its group, so two groups can
3887 each have a project with the web name `app`. Changing `name` renames the project on the web while
3888 keeping its identifier unchanged.
3889- **Former names:** `formerNames` lists a project's previous web names within its group. Requests to
3890 `/tools/tool/…` redirect to `/tools/app/…`.
3891- **Short aliases:** `aliases` on a project lists single-segment shortcuts at the root of the URL
3892 path. Requests to `/app/…` redirect to `/tools/app/…`.
3893
3894Only projects in a group have web URLs. A project that sets a custom `name`, a nonempty
3895`formerNames`, or a nonempty `aliases` must also set `group`. Explicit empty lists are valid without
3896it.
3897
3898URL names fall into two namespaces. First-segment names — group `name` values, group `aliases`, and
3899project `aliases` — share one namespace across the whole server. Second-segment names — the `name`
3900and `formerNames` of projects in the same group — share one namespace per group, and names in
3901different groups never collide. Within each namespace, names are compared case-insensitively in
3902ASCII, and duplicate names are rejected. `valley-web` reserves paths starting with `/-/` for its own
3903routes. Because every valid name starts with an ASCII letter or digit, no group or alias can be `-`,
3904and server routes under `/-/` never collide with group or alias routes. Three checks enforce these
3905rules (`implemented`):
3906
39071. `cue vet` validates the host declaration at build time (`schema/valley.cue`).
39082. `valley-web-publish` validates `--host` with `export.CheckNames` before starting a pass
3909 (`web/cmd/valley-web-publish/host.go`, `web/export/groups.go`). It also requires `--host` to be a
3910 JSON object with non-null `projects` and `groups` maps, non-null project and group entries, and
3911 valid project names as keys, so a truncated or malformed file cannot be misread as an empty host
3912 declaration.
39133. `export.Validate` runs `export.CheckNames` when the publisher encodes `export.json` and when the
3914 receiver or `valley-web` decodes it (`web/export/export.go`).
3915
3916`export.json` includes only the groups that contain at least one exported project, along with each
3917exported project's group, web name, former names, and short aliases (`web/export/project.go`).
3918Groups that contain no exported project, as well as the web names, former names, and aliases of
3919projects that are not exported, are omitted. An export that omits `groups` and per-project `group`
3920fields still decodes, and `valley-web` serves none of its projects because they have no group URL.
3921
3922`valley-web` responds to requests under a group alias, a project short alias, or a project former
3923name with a `308` permanent redirect. A group alias redirects to the same path under the group's
3924`name`. A project short alias redirects to the same path under `/<group>/<project>`, and a former
3925name redirects to the same path under the project's current web name. The server copies the
3926remaining path and raw query string verbatim into `Location`, without path cleaning, and preserves a
3927trailing `?` when the query string is empty. Because `Location` always begins with `/` followed by a
3928group name, it stays on the server's origin. When a client resolves dot segments in the redirected
3929path, the resulting request lands on another path on the same server and is handled normally.
3930Requests for a project the reader may not see — under its group, an unknown group, a short alias, or
3931a former name — return the same `404` response as requests for a nonexistent project (see
3932[Each reader's view](#each-readers-view)). The server renders a single static `404` page at startup
3933that includes no data from the request or the export (`web/server/render.go`; see
3934[Web server (`valley-web`)](./reference.md#web-server-valley-web)).
3935
3936When loading a new generation, `valley-web` decodes `export.json` and validates its names. Building
3937a reader's index then copies the reader's projects and indexes their groups, aliases, and former
3938names. Each step checks its context before processing each name, so a cancelled load stops at the
3939next cancellation check and releases its generation and any loader slot it still holds, and a
3940cancelled index build stops and releases its place (`web/export/groups.go`, `web/export/export.go`,
3941`web/server/projection.go`, `web/server/plan.go`).
3942
3943Checked by `cue-vet`, which verifies that the eight rejected host declarations report the colliding
3944name or missing group and exports two groups that each contain a project named `app`; by `web-unit`
3945(`TestBuildRefuses`, `TestBuildExportsThePublicProjectsGroups`, `TestDecodeIsStrict`,
3946`TestDecodeHoldsGroupsToTheirProjects`, `TestDecodeTakesAnExportWithoutGroups`,
3947`TestCheckNamesStopsWhenCancelled`, `TestValidatingGroupsStopsWhenCancelled`,
3948`TestGroupsComeFromTheHostDeclaration`, and `TestAMalformedOrCollidingHostDeclarationIsRefused`);
3949and by `web-server-unit` (`TestHiddenProjectAnswersLikeMissing`, `TestAliasesRedirectPermanently`,
3950`TestTwoGroupsEachHoldAnApp`, `TestRedirectsLeadWhereTheBrowserGoes`,
3951`TestPlacingStopsWhenCancelled`, `TestNotFoundIsTheOnePage`, and
3952`TestProjectNamesBesideTheServersPaths`, which serves groups and projects named `source`, `knots`,
3953and `web-export` on every route and checks that paths under `/-/` answer `404`).
3954
3955### Slow readers
3956
3957`valley-web` renders each response in full before writing it to the connection. Rendered responses
3958draw their memory in 64 KiB pieces from a shared 64 MiB budget (`server.MaxBuffered`) and hold those
3959pieces until the write finishes or the 60-second write timeout expires (`web/server/render.go`).
3960Without a cap on large responses, a few clients that stop reading large knot, directory, or file
3961pages could hold the entire 64 MiB budget until the write timeout, causing every other request to
3962answer `503`. Behind a reverse proxy, every request arrives from the proxy's address. A per-address
3963limit there is one limit shared by every reader of the proxy, because it cannot tell those readers
3964apart.
3965
3966To keep room for small pages, the budget caps the memory held by responses larger than 256 KiB
3967(`server.SmallPage`) at 48 MiB (`server.MaxLarge`; see
3968[Web server (`valley-web`)](./reference.md#web-server-valley-web)). While a response is 256 KiB or
3969smaller, its pieces count only against the 64 MiB total. As soon as a response grows past 256 KiB,
3970all of its pieces — including the first 256 KiB — count against the 48 MiB large-response cap as
3971well. Slow readers of large pages can therefore hold at most 48 MiB at once, leaving at least 16 MiB
3972for small pages.
3973
3974Checked by `web-server-unit` (`TestSlowReadersShareTheBudget`), which opens stalled connections
3975requesting more than 64 MiB in total across three large page sizes: one 64 KiB piece past 256 KiB, 1
3976MiB, and 4 MiB. Counting a large response's first 256 KiB against the 48 MiB cap prevents 64 stalled
39771 MiB responses from consuming all 64 MiB. The stalled readers hold at most 48 MiB, and requests for
3978the knots page, a knot page, and a directory page still succeed.
3979
3980### A source request's git work
3981
3982At most 8 source requests (tree, file, log, or archive) may run `git` at once (`server.MaxGit`). A
3983request takes a `git` slot only after its view is ready and its route is resolved through it (see
3984[Requests, loads and indexes](#requests-loads-and-indexes)). Waiting for an export to be read or an
3985index to be built therefore uses the request's 15-second deadline and holds no `git` slot. To keep a
3986slow `git` command from holding a slot for the full request timeout, a source request may hold its
3987`git` slot for at most 5 seconds from when it takes the slot (`web/server/server.go`). That 5-second
3988limit covers all of the request's `git` commands. When the 5 seconds expire, the server stops `git`,
3989releases the slot, and answers `503`. When `git` finishes in time, the request releases its `git`
3990slot before rendering HTML, so page rendering holds no `git` slot (`web/server/render.go`).
3991
3992Rendering Markdown takes memory that grows with the file, not with the page: the renderer parses the
3993whole document before it writes anything. The renderer caps what it builds (`web/markdown`). A
3994document holds at most 65,536 blocks (`markdown.MaxBlocks`), counting quotes, lists and list items.
3995Its inline content takes at most 262,144 nodes (`markdown.MaxInlineNodes`). Within a block, at most
39964,096 brackets wait for their `]`. Past each cap, the rest of the document renders as escaped text.
3997To match a reference such as `[label]`, the renderer copies the label. A render copies at most 4 MiB
3998of labels, and past that a reference renders as text. So one render of a file of up to 1 MiB
3999allocates less than 128 MiB in all when `MaxOutput` is set, as the server always sets it
4000(**implemented**). `MaxOutput` zero means unlimited output.
4001
4002Checked by `web-unit` (`TestAllocation`). It renders each input of the renderer's adversarial suite
4003at 1 MiB, measures the bytes allocated and the heap's peak with `runtime.ReadMemStats`, and fails if
4004either passes 128 MiB. Some inputs nest emphasis or links, or repeat a reference, and are built to
4005stay under the inline cap. Each of them is measured a second time, padded to 1 MiB with the content
4006that allocates most. The most any input allocates is 69 MiB: a paragraph past the inline cap
4007followed by empty headings past the block cap. `TestRepositoryDocs` checks that each of the
4008repository's documents, the largest among them `docs/reference.md`, renders whole and takes less
4009than a quarter of each cap.
4010
4011At most 2 source requests render Markdown at once (`server.MaxRendering`). Two renders allocate at
4012most 256 MiB, and rendered responses hold at most 64 MiB (`server.MaxBuffered`; see
4013[Slow readers](#slow-readers)). Together that is 320 MiB, well under the 1 GiB `MemoryMax` that
4014`valley-web` has by default (`webMemoryMax`, a **deployment choice**). The server's other memory,
4015such as the exports it has read and the `git` processes it runs, is separate and not counted in
4016these 320 MiB. A request waits for a rendering slot while it still holds its `git` slot, and
4017releases the `git` slot once it has one (`web/server/source.go`). The requests that hold a file's
4018text while waiting to render are therefore among the 8 that hold a `git` slot. The renderer stops
4019once its output would pass 2 MiB, or once the request's context ends (`web/markdown`).
4020
4021Each source route also bounds the work it asks `git` to do (`web/server/source.go`; see
4022[Web server (`valley-web`)](./reference.md#web-server-valley-web) for the limits). When resolving a
4023path through intermediate directories, the server runs `git ls-tree` without `--long`, because
4024`--long` looks up the blob size of every entry in each directory. All directories along the path
4025share one 4 MiB output budget (`server.MaxRead`), so resolving a deep path reads no more from `git`
4026than listing a single directory.
4027
4028On a history page, the server runs `git log --date-order --max-count=50` starting from the page's
4029starting commits (`<commit>` on the first page, or the commits in `?from=` on an older page). Each
4030page starts `git log` directly at those commits and skips no commits of newer pages. For each page,
4031`git` prints at most 50 commits (`server.LogPage`), and the page reads at most 4 MiB of that output
4032(`server.MaxRead`). All of this `git` work runs within the 5 seconds that the request holds its
4033`git` slot.
4034
4035As the page lists commits, it tracks the frontier for the next older page: the page's starting
4036commits plus the retained parents of each commit shown on the page, minus the commits shown on the
4037page. A commit's retained parents are its first 128 parents (`server.MaxParents`). Only a merge with
4038more than 128 parents has parents that are not retained. Because `--date-order` never lists a commit
4039before any of its children, every unshown ancestor that `<commit>` reaches through retained parents
4040is reachable from that frontier. No commit already shown on this page or a newer page is reachable
4041from it.
4042
4043While the frontier holds at most 64 commits (`server.MaxFrontier`), the "Older" link passes all of
4044them in `?from=`. Following "Older" from the first page then visits each ancestor reached through
4045retained parents once, including across merges. When wide merges leave more than 64 commits in the
4046frontier, the "Older" link passes the first 64 and the page adds a separate `?from=<id>` link for
4047each remaining commit. Those links keep every ancestor along retained parents reachable, though two
4048separate links may converge on a shared ancestor and show it on both paths. To bound the number of
4049links on a page, a page stops before any commit after the first that would leave more than 192
4050unshown commits (`server.MaxLeftToShow`). The first commit on a page always fits within 192 because
4051the page starts from at most 64 commits (leaving 63 others) and follows at most 128 parents
4052(`server.MaxParents`).
4053
4054`git log` prints all of a commit's parent IDs on one line, which for a merge with 400 parents
4055exceeds 16 KiB. To keep a long parent line from truncating a commit's ID or subject, the server
4056formats each commit as two NUL-terminated records — first its ID and parents, then its date, author,
4057and subject — and keeps up to 16 KiB of each record. Sixteen KiB holds a commit ID and 128 parents
4058in both SHA-1 and SHA-256 object formats. When a merge has more than 128 parents, the page shows the
4059commit with a note. The page parses only the first 128 parents, so a parent line cut at 16 KiB still
4060parses. A merge with any number of parents therefore renders, within the request's usual limits on
4061output and time.
4062
4063The page retains only a merge's first 128 parents for older pages. This limit applies to the
4064frontier alone. `git log` still walks every parent of the merge, so a commit reached only through a
4065later parent may appear on the same page, and the page retains that commit's parents in turn.
4066Commits reached only through later parents may be omitted from older pages.
4067
4068When the receiver accepts a bundle or carries a repository into a new generation, it writes a
4069commit-graph into the repository (`web/export/bundle.go`). Already-activated generations are left
4070untouched, so a generation activated without commit-graphs has none until the next activation
4071carries its repositories again. With a commit-graph, `git merge-base` checks commit reachability
4072without parsing each commit, and `git log --date-order` walks the history faster. Without a
4073commit-graph, `git log --date-order` walks the commit history before printing a commit, within the 5
4074seconds that the request holds its `git` slot.
4075
4076`export.Reachable` requires every commit ID to match the length of the project's `source_tip`
4077(`web/export/bundle.go`). In a SHA-256 repository, `git` treats 40 hex digits as an abbreviated
4078prefix, and in a SHA-1 repository it treats 64 hex digits as the commit named by their first 40 hex
4079digits. Requiring the exact length of `source_tip` gives each page a single address.
4080
4081Checked by `web-server-unit`:
4082
4083- `TestSourceGitHasItsOwnBound`, `TestAWaitForAViewHoldsNoGitSlot`, and
4084 `TestRenderingHoldsNoGitSlot` test a `git` command that never finishes, a slow export read, and a
4085 slow page render.
4086- `TestResolveSharesOneBudget` resolves a path through two large directories.
4087- `TestHistoryAcrossMerges` follows the "Older" links across a two-branch merge that spans multiple
4088 pages and checks that every commit appears once. `TestWideHistoryStaysReachable` follows every
4089 link from a 65-branch merge and reaches every commit. `TestCrowdedHistoryEndsEarly` serves a merge
4090 whose next commit would leave 199 unshown commits and reaches every commit through its links.
4091- `TestMergeOfManyParents` serves a 420-parent merge whose ID and parent line exceed 16 KiB, both as
4092 the first commit on a page and as the second.
4093- `TestSHA256CommitIDs` serves a SHA-256 project.
4094
4095Also checked by `web-unit` (`TestAcceptBundle` and `TestReachable`), which test the commit-graph and
4096both object formats.
4097
4098### Source archives
4099
4100A reader can download a commit's tree as a gzipped tar archive at
4101`/<group>/<project>/source/archive/<commit>.tar.gz` (`web/server/archive.go`; see
4102[Web server (`valley-web`)](./reference.md#web-server-valley-web) for routes, headers, and limits).
4103Every directory page links to the archive for its commit.
4104
4105The archive covers the same source as the file pages: the tree of a commit that the project's
4106published `main` reaches, and none of the history. It is not limited to what a file page shows. It
4107also holds binary files, and files larger than the 1 MiB a file page shows (`server.MaxFile`).
4108
4109`/<group>/<project>/source/archive/main.tar.gz` redirects with `302` to the archive of the commit at
4110`main`'s tip, using the same headers as `/<group>/<project>/source/`. The redirect is temporary
4111because `main` moves. A script or agent can fetch `main.tar.gz` with `curl -L` to download the
4112current tip directly. `main` is the only name the route accepts in place of a commit ID; any other
4113ref name, `HEAD`, or an abbreviated ID answers `404`. Because the redirect reads only the export's
4114`source_tip`, it runs no `git` command and takes no `git` slot, just like
4115`/<group>/<project>/source/`.
4116
4117Both archive routes use the same project lookup, reachability check, and authorization check as the
4118other source routes (`web/server/source.go`). A project the reader may not see answers `404` on both
4119routes, matching its tree page, and takes no `git` slot.
4120
4121The server writes the tar archive itself, in Go, from the commit's tree. It lists the tree with
4122`git ls-tree -r -t -l -z`, and reads every file's content with one `git cat-file --batch` process.
4123Both commands run through the `export` package's `git` helpers, in the same isolated environment as
4124every other source request. Neither command reads git attributes, so the archive does not apply
4125`export-ignore` or `export-subst`. The archive is the commit's tree byte for byte.
4126
4127Every entry is placed under one directory named from the project's web name and the commit's first
412812 hex digits. The entries follow the tree's order, and each directory comes before what it holds.
4129
4130- A regular file has mode `0644`, or `0755` when git records it as executable (`100755`).
4131- A symbolic link is a tar symbolic link whose target is the link's content in git. The server never
4132 follows it.
4133- A submodule is an empty directory.
4134- Every entry carries the commit's committer time as its modification time, uid and gid 0, and empty
4135 user and group names.
4136- Go's tar writer chooses USTAR or PAX for each header, whichever the header needs.
4137
4138The server compresses the tar stream in process with Go's `compress/gzip` at a fixed compression
4139level, with an empty file name and zero modification time in the gzip header. The archive's bytes do
4140not depend on the time of the request, the repository's refs, its git configuration, or attributes.
4141The tar paths include the project's web name. So a commit produces the same archive bytes on every
4142request to the same build under the same web name.
4143
4144The server checks the tree's listing before it reads any file. It refuses an archive whose files add
4145up to more than 32 MiB before compression (`server.MaxArchiveInput`). It also refuses one whose tree
4146holds more than 10,000 entries (`server.MaxArchiveEntries`), or whose listing is longer than 4 MiB
4147(`server.MaxRead`). A refused archive answers `500` with the "Page too large" page.
4148
4149The server then streams each file from `git` through the tar and gzip writers into the response
4150body. The body uses the same response budget (`server.MaxBuffered`) and 8 MiB response limit
4151(`server.MaxResponse`) as HTML pages. So the server holds the compressed archive in memory, and
4152never a whole file. It builds the archive while holding the request's `git` slot (within the
41535-second `git` timeout), releases the slot once the archive is built, and re-checks the stored
4154authorization before writing the first byte. A compressed archive that exceeds 8 MiB is discarded
4155and answers `500` with the "Page too large" page. Like every response, an archive carries
4156`Cache-Control: private, no-store`, because the authorization can change while a commit's archive
4157URL stays the same.
4158
4159Checked by `web-server-unit`:
4160
4161- `TestSourceArchive` compares the archive's entries, in order, against the commit's tree, with
4162 their modes, times, and contents. It checks that two requests return identical bytes, verifies the
4163 headers and the link on directory pages, and checks the `404` response for invalid or unreachable
4164 commit names and for projects excluded by the authorization.
4165- `TestArchiveAppliesNoAttributes` commits a `.gitattributes` that sets `export-subst` and
4166 `export-ignore`, and a file that holds `$Format:%ar$`. The archive holds every file, and that file
4167 verbatim. The test then moves a ref, and adds attributes and git configuration to the repository,
4168 and the archive keeps the same bytes.
4169- `TestArchiveLinksAndSubmodules` checks a symbolic link, a submodule, an executable file, and the
4170 PAX format for a long name and a long link target.
4171- `TestArchiveInputBound` checks that a tree whose files pass 32 MiB, and a tree of more than 10,000
4172 entries, answer the "Page too large" page and hold none of the response budget.
4173 `TestArchiveTooLarge` checks an archive whose compressed bytes exceed a shortened `maxResponse`
4174 bound.
4175- `TestArchiveStreamsIntoTheBody` serves a 24 MiB file that compresses to less than 256 KiB. Once
4176 the response is rendered, it holds only the budget pieces that the compressed body fills.
4177- `TestArchiveOfMainsTip` checks the redirect's status, `Location`, and headers against
4178 `/<group>/<project>/source/`. It verifies that the redirect takes no `git` slot and follows `main`
4179 when `main` advances, and checks that `HEAD.tar.gz` and a branch name answer `404`.
4180- `TestHiddenProjectAnswersLikeMissing` checks the redirect for a project excluded by the
4181 authorization.
4182
4183`web-push-e2e` downloads an archive from `valley-web`, lists it with `tar`, and fetches
4184`main.tar.gz` with `curl -L` to verify that it returns the same bytes.
4185
4186### Unpublished blockers
4187
4188A knot's `waiting_on` lists each `blocked_by` reference that remains a blocker. A reference remains
4189a blocker while it names an open knot, a missing knot, or a knot in a graph that could not be read
4190(`knot/derive.go`). In `export.json`, the export removes every reference into an unpublished project
4191from `waiting_on` (`web/export/project.go`). The knot's `state` is unchanged. When the export
4192removes at least one reference from a knot's `waiting_on`, it sets `"waiting_on_hidden": true` on
4193the knot. The server applies the same rule for each reader, stripping references into projects
4194outside that reader's view (see [Each reader's view](#each-readers-view)). The knots page's "waits
4195on" chip then includes "a knot in an unpublished project" alongside any blockers the reader sees
4196(`web/server/knot.go`; see [Web server (`valley-web`)](./reference.md#web-server-valley-web)).
4197
4198In `export.json`, `blocked_by` and `edges` still keep each hidden blocker's `"<project>:<id>"`
4199reference. When a knot names a single hidden blocker, a reader of `export.json` can tell from
4200`waiting_on_hidden` whether that reference remains a blocker. The field is present while it does,
4201and absent once the hidden knot has a terminal status, even when an exported blocker keeps the knot
4202`blocked`. The export permits this inference.
4203
4204Checked by `web-unit`, where `TestBuildHidesForeignEdges` checks that `waiting_on_hidden` is set on
4205the fixture's knot with a hidden blocker, and `TestWaitingOnHiddenFollowsAHiddenBlocker` checks that
4206the field is omitted once that hidden blocker is done. Also checked by `web-server-unit`
4207(`TestWaitsOnChip`), which checks that the knots page's chip lists both the public blocker and the
4208unpublished one.
4209
4210## The receiver
4211
4212`valley-web-receive` receives export uploads from `valley-web-publish` into a state directory using
4213the three-step upload protocol in package `export` (`web/cmd/valley-web-receive/`). `valley-web`
4214serves the activated export from that directory. The receiver's flags, routes, and limits are in
4215[Web export receiver (`valley-web-receive`)](./reference.md#web-export-receiver-valley-web-receive).
4216
4217### Two processes over one state directory
4218
4219`valley-web-receive` and `valley-web` run as separate processes that share only the state directory.
4220The receiver opens the directory with `export.OpenStore` and is its only writer. `valley-web` opens
4221it with `export.OpenReadOnly` and writes nothing to the store (see
4222[Reading the state directory](#reading-the-state-directory)). Because the store coordinates access
4223with `flock(2)` locks across processes, activating a new export never deletes a generation that an
4224in-flight `valley-web` request still holds (`web/export/store.go`).
4225
4226Running the receiver and `valley-web` as separate processes isolates public reads from uploads in
4227three ways:
4228
4229- **Separate budgets.** Each process has its own listener and concurrency limits. The receiver
4230 listens on the address the publisher reaches, and `valley-web` listens on the address readers
4231 reach. When uploads saturate the receiver, it answers additional upload requests with `503` while
4232 `valley-web` continues serving within its own limits.
4233- **Separate users.** `valley-web` handles requests from any reader. Its user has read-only access
4234 to the state directory and no access to the receiver token, so a fault in `valley-web` cannot
4235 modify the stored export or expose the token.
4236- **Separate memory.** Each process's memory limit is a **deployment choice**. A limit covers both
4237 the Go process and the `git` commands it spawns. On NixOS, the receiver module sets `MemoryMax`
4238 with no swap on each service unit, from its `receiverMemoryMax` and `webMemoryMax` options, which
4239 default to `2G` and `1G`. In containers, each container's memory and swap limits are set where the
4240 container is started; the guide's example commands set both. Without per-process memory limits, a
4241 memory spike in the receiver could exhaust host memory and affect `valley-web`.
4242
4243A single process with two listeners would share one heap, one file-descriptor table, and one Unix
4244user between public reads and uploads, allowing load or a fault on one side to affect the other.
4245
4246### Authenticating the transport
4247
4248Every request to the receiver must carry a bearer token in `Authorization: Bearer <token>`
4249(`web/export/token.go`). The receiver checks this header before routing the request, taking a
4250request slot, or reading any of the request body (`web/cmd/valley-web-receive/`). It hashes both the
4251received `Authorization` header and the expected header with SHA-256 and compares the digests in
4252constant time. If the header is missing or does not match, the receiver replies `401` with refusal
4253code `unauthenticated` and closes the connection.
4254
4255The bearer token and the manifest signature check different things. The manifest signature controls
4256what the edge serves: the receiver stages a manifest only when it opens under a pinned verifier key,
4257and keeps only bodies whose SHA-256 digests and sizes the manifest declares. The bearer token
4258controls who may use the receiver at all. Without the token check, any client able to reach the
4259receiver could force it to verify manifests, stream bodies into staging up to the size caps, or
4260start commit requests that run `git`. The token check rejects unauthenticated requests before any of
4261that work begins.
4262
4263The publisher reads the token from `--receiver-token` (`web/cmd/valley-web-publish/main.go`), and
4264the receiver reads it from `--token-file`. Both use `export.ReadToken`, which requires one line of
426532 to 256 visible ASCII characters. Because the publisher's HTTP client follows no redirects, it
4266sends the token only to the configured receiver URL (`web/cmd/valley-web-publish/upload.go`).
4267Security properties of the token are covered in
4268[The edge's receiver](./security.md#the-edges-receiver).
4269
4270### Bounds
4271
4272The receiver bounds concurrent requests, open connections, body sizes, staged files, and total disk
4273usage (`web/cmd/valley-web-receive/main.go`, `web/cmd/valley-web-receive/receive.go`,
4274`web/export/store.go`; see
4275[Web export receiver (`valley-web-receive`)](./reference.md#web-export-receiver-valley-web-receive)):
4276
4277- **Requests.** At most 4 upload requests and 2 authorization requests run at once, in separate
4278 pools so saturated uploads leave room for an authorization. Any additional authenticated request
4279 receives `503` with a `Retry-After` header and no refusal body, and the publisher retries it after
4280 a pause. Unauthenticated requests take no request slot. Once a request's headers arrive, a
4281 per-step time limit bounds connection reads and writes as well as store operations: 1 minute for a
4282 manifest, 30 minutes for a body, and 30 minutes for a commit. If that limit expires or the client
4283 disconnects while a manifest request is waiting for the store lock, measuring the state directory,
4284 sweeping it, or waiting for an older upload's body writers to stop, `Store.Stage` stops and
4285 releases the lock. It checks the context before each directory it deletes or creates, and each
4286 deletion stops part way once the context is done, leaving the rest in the trash for the next
4287 sweep. Likewise, if the limit expires or the client disconnects while a commit request waits for
4288 the lock or builds repositories, `Store.Activate` kills the process group of any running `git`,
4289 with every process that `git` started, and activates nothing. Each `git` runs in a process group
4290 of its own (`web/export/bundle.go`).
4291- **Connections.** At most 32 connections are open at once; additional connections wait in the
4292 listen queue. The server closes a connection that sends no complete request headers within 10
4293 seconds, and closes an idle connection after 1 minute. Every request — including `OPTIONS *` —
4294 reaches the receiver's own handler, which refuses unauthenticated requests and closes their
4295 connections before reading any request body. On shutdown, the receiver closes its listener first,
4296 which immediately unblocks any wait for a free connection slot. It gives in-flight requests up to
4297 10 seconds to finish, then closes their connections to cancel their contexts, which kills the
4298 process group of any commit's `git`. It waits up to 5 seconds more for those requests and their
4299 `git` subprocesses to exit before terminating, so a stop takes at most 15 seconds regardless of
4300 how many connections are open.
4301- **Bodies.** At step 1, `Manifest.CheckSizes` refuses a manifest as `too-large` when any declared
4302 body exceeds `--max-body` or when the unique declared bodies together exceed `--max-upload`. At
4303 step 2, `export.StageBody` checks `--max-body` again and reads at most one byte past the declared
4304 size.
4305- **Staging.** `Store.Stage` discards every older staged upload when it stages a manifest, so at
4306 most one upload is staged at a time. The staging directory holds that upload's completed bodies
4307 and at most one partial file for each body currently being uploaded. A request for a body while
4308 another request is already staging the same body of the same upload receives `503`. Each body
4309 request registers as a store writer (`Store.Writer`). Before `Store.Stage` deletes an older
4310 upload, it stops that upload's body writers and waits until each has closed and removed its
4311 partial file. As a result, no deleted partial file remains held open on disk, and a stalled body
4312 request from the older upload never blocks the newer upload's request for the same body with
4313 `503`. `Store.Activate` stops and waits for the upload's body writers in the same way before
4314 removing `bodies/`. Staging remains private to the receiver's user until activation (see
4315 [Reading the state directory](#reading-the-state-directory)).
4316- **Storage.** `--max-upload` counts each unique body once, whereas activation writes a bare
4317 repository for every exported project (even when several projects share one bundle) and writes a
4318 new generation alongside any existing ones still held. The receiver therefore caps the disk space
4319 used by the entire state directory at `--max-storage` (`Store.MaxStorage`). At step 1,
4320 `Store.Stage` estimates the post-upload directory size by taking current disk usage (excluding
4321 staging directories being replaced) and adding each unique declared body once plus one repository
4322 per project, sized at the larger of its bundle or the carried repository plus 1 MiB for Git's own
4323 files. Because an old generation that a reader held during the previous activation's sweep may now
4324 be free, `Store.Stage` sweeps unheld old generations and re-measures before refusing a manifest as
4325 `too-large`. Because a repository with many small objects can still take more space for its pack
4326 index and commit-graph than the step-1 estimate, `Store.Activate` re-measures the state directory
4327 after building each repository. If the directory exceeds `--max-storage`, `Store.Activate` removes
4328 the newly built repository and refuses the commit as `too-large`.
4329
4330 `--max-storage` is best effort. Building a single repository can temporarily pass the cap by the
4331 amount the step-1 estimate missed before the post-build check removes it, and a file held open
4332 after deletion consumes disk space that directory measurements cannot see. The hard bound is the
4333 filesystem the state directory lives on: a fixed-size volume or a quota. Which mechanism an edge
4334 uses, and its size, is a **deployment choice**. Every edge should use one sized slightly above
4335 `--max-storage` (see [Run the web edge](./guide.md#run-the-web-edge)).
4336
4337The receiver tracks the newest staged upload in memory. After a restart, it refuses a body or commit
4338for an upload staged before the restart with `no-manifest`, and the publisher signs a new manifest.
4339
4340### Running the receiver and `valley-web`
4341
4342On NixOS, `services.valley.webReceiver` runs two systemd units, `valley-web-receive` and
4343`valley-web` (`nix/web-receiver.nix`). They run as users `valley-web-receive` and `valley-web`, both
4344in group `valley-web`. The receiver unit owns the state directory (`/var/lib/valley-web` by default)
4345with mode `0750`, so `valley-web` reads it through the shared group, while `valley-web`'s unit
4346mounts the state directory read-only. When `origin` is set, systemd-tmpfiles creates the state
4347directory owned by `valley-web-receive` (mode `0750`) and `<stateDir>/browser` inside it owned by
4348`valley-web` (mode `0700`). `valley-web`'s unit can write only `<stateDir>/browser`, and the
4349receiver's unit cannot access `<stateDir>/browser`. Because systemd-tmpfiles gives the state
4350directory the owner that `StateDirectory` on `valley-web-receive.service` expects, systemd does not
4351recursively chown `<stateDir>/browser` when starting the receiver. The receiver unit reads the token
4352file as a systemd credential from a path outside the Nix store. Aside from those two directories,
4353the only writable paths in either unit are temporary: each unit's private `/tmp` and `/var/tmp` from
4354`PrivateTmp` (invisible to other units and removed by systemd when the unit stops) and the host's
4355`/dev/shm` from `PrivateDevices`. Neither unit requires the other. `valley-web` starts after the
4356receiver and keeps serving while the receiver restarts. Each unit has its own `MemoryMax` with no
4357swap.
4358
4359On a host that does not run NixOS, the `valley-web-image` package builds a container image with Nix
4360(`nix/packages.nix`). It contains `valley-web`, `valley-web-receive`, and the `git` binary both run.
4361Its `/etc/passwd` and `/etc/group` define users `valley-web-receive` (uid 990) and `valley-web` (uid
4362991), both in group `valley-web` (gid 990). Its volume directory, `/var/lib/valley-web`, is owned by
4363the receiver's user with mode `0750` and contains `browser/`, owned by `valley-web` with mode
4364`0700`. The image defaults to user `valley-web` and defines no entrypoint or default command. An
4365edge runs two containers from this image sharing the state volume: the receiver runs as
4366`valley-web-receive` with the state volume writable, and `valley-web` runs as `valley-web` with the
4367state volume read-only and a second writable volume mounted at `/var/lib/valley-web/browser` (see
4368[Run the web edge](./guide.md#run-the-web-edge)). How an edge runs the containers, where they
4369listen, how the token reaches them, and each container's memory and swap limits are **deployment
4370choices**.
4371
4372Checked by:
4373
4374- `web-receiver-unit`, which runs the receiver as a separate process over the shared fixture and
4375 real `git`:
4376 - `TestAnUploadActivatesAndValleyWebServesIt` runs each step of an upload with the real
4377 `valley-web` serving the activated export, and checks that replaying the manifest or commit is
4378 refused.
4379 - `TestAnUnauthenticatedRequestIsRefused` checks that requests without a valid token are refused
4380 before anything is staged.
4381 - `TestAManifestIsAdmittedOnlyWhenFresh` checks that stale, future-dated, foreign-key, and
4382 foreign-destination manifests are refused.
4383 - `TestABodyIsKeptOnlyWhenItVerifies` checks that invalid bodies are refused, a concurrent upload
4384 of the same body receives `503`, and an interrupted body upload leaves the active export
4385 unchanged.
4386 - `TestAnOversizedUploadIsRefused` and `TestAnUploadPastTheStorageCapIsRefused` check that uploads
4387 exceeding `--max-body`, `--max-upload`, or `--max-storage` (including a manifest naming one
4388 bundle for eight projects) are refused while uploads within the caps succeed.
4389 - `TestASaturatedUploadLeavesValleyWebServing` holds all request slots with stalled manifests and
4390 then holds all connections with incomplete headers while `valley-web` serves every page, and
4391 checks that a body upload completes once the header timeout closes the stalled connections.
4392 - `TestOptionsStarHoldsNoConnection` sends `OPTIONS *` with a withheld body on every connection
4393 slot and checks that each is answered immediately and an upload succeeds.
4394 - `TestAManifestStopsWaitingWhenItsClientGoesAway` checks that a manifest waiting on the store
4395 lock stages nothing after its client disconnects.
4396 - `TestANewerManifestStopsTheOlderUploadsBodies` checks that staging a newer manifest stops a
4397 stalled body upload of the older manifest with `superseded`, leaves no partial file open, and
4398 accepts the newer manifest's upload of the same body.
4399 - `TestAReleasedGenerationMakesRoomForAnUpload` checks that a manifest is refused for space while
4400 a reader holds a large old generation and is accepted once the reader releases it.
4401 - `TestStopsOnSIGTERM` checks that `SIGTERM` stops the receiver when all connections are held. It
4402 allows the 10-second stop and 5-second drain timeouts plus 5 seconds of tolerance, 20 seconds in
4403 all, and waits up to 25 seconds for the receiver to exit.
4404 - `TestACommitWhoseClientGoesAwayStopsItsGit` and `TestAStopWaitsForTheGitACommitRuns` run a `git`
4405 that stalls in `commit-graph` as a shell with a forked child that holds `git`'s output open.
4406 They check that a client disconnecting during a commit, and a `SIGTERM` during one, each kill
4407 both the shell and its child. After the disconnect, the bundle stays staged and the commit made
4408 again activates the upload. After the `SIGTERM`, the receiver exits only once the commit has
4409 ended.
4410- `web-unit`, which tests `Store.Stage` and `Store.Activate` lock cancellation
4411 (`TestStoreWaitsForItsLockUntilTheContextIsDone`), a capacity sweep that stops once its context is
4412 done (`TestStoreSweepStopsWithItsContext`), stopping active body writers on discard and commit
4413 (`TestStoreStopsTheWritersOfDiscardedBodies`), post-build storage enforcement
4414 (`TestStoreHoldsActivationToMaxStorage`), and end-to-end publication from `valley-web-publish` to
4415 the real receiver and `valley-web` including wrong-token refusal and grant withdrawal
4416 (`TestPublishesToTheRealReceiver`).
4417- `module-eval`, which checks the users, file modes, credentials, memory caps, and publisher IP
4418 address filter rendered by the NixOS modules, and checks that evaluation fails when the publisher
4419 has no allowed address; `web-publisher-e2e`, which checks in a NixOS VM that the token reaches the
4420 publisher unit as a credential while the source file stays readable only by root, and that the
4421 unit can connect to a listener on its allowed address while connections to disallowed IPv4 and
4422 IPv6 listeners fail (even though root can reach them); and `web-image`, which unpacks the
4423 container image and checks its programs, users, volume, and default user.
4424- `web-push-e2e`, which runs the full push path in the build sandbox as a single user using the
4425 packaged `valley-web-publish`, `valley-web-receive`, `valley-web` (as built and wrapped by
4426 `nix/packages.nix`), `valley` CLI, and `git`. It verifies that a pass publishes two projects that
4427 `valley-web` serves at their group URLs, that a short alias and a former name redirect with `308`,
4428 and that an upload with a wrong token fails as `unauthenticated` while the edge keeps serving. It
4429 then verifies that withdrawing a read grant removes the project on the next pass, that both
4430 servers preserve the active export across a restart, and that stopping the receiver leaves
4431 `valley-web` serving until the receiver starts again and the next pass applies the withdrawal.
4432 Because neither `module-eval` nor `web-image` runs the edge units or containers, runtime
4433 enforcement of the memory caps and sandbox on the edge is unchecked.
4434
4435## The life of a change
4436
44371. An author pushes a topic branch. The hook accepts it, and the bus gets `ref-updated`. The mirrors
4438 never get the branch.
44392. The author marks the branch's head ready with `valley ready`. That writes the change's record at
4440 `refs/the-valley/changes/main/<change-id>`, with the head as a version. `valley pending` and
4441 `valley changes --json` list the change by its handle.
44423. The operator approves one head of the change: with `[a]pprove` in `valley review <handle>`, or
4443 with `valley approve <handle> --head <sha>` from a front end. Approval reuses eligible evidence
4444 `origin` already holds for that head's tree (see [The valley command](#the-valley-command)), runs
4445 the remaining required checks over that head, and in one push files any new evidence and the
4446 integration request `refs/the-valley/integration-requests/main/c-<change-id>` at that head. The
4447 hook verifies each note and the `approve` grant.
44484. On its next pass the integrator reads the records. It refuses a request that would bring a
4449 version of a change that is not `ready`, and one whose commits hold a merge. Otherwise it builds
4450 the candidate, derives the policy, judges the evidence, and lands or refuses. If the author
4451 unreadies or withdraws the change before it lands, the request stays and does not land; a
4452 withdrawal also deletes it. Only a record written in the moment before the target moves is
4453 missed.
44545. On a landing, the publisher sends `ref-updated` to the bus and pushes `main` and tags to the
4455 mirrors. `valley status <handle>` shows the outcome, and the version's landing evidence.
4456
4457A branch no record is on is approved by its name and requested under it.
4458
4459## What a deployment supplies
4460
4461The host module installs the valley's services and hooks (`nix/valley-host.nix`). A deployment
4462supplies the host configuration, the project declaration and the secrets (**deployment choice**).
4463[Running a valley host](./guide.md#running-a-valley-host) walks through each step.
4464
4465- **The host configuration.** The host's NixOS configuration imports
4466 `the-valley.nixosModules.valley-host` and points `services.valley.config` at `valley.cue`. It
4467 enables the services the host runs, such as the bus, the integrator and the identity compiler, and
4468 names the instance repository in `services.valley.integrator.instanceProject`. It can also declare
4469 static SSH keys in `services.valley.authorizedKeys` beside the keys the registry compiles.
4470- **The declaration.** `valley.cue` names the projects, the refs each one protects, their mirrors,
4471 and the backup policy. A backup is a restic run of the data directory over sftp. By default it
4472 runs nightly and keeps 7 daily, 4 weekly and 6 monthly snapshots (`schema/valley.cue`).
4473- **The secrets.** The deployment provisions each secret as a file outside the Nix store. These are
4474 the integrator's signing key (`services.valley.integrator.signingKeyFile`), the git user's ssh key
4475 for mirror pushes, and the four backup files (`services.valley.backup.*`): the repository URL,
4476 password, ssh key and known hosts. The build refuses a host whose declaration enables backup
4477 without all four backup files (`nix/valley-host.nix`).
4478
4479## Not deployed or not wired yet
4480
4481| What | State |
4482| -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
4483| `sigverify` | On `main` and tested. Nothing calls it. |
4484| Hardware-backed keys in the registry | `identity compile` verifies YubiKey PIV attestations. No host service or gate uses them. |
4485| SSHSIG evidence | Attestations use the signed-note format. |
4486| Approvals | The integrator checks evidence only. No approval is required for any path class. |
4487| Approval carry | `valley checks` reports a change's carry mode. Nothing acts on it. |
4488| The restacker | The host module runs it on each project listed (`services.valley.restacker`). It is off by default, and a deployment registers its principal. |
4489| The check worker | The host module runs it on a timer (`services.valley.worker`). It is off by default. |
4490| The build slice | `services.valley.buildSlice` caps every build of the nix daemon. It is off by default. |
4491| The web server and export | `valley-web-publish` uploads exports, `valley-web-receive` activates them, and `valley-web` serves them (`web/`). `services.valley.webReceiver` and the `valley-web-image` package run the receiver and `valley-web` on an edge. Whether an edge runs them is a deployment choice. |
4492| Named readers at the edge | `valley-web-publish` exports each project a named principal may read, with that principal in its authorization. `valley-web` signs readers in and serves each session as its principal only when started with `--origin`. Whether an edge sets an origin is a deployment choice. |
4493| Withdrawal without the instance and registry | The policy path withdraws a project without reading any content, but it signs nothing when it cannot read the instance repository or the identity registry. A project whose own policy cannot be read keeps its stored readers that a grant still covers. |
4494| Filesystem sandbox for the web publisher | The unit's filesystem is read-only and named key paths are hidden, but the unit can read the host's other repositories, not only the declared ones. |
4495| Clones from the edge | `valley-web` serves no git clone route. |
4496| Read grants over ssh | sshd lets every admitted key fetch every repository (`valleyhook/shell.go`). Read grants govern only web exports. |
4497| Reviews | `review/` defines the record and its history. The hook refuses every push to them. |
4498| A crash-safe landing ledger | Landing is several separate ref updates. |
4499| Policy and registry snapshot in the outcome | The outcome record holds the head, the tip and an evidence hash. |
4500| Registry compile on an instance landing | The compiler runs on its 5-minute timer only. |
4501| Bus authentication | The bus listens on localhost with no authentication. |