gunk-dev/the-valley

reference.md

source34d12a6791c4main's published tip history
387.2 KiB · Rendered
1# Reference
2
3This manual specifies the commands, environment variables, git refs, wire formats, JSON outputs, and
4CUE schemas of the-valley.
5
6Claims below separate code guarantees (`implemented`), instance configuration (`deployment choice`,
7covering `valley.cue`, `services.valley`, `policy/`, and `identity/`), and mechanisms that do not
8work yet (`not built`). Unless a rule or option is marked `deployment choice` or `not built`, it is
9`implemented` at HEAD. See [Concepts and glossary](./concepts.md) for how the pieces fit together
10and [A guide to working in the valley](./guide.md) for step-by-step workflows.
11
12- [CLI reference](#cli-reference) — `valley` subcommands, flags, exit codes, naming rules, and host
13 helpers.
14- [Environment variables and configuration](#environment-variables-and-configuration) — git config
15 keys, environment variables, client state files, and NixOS options.
16- [Project storage ref layout and bounds](#project-storage-ref-layout-and-bounds) — ref namespaces,
17 push permissions, object types, and size limits.
18- [Wire formats and JSON schemas](#wire-formats-and-json-schemas) — change records, restack reports,
19 review records, signed notes, digest manifests, transfer statements, outcome records, knots, CLI
20 JSON contracts, the web export, and the web server.
21- [CUE configuration schemas](#cue-configuration-schemas) — `schema/valley.cue`,
22 `schema/verification.cue`, `schema/read.cue`, `schema/attestation.cue`, `schema/identity.cue`,
23 `schema/node.cue`, and `schema/events.cue`.
24
25---
26
27## CLI reference
28
29`valley` is the command-line tool for authoring, reviewing, approving, rebasing, and inspecting
30changes and the plan graph.
31
32```sh
33valley <verb> [args]
34```
35
36### Naming changes, handles, branches, and requests
37
38Commands that inspect or act on an existing change (`status`, `review`, `approve`, `rebase`,
39`unready`, and `withdraw`) accept a Change ID, a short handle, or a branch name, whereas
40`valley ready [<branch>]` takes a branch name as its positional argument.
41
42```sh
43valley status kqxm # by handle
44valley status kqxmnxvpwlkmqtsrzyoukklnpmqrstuv # by 32-letter Change ID
45valley status demo:kqxm # by <repo>:<handle>
46valley status topic # by branch name
47valley status origin/topic # explicitly as a branch
48```
49
50- **Change ID (`[k-z]{32}`):** A 32-character lowercase identifier using letters `k` through `z`.
51 `valley ready` generates a new Change ID from 16 random bytes (encoding each nibble `0`–`15` as
52 `z` down to `k`).
53- **Handle (`[k-z]{4,32}`):** The shortest prefix of a Change ID (at least 4 characters) that no
54 other change currently recorded on `origin` shares. A handle can lengthen if a later change shares
55 its prefix. In single-repository commands, `<repo>:<handle>` is also accepted when `<repo>`
56 matches the current repository's name. In multi-repository listings (`--all`), a Change ID
57 recorded in more than one listed repository is formatted as `<repo>:<prefix>` in each.
58- **Branch name:** Any ref name accepted by `git check-ref-format refs/heads/<name>`. No
59 slash-separated segment may be empty, start with `.`, or end with `.lock`; the name may not end
60 with `.`, contain `..` or `@{`, or contain ASCII control characters, space, or `~ ^ : ? * [ \`. In
61 change records (`record.json`), `branch` must also be valid UTF-8; in restack reports
62 (`report.json`), branch names are additionally bounded to 255 bytes (`maxBranchLen = 255`).
63- **Resolution order:**
64 - A name starting with `origin/` is always treated as the branch `<branch>`.
65 - A handle that is also a branch name on `origin` is refused as ambiguous unless the change's
66 active version records that branch.
67 - When a branch name is given (with or without `origin/`), `review`, `approve`, `rebase`,
68 `unready`, `withdraw`, and `status` check all records on `origin` whose active version has not
69 landed (`landed` or `landed-recorded`). If exactly one unlanded change's active version records
70 that branch, the command acts on that change at its recorded active version head. If more than
71 one unlanded change's active version records that branch, the command refuses and lists the
72 colliding changes. If no unlanded change is on that branch, `status`, `review`, `approve`, and
73 `rebase` act on the branch directly, whereas `unready` and `withdraw` refuse because they
74 require a recorded change.
75- **Request name (`<request>`):**
76 - For a recorded change: `c-<change-id>` (such as `c-nxvpwlkmqtsrzyoukklnpmqrstuvwxyz`), stored at
77 `refs/the-valley/integration-requests/main/c-<change-id>`.
78 - For an unrecorded branch: the branch name with every `/` replaced by `-`. A branch whose request
79 name would take the reserved `c-<change-id>` shape is refused by `valley approve` and
80 `valley status`.
81- **Principal, project, and run names:** Must match `^[a-zA-Z0-9][a-zA-Z0-9._-]*$`. In the plan
82 graph, principal, project, and run names are additionally bounded to 64 bytes (`MaxName = 64`).
83
84### Exit codes and git environment sanitization
85
86Every `valley` command sanitizes git object-replacement environment variables before running git and
87exits with a small set of status codes.
88
89```sh
90export GIT_NO_REPLACE_OBJECTS=1
91unset GIT_REPLACE_REF_BASE GIT_GRAFT_FILE GIT_OBJECT_DIRECTORY GIT_ALTERNATE_OBJECT_DIRECTORIES
92```
93
94| Exit code | Meaning |
95| :-------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
96| `0` | Command succeeded (`self-update` also exits `0` when already up to date, when another run holds the lock, when pinned, or when the current branch tip already failed and `--retry` is not given). |
97| `1` | Command refused or failed (invalid state, failed check, rejected push, missing git config, runtime error, or invalid CLI flags in `status`, `ready`, `unready`, `withdraw`, `changes`, `pending`, `rebase`, `plan`, or `bin/valley`). |
98| `2` | Invalid `valley knot` or `valley self-update` CLI usage, bad `VALLEY_NOW` timestamp in `knot` or `plan`, or unknown `valley-go` verb. |
99| `3` | Plan graph compare-and-set or precondition conflict in `valley knot` (such as concurrent modification of a field without `--force`, a failed `--if <field>=<value>` check, or a claim held by another run). |
100| `130` | Interrupted by `SIGINT` or `SIGTERM` during `valley review`, `valley approve`, `valley rebase`, or `valley self-update`. |
101
102### `valley ready`
103
104`valley ready` creates or updates a change record on `origin`
105(`refs/the-valley/changes/main/<change-id>`) and marks its active version `ready`.
106
107```sh
108valley ready --stamp
109valley ready [--head <sha>] [--change <id>] [--if-active <sha>] [--stamp] [<branch>]
110```
111
112- **Arguments and flags:**
113 - `[<branch>]`: Branch name (with or without `origin/`). Defaults to the current checked-out
114 branch (`git symbolic-ref --short HEAD`).
115 - `--stamp`: For a new change whose local branch tip is not yet on `origin`, amends the local
116 branch head with a `Change-Id: <id>` trailer, pushes the branch to `origin` with a lease on the
117 remote branch state read at start, and creates `v1`. Refused if the change already has a record
118 on `origin`, if the local head commit is already on `origin/<branch>`, or if combined with
119 `--head` or `--if-active`.
120 - `--head <sha>`: Marks a specific commit `<sha>` ready instead of `origin/<branch>`. `<sha>` must
121 already be an ancestor of `origin/<branch>`.
122 - `--change <id>`: Specifies the 32-letter Change ID explicitly. Required when the commit has
123 neither a `jj` `change-id` commit header nor a `Change-Id:` trailer and should update an
124 existing change.
125 - `--if-active <sha>`: Full commit object ID. Adds the new version only if the change is currently
126 `ready` and its active version's head is `<sha>`.
127- **Behavior:**
128 - Requires `git config valley.principal` to be set to a valid principal name.
129 - Resolves the Change ID from `--change`, the commit's `change-id` header (`jj`), or the commit's
130 `Change-Id:` message trailer, or generates a new ID. Refuses if a header, trailer, or `--change`
131 disagree, or if multiple `Change-Id:` trailers carry different IDs.
132 - Refuses if the commit is already an ancestor of `origin/main`, has no merge base or multiple
133 merge bases with `origin/main`, or includes a merge commit in `base..head`.
134 - If the change has no record on `origin`, creates `v1` (`state: "ready"`, `seq: 1`, `active: 1`).
135 If the change is `draft` or `withdrawn` and the target head equals the active version's head,
136 transitions the record back to `ready` (`seq + 1`) without adding a version. If the change is
137 already `ready` at the active version's head, refuses because the head has not changed.
138 Otherwise, appends `v(N+1)` (`state: "ready"`, `seq + 1`, `active: N+1`).
139 - Pushes `refs/the-valley/changes/main/<id>` with `--force-with-lease` on the prior record commit
140 and prints `<repo> <handle> v<n> ready`.
141
142### `valley unready`
143
144`valley unready` pauses a `ready` change by setting its recorded state to `draft`.
145
146```sh
147valley unready kqxm
148valley unready <change>
149```
150
151- **Behavior:** Requires `git config valley.principal`. Reads the change record on `origin` (by
152 Change ID, handle, or a branch that an unlanded change's active version is on); refuses and exits
153 `1` if the change is already `draft` or `withdrawn`. Otherwise writes a single-parent record
154 commit (`P = [old]`) setting `state: "draft"` and incrementing `seq` by 1, leased on `old`. Prints
155 a note to `stderr` if a pending integration request still exists on `origin` (an existing request
156 is not deleted by `unready`, and the integrator refuses to land it while the change is `draft`, so
157 it stands until the change is readied again).
158
159### `valley withdraw`
160
161`valley withdraw` marks a `ready` or `draft` change `withdrawn` so the integrator voids its pending
162requests on its next pass.
163
164```sh
165valley withdraw kqxm
166valley withdraw <change>
167```
168
169- **Behavior:** Requires `git config valley.principal`. Reads the change record on `origin` (by
170 Change ID, handle, or a branch that an unlanded change's active version is on); refuses and exits
171 `1` if the change is already `withdrawn`. Otherwise writes a single-parent record commit
172 (`P = [old]`) setting `state: "withdrawn"` and incrementing `seq` by 1, leased on `old`. If a
173 pending request exists on `origin`, warns on `stderr` that the integrator will delete it on its
174 next pass while the change stays `withdrawn` (if the change is readied again before that pass, a
175 holder of the `approve` grant, also accepted as `request`, must delete the request ref directly).
176
177### `valley pending`
178
179`valley pending` lists work waiting to land in three sections: `ready` changes whose active version
180has not landed, unrecorded `branches` ahead of `main` that no landed version's head reaches, and
181`drafts`.
182
183```sh
184valley pending
185valley pending [--all] [--repo <name>] [--checks] [--json] [-v] [--known-signers <file>] [--integrator-name <name>]
186```
187
188- **Flags:**
189 - `--all`: Queries every project listed at `refs/the-valley/projects` in the instance repository
190 (discovered via `policy/valley` on `origin/main` or `policy/instance/` when the current repo is
191 the instance repo), keeping clones under `$XDG_CACHE_HOME/valley/repos`. If discovery is
192 unavailable and `--repo` is not set, warns on `stderr` and lists the current repository alone.
193 - `--repo <name>`: Queries that one project. When `<name>` matches the current repository, reads
194 the local repository directly without discovery; when passed together with `--all`, `--repo`
195 takes precedence.
196 - `--checks`: Appends a line to each change in human output showing how many checks the composed
197 verification policy requires of it, grouped by `quick` and `slow` cost (ignored when combined
198 with `--json`).
199 - `--json`: Emits [`valley-pending/v1`](#valley-changesv1-and-valley-pendingv1) JSON.
200 - `-v`: Warns on `stderr` when a project's plan graph (`refs/the-valley/knots`) cannot be read.
201 - `--known-signers <file>`, `--integrator-name <name>`: The known-signers file and the
202 integrator's signing name a transfer statement is verified with. Each takes precedence over its
203 environment variable and over the host's publication (see
204 [Environment variables](#environment-variables)). When either value comes from the publication,
205 its `signer-projects` file is read too. While that file names the integrator name, no transfer
206 statement is verified. A publication whose `signer-projects` does not read is not used.
207- **Behavior:** Groups stacked entries under their top entry by commit ancestry, shows linked knots
208 (`<title> · <knot-id>`), marks `includes <handle>` for unlanded non-entry changes (such as
209 `withdrawn` changes) contained in a head, and marks `uncertain` when a version's landing cannot be
210 verified. Also writes the shell-completion handle cache for the current repository at
211 `<git-common-dir>/valley/handles`.
212
213### `valley changes`
214
215`valley changes` outputs every change recorded on `origin` across all recorded states (`ready`,
216`draft`, and `withdrawn`, whether submitted or unlanded) as a
217[`valley-changes/v1`](#valley-changesv1-and-valley-pendingv1) JSON document.
218
219```sh
220valley changes --json
221valley changes --json [--all] [--repo <name>] [-v] [--known-signers <file>] [--integrator-name <name>]
222```
223
224- **Flags:** `--json` (required; running `valley changes` without `--json` exits `1` and suggests
225 `valley pending` for human output), `--all`, `--repo <name>`, `-v`, `--known-signers <file>` and
226 `--integrator-name <name>` (as for [`valley pending`](#valley-pending)).
227
228### `valley status`
229
230`valley status` inspects a single change or branch on `origin`, reporting its active version,
231landing state, restack report, pending integration request, and last recorded integrator outcome.
232
233```sh
234valley status kqxm
235valley status [--json] [-v] [--known-signers <file>] [--integrator-name <name>] <change>
236```
237
238- **Arguments and flags:**
239 - `<change>`: Change ID, handle, or branch name.
240 - `--json`: Emits a single-line [`valley-status/v1`](#valley-statusv1) JSON object including
241 linked knots.
242 - `-v`: With `--json`, warns on `stderr` if the plan graph cannot be read.
243 - `--known-signers <file>`, `--integrator-name <name>`: As for
244 [`valley pending`](#valley-pending).
245- **Behavior:** Fetches the needed objects from `origin` without updating `FETCH_HEAD` or moving any
246 local branch. Computes one of 13 status states (`integrated`, `integrated-recorded`,
247 `outdated-request`, `outcome-unreadable`, `voided-withdrawn`, `not-requested`,
248 `awaiting-decision`, `awaiting-new-decision`, `stale`, `rejected`, `refused-not-ready`,
249 `refused-merge`, or `failed`).
250
251### `valley review`
252
253`valley review` pages a change's diff (or a stack layer by layer from bottom to top), shows linked
254knots and comparison against any prior approved version, and prompts to approve, rebase, view the
255full diff, reject the remote branch, or skip.
256
257```sh
258valley review kqxm
259valley review [-v] <change>
260```
261
262- **Arguments and flags:**
263 - `<change>`: Change ID, handle, or branch name. The change's active version must record a
264 non-empty `branch`.
265 - `-v`: Warns on `stderr` if the plan graph cannot be read.
266- **Comparison against the approved version (`valley-go compare`):**
267 - Before paging a recorded change, `valley review` identifies the change's **approved version**:
268 the greatest version `vM` below the shown version `vN` whose exact `head` commit is named on
269 `origin` by a pending integration request or a `land`, `stale`, or `reject` outcome record under
270 `c-<change-id>` or an unambiguous branch request name. If the greatest version with evidence is
271 ambiguous, no fallback to an older version occurs.
272 - If an approved version is found and both versions have a single merge base (`B0` and `B1`) on
273 `origin/main`'s first-parent history with `B0` equal to or an ancestor of `B1`,
274 `valley-go compare` computes
275 [`valley-delta-v1`](#canonical-digest-manifests-valley-tree-v1-valley-inputs-v1-valley-delta-v1)
276 between each version's merge base and its head:
277 - `clean`: Both versions produce the identical `valley-delta-v1` file delta. `valley review`
278 prints `<change> v<n> at <head>: clean restack of approved v<m> at <old head>.`, the two
279 bases, and any commits `main` landed between them, and pages nothing.
280 - `changed`: The deltas differ. `valley review` pages `changed since approved v<m>`, the paths
281 whose delta entries differ, `git range-diff`, and the shown version's diff restricted to those
282 changed paths.
283 - `none`: No approved version can be compared; `valley review` pages the full log and diff
284 against `origin/main` (or the layer below in a stack).
285- **Interactive prompt actions:**
286 - `[a]pprove` (or `[a]pprove all <n>` at the top of a stack, or `[a]pprove <lands>` on a lower
287 layer): Runs all required checks in a temporary worktree of the shown head, signs attestations
288 with `VALLEY_ATTEST_KEY`, and pushes the attestations and
289 `refs/the-valley/integration-requests/main/<request>` in one atomic, leased `git push`. Not
290 offered when the change (or any layer at or below it) is `draft` or `withdrawn`, or after its
291 checks fail at that head.
292 - `[b]ase` (or `[b]ase all <n>` before paging a stack whose bottom does not fast-forward from
293 `origin/main`): Rebases the change or stack onto `origin/main` via `valley-go rebase`, then
294 re-reads and re-pages the rebased commits.
295 - `[v]iew full diff`: Pages the full log and diff against `origin/main` (or the layer below)
296 regardless of approved-version comparison.
297 - `[r]eject`: Confirms and deletes the remote branch `refs/heads/<branch>` on `origin`, leased on
298 the recorded head (offered only on a single change or the ready top of a stack).
299 - `[n]ext layer`: In a stack review, advances to the next layer up.
300 - `[s]kip` / `[s]top`: Exits without modifying `origin`.
301- **Inline review notes:** Pressing `v` inside `less` opens the diff buffer in `$EDITOR`. Any lines
302 inserted by the reviewer are anchored to their file and new-side line number, appended to
303 `$XDG_STATE_HOME/valley/notes/<branch>.md`, and printed at the end of the review.
304
305### `valley approve`
306
307`valley approve` files a change's integration request without paging the diff. It reuses the
308evidence `origin` already holds for the change's required checks, runs and signs the rest, and
309publishes the new evidence with the request in one atomic push.
310
311```sh
312valley approve kqxm
313valley approve --head 99b5f2f7c1d2e3f4a5b6c7d8e9f0a1b2c3d4e5f6 kqxm
314valley approve [--head <sha>] <change>
315```
316
317- **Arguments and flags:**
318 - `<change>`: Change ID, handle, or branch name.
319 - `--head <sha>`: Approves that exact commit. For a recorded change, `<sha>` must be one of the
320 record's version heads (active or prior); without `--head`, `approve` prompts on a terminal to
321 confirm the active version's head and title, and refuses off a terminal. For an unrecorded
322 branch, `<sha>` (if given) must match `origin/<branch>`'s current tip.
323- **Behavior:**
324 - Requires the pushing SSH key's principal to hold the `approve` grant on the host (the grant that
325 lets a principal approve, also accepted as `request`).
326 - Refuses if the change record is `draft` or `withdrawn`, if the commits include a merge, if the
327 head brings an unlanded version of another change that is `draft` or `withdrawn`, or if the head
328 does not fast-forward from `origin/main` while bringing an unlanded lower change in a stale
329 stack (instructing the user to run `valley rebase <change>` first).
330 - Composes the verification policy from `origin/main` and the instance repository's
331 `refs/heads/main`, and derives the required checks for `base..head`.
332 - When a check is required, lists `origin`'s `refs/the-valley/attestations/<tree-digest>/*` for
333 the head's tree and fetches the objects they name (`valley-go coverage`). It never counts a
334 local attestation ref as evidence. A listing or a fetch that fails is refused, and nothing runs
335 or is published.
336 - Judges each required `nix` check by the note the integrator judges it by: the first note for the
337 check, with the refs in byte order, that `attest verify` accepts under the `known-signers` file
338 the host publishes at `refs/the-valley/signers`. It reads each note byte for byte. With no
339 publication, nothing is reused.
340 - Counts a note as accepted only when one of its verified signers counts in this project. That
341 signer is not the publication's `integrator-name`, and the publication's `signer-projects` file,
342 when there is one, lets it count in this project. The project is the last path segment of
343 `origin`'s URL, without `.git`. A publication whose `signer-projects` is not a file, or does not
344 read, is not used, so nothing is reused.
345 - Reuses that note when it is pure evidence for the check's name and flake attribute, and records
346 `passed`. When `VALLEY_KNOWN_SIGNERS` is set, `attest verify` must accept the note under that
347 file too, by a signer that counts in this project, so a local file can narrow what is reused but
348 never widen it. A `command` check is never reused.
349 - Prints `reusing the evidence origin holds for <change> at <head>:`, then one line per reused
350 check naming its signer. For each check whose note it does not reuse, it prints the reason on
351 `stderr`, for example
352 `valley: not reusing code-build: the integrator judges it by <ref>:code-build/statement.note, and its predicate.result is "failed", not "passed"`.
353 - Runs every other required check with `attest run` in a temporary worktree, using
354 `VALLEY_ATTEST_KEY` (and optional `VALLEY_ATTEST_NAME`). When every required check is reused,
355 nothing runs and no signing key is needed.
356 - Before running anything, refuses when `origin` already holds this signer's ref for the tree,
357 `refs/the-valley/attestations/<tree-digest>/<key-hash>`. That namespace is create-only, so the
358 new evidence would have nowhere to go
359 ([bd-7b7d58f](../archive/.the-valley/bugs/bd-7b7d58f-same-tree-re-attestation-cannot-be-published.md)).
360 - Pushes the attestation refs stored for the tree (when checks ran) and
361 `refs/the-valley/integration-requests/main/<request>` (leased on the prior request value) in one
362 `git push --atomic`. When the request already names the head and there is no new evidence, it
363 makes no push.
364 - Ends with a summary: `request` with the request ref and head, `evidence` for each attestation
365 ref it published, `reused` for each ref on `origin` whose evidence it reused, and `checks` for
366 every required check.
367 - Prints a `time` line after each check's `check` line: the check's name, its result, how long it
368 took, and how it was satisfied. It passes `--timings` to `attest run`, so each check is also
369 logged to the local [timing log](#the-timing-log). The log is not evidence, and a log that
370 cannot be written is a warning: approval continues.
371
372### `valley rebase`
373
374`valley rebase` rebases a change and its entire underlying stack onto `origin/main`, pushes all
375updated branches atomically, and records a new version on each rebased change.
376
377```sh
378valley rebase kqxm
379valley rebase [--known-signers <file>] [--integrator-name <name>] <change>
380```
381
382- **Arguments:** `<change>` (Change ID, handle, or branch name). (`valley-go rebase` also accepts
383 `--head <full-sha>` when invoked by `valley review`'s `[b]ase`).
384- **Flags:** `--known-signers <file>` and `--integrator-name <name>`, as for
385 [`valley pending`](#valley-pending).
386- **Behavior:**
387 - Requires `git config valley.principal` whenever the stack contains a recorded change.
388 - Captures one snapshot of `origin` and builds the stack of unlanded changes and branches beneath
389 `<change>`. Commits at the bottom that have already landed on `origin/main` (`landed` or
390 `landed-recorded`, its transfer statement verified as [`valley changes`](#valley-changes)
391 verifies one) drop out automatically.
392 - If the stack already fast-forwards from `origin/main`, changes nothing and exits `0`.
393 - Refuses without changing anything if any layer in the stack is `draft` or `withdrawn`, has no
394 recorded branch, has a missing or moved remote branch (`origin/<branch> != head`), shares a
395 branch with another layer, contains a merge commit, or contains a version head of a non-ready
396 change or a change outside the stack.
397 - Rebases every layer bottom-first in a temporary worktree. On a merge conflict in any layer,
398 aborts, pushes nothing, and prints the conflicting layer and file paths.
399 - Publishes in two phases:
400 1. One `git push --atomic` moving every layer's `refs/heads/<branch>` with `--force-with-lease`
401 on the tips read in the snapshot.
402 2. Bottom-first, adds a new version to each recorded change's
403 `refs/the-valley/changes/main/<id>` just as `valley ready --if-active <old-head>` does. If
404 any phase-2 record write fails, prints a manifest and the exact
405 `valley ready --change <id> --head <new-sha> --if-active <old-sha> <branch>` command to
406 finish it, and exits `1`.
407
408### `valley checks`
409
410`valley checks` composes the instance floor and project verification policy and prints the checks
411required for the diff between two commits, along with the matched path classes and carry mode.
412
413```sh
414valley checks
415valley checks --names --cost quick
416valley checks [--schema <file>] [--instance <dir>] [--project <dir>] [--names] [--cost quick|slow] [<base> [<head>]]
417```
418
419- **Arguments and flags:**
420 - `[<base> [<head>]]`: `<head>` defaults to `HEAD`; `<base>` defaults to
421 `git merge-base <target> <head>` where `<target>` is `origin/main` (falling back to local `main`
422 only if `origin/main` does not exist).
423 - `--schema <file>`: CUE verification schema file (default: `$VALLEY_POLICY_SCHEMA`,
424 `$VALLEY_VERIFICATION_SCHEMA`, or `<repo-root>/schema/verification.cue`).
425 - `--instance <dir>`: Directory of `*.cue` files for the instance floor. By default, read from
426 `policy/instance/` at `origin/main` if present in this repository, or fetched from
427 `refs/heads/main` of the repository URL named in `policy/valley` at `origin/main`.
428 - `--project <dir>`: Directory of `*.cue` files for the project layer. By default, read from
429 `policy/project/` at `origin/main` (or an empty `package verification` layer if
430 `policy/project/` holds no `*.cue` files).
431 - `--names`: Prints only the required check names, sorted, one per line.
432 - `--cost quick|slow`: Requires `--names`; filters the `--names` output to checks with
433 `cost: "quick"` or `cost: "slow"`.
434- **Behavior:** Reads all added, modified, deleted, renamed (both old and new paths), and copied
435 paths from `git diff --no-relative --name-status -M -z <base> <head>`, matches them against
436 `policy.classes` (and `policy.unclassified` when any path matches no class), probes whether each
437 required check is `mandatory` (pinned by the floor) or `default`, resolves the strictest `carry`
438 mode (`exact`, `same-class`, or `same-paths`) across matched classes, and prints the report
439 without running any check. A layer's documents are the `*.cue` entries directly in its directory
440 whose names do not begin with a dot. The derivation runs in the C locale whatever the caller's
441 locale: a glob matches bytes, so `?` matches one byte, and lists sort bytewise.
442
443### `valley plan`
444
445`valley plan` renders the project's live plan graph (`refs/the-valley/knots`) as a milestone tree
446followed by `waiting on you`, `in flight`, and `open residuals` sections.
447
448```sh
449valley plan
450valley plan [--project <name> | --all] [--owner <principal>] [--json] [--known-signers <file>] [--integrator-name <name>]
451```
452
453- **Flags:**
454 - `--project <name>`: Reads the plan graph of `<name>` on the same host (cannot be combined with
455 `--all`).
456 - `--all`: Reads the plan graph of every project listed at `refs/the-valley/projects` in the
457 host's instance repository.
458 - `--owner <principal>`: Overrides `git config valley.principal` when selecting which knots appear
459 under `waiting on you`.
460 - `--json`: Emits [`valley-plan/v1`](#valley-planv1) JSON.
461 - `--known-signers <file>`, `--integrator-name <name>`: As for
462 [`valley pending`](#valley-pending), for the changes listed as ready for approval.
463- **Glyphs and sections:**
464 - Root `outcome` knots (those with no `parent`) are milestones, showing descendant progress
465 (`done/of` over non-abandoned descendants). Active non-outcome knots with no `parent` appear
466 under `no milestone`.
467 - State glyphs: `○` (`ready`), `◐` (`in-progress`), `⊘` (`blocked`), `◇` (`active`, such as an
468 open `idea` or `question`, or an unclaimed `outcome` with children that is not itself ready),
469 `✓` (`done`: `done`, `closed`, `graduated`, `answered`), `✗` (`abandoned`: `abandoned`,
470 `discarded`, `superseded`, `dropped`).
471
472### `valley knot`
473
474`valley knot` reads and writes knots in the plan graph at `refs/the-valley/knots` on `origin`
475without a local branch checkout or review step.
476
477```sh
478valley knot new outcome "Publish the CLI reference" --owner operator
479valley knot <verb> [args] [--project <name>] [--json]
480```
481
482Every `valley knot` subcommand accepts `--project <name>` (to act on another project on the same
483host) and `--json` (to emit
484[`valley-knot/v1`, `valley-knots/v1`, `valley-knot-op/v1`, `valley-knot-log/v1`, or `valley-knot-schema/v1`](#valley-knot---json-valley-knotv1-valley-knotsv1-valley-knot-opv1-valley-knot-logv1-valley-knot-schemav1)).
485All write subcommands require `git config valley.principal` and retry lease races up to 5 attempts
486(`knot.Attempts = 5`). After a push whose outcome could not be determined, `valley knot` searches
487the latest 64 commits (`knot.OpSearch = 64`) on `refs/the-valley/knots` for the operation's
488`Valley-Op` trailer before retrying.
489
490| Subcommand | Synopsis and contract |
491| :--------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
492| `new` | `valley knot new <type> <title> [--parent <id>] [--blocked-by <id>]... [--owner <p>] [--target <project>] [--body -]`<br>Creates a knot of `<type>` (`outcome`, `bug`, `idea`, or `question`) in its initial active status (`open` for `outcome`/`bug`/`question`, `raw` for `idea`). Computes `<slug>` from `<title>` (up to 48 bytes) and derives `<id>` as `<prefix>-<first-7-hex-of-sha256(slug)>`; if `<id>` is already taken in the graph, appends `-2`, `-3`, … to `<slug>` (trimming the base slug to fit 48 bytes) until `<id>` is unused. `--blocked-by` and `--target` are valid on `outcome` and `bug` only. `--body -` reads Markdown body text from stdin. |
493| `show` | `valley knot show <id> [--at <commit>] [--project <name>] [--json]`<br>Displays all fields, derived edges (`blocks`, `children`, `progress`, `claim`, `ready`, `waiting_on`, `cleared_by_ending`, `dangling`, `unresolved`), Markdown body, and comments for `<id>`. Each comment shows its ID (`<YYYYMMDDTHHMMSSZ>-<16-hex-op>`) and, if edited, when and by whom it was edited. `--at <commit>` shows `<id>` at `<commit>`. `<commit>` must be a full or abbreviated (at least 4 lowercase hex digits) object ID of the fetched tip of `refs/the-valley/knots` or one of its ancestors. Any other commit, or a knot that does not exist at `<commit>`, exits `1`. Even with `--at`, a claim's `age_seconds` and `stale` are computed against the current clock (`VALLEY_NOW` when set), and each `<project>:<id>` in `blocked_by` is resolved against that project's current tip. |
494| `log` | `valley knot log <id> [--project <name>] [--json]`<br>Lists every commit on `refs/the-valley/knots` that added, changed, or deleted `<id>`'s knot file or a file under `comments/<id>/`, newest first in topological order, down to and including the root commit. Each entry shows the commit ID, UTC committer time, committer name, `Valley-Op` operation ID, commit subject, and each touched file marked `added`, `changed`, or `deleted`. `knot.ParseCommit` reads the time, committer, and operation ID from the commit object. |
495| `list` | `valley knot list [--type <t>] [--status <s>] [--owner <p>] [--ready] [--project <name>] [--json]`<br>Lists knots matching all given filters. `--status` accepts `active`, `terminal`, or any status name (`open`, `in-progress`, `done`, `abandoned`, `closed`, `raw`, `exploring`, `adopted`, `graduated`, `superseded`, `discarded`, `answered`, `dropped`). `--ready` filters to active, unclaimed `outcome` or `bug` knots with no unresolved or active blockers. |
496| `set` | `valley knot set <id> <field>=<value>... [--if <field>=<value>]... [--force]`<br>Updates `status`, `title`, `source`, `owner`, `target`, or `graduated_into` (setting an optional field to `""` clears it; setting `status` on an `outcome` or `bug` to a terminal status also clears `claimed_by` and `claimed_at`). Uses compare-and-set on the initial values of modified fields across lease retries unless `--force` is passed. `--if <field>=<value>` requires `<field>` to equal `<value>` (accepting any of the 15 frontmatter fields, with list fields `blocked_by` and `changes` compared as comma-joined strings); exits `3` on conflict. Changing `title` keeps `<id>` and `<slug>` unchanged. |
497| `link` | `valley knot link <id> (--blocked-by <ref> \| --parent <id> \| --change <link>)... [--if <field>=<value>]...`<br>Adds one or more edges on `<id>`. `--parent <id>` sets `parent` to a local `outcome` (using compare-and-set on the old `parent`). `--blocked-by <ref>` adds a local `<id>` or cross-project `<project>:<id>` to `blocked_by` (on `outcome` or `bug`). `--change <link>` adds `valley:<project>/<change-id>` or `https://github.com/<org>/<repo>/pull/<n>` to `changes` (on `outcome`, `bug`, or `question`). |
498| `unlink` | `valley knot unlink <id> (--blocked-by <ref> \| --parent <id> \| --change <link>)... [--if <field>=<value>]...`<br>Removes the specified `--blocked-by`, `--parent` (accepts `--parent <current-parent-id>` or `--parent=""`), or `--change` edges from `<id>`. |
499| `edit` | `valley knot edit <id> --body - [--if <field>=<value>]...`<br>Replaces `<id>`'s Markdown body with text read from stdin (compare-and-set on the old body). Passing an empty stdin clears the body. |
500| `comment` | `valley knot comment <id> (-m <text> \| --body -) [--edit <comment-id>]`<br>Without `--edit`, adds a comment file at `comments/<id>/<YYYYMMDDTHHMMSSZ>-<16-hex-op>.md` with `author` set to `git config valley.principal`. `--edit <comment-id>` replaces the body of the comment at `comments/<id>/<comment-id>.md`. The comment keeps its `author` and path; `edited` is set to the current UTC timestamp (`RFC 3339`) and `edited_by` is set to `git config valley.principal`. A `<comment-id>` that does not match `<YYYYMMDDTHHMMSSZ>-<16-hex-op>` exits `2`. A `<comment-id>` not found on `<id>` (including one belonging to another knot) exits `1`. Edits use compare-and-set on the comment file's initial blob across lease retries and exit `3` on conflict. If the comment body already equals the new text, the command prints a note to `stderr` and exits `0`. The CLI does not check who may edit a comment; the host's hook admits an edit only from the comment's `author` or from a principal holding the `approve` grant (also accepted as `request`). Comments are never deleted. |
501| `claim` | `valley knot claim <id> --run <run-id> [--if <field>=<value>]...`<br>Claims an active, unclaimed `outcome` or `bug` for `<run-id>`, setting `claimed_by` to `<run-id>`, `claimed_at` to the current UTC timestamp (`RFC 3339`), and transitioning an `open` `outcome` to `in-progress`. If already claimed by the same `<run-id>`, prints a note to `stderr` and exits `0`; if `<id>` is not active or is an `idea` or `question`, exits `1`; if claimed by another run, exits `3`. |
502| `unclaim` | `valley knot unclaim <id> [--if <field>=<value>]...`<br>Clears `claimed_by` and `claimed_at` on `<id>` (leaving `status` unchanged). Exits `3` if the claim changed concurrently before the release landed. |
503| `schema` | `valley knot schema [--json]`<br>Prints the knot types, statuses, fields, edges, and graph limits in human text or [`valley-knot-schema/v1`](#valley-knot---json-valley-knotv1-valley-knotsv1-valley-knot-opv1-valley-knot-logv1-valley-knot-schemav1) JSON. |
504
505### `valley tail` and `valley replay`
506
507`valley tail` subscribes to NATS bus events, and `valley replay` publishes one `ref-updated` event
508for every current ref in a git repository.
509
510```sh
511valley tail [subject]
512valley replay [repo-dir]
513```
514
515- `valley tail [subject]`: Runs `nats sub <subject>` (default subject: `valley.>`). Uses `NATS_URL`
516 or the active `nats` CLI context (default `localhost`).
517- `valley replay [repo-dir]`: Iterates `git -C <repo-dir> for-each-ref` (default `<repo-dir>`: `.`)
518 and publishes
519 `{"event":"ref-updated","repo":"<repo>","ref":"<ref>","old":"0000...","new":"<sha>"}` to
520 `valley.git.<repo>.ref-updated` for each ref.
521
522### `valley self-update`, `--version`, and `help`
523
524`valley self-update` builds, smoke-tests, and installs the tip of a configured branch of the-valley
525into the user's default Nix profile, while `--version` and `help` report the CLI stamp and usage.
526
527```sh
528valley self-update [-v] [--retry | --rollback | --pin | --unpin] [--repo <url>] [--branch <name>]
529valley --version
530valley help [<verb>]
531```
532
533- **`valley self-update` flags:**
534 - `--repo <url>`: Source repository URL (`https://`, `ssh://`, `git://`, `file://`, absolute path,
535 or `user@host:path` with characters in `[A-Za-z0-9._~/:@-]`), overriding
536 `git config valley.selfUpdate.repo`. If neither is set, `self-update` is disabled and exits `0`.
537 - `--branch <name>`: Branch to track, overriding `git config valley.selfUpdate.branch` (default
538 `main`).
539 - `-v`, `--verbose`: Prints status even when the installed `valley` is already at the branch tip.
540 - `--retry`: Retries building the branch tip even if that exact commit already failed its build or
541 smoke test.
542 - `--rollback`: Reinstalls the previous store path recorded in
543 `$XDG_STATE_HOME/valley/self-update.json` (running `--rollback` again switches back).
544 - `--pin` / `--unpin`: Freezes or unfreezes the installed `valley` in
545 `$XDG_STATE_HOME/valley/self-update.json`; while pinned, `valley self-update` exits `0` without
546 building or installing.
547- **`valley --version`:** Prints `valley <version>-<short-rev>` (with `-dirty` for a dirty build
548 tree or `-unknown` when Nix had no commit rev) when built by Nix (`nix/packages.nix`), or
549 `valley unstamped (run from a checkout, not built by nix)` when run directly from a checkout.
550- **`valley help [<verb>]`** (also `valley -h`, `valley --help`, or `valley` with no arguments):
551 Prints a one-screen command summary when called with no `<verb>`, or detailed usage for `<verb>`
552 (`pending`, `changes`, `review`, `approve`, `rebase`, `status`, `ready`, `unready`, `withdraw`,
553 `knot`, `plan`, `checks`, `tail`, `replay`, or `self-update`). `valley <verb> --help` and
554 `valley <verb> -h` print the same per-verb help.
555
556### Helper and host commands
557
558The `valley` package, the NixOS host module, and the web publisher's module build seven Go binaries
559that `bin/valley` and `systemd` invoke ([`nix/packages.nix`](../nix/packages.nix)).
560
561```sh
562attest key --key ~/.ssh/valley-attest --name operator
563valley-worker --repo the-valley --key ~/.ssh/valley-worker --name worker/attestations
564```
565
566- **`attest`** ([`attest/main.go`](../attest/main.go)): Composes, signs, stores, and verifies
567 `the-valley/attestation/v1` notes and computes canonical digests. Exits `0` on success, `1` on
568 verification or runtime failure, `2` on invalid flags.
569 - `attest run [--repo <dir>] [--rev <rev>] [--check <name>[=<attr>]]... [--command <name>=<cmd>]... [--environment <name>] --key <path> [--name <name>] [--provenance <file>] [--schema <file>] [--system <system>] [--push <remote>] [--branch <ref>] [--timings] [--change <id>] [--change-version <n>] [--cost <name>=<class>]...`
570 — prints a `time` line per check. `--timings` appends each check's timing to the
571 [timing log](#the-timing-log); `--change`, `--change-version` and `--cost` supply the fields
572 `attest` cannot read itself.
573 - Runs every `nix` check first. One nix evaluation names every check's derivation.
574 - Builds each derivation in a `nix build --no-link --print-out-paths <drv>^*` of its own. Up to
575 one build runs per CPU at a time, and the nix daemon runs them side by side. Checks with the
576 same derivation share its one build.
577 - The machine's `max-jobs` and `cores` settings apply within each build, not across them. So up
578 to one check derivation per CPU builds at once.
579 - Decides each `nix` check by its own build, as when checks were built one at a time. A check
580 passed when its build succeeded. A check that failed keeps its own build's `stderr` as its
581 log. When the build wrote nothing there, such as when `nix` could not start or was killed by a
582 signal, the log is the error that ended the build. A build that prints other than one output
583 path is an error, since a check attribute must produce exactly one.
584 - A check that does not evaluate is an error for that check alone. Every other check is still
585 built and reported. When the shared evaluation stops at an error nix cannot catch, such as a
586 type error, each check is evaluated on its own.
587 - Runs the `command` checks after the `nix` checks, one at a time, in the order given.
588 - Prints each check's `check` and `time` lines, then the log of every check that failed, under
589 `--- <name> ---` on `stderr`. Publishes nothing unless every check passed, and exits `1`.
590 - `attest verify --note <file> --known-keys <file> [--signer <name>]... [--schema <file>] [--repo <dir>] [--rev <rev>]`
591 - `attest digest [--repo <dir>] [--rev <rev>]` — prints `valley-tree-v1:<64-hex>`.
592 - `attest inputs [--repo <dir>] [--rev <rev>] [--check <name>[=<attr>]]... [--system <system>]` —
593 prints `<check> valley-inputs-v1:<64-hex> sha256:<64-hex-drv>` per check without building.
594 - Exports the tree once and evaluates every check named in one `nix` evaluation, as `attest run`
595 does. One check alone is evaluated on its own.
596 - Prints one line per check on `stdout`, in the order given.
597 - A check that does not evaluate ends the command. The lines of the checks before it are
598 printed, its error goes to `stderr` as `attest: evaluating …`, and the exit status is `1`.
599 - `attest render [<file>]` — renders statement JSON (or canonical statement text) on `<file>` or
600 stdin to canonical statement text.
601 - `attest sign --key <path> [--name <name>]` — signs canonical statement text on stdin into a
602 note, or appends a signature line to an existing note on stdin.
603 - `attest key --key <path> [--name <name>]` — prints the `<name>+<8-hex-hash>+<base64>` verifier
604 key line.
605- **`valley-go`** ([`status/main.go`](../status/main.go)): Internal helper binary invoked by
606 `bin/valley` for `status`, `ready`, `unready`, `withdraw`, `changes`, `pending`, `rebase`, `knot`,
607 `plan`, and `self-update`, plus internal plumbing verbs (`resolve <change>`, `stack <change>`,
608 `does [-v] <change-id>...`, `brings [--change <id>] <head>`, `versions <change-id>`,
609 `compare --tip <commit> <change-id> <version> <head>`,
610 `coverage --head <sha> [--check <name>=<attribute>]...`), and
611 `checks [--schema <file>] --instance <dir> --project <dir> <base> <head>`, which prints the Go
612 deriver's `valley-checks/v1` document and which `bin/valley` does not run. `work` is the check
613 worker, which `valley-worker` runs. `status`, `stack`, `rebase`, `brings`, `changes`, `pending`
614 and `plan` also take `--known-signers <file>` and `--integrator-name <name>`.
615- **`valley-worker`** ([`status/worker.go`](../status/worker.go)): One pass of the check worker (see
616 [The check worker](architecture.md#the-check-worker)). It is `valley-go work`, wrapped with this
617 flake's git, cue and `attest` and with `VALLEY_VERIFICATION_SCHEMA` set. It runs the machine's own
618 `nix`. On a host, `services.valley.worker` runs it on a timer (see
619 [NixOS host options](#nixos-host-options)).
620 - `valley-worker --repo <name>... --key <path> [--name <name>] [--state <dir>] [--wake <dir>]` —
621 run in a clone of any project the host serves.
622 - `--repo <name>`: A project to build evidence for, once per project. At least one is required.
623 The worker builds evidence for no other project. To find a project other than its clone's own,
624 it reads `policy/valley` on `origin`'s `main` and the instance repository's
625 `refs/the-valley/projects`. When that `main` holds `policy/instance` and no `policy/valley`,
626 `origin` is itself the instance repository. It can also fetch `main` of the owning valley a
627 project's `policy/valley` names.
628 - `--key <path>` and `--name <name>`: The worker's signing key and signing name, passed to
629 `attest run`. The name defaults as `attest`'s does.
630 - `--state <dir>`: The directory holding the lock and the record of failed batches and pushes
631 (default `${XDG_STATE_HOME:-$HOME/.local/state}/valley/worker`).
632 - `--wake <dir>`: A wake directory (see
633 [The worker's wakeups](architecture.md#the-workers-wakeups)). Before it reads anything, the
634 pass takes `<dir>/lock` and renames `<dir>/due` to `<dir>/claimed`. It removes `claimed` once
635 it has read every project and recorded every failure it met. A pass that could not take the
636 lock or rename `due` still reads and builds, and then exits `75` instead of `0` or `1`.
637 - Prints lines of the form `<project>: <handle> v<n> at <short-head>: <what>` for the ready
638 changes in a project whose policy at `main` loads. A change it builds or publishes gets one line
639 for each step, with what `attest run` prints between them. `<what>` is usually one of these.
640 Errors print their own messages.
641 - `requires no nix check`
642 - `origin holds evidence for every nix check it requires`
643 - `building <check>, <check>`, then what `attest run` prints, then `published <ref>`
644 - `origin already holds <ref>, this worker's evidence for its tree, and it does not cover <checks>. …`
645 - `an earlier pass stored <ref>, and origin does not hold it`, then the line for publishing it
646 - `its batch <checks> failed <n> times in a row, so it is not built again before <time>`
647 - `the batch did not pass (<reason>); it is not built again before <time>`
648 - `publishing <ref> failed <n> times in a row, so it is not pushed again before <time>`
649 - `could not publish <ref>; it is not pushed again before <time>`
650 - A project with ready changes gets one line for the whole project instead when `origin` has no
651 `main`, or when the policy at `main` does not load. Its changes are skipped. The line is
652 `<project>: origin has no main to read the policy at, so nothing is built`, or
653 `<project>: the policy at main did not read, so nothing is built: <reason>`.
654 - A pass that finds the lock held prints
655 `valley: another pass holds <state>/lock; waiting for it to end` on `stderr`, and waits.
656 - Exits `0` when everything it tried succeeded, and `2` when `VALLEY_NOW` is not a time. It exits
657 `1` for invalid flags, when a read of `origin` failed, which stops the pass, and when anything
658 else went wrong. A `failures.json` that cannot be read or does not parse is the exception: the
659 pass prints `valley: <state>/failures.json does not read, so everything it held is tried again`
660 on `stderr`, starts the record empty, and goes on.
661- **`valleyhook`** ([`valleyhook/main.go`](../valleyhook/main.go),
662 [`valleyhook/shell.go`](../valleyhook/shell.go)):
663 - `valleyhook pre-receive --project <name> --policy <json-file> [--grants <file>]... [--known-signers <file>]... [--principal <name>] [--then <hook-file>]`
664 — validates ref updates on stdin.
665 - `valleyhook shell --converged <file> --expect <id> [--hold <file>] [--authorized-keys <file>]... -- [-c <command>]`
666 — login shell for the `git` user on a valley host.
667- **`valley-integrator`** (binary `integrator`; [`integrator/main.go`](../integrator/main.go)):
668 - `integrator reconcile [flags]` and `integrator watch [--interval <duration>] [flags]` — requires
669 `--key`, `--known-signers`, `--schema` (default `$VALLEY_VERIFICATION_SCHEMA`),
670 `--attest-schema` (default `$VALLEY_ATTEST_SCHEMA`), and either `--instance-repo` or
671 `--instance` (optional flags: `--repo`, `--project`, `--name`, `--signer-projects`,
672 `--instance-ref`, `--instance-policy`, `--project-policy`, `--event-schema`, `--bus`,
673 `--publish-queue`, `--system`, `--interval`, `--now`).
674 - `--signer-projects <file>` restricts signers to projects. Each line names a signer, then the
675 projects whose evidence it may sign, separated by spaces, as in
676 `worker/attestations the-valley app`. A signer the file names counts only in the projects on its
677 line. The project is the one the controller serves (`--project`, by default the repository's
678 name). In any other project the controller reports that signer's evidence as
679 `signed by no signer the integrator holds`. A line with a name and no project lets that signer
680 count nowhere. A signer the file does not name counts wherever `--known-signers` lets it. Blank
681 lines and lines that open with `#` are skipped. Every name and project is printable ASCII with
682 no space. The controller reads the file once, at start. A file that cannot be read, names a
683 signer twice, holds a word that is not printable ASCII, names a signer no verifier key can
684 carry, or names the controller's own `--name` stops the controller before it judges anything.
685 The controller's own signature never makes a check's attestation count. It countersigns the
686 attestations a landing carried, and that vouches for the landing, not for the check. Another
687 controller's signature counts like any signer's, so a host whose `--known-signers` holds another
688 controller's key lists that controller's name in this file with no project.
689 - `integrator publish-signers --instance-repo <dir> --known-signers <file> [--name <name>] [--signer-projects <file>]`
690 — writes the signers publication, `refs/the-valley/signers`, into the instance repository: the
691 known-signers file and the signing name (default `<hostname>/attestations`, as for `watch`).
692 Given `--signer-projects`, the publication holds that file too, unless it is empty. Refuses a
693 file that is not verifier keys, a name no verifier key can carry, or a signer projects file the
694 controllers would refuse, such as one that names `--name`, and writes nothing when the
695 publication would not change. Publishes a file with no key in it. Holds a lock in the instance
696 repository from reading the file to moving the ref, so runs at once take turns.
697- **`valley-identity`** (binary `identity`; [`identity/main.go`](../identity/main.go)):
698 - `identity compile --repo <dir> [--ref <ref>] [--dir <dir>] [--schema <file>] --known-signers <file> --authorized-keys <file> --grants <file> [--approval-signers <file>] [--approval-signers-hardware <file>] [--declared-keys <file>] [--now <YYYY-MM-DD>]`
699 — compiles `identity/*.cue` from an instance repository tip into runtime files.
700 `--approval-signers` and `--approval-signers-hardware` each write one of the
701 [approval signers files](#approval-signers-files), and neither is written without its flag.
702- **`valley-restacker`** ([`restack/main.go`](../restack/main.go)):
703 - `valley-restacker run --repo <url> --state <dir> --principal <name> --schema <file> [--interval <duration>] [flags]`
704 — runs a write pass immediately and then waits `--interval` (default `15s`) after each pass
705 before starting the next, until stopped. It holds the lock on `--state` for as long as it runs,
706 including after a pass that ends at its `--timeout`. When a pass fails, `run` writes the error
707 to stderr and doubles the wait before the next pass, from `--interval` up to `5m`, until a pass
708 succeeds. It prints output only when a pass tries a write, whether or not origin takes it, or
709 leaves a journal open.
710 - `valley-restacker once --repo <url> --state <dir> --principal <name> --schema <file> [flags]` —
711 runs one write pass. If `--state` holds a journal, the pass settles it first, then plans each
712 family, adds the pass's writes to the journal, and pushes them (see
713 [Publishing](architecture.md#publishing)). It reads a full snapshot of origin again before each
714 phase, so a request pauses a family's versions only when that phase's snapshot shows it. Any
715 family still open in the journal stays there, and any family in the new plan that shares a
716 change or branch with it waits. Two families in the same plan that would otherwise be marked
717 `restack` or `hold`, and that share a change or branch, also wait. For example, two ready
718 changes on the same branch wait when they are captured as separate families. If the journal
719 cannot be read or parsed, or belongs to another repository, target, or principal, the pass
720 fails.
721 - `valley-restacker once --report-only --repo <url> --state <dir> --principal <name> --schema <file> [flags]`
722 — plans and builds a pass's writes in the scratch repository, decides the existing journal if
723 `--state` holds one, and pushes nothing.
724 - Shared flags:
725 `[--target main] [--commit-name <name>] [--commit-email <email>] [--timeout <duration>] [--known-signers <file>] [--integrator-name <name>] [--signer-projects <file>] [--attest <path>] [--instance-repo <url> | --instance <dir>] [--instance-ref <ref>] [--instance-policy <dir>] [--project-policy <dir>] [--json]`.
726 `--timeout` (default `10m`) bounds each pass. After a pass that ends at its timeout, `once` lets
727 go of the lock on `--state`, while `run` keeps it and starts the next pass after the wait. If
728 `--signer-projects` cannot be read or parsed, the pass fails; while it lists
729 `--integrator-name`, transfer statements do not prove any landing. With `--json`, a pass prints
730 its `Plan` object: each family with its `action` (`leave`, `current`, `hold`, `restack`, or
731 `wait`), `actions` (each write the pass tried, including those origin refused and those it did
732 not push — `branches`, `version`, `report`, or `replacement` — and its result `pushed`,
733 `refused`, `unknown`, or `unpushed`), and `pending` (what recovery last decided for a journal
734 left open, or `null`).
735 - The `--state` directory holds `binding.json`, `lock`, the scratch repository `scratch/`,
736 `journal.json` while a journal is open, and `observations/<digest>.json` for the full
737 observation of each report that omits truncated fields (see
738 [What a pass builds](architecture.md#what-a-pass-builds)). The restacker never deletes files
739 from `observations/`, and automatic cleanup is `not built`, so observation files accumulate
740 without bound. To reclaim space, an operator removes old files manually, for example with
741 `find <state>/observations -name '*.json' -mtime +90 -delete`. Deleting a file leaves any report
742 that names it pointing to a missing path, so choose an age past which those reports do not
743 matter.
744- **`valley-web-publish`**
745 ([`web/cmd/valley-web-publish/main.go`](../web/cmd/valley-web-publish/main.go)): One pass of the
746 web publisher (see [Web export publisher](#web-export-publisher)). It is wrapped with this flake's
747 `git`, `cue`, and `valley`, with `VALLEY_READ_SCHEMA` set to `schema/read.cue` and
748 `VALLEY_IDENTITY_SCHEMA` set to `schema/identity.cue`. On a host, `services.valley.webPublisher`
749 runs it on a timer (see [The web publisher's options](#the-web-publishers-options)).
750 - `valley-web-publish --instance-repo <url> --instance <name> --destination <name> --host <file> (--receiver <url> --receiver-token <file> | --out <dir>) [--principals <file>] [--state <dir>] [--read-schema <file>] [--identity-schema <file>] [--registry-ref <ref>] [--registry-dir <dir>] [--recheck <duration>] [--policy-only] [--max-bundles <size>] [--max-storage <size>]`
751 - `--instance-repo <url>`: An absolute local path to the instance repository. It is the `origin`
752 of the publisher's own bare repository, and the CLI discovers projects and signers through it.
753 Its `main` must hold `policy/instance` and no `policy/valley`. `<url>` must hold no `#`, no
754 control character, and no space at either end, because `policy/valley` cannot name such a URL.
755 - `--instance <name>`: The instance the manifest names. The export key signs under
756 `<name>/web-export`.
757 - `--destination <name>`: The receiver the manifest is for. It is also the destination of the
758 `edge-read` boundary whose read grants decide what each reader, `anyone` or a named principal,
759 may read there.
760 - `--host <file>`: Path to the `cue export` JSON of the host declaration under
761 `schema/valley.cue`. The publisher reads the declared groups and each project's `group`, web
762 `name`, `formerNames`, and short `aliases` to build web URLs (see
763 [Groups and web URLs](./architecture.md#groups-and-web-urls)). It decodes the file with
764 `exactjson`, which refuses unknown keys and duplicate keys in the same object. Before any pass
765 runs, it checks that the document is a JSON object, that `projects` and `groups` are present
766 and non-`null` objects, that every project and group entry is non-`null`, and that every
767 project identifier is a valid project name. It also refuses a declaration whose names collide
768 or that names an undeclared group (`export.CheckNames`). A project in no group is not
769 exported.
770 - `--receiver <url>`: The receiver's base URL, `http` or `https`, with no user, query, or
771 fragment. The upload's paths are appended to it.
772 - `--receiver-token <file>`: Path to the file holding the receiver's bearer token, sent in every
773 upload request's `Authorization` header. The file must contain one line of 32 to 256 visible
774 ASCII characters, matching the receiver's `--token-file`. Required with `--receiver` and
775 refused with `--out`.
776 - `--out <dir>`: Write the authorization and the export to `<dir>` instead of sending them.
777 `<dir>` must not exist or must be empty. Pass either `--receiver` or `--out`.
778 - `--principals <file>`: The display mapping, a JSON object from each principal's name to the
779 name an export shows. Without it, every principal is shown as `contributor`.
780 - `--state <dir>`: The state directory (default
781 `${XDG_STATE_HOME:-$HOME/.local/state}/valley/web-publish`).
782 - `--read-schema <file>`: The read policy schema, `schema/read.cue` (default
783 `$VALLEY_READ_SCHEMA`).
784 - `--identity-schema <file>`: The identity registry schema, `schema/identity.cue` (default
785 `$VALLEY_IDENTITY_SCHEMA`).
786 - `--registry-ref <ref>`: The full ref name in the instance repository whose tip carries the
787 identity registry (default `refs/heads/main`). The pass resolves `<ref>` once by that exact
788 name with `git show-ref` and reads the registry from the commit it points to. When `<ref>` is
789 not `refs/heads/main`, an instance repository without it has no registry, so every project is
790 private, even if a branch with a suffixed name such as `refs/heads/refs/heads/registry`
791 exists. An instance repository without `refs/heads/main` is not an instance repository, so the
792 pass aborts instead of building an empty export.
793 - `--registry-dir <dir>`: The identity registry's directory in that commit (default `identity`).
794 - `--recheck <duration>`: How long an acknowledgement from the receiver is trusted (default
795 `1h`).
796 - `--policy-only`: Run only the policy path: check the policy, sign an authorization, and send
797 it. It reads no plan, knot, or bundle and takes only the authorization lock, and with
798 `--links` the links lock, so a stalled content pass never holds it up. Requires `--receiver`.
799 - `--max-bundles <size>`: The most the bundles of one export may hold together (default `1G`).
800 - `--max-storage <size>`: The most the state directory and the caches may hold (default `16G`).
801 - A `<size>` is a number of bytes, or a number followed by `K`, `M`, `G`, or `T` for KiB, MiB,
802 GiB, or TiB.
803 - Prints
804 `valley-web-publish: the receiver stored authorization <sequence>: <project> to <readers>; ...`
805 once the receiver stores the pass's authorization (for example,
806 `app to alice, anyone, operator; site to anyone`). When the authorization carries links, the
807 line appends `; <n> read links`. When it names no projects, the line prints
808 `no project may be read` in place of the project list. A content pass then prints
809 `valley-web-publish: exported: <projects>; not exported: <projects>`, followed by one line
810 stating what it did. Warnings and CLI error output go to `stderr`.
811 - When the full authorization is over the size limit, the pass sends the bounded fallback in its
812 place, prints `valley-web-publish: pending: <project> to <readers>; ...; <n> read links` after
813 the stored line, and fails before any content work with an error that begins
814 `the authorization is too large to send`. A project with more than four pending readers is shown
815 as `<project> to <n> readers`. A read link the fallback does not carry stays `pending` in
816 `link list`.
817 - When the fallback is itself over the size limit, the pass restricts it until it fits and prints
818 `valley-web-publish: dropped: <project> to <readers>; ...; <n> read links` after the pending
819 line, in the same form. The pass prints the `pending` and `dropped` lines and names both in its
820 error even when writing to `--out` or when sending the authorization fails. When the receiver
821 refuses a fallback as `replayed` or `stale-basis`, the pass prints that fallback's `pending` and
822 `dropped` lines before rechecking the policy. If a later attempt then fails — even before
823 signing — the pass's error still names what the refused fallback left pending and dropped.
824 - Exits `0` when the pass sent its authorization and uploaded the export, found no content to
825 send, or wrote `--out`. It exits `1` when the pass failed, and `2` for invalid flags. When a
826 content pass fails, it has already sent its authorization. A content pass that fails before its
827 upload sends no content; one that fails during its upload may have sent some bodies, and the
828 receiver activates nothing until a commit succeeds.
829- **`valley-read-coverage`**
830 ([`readaccess/cmd/valley-read-coverage/main.go`](../readaccess/cmd/valley-read-coverage/main.go)):
831 Evaluates the two read-access consents for `<principal>` at `<destination>` and lists each project
832 that lacks either consent (see [Read policy](#read-policy-schemareadcue)). It reads the registry
833 at the instance repository's `--registry-ref` and each project's `policy/read` at its `main`, and
834 modifies nothing. It is wrapped with this flake's `git` and `cue`, with `VALLEY_READ_SCHEMA` and
835 `VALLEY_IDENTITY_SCHEMA` set to the two schemas.
836
837 ```sh
838 valley-read-coverage --instance-repo /srv/git/valley.git --destination example.org --reader operator
839 ```
840
841 ```text
842 docs: no project consent (its main holds no policy/read)
843 site: no project consent (its policy/read does not name operator)
844 operator may read 2 of 4 projects at example.org
845 ```
846
847 - `valley-read-coverage --instance-repo <dir> --destination <name> --reader <principal> [--registry-ref <ref>] [--registry-dir <dir>] [--read-schema <file>] [--identity-schema <file>]`
848 - `--instance-repo <dir>`: An absolute local path to the instance repository. Its
849 `refs/the-valley/projects` lists the projects. Each project's repository sits beside it, named
850 `<project>.git` when `<dir>` ends in `.git`, and `<project>` otherwise.
851 - `--reader <principal>`: The principal to check, or `anyone` for a reader with no credential.
852 - `--registry-ref`, `--registry-dir`, `--read-schema`, `--identity-schema`: Same as for
853 `valley-web-publish`. Pass the same `--registry-ref` that the host configures for the identity
854 compiler so the report reads the same registry ref as the publisher.
855 - Prints one line for each project where `<principal>` lacks a consent: `no project consent` when
856 the project has no `main`, no valid `policy/read`, or a `policy/read` that does not name
857 `<principal>`, and `no instance grant` when no read grant for `<principal>` at `<destination>`
858 covers the project with the identity its policy declares. If a project has no valid policy, it
859 has no identity, so a grant counts when it covers `"all"` or names the project. The final line
860 prints `<principal> may read <readable> of <total> projects at <destination>`.
861 - Exits `0` when it read every project (whether or not any project lacks a consent), `1` when a
862 repository or schema could not be read, and `2` for invalid flags.
863
864---
865
866## Environment variables and configuration
867
868`valley` and its helpers read three `valley.*` git configuration keys, environment variables for
869signing and schema paths, and local state and cache files.
870
871### Git configuration
872
873Configure your principal name in each project clone, and optionally configure `self-update` in your
874global git config.
875
876```sh
877git config valley.principal operator
878git config --global valley.selfUpdate.repo git@valley.example:the-valley
879git config --global valley.selfUpdate.branch main
880```
881
882| Git config key | Scope | Read by | Meaning |
883| :------------------------- | :------------------ | :---------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
884| `valley.principal` | repo or global | `ready`, `unready`, `withdraw`, `rebase`, `knot` (writes), `plan` | The principal name your SSH key authenticates as on the host. Required for writing change records (`owner` / `uploader`) and knots (`created_by`, `author`, commit `Committer`), and used as the default operator in `valley plan`. |
885| `valley.selfUpdate.repo` | global (`--global`) | `self-update` | Default repository URL for `valley self-update` when `--repo` is not passed. |
886| `valley.selfUpdate.branch` | global (`--global`) | `self-update` | Default branch name for `valley self-update` when `--branch` is not passed (defaults to `main`). |
887| `pager.diff`, `core.pager` | repo or global | `review` | Diff renderer used as `less`'s input preprocessor when `valley review` pages a diff (`git var GIT_PAGER` fallback). |
888
889### Environment variables
890
891The client verifies recorded landings with the signers the host publishes, so it needs no setting
892for them. Set `VALLEY_KNOWN_SIGNERS` and `VALLEY_INTEGRATOR_SIGNER` only to use other values. Set
893`VALLEY_ATTEST_KEY` (and `VALLEY_ATTEST_NAME`) to sign check evidence during approval.
894
895```sh
896export VALLEY_KNOWN_SIGNERS="$HOME/.config/valley/known-signers"
897export VALLEY_INTEGRATOR_SIGNER=integrator
898export VALLEY_ATTEST_KEY="$HOME/.ssh/valley-attest"
899export VALLEY_ATTEST_NAME=operator
900```
901
902| Environment variable | Read by | Meaning |
903| :--------------------------- | :-------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
904| `VALLEY_KNOWN_SIGNERS` | `status`, `changes`, `pending`, `rebase`, `plan`, `approve` | Path to the `known-signers` file of verifier keys used to verify the integrator's transfer statement on recorded (`landed-recorded`) landings. `--known-signers` takes precedence over it, and it takes precedence over the `known-signers` file the host publishes at `refs/the-valley/signers`. With neither of the three, recorded landings cannot be verified and report as `uncertain`. `approve` and `[a]pprove` reuse evidence from `origin` only when its note verifies under the file the host publishes, and also under this file when it is set: here it can narrow what is reused, never widen it. |
905| `VALLEY_INTEGRATOR_SIGNER` | `status`, `changes`, `pending`, `rebase`, `plan` | The signing name (`<signer-name>`) the host's integrator signs transfer statements under. `--integrator-name` takes precedence over it, and it takes precedence over the `integrator-name` the host publishes. A file that cannot be read, does not read as verifier keys, or holds no key under the name is reported on `stderr`, and no statement is verified. |
906| `VALLEY_ATTEST_KEY` | `approve`, `review` (`[a]pprove`) | Path to the OpenSSH `ssh-ed25519` private key passed to `attest run --key` whenever a required check has to run, because `origin` holds no evidence `approve` can reuse for it. |
907| `VALLEY_ATTEST_NAME` | `approve`, `review` (`[a]pprove`) | Signer name passed to `attest run --name` (when unset, `attest` defaults to `<hostname>/attestations`, or `localhost/attestations` if `os.Hostname` fails). |
908| `VALLEY_VERIFICATION_SCHEMA` | `checks`, `approve`, `review`, `integrator`, `valley-restacker` | Path to `schema/verification.cue`. Set automatically by the Nix wrapper, `valley-worker`'s included; falls back to `<repo>/schema/verification.cue` when running `bin/valley` from a checkout. |
909| `VALLEY_POLICY_SCHEMA` | `checks`, `approve`, `review` | Optional override for the verification policy schema path in `bin/valley` (takes precedence over `VALLEY_VERIFICATION_SCHEMA` when `--schema` is not passed). |
910| `VALLEY_ATTEST_SCHEMA` | `attest`, `integrator` | Path to `schema/attestation.cue`, set by the Nix wrapper. |
911| `VALLEY_EVENT_SCHEMA` | `integrator` | Path to `schema/events.cue`, set by the Nix wrapper. |
912| `VALLEY_IDENTITY_SCHEMA` | `identity` | Path to `schema/identity.cue`, set by the Nix wrapper. |
913| `VALLEY_COMMAND` | `pending --checks` | Executable invoked by `valley-go pending --checks` to run `<valley> checks <base> <head>` (`bin/valley` sets `VALLEY_COMMAND` to its own path; defaults to `"valley"`). |
914| `VALLEY_NOW` | `knot`, `plan`, `valley-worker` | Optional UTC timestamp in `RFC 3339` format (`YYYY-MM-DDTHH:MM:SSZ`) overriding the system clock for knot `created` dates, comment stamps, comment edit times, claim timestamps, claim age calculations, and the check worker's waits after a failed batch. Invalid values exit `2`. |
915| `VALLEY_VERSION` | `bin/valley`, `self-update` | Package stamp (`<version>-<rev>`) baked into the Nix-wrapped `valley` script, captured into `VALLEY_STAMP` and unset on startup so child processes do not inherit it, and passed explicitly to `valley-go self-update`. |
916| `VALLEY_PRINCIPAL` | `valleyhook shell`, host `pre-receive` wrapper | Host-side environment variable set by `valleyhook shell` after looking up the key named in `SSH_USER_AUTH` against the host's `authorized_keys` files. Any client-supplied `VALLEY_PRINCIPAL` or `GIT_*` environment variable is stripped by `valleyhook shell` before `git-shell` runs. |
917| `SSH_USER_AUTH` | `valleyhook shell` | Path to the file written by OpenSSH `sshd` (`ExposeAuthInfo yes`) containing the public key that authenticated the SSH session. |
918| `XDG_STATE_HOME` | `review`, `approve` (via `attest run --timings`), `self-update` | Base directory for persistent client state, and for the check worker's (defaults to `~/.local/state`). |
919| `XDG_CACHE_HOME` | `pending`, `changes`, `plan`, `knot`, `valley-worker` | Base directory for cached cross-project clones (defaults to `~/.cache`). |
920| `EDITOR` | `review` (via `less`) | Editor invoked when pressing `v` while paging a diff in `valley review`. |
921| `GIT_PAGER`, `PAGER`, `LESS` | `review` | Pager and diff-renderer environment variables read by `valley review` (`LESS` defaults to `FRX` when unset). |
922| `NO_COLOR` | `pending`, `plan` | When set to a non-empty value, disables ANSI bold and color sequences on terminal output. |
923| `NATS_URL` | `tail`, `replay` (via `nats`) | NATS server URL used by the `nats` CLI when streaming or replaying bus events. |
924
925### Client state and cache files
926
927The client stores review notes, check timings and `self-update` state under `$XDG_STATE_HOME`,
928cached multi-repository clones under `$XDG_CACHE_HOME`, and tab-completion handles inside the local
929git directory:
930
931- `${XDG_STATE_HOME:-$HOME/.local/state}/valley/notes/<branch>.md`: Markdown review notes captured
932 by `v` in `valley review`.
933- `${XDG_STATE_HOME:-$HOME/.local/state}/valley/timings.jsonl`: How long each check took when
934 `valley approve` ran it, one JSON line per check (see [The timing log](#the-timing-log)).
935- `${XDG_STATE_HOME:-$HOME/.local/state}/valley/self-update.json` and `self-update.lock`: Installed
936 store paths, commits, pin flag, last failure record, and lock file for `valley self-update`.
937- `${XDG_STATE_HOME:-$HOME/.local/state}/valley/worker/lock` and `failures.json`: The check worker's
938 lock, and its record of failed batches and pushes (`--state` names another directory). The record
939 holds `projects`, by project name, each a map from `build <tree digest> <check>,<check>` or
940 `push <object ID>` to `failures`, how many times in a row it failed, and `retry`, the time before
941 which it is not tried again.
942- `${XDG_CACHE_HOME:-$HOME/.cache}/valley/repos/<16-hex-url-hash>-<project>`: Cached non-bare git
943 repositories (`git init --quiet` with no working tree checkout) fetched when `--all`, `--repo`, or
944 `--project` reads another project on the host. A clone is made in a temporary directory beside it
945 and renamed into place, so a making that is interrupted leaves no clone. A clone whose
946 configuration names no origin is set aside and made again. The check worker keeps the attestation
947 refs it stores in the clone it reads a project through.
948- `${TMPDIR:-/tmp}/valley-known-signers-*`: A copy of the `known-signers` file the host publishes,
949 for `attest verify` to read. It exists only while a command that verifies a transfer statement
950 runs.
951- `<git-common-dir>/valley/handles`: Tab-separated list (`<handle>\t<state>\t<branch>\t<title>`) of
952 unlanded `ready` and `draft` changes in the current repository, written by `valley pending` and
953 `valley changes` and read by [`completions/_valley`](../completions/_valley).
954
955### The timing log
956
957The timing log records how long each check took when `valley approve` ran it. It is a local
958measurement for the operator, and it is not evidence: nothing signs it, stores it at a ref, or
959pushes it, and nothing reads it to decide anything (`implemented`).
960
961```text
962$ tail -n 1 ~/.local/state/valley/timings.jsonl
963{"time":"2026-10-20T12:01:43.601Z","repository":"ssh://valley.example/the-valley.git","change":"kqxmrvtzkqxmrvtzkqxmrvtzkqxmrvtz","version":2,"head":"4ae651e56c34b79b324aca341508cf35c3aaae8e","check":"prose-format","runner":"nix","cost":"quick","result":"passed","satisfied":"cached","duration_ms":1234,"eval_ms":980}
964```
965
966`attest run --timings` appends one line per check to
967`${XDG_STATE_HOME:-$HOME/.local/state}/valley/timings.jsonl`, whether the check passed or failed.
968The line for a `nix` check is appended once it and every `nix` check before it have ended, and the
969line for each `command` check when it finishes. It creates the file and its directory when they are
970missing, readable by their owner alone. A log that others can read is made readable by its owner
971alone before a line is added. Anything at the path that is not a regular file, such as a FIFO, is
972refused. `valley approve` passes `--timings` whenever it runs checks. Without the flag, `attest run`
973prints its `time` lines, writes no log, and does not ask the nix store whether an output is already
974there.
975
976- `time` (`string`): When the check started, in UTC, to the millisecond. Every `nix` check starts
977 when the shared evaluation starts.
978- `repository` (`string`): The repository's `origin` remote, reduced to what names it. A URL keeps
979 its scheme, host and path, and loses any user name, password, query and fragment. The scp-like
980 form `user@host:path` keeps `host:path`. A local path is kept as it is. An `origin` in any other
981 form is withheld. In its place, and when there is no `origin`, the field is the directory of the
982 main working tree.
983- `change` (`string`) and `version` (`integer`): The change ID and the version being approved.
984 Omitted for a branch no record is on.
985- `head` (`string`): The commit the check ran over.
986- `check` (`string`) and `runner` (`string`): The check's name, and its runner, `nix` or `command`.
987- `cost` (`string`): The cost class the policy declares for the check, `quick` or `slow`.
988- `result` (`string`): `passed`, `failed`, or `error` when the check could not run at all, such as a
989 flake check that does not evaluate.
990- `satisfied` (`string`): `ran` when the command ran or nix built or fetched the output, `cached`
991 when the output was already in the local nix store so nix built nothing, and `unknown` when the
992 store could not be asked or did not answer within five seconds. `attest run` runs every check it
993 is given, so it never reuses evidence that already exists.
994- `duration_ms` (`integer`): The check's wall time in milliseconds. For a `command` check, it is the
995 time the command ran. For a `nix` check, it is the check's evaluation (`eval_ms`), the store
996 probe, and the time its own build ran. A `nix` check that does not evaluate ends at its evaluation
997 error.
998 - Summing `duration_ms` over one run's checks overcounts the run's wall time. Every `nix` check
999 counts the one shared evaluation, and the `nix` checks build at the same time.
1000- `eval_ms` (`integer`): How long evaluating a `nix` check took, in milliseconds. It counts the
1001 shared evaluation of all the `nix` checks, plus the time spent on this check alone, such as
1002 digesting its inputs or evaluating it on its own. Omitted for a `command` check.
1003
1004A log that cannot be written produces one warning on standard error, and the run continues. Each
1005`time` line, warning and log line has one second to be written. One that fails or takes longer is
1006dropped, and the run continues without it.
1007
1008### NixOS host options
1009
1010On a NixOS valley host, machine paths, service toggles, static keys, and static grants are
1011configured under `services.valley` (`deployment choice`;
1012[`nix/valley-host.nix`](../nix/valley-host.nix)).
1013
1014```nix
1015services.valley = {
1016 enable = true;
1017 config = ./valley.cue;
1018 dataDir = "/srv/git";
1019 authorizedKeys = [
1020 { principal = "operator"; key = "ssh-ed25519 AAAA... operator"; }
1021 ];
1022};
1023```
1024
1025| NixOS option (`services.valley.*`) | Default | Meaning |
1026| :------------------------------------------------------------------------------------------- | :------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1027| `enable` | `false` | Enables the valley git host (`valleyhook shell`, `valley-init` service, and repository hooks). |
1028| `user`, `group`, `dataDir` | `"git"`, `"git"`, `"/srv/git"` | System user and group owning the bare `<project>.git` repositories, and the directory holding `<project>.git`, `.valley-converged`, and the optional `.valley-hold` push-hold sentinel. |
1029| `config` | (required) | Path to the host's `valley.cue` declaration (`package valley`), validated against `schema/valley.cue` at build time. |
1030| `authorizedKeys` | `[]` (must be non-empty when `enable = true`) | Static SSH public keys written to `/etc/ssh/authorized_keys.d/<user>`: plain strings authenticate as anonymous pushers (`VALLEY_PRINCIPAL=""`), and `{ key, principal }` submodules authenticate as `<principal>`. No key may appear twice, and `users.users.<user>.openssh.authorizedKeys.keyFiles` must be empty. |
1031| `extraPreReceive` | `{}` | Attribute set mapping project name to a Nix store-path script run by `valleyhook pre-receive --then` after the push policy accepts a push. |
1032| `grants.approve`, `grants.request`, `grants.restack` | `[]`, `[]`, `[]` | Static principal lists holding the `approve` (approval) and `restack` boundary grants in `valleyhook`. `grants.request` declares the `approve` grant under the name it is also accepted as: its holders are the principals named in either list, and a principal named in both holds the grant once. |
1033| `bus.enable`, `bus.listen`, `bus.storeDir` | `false`, `"127.0.0.1:4222"`, `"${dataDir}/.bus"` | Optional local NATS JetStream server for `valley.git.<repo>.*` events. |
1034| `integrator.enable`, `integrator.user` | `false`, `"valley-integrator"` | Spawns `valley-integrator@<project>` for every git-enabled project in `valley.cue` that declares a `protection` block (requires at least one protected project; `integrator.user` must differ from `services.valley.user`). |
1035| `integrator.signingKeyFile`, `integrator.signingName` | `null` (required when enabled), `null` | Runtime path to the integrator's Ed25519 private key and optional signer name (when `null`, `integrator` defaults to `<hostname>/attestations`). The effective name is published at `refs/the-valley/signers`. |
1036| `integrator.knownSignersFile` | `null` | Runtime path to the `known-signers` file of trusted verifier keys (used by both `valleyhook` and `valley-integrator`). Required when `integrator.enable = true` and `identity.enable = false`; must be `null` whenever `identity.enable = true`. |
1037| `integrator.signerProjects` | `{}` | Signer names mapped to the projects their evidence counts in, as in `{ "worker/attestations" = [ "the-valley" ]; }`. Rendered into the controllers' `--signer-projects` and published. An empty list counts nowhere. Names and projects are printable ASCII with no space; the integrator's own name is refused. |
1038| `integrator.instanceProject`, `integrator.instancePolicy` | `null`, `null` | Exactly one must be set when `integrator.enable = true`: `instanceProject` names the hosted repository carrying `policy/instance/` (whose `refs/heads/main` must be protected) and causes `valley-init` to write `refs/the-valley/projects` and `valley-signers` to write `refs/the-valley/signers` there; `instancePolicy` names a local directory of floor `*.cue` files. |
1039| `integrator.interval` | `"15s"` | Poll interval between `integrator watch` reconciliation passes. |
1040| `identity.enable`, `identity.ref`, `identity.directory`, `identity.interval` | `false`, `"refs/heads/main"`, `"identity"`, `"5m"` | Compiles `<directory>/*.cue` from `integrator.instanceProject` at `<ref>` (which must be covered by `protection`) into `/var/lib/valley-identity/{known-signers,authorized_keys.<user>,grants}` on a timer (`knownSignersFile` must be `null`). |
1041| `buildSlice.enable`, `buildSlice.cpuQuota`, `buildSlice.memoryMax` | `false`, `"400%"`, `"8G"` | Places `nix-daemon.service` in `valley-builds.slice` with `CPUQuota`, `MemoryMax`, and `MemorySwapMax=0`, capping the total CPU and memory of all Nix daemon builds across all users on the host. When the slice hits `MemoryMax`, the kernel OOM killer kills whichever process in the slice uses the most memory, even if another build pushed the slice over the cap. Required when `worker.enable = true` (see [The build slice](architecture.md#the-build-slice)). |
1042| `worker.enable`, `worker.projects`, `worker.signerName` | `false`, `[]`, (required when enabled) | Runs `valley-worker` on a timer over `projects` as the `valley-worker` user, signing attestations as `signerName`. Requires `buildSlice.enable = true`, `integrator.enable = true`, `integrator.instanceProject != null`, non-empty `projects` served by this host, `signerName` different from the integrator's signing name, and `integrator.signerProjects.<signerName>` set to the exact `projects` list. Runs in `valley-builds.slice` pinned to CPU 0 (`CPUAffinity=0`) with `max-jobs = 1` and `cores = 4`. Connects to the host's repositories over `localhost` SSH as `user` (`git` by default); its generated key must be enrolled before it can fetch or push (see [The worker on the host](architecture.md#the-worker-on-the-host)). |
1043| `restacker.enable`, `restacker.projects`, `restacker.sshKeyFile` | `false`, `[]`, `null` | Runs `valley-restacker run` as `valley-restacker@<project>.service` for each of `projects`, under the `valley-restacker` user and group it creates, with state in `/var/lib/valley-restacker/<project>` (mode `0700`). Requires non-empty `projects` served by this host, `sshKeyFile`, `services.openssh.enable`, and exactly one of `integrator.instanceProject` or `integrator.instancePolicy` for the instance floor. `sshKeyFile` is the private key passed via systemd `LoadCredential` to authenticate to the host's sshd as `restacker.principal`. Enrolling the public key in `authorizedKeys` and granting the principal `restack` are **deployment choices** (see [The restacker on the host](architecture.md#the-restacker-on-the-host)). |
1044| `restacker.principal`, `restacker.interval` | `"valley-restacker"`, `"15s"` | Principal name that `valley-restacker` pushes as and records as the uploader of each version it adds, and its `--interval` between passes. |
1045| `worker.interval`, `worker.stateDir` | `"1m"`, `"/var/lib/valley-worker"` | Delay (`OnUnitInactiveSec`) between the end of one `valley-worker.service` pass and the start of the next, and the `0700` state directory owned by `valley-worker`. Holds the worker's Ed25519 private key (`key`, mode `0400`, generated on first start), its public key (`key.pub`) and `known-signers` line (`verifier`), its `known_hosts`, the scratch repository (`origin/`), cached project clones (`cache/`), and `lock` and `failures.json`. |
1046| `backup.repositoryFile`, `backup.passwordFile`, `backup.sshKeyFile`, `backup.knownHostsFile` | `null` | Runtime secret paths required whenever `valley.cue` enables `backup` (`backup.enable` defaults to `true` when `backup` is declared). |
1047
1048#### The web publisher's options
1049
1050The web publisher's module, `nixosModules.web-publisher`
1051([`nix/web-publisher.nix`](../nix/web-publisher.nix)), adds `services.valley.webPublisher` to a host
1052that imports the host module (`deployment choice`).
1053
1054```nix
1055imports = [ the-valley.nixosModules.default the-valley.nixosModules.web-publisher ];
1056services.valley.webPublisher = {
1057 enable = true;
1058 destination = "example.org";
1059 receiver = "https://example.org";
1060 receiverTokenFile = "/run/keys/valley-web-receiver-token";
1061 principals = { operator = "operator"; alice = "agent"; };
1062};
1063```
1064
1065| NixOS option (`services.valley.webPublisher.*`) | Default | Meaning |
1066| :---------------------------------------------- | :------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1067| `enable` | `false` | Runs `valley-web-publish` on a timer. Needs `services.valley.integrator.instanceProject`, the instance repository the publisher reads. |
1068| `destination` | (required) | The receiver's name, which every manifest is signed for. |
1069| `receiver` | (required) | The receiver's base URL, `http://` or `https://`. |
1070| `receiverTokenFile` | (required) | Runtime path (outside the Nix store) to the file holding the receiver's bearer token. Loaded as systemd credential `receiver-token` and passed as `--receiver-token`. |
1071| `principals` | `{}` | The display mapping, written to a JSON file for `--principals`. A principal it does not name is shown as `contributor`. |
1072| `stateDir` | `"/var/lib/valley-web-publish"` | The state directory, under `/var/lib`. The cache is the directory of the same name under `/var/cache`, given to the service as `XDG_CACHE_HOME`. |
1073| `memoryMax` | `"1G"` | The most memory a pass may use, with every program it runs (`MemoryMax`, with `MemorySwapMax=0`). Past it, the kernel ends the pass. |
1074| `maxBundles` | `"1G"` | Passed as `--max-bundles`: the most the bundles of one export may hold together. |
1075| `maxStorage` | `"16G"` | Passed as `--max-storage`: the most the state and cache directories may hold. |
1076| `allowedAddresses` | (required) | IPv4 or IPv6 addresses and prefixes that a pass may connect to (`IPAddressAllow`); the unit blocks all other addresses (`IPAddressDeny=any`). Set this to the receiver's addresses. The filter matches destination IP addresses only and permits any port on a listed address. Because the unit sets `GODEBUG=netdns=cgo`, the C library resolves host names through `nscd` outside the unit; include the DNS resolver's address only when `nscd` is disabled. Before each pass, `valley-web-publish-egress-check` sends a UDP datagram to `198.51.100.1` port `9` and starts the pass only if the filter rejects it with `EPERM`. An empty list or an entry covering `198.51.100.1` fails a module assertion. |
1077
1078The module also passes `services.valley.identity.ref` as `--registry-ref` and
1079`services.valley.identity.directory` as `--registry-dir`, so the publisher reads the registry from
1080the same directory and ref in the instance repository as the identity compiler. It passes the host
1081module's JSON export of `services.valley.config` as `--host`, so the publisher reads the groups and
1082project placements the host declares. When the publisher is enabled, the host module requires the
1083instance repository's `protection` to cover that ref, just as it does when the identity compiler is
1084enabled (`implemented`, `nix/valley-host.nix`).
1085
1086- **The pass:** `valley-web-publish.service` is a oneshot. It runs
1087 `valley-web-publish --instance-repo <dataDir>/<instanceProject>.git --instance <networking.hostName>`
1088 with the destination, receiver, token, display mapping, state directory, and size bounds above.
1089 The token reaches the unit via systemd `LoadCredential`, so the token file on disk can remain
1090 readable only by root. A token file path in the Nix store fails a module assertion. No switch
1091 starts the service: nothing wants it, and a changed unit is not restarted
1092 (`restartIfChanged = false`). A pass that runs longer than an hour is stopped (`TimeoutStartSec`).
1093- **The timer:** `valley-web-publish.timer` starts the first pass five minutes after the timer
1094 starts (`OnActiveSec`). After that it starts a pass five minutes after the last one ended
1095 (`OnUnitInactiveSec`). Both are delays only. When the switch that starts the timer runs longer
1096 than five minutes, the first pass can start inside it, and a later pass can start inside any later
1097 switch.
1098- **The sandbox:** The service runs as a dynamic user (`DynamicUser`) with the git group
1099 (`SupplementaryGroups`), so it can read the repositories and owns nothing on disk but its state
1100 and cache. Its environment carries `safe.directory` entries as `GIT_CONFIG_COUNT`,
1101 `GIT_CONFIG_KEY_<n>`, and `GIT_CONFIG_VALUE_<n>`. git reads them after the system and global
1102 configuration, and adds them to what those set. So the first entry is empty, which resets the
1103 list, and one exact entry follows for each repository the host declaration serves, with no
1104 wildcard. A system configuration with `safe.directory=*` then trusts no other repository for the
1105 service. `ProtectSystem=strict` leaves the filesystem read-only except the state and cache
1106 directories, and the repositories are listed in `ReadOnlyPaths`. `InaccessiblePaths` holds the git
1107 user's `<dataDir>/.ssh`, `/var/lib/valley-integrator`, the integrator's signing key file, the
1108 worker's state directory when the worker runs, and the backup's secret files. `web-publisher-e2e`
1109 runs the unit in a NixOS machine with a probe in place of the publisher under a system
1110 configuration with `safe.directory=*`. The probe reads a served repository and the token
1111 credential, and cannot read an undeclared repository, write to a repository, or read the git
1112 user's ssh key, the backup key, or the token's source file.
1113
1114#### The web receiver's options
1115
1116The web receiver module, `nixosModules.web-receiver`
1117([`nix/web-receiver.nix`](../nix/web-receiver.nix)), adds `services.valley.webReceiver` to an edge
1118host (`deployment choice`). It stands alone and requires no other module of the-valley.
1119
1120```nix
1121imports = [ the-valley.nixosModules.web-receiver ];
1122services.valley.webReceiver = {
1123 enable = true;
1124 instance = "valley-host";
1125 destination = "example.org";
1126 verifiers = [ "valley-host/web-export+1a2b3c4d+AQ..." ];
1127 tokenFile = "/run/keys/valley-web-receiver-token";
1128 listen = "192.0.2.10:8081";
1129 webListen = "127.0.0.1:8080";
1130};
1131```
1132
1133| NixOS option (`services.valley.webReceiver.*`) | Default | Meaning |
1134| :--------------------------------------------- | :---------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------- |
1135| `enable` | `false` | Runs `valley-web-receive` and `valley-web` over a shared state directory. |
1136| `instance` | (required) | Instance name required in every manifest (matches the publishing host's `networking.hostName`). |
1137| `destination` | (required) | Destination name required in every manifest (matches the publisher's `destination`). |
1138| `verifiers` | (required) | Non-empty list of publisher verifier lines, written to a Nix store file for `--verifiers`. An empty list fails a module assertion. |
1139| `tokenFile` | (required) | Runtime path (outside the Nix store) to the bearer token file. Loaded by the receiver unit as credential `token` and passed as `--token-file`. |
1140| `listen` | (required) | TCP listen address for `valley-web-receive`, reached by the publisher. |
1141| `webListen` | (required) | TCP listen address for `valley-web`, reached by readers or a reverse proxy. |
1142| `origin` | `null` | Public HTTPS origin passed to `valley-web` as `--origin`. When set, readers sign in with read links, and the module provisions `browser/`. |
1143| `stateDir` | `"/var/lib/valley-web"` | Shared state directory under `/var/lib`. Both units take its descriptor, `<stateDir>/store`, as `--state`. |
1144| `maxBody`, `maxUpload`, `maxStorage` | `"1G"`, `"2G"`, `"8G"` | Size limits passed to `valley-web-receive` as `--max-body`, `--max-upload`, and `--max-storage`. |
1145| `receiverMemoryMax`, `webMemoryMax` | `"2G"`, `"1G"` | Per-unit `MemoryMax` (with `MemorySwapMax=0`) for `valley-web-receive.service` and `valley-web.service`. |
1146
1147- **The units:** `valley-web-receive.service` runs as system user `valley-web-receive` and
1148 `valley-web.service` runs as system user `valley-web`, both in group `valley-web`. Both units
1149 start at boot (`wantedBy = multi-user.target`) and restart on failure (`Restart=on-failure`).
1150 `valley-web.service` starts after `valley-web-receive.service`, and neither unit requires the
1151 other.
1152- **The state directory:** `valley-web-receive.service` owns the state directory (`StateDirectory`)
1153 with mode `0750` and group `valley-web`, so `valley-web` reads it through the group.
1154 `valley-web.service` lists the state directory in `ReadOnlyPaths`.
1155- **The browser state:** When `origin` is set, systemd-tmpfiles creates the state directory as
1156 `valley-web-receive:valley-web` with mode `0750` and `<stateDir>/browser` as
1157 `valley-web:valley-web` with mode `0700` before either unit starts. `valley-web.service` lists
1158 `<stateDir>/browser` in `ReadWritePaths`, and `valley-web-receive.service` lists it in
1159 `InaccessiblePaths`. `valley-web.service` also sets `LimitCORE=0` to disable core dumps.
1160- **The sandbox:** Both units run with `ProtectSystem=strict`, `PrivateTmp`, `PrivateDevices`,
1161 `NoNewPrivileges`, no capabilities, `@system-service` system calls, and `UMask=0077`. Each unit
1162 can write to its private `/tmp` and `/var/tmp` (created by `PrivateTmp` and removed by systemd
1163 when the unit stops) and to the host's `/dev/shm` (kept writable by `PrivateDevices`). Aside from
1164 those temporary paths, `valley-web.service` can write only to `<stateDir>/browser` when `origin`
1165 is set, and nowhere when `origin` is unset. `valley-web-receive.service` can write only to the
1166 state directory outside `browser/`.
1167
1168`module-eval` checks the rendered unit settings, users, modes, credentials, ordering, and limits
1169without running the units.
1170
1171---
1172
1173## Project storage ref layout and bounds
1174
1175Every repository on a valley host separates **the source** (`refs/heads/main` and `refs/tags/*`),
1176topic branches (`refs/heads/<branch>`), and **project storage** (`refs/the-valley/*`), and
1177`valleyhook pre-receive` validates every SSH push against fixed structural rules and size limits
1178([`valleyhook/policy.go`](../valleyhook/policy.go)).
1179
1180### Push-wide bounds
1181
1182`valleyhook` enforces four repository-wide and push-wide counters before accepting a push:
1183
1184```sh
1185git push --atomic origin topic refs/the-valley/changes/main/nxvpwlkmqtsrzyoukklnpmqrstuvwxyz
1186```
1187
1188| Bound | Value | Enforcement |
1189| :--------------------------------------------------- | :------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1190| Ref updates per push (`maxUpdates`) | `<= 1,000` | Refuses the entire push before evaluating any ref. |
1191| Change record updates per push (`MaxRecordUpdates`) | `<= 32` | Refuses the push if more than 32 `refs/the-valley/changes/*` refs are updated in one push. |
1192| Change records per repository (`MaxRecords`) | `<= 2,000` (soft push cap)<br>`<= 4,000` (hard integrator cap) | `valleyhook` refuses creating a new change record when `existingRecords + recordCreates > 2,000` (concurrent pushes can briefly exceed it). The integrator refuses to reconcile any pass if a repository holds more than `4,000` change records (`recordLimit = 4000`). |
1193| Restack report updates per push (`MaxReportUpdates`) | `<= 64` | Refuses the push if more than 64 `refs/the-valley/restack/*` refs are updated in one push. |
1194
1195### Ref layout, permissions, and object bounds
1196
1197The table below lists every ref namespace on a valley host, who may write it over SSH vs. locally on
1198the host, the required git object type, and the size bounds enforced by `valleyhook`. After checking
1199a ref's namespace rule below, `valleyhook` also checks `#Protection.refs` (`deployment choice`): if
1200any protected pattern matches a ref in **any** namespace (`refs/heads/*`, `refs/tags/*`, or
1201`refs/the-valley/*`), the pushing principal must also be listed in `#Protection.writers`.
1202
1203| Ref pattern | Purpose | Who may write | Object type and layout | Size and structure bounds |
1204| :-------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1205| `refs/heads/main` (or any ref matching `#Protection.refs`) | Protected integration branch (`the source`) | **Local host write:** `valley-integrator` via `git update-ref` (`implemented`).<br>**SSH push:** Only principals listed in `#Protection.writers` (`deployment choice`, default `[]` when `protection` is declared; if `protection` is omitted in `valley.cue`, all branches are open). | Commit object | Standard git commit; `refs/heads/main` is replicated to `mirrors` by `valley-publish`. |
1206| `refs/heads/<branch>` (unprotected) | Topic branches | Any SSH key in `authorized_keys` (named principal or anonymous pusher). | Commit object | `<branch>` must pass `git check-ref-format`; not replicated to `mirrors`. |
1207| `refs/tags/<tag>` (and any ref outside `refs/heads/`, `refs/replace/`, `refs/notes/`, `refs/the-valley/`) | Release tags (`the source`) and custom refs | Closed by default (`implemented`); opened over SSH only to principals listed in a matching `#Project.grants.<name>` (`#RefGrant`) in `valley.cue` (`deployment choice`), and also requires `#Protection.writers` if matched by `#Protection.refs`. | Any git object (tag, commit, tree, or blob) | `refs/tags/*` is replicated to `mirrors` by `valley-publish`. |
1208| `refs/replace/*`, `refs/notes/*` | Git object replacements and notes | **Nobody.** Categorically refused on all SSH pushes (`implemented`). | — | Always refused. |
1209| Any symbolic ref | Symbolic ref target | **Nobody.** Categorically refused on all SSH pushes (`implemented`). | — | Always refused. |
1210| `refs/refs/*`, `refs/heads/refs/*`, `refs/tags/refs/*`, `refs/remotes/refs/*` | A ref named like another ref: when the ref it is named for is missing, git reads, fetches and pushes to it in that ref's place | **Nobody** creates or updates one, whatever a grant or a protection block says (`implemented`). A delete follows the rule of its namespace. | — | Report existing ones with the `git for-each-ref` invocation in [Find refs named like other refs](./guide.md#find-refs-named-like-other-refs). |
1211| `refs/the-valley/changes/main/<change-id>` | Change record (`valley-change-record/v1`) | **Create:** Any named principal (becomes `owner`).<br>**Add version / `unready` / `re-ready` / `withdraw`:** Change `owner` or an `approve` grant holder.<br>**Add restacked version (`ready` → `ready`, same `branch` & `title`):** `restack` grant holder.<br>**Delete:** `approve` grant holder only.<br>(`valleyhook` accepts target `main` only; `<change-id>` is `[k-z]{32}`). | **Commit** whose root **tree** contains a single regular file (`100644`) named `record.json`. | Commit `<= 4 KiB` (`4,096` bytes);<br>Tree `<= 1 KiB` (`1,024` bytes, 1 entry `100644 record.json`);<br>Blob `record.json` `<= 64 KiB` (`65,536` bytes);<br>`<= 1,000` versions, `seq <= 100,000`. |
1212| `refs/the-valley/restack/main/<change-id>` | Restack report (`valley-restack-report/v1`) | **Create / extend (`P = []` or `P = [old]`):** Principals holding the `restack` grant, only for a `<change-id>` that already has a change record on `main`.<br>**Delete or history rewrite:** Refused. | **Commit** whose root **tree** contains a single regular file (`100644`) named `report.json`. | Commit `<= 4 KiB` (`4,096` bytes);<br>Tree `<= 1 KiB` (`1,024` bytes, 1 entry `100644 report.json`);<br>Blob `report.json` `<= 64 KiB` (`65,536` bytes);<br>`<= 64` layers, `<= 100` conflict paths, `<= 64` blocking requests. |
1213| `refs/the-valley/reviews/<target>/<change-id>` | Review history (`the-valley/review/v1`) | **SSH push:** Nobody (`implemented`): the hook has no rule for the namespace and refuses it. Admitting appends is `not built`; see [Review record](#review-record-the-valleyreviewv1). | **Commit** whose root **tree** contains a single regular file (`100644`) named `review.json`. | Commit `<= 4 KiB`;<br>Tree `<= 1 KiB`;<br>Blob `review.json` `<= 64 KiB`;<br>`<= 512` reviews per history. |
1214| `refs/the-valley/attestations/<tree-digest>/<key-hash>` | Signed check attestations and integrator transfer statements | **Create over SSH:** Any pusher, provided `--known-signers` is configured and every note in the tree verifies under a known signer with key hash `<key-hash>` (`[0-9a-f]{8}`) for `<tree-digest>` (`[0-9a-f]{64}`).<br>**Update or delete over SSH:** Refused (create-only).<br>**Local host write:** `valley-integrator` writes countersigned `<check>/statement.note` and its transfer statement at `transfer.d/<2 hex>/<2 hex>/<rest>.note` under its own `<key-hash>`, in the landing's ref transaction. It keeps every other note the ref holds, and refuses to write a tree past these bounds. | **Tree** object (not a commit) containing `100644` note blobs (such as `<check>/statement.note` and `transfer.d/<2 hex>/<2 hex>/<rest>.note`). | Tree depth `<= 4` (root tree is depth 1);<br>`<= 64` entries per tree object;<br>`<= 256` total entries visited across walk (`>= 1` note blob required);<br>Each tree object `<= 16 KiB` (`16,384` bytes);<br>Each note blob (`100644`) `<= 64 KiB` (`65,536` bytes);<br>Total bytes read in walk `<= 1 MiB` (`1,048,576` bytes). |
1215| `refs/the-valley/integration-requests/<target>/<request>` | Integration request (approval of a commit) | **Create / replace / delete over SSH:** Principals holding the `approve` grant, also accepted as `request` (`valleyhook` checks the `refs/the-valley/integration-requests/` prefix and the `approve` grant).<br>**Local host delete:** `valley-integrator` deletes the ref (CAS on request head) when a change lands or when voiding a `withdrawn` change's request. | **Commit** object (written by `valley approve` and required by `valley-integrator` at `refs/the-valley/integration-requests/main/<request>`, where `<request>` contains no `/`). | Must resolve to a commit object in the repository for the integrator to consider it. |
1216| `refs/the-valley/integration-outcomes/<target>/<request>` | Integrator outcome record | **SSH push:** Nobody (`implemented`).<br>**Local host write:** `valley-integrator` writes after judging a request, and for a landing in the landing's ref transaction. | **Blob** object (single line of space-separated fields). | 4 or 5 whitespace-separated fields terminated by `\n`. |
1217| `refs/the-valley/integration-landings/<target>/<head>` | Integrator landing record | **SSH push:** Nobody (`implemented`).<br>**Local host write:** `valley-integrator` writes one per landed head, in the landing's ref transaction. | **Commit** object with no parent, whose tree holds one blob, `landing`. | Three lines, each `<key> <value>\n`: `landed`, `request`, `head`. |
1218| `refs/the-valley/integration-inputs/<target>/<request>` | Integrator inputs record | **SSH push:** Nobody (`implemented`).<br>**Local host write:** `valley-integrator` writes it with the outcome record of the same name, in one ref transaction, except for a landing or a voiding. | **Blob** object (single line of two space-separated fields). | `<inputs-digest> <outcome-blob-oid>\n` (see [Integrator inputs record](#integrator-inputs-record-refsthe-valleyintegration-inputstargetrequest)). |
1219| `refs/the-valley/knots` | Project plan graph (exact ref name; `refs/the-valley/knots/*` is closed) | **Create (`P = []`) / update (`P = [old]`):** Any named principal (`Committer` must match pushing principal, commit message must end with `Valley-Op: <16-hex>`).<br>**Delete or non-fast-forward:** Refused. | **Commit** whose **tree** holds `<type-dir>/<id>-<slug>.md` and `comments/<id>/<stamp>-<op>.md` (`100644` blobs). | Commit `<= 16 KiB` (`16,384` bytes);<br>Changed paths per commit `<= 32`;<br>Tree depth `<= 3`, `<= 20,000` entries/tree, `<= 30,005` total walk entries, each tree `<= 2 MiB`;<br>Knot file `<= 64 KiB`, `<= 5,000` knots;<br>Comment file `<= 16 KiB`, `<= 20,000` comments;<br>Total walk read `<= 64 MiB`, hook deadline `5s`. |
1220| `refs/the-valley/projects` | Hosted project list in the instance repository | **SSH push:** Nobody (`implemented`).<br>**Local host write:** `valley-init` writes in `integrator.instanceProject`. | **Blob** object | Sorted enabled git project names, one per line, terminated by `\n`. |
1221| `refs/the-valley/signers` | What clients verify transfer statements with, in the instance repository | **SSH push:** Nobody (`implemented`).<br>**Local host write:** `valley-signers` (`integrator publish-signers`) writes in `integrator.instanceProject`, under a lock and with a compare-and-swap. The integrator, in the `git` group that can write the repository, can also write it. | **Tree** object | `100644` blobs: `integrator-name`, the signing name followed by `\n`; `known-signers`, the controllers' known-signers file, byte for byte; and, when `integrator.signerProjects` is set, `signer-projects`, their signer projects file, byte for byte. |
1222| Any other `refs/the-valley/*` | Reserved for host machinery | **SSH push:** Nobody (`implemented`). | — | Always refused on push. |
1223
1224---
1225
1226## Wire formats and JSON schemas
1227
1228This section specifies the exact wire formats for records in project storage and the JSON documents
1229emitted by `--json` commands.
1230
1231### Change record (`valley-change-record/v1`)
1232
1233A change record tracks a change's owner, target branch, state (`ready`, `draft`, or `withdrawn`),
1234version history, and active version as `record.json` inside a commit at
1235`refs/the-valley/changes/main/<change-id>` ([`change/record.go`](../change/record.go),
1236[`valleyhook/record.go`](../valleyhook/record.go)).
1237
1238```json
1239{
1240 "schema": "valley-change-record/v1",
1241 "change_id": "nxvpwlkmqtsrzyoukklnpmqrstuvwxyz",
1242 "target": "main",
1243 "owner": "operator",
1244 "state": "ready",
1245 "seq": 2,
1246 "versions": [
1247 {
1248 "n": 1,
1249 "head": "git-sha1:1111111111111111111111111111111111111111",
1250 "title": "Add greeting helper",
1251 "branch": "greeting",
1252 "uploader": "operator"
1253 },
1254 {
1255 "n": 2,
1256 "head": "git-sha1:2222222222222222222222222222222222222222",
1257 "title": "Add greeting helper",
1258 "branch": "greeting",
1259 "uploader": "operator"
1260 }
1261 ],
1262 "active": 2
1263}
1264```
1265
1266- **Strict JSON rules:** Valid UTF-8, no duplicate keys in any object, no unknown fields, no
1267 trailing tokens after the root object, and plain digit integers only (`3.0` and `3e0` are
1268 rejected).
1269- **Top-level fields:**
1270 - `schema` (`string`): Must be `"valley-change-record/v1"`.
1271 - `change_id` (`string`): 32 lowercase letters in `k`–`z` (`[k-z]{32}`), matching `<change-id>` in
1272 the ref name.
1273 - `target` (`string`): Valid UTF-8 branch name matching `<target>` in the ref name (`valleyhook`
1274 admits `"main"` only).
1275 - `owner` (`string`): Principal name (`^[a-zA-Z0-9][a-zA-Z0-9._-]*$`). Set to the pushing
1276 principal on creation and never changes on update.
1277 - `state` (`string`): `"ready"`, `"draft"`, or `"withdrawn"`.
1278 - `seq` (`int`): Monotonically increasing update counter in `1..100000` (`MaxSeq = 100000`).
1279 Starts at `1` on creation and increases by exactly `1` on every update.
1280 - `versions` (`array` of objects): `1..1000` entries (`MaxVersions = 1000`), numbered
1281 `n: 1, 2, ...` in order with no gaps. Prior versions are immutable once recorded.
1282 - `active` (`int`): 1-based version number in `1..len(versions)`. Every `valleyhook` transition
1283 sets `active` to `1` on create, keeps `active` unchanged on state changes, and sets `active` to
1284 `len(versions)` on a new version, so `active` on a host-validated record always equals
1285 `len(versions)`.
1286- **`versions[]` fields:**
1287 - `n` (`int`): `i + 1` (1-based index).
1288 - `head` (`string`): `"git-sha1:<40-lowercase-hex>"` naming a commit object in the repository.
1289 - `title` (`string`): `1..200` bytes (`MaxTitle = 200`) of valid UTF-8 with no Unicode control
1290 characters.
1291 - `branch` (`string`): `""` (empty) or a valid UTF-8 git branch name (`ValidBranch`).
1292 - `uploader` (`string`): Principal name of the pusher that added this version.
1293- **Record commit parent-history and transition table:**
1294
1295| Transition | Authorized principal | Record commit parents `P` | State and field rules |
1296| :-------------- | :---------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1297| **Create** | Any named principal (`p`) | `P = [h]` (1 parent: version 1's `head` commit `h`) | `seq = 1`, `active = 1`, `len(versions) = 1`, `versions[0].head = "git-sha1:" + h`, `owner = p`, `versions[0].uploader = p`, `state = "ready"`. |
1298| **New version** | `owner` or `approve` grant holder | `P = [old, h]` (2 parents: replaced record commit `old`, then new version's `head` commit `h`) | Appends exactly 1 version (`n = len(before.versions) + 1`, `head = "git-sha1:" + h != before.activeVersion.head`, `uploader = p`), `active = n`, `seq = before.seq + 1`, `state = "ready"` (from `ready`, `draft`, or `withdrawn`). |
1299| **Unready** | `owner` or `approve` grant holder | `P = [old]` (1 parent: replaced record commit `old`) | `before.state = "ready"` → `after.state = "draft"`; `seq = before.seq + 1`; `owner`, `active`, and `versions` unchanged. |
1300| **Re-ready** | `owner` or `approve` grant holder | `P = [old]` (1 parent: replaced record commit `old`) | `before.state` in `{"draft", "withdrawn"}` → `after.state = "ready"`; `seq = before.seq + 1`; `owner`, `active`, and `versions` unchanged. (`withdrawn` → `draft` is refused.) |
1301| **Withdraw** | `owner` or `approve` grant holder | `P = [old]` (1 parent: replaced record commit `old`) | `before.state` in `{"ready", "draft"}` → `after.state = "withdrawn"`; `seq = before.seq + 1`; `owner`, `active`, and `versions` unchanged. |
1302| **Restack** | `restack` grant holder (who is neither `owner` nor an `approve` holder) | `P = [old, h]` (2 parents: replaced record commit `old`, then new version's `head` commit `h`) | `before.state = "ready"` → `after.state = "ready"`; appends 1 version (`head = "git-sha1:" + h != before.activeVersion.head`, `uploader = p`) keeping `branch == before.activeVersion.branch` and `title == before.activeVersion.title`; `active = n`, `seq = before.seq + 1`. |
1303| **Delete** | `approve` grant holder | Ref deletion (`new = 0000...`) | Deletes `refs/the-valley/changes/main/<change-id>`. |
1304
1305### Restack report (`valley-restack-report/v1`)
1306
1307A restack report records what an automated restack attempt observed and published for a change as
1308`report.json` inside a commit at `refs/the-valley/restack/main/<change-id>`
1309([`change/report.go`](../change/report.go), [`valleyhook/report.go`](../valleyhook/report.go),
1310[`rebase/report.go`](../rebase/report.go)).
1311
1312```json
1313{
1314 "schema": "valley-restack-report/v1",
1315 "change_id": "nxvpwlkmqtsrzyoukklnpmqrstuvwxyz",
1316 "target": "main",
1317 "target_tip": "git-sha1:3333333333333333333333333333333333333333",
1318 "operation": "20261017T203500Z-1",
1319 "result": "conflict",
1320 "layers": [
1321 {
1322 "change_id": "nxvpwlkmqtsrzyoukklnpmqrstuvwxyz",
1323 "record": "git-sha1:4444444444444444444444444444444444444444",
1324 "version": 2,
1325 "head": "git-sha1:2222222222222222222222222222222222222222",
1326 "branch": "greeting",
1327 "branch_tip": "git-sha1:2222222222222222222222222222222222222222",
1328 "published": null
1329 }
1330 ],
1331 "failing_layer": "nxvpwlkmqtsrzyoukklnpmqrstuvwxyz",
1332 "conflict_paths": ["greeting.txt"],
1333 "blocking_requests": [],
1334 "refusal": null
1335}
1336```
1337
1338- **Parent history:** The first report commit at `refs/the-valley/restack/main/<change-id>` has `0`
1339 parents (`P = []`); every subsequent report commit has the replaced report commit as its single
1340 parent (`P = [old]`); deletions are refused.
1341- **Fields and cross-field invariants:**
1342 - `schema` (`string`): Must be `"valley-restack-report/v1"`.
1343 - `change_id` (`string`): `[k-z]{32}`, matching the ref's `<change-id>` and appearing in
1344 `layers[]`.
1345 - `target` (`string`): Valid UTF-8 branch name matching the ref's `<target>` (`"main"` in
1346 `valleyhook`).
1347 - `target_tip` (`string`): `"git-sha1:<40-hex>"`.
1348 - `operation` (`string`): `1..64` bytes (`MaxOperation = 64`) matching
1349 `^[a-zA-Z0-9][a-zA-Z0-9._:-]*$`.
1350 - `result` (`string`): One of `"conflict"`, `"blocked"`, `"partial"`, `"complete"`, or
1351 `"superseded"`.
1352 - `layers` (`array` of objects): `1..64` items (`MaxRestackLayers = 64`), unique by `change_id`,
1353 containing the report's `change_id`. Each item has:
1354 - `change_id` (`string`): `[k-z]{32}`.
1355 - `record` (`string`): `"git-sha1:<40-hex>"` (the change record commit observed).
1356 - `version` (`int`): `1..1000` (the active version number observed).
1357 - `head` (`string`): `"git-sha1:<40-hex>"` (that version's head).
1358 - `branch` (`string`): `""` or valid UTF-8 branch name.
1359 - `branch_tip` (`string` or `null`): `"git-sha1:<40-hex>"` or `null` (must be `null` when
1360 `branch == ""`).
1361 - `published` (`object` or `null`): Must be `null` when `branch == ""` or when `result` is
1362 `"conflict"` or `"blocked"`. When non-null, carries
1363 `{ "head": "git-sha1:<40-hex>", "version": <int 1..1000 or null>, "record": <"git-sha1:<40-hex>" or null> }`
1364 where `version` and `record` are either both non-null or both `null`. When
1365 `result == "complete"`, every layer must have a non-null `published` with non-null `version`
1366 and `record`.
1367 - `failing_layer` (`string` or `null`): `null` or a `change_id` present in `layers[]` (required to
1368 be non-null when `result == "conflict"`).
1369 - `conflict_paths` (`array` of `string`): `0..100` items (`MaxConflictPaths = 100`), each
1370 `1..1024` bytes (`MaxConflictPath = 1024`) of valid UTF-8 without control characters.
1371 - `blocking_requests` (`array` of objects): `0..64` items (`MaxBlockingRequest = 64`), unique by
1372 `ref`. Each item has `ref` (`refs/the-valley/integration-requests/<target>/<name>`, `<= 256`
1373 bytes, `MaxRequestRef = 256`) and `tip` (`"git-sha1:<40-hex>"`).
1374 - `refusal` (`string` or `null`): `null` or `1..2048` bytes (`MaxRefusal = 2048`) of valid UTF-8
1375 without control characters.
1376- **Currency rule (`Origin.Current`):** A report is marked `current: true` in CLI outputs only while
1377 `refs/heads/main` is still at `target_tip`, every `blocking_requests[]` ref is still at `tip`, and
1378 for every layer, `refs/the-valley/changes/main/<change_id>` is at `published.record` (if non-null,
1379 else `record`) and `refs/heads/<branch>` (when `branch != ""`) is at `published.head` (if
1380 `published` is non-null, else `branch_tip`, or still absent when `branch_tip == null`). Otherwise
1381 `current` is `false` (historical).
1382
1383### Review record (`the-valley/review/v1`)
1384
1385A review records one reviewer's judgment of one version of a change as `review.json` inside a commit
1386at `refs/the-valley/reviews/<target>/<change-id>` ([`review/review.go`](../review/review.go),
1387[`review/binding.go`](../review/binding.go), [`review/history.go`](../review/history.go)). The
1388module is `implemented`. Admitting a review over SSH is `not built`: the push hook refuses every
1389push to `refs/the-valley/reviews/`.
1390
1391```json
1392{
1393 "schema": "the-valley/review/v1",
1394 "review_id": "0123456789abcdef0123456789abcdef",
1395 "change_id": "nxvpwlkmqtsrzyoukklnpmqrstuvwxyz",
1396 "target": "main",
1397 "review": "docs-style",
1398 "reviewer": "alice",
1399 "verdict": "request-changes",
1400 "withdraws": null,
1401 "binding": {
1402 "record": "git-sha1:4444444444444444444444444444444444444444",
1403 "version": 2,
1404 "head": "git-sha1:2222222222222222222222222222222222222222",
1405 "target_tip": "git-sha1:3333333333333333333333333333333333333333",
1406 "base": "git-sha1:1111111111111111111111111111111111111111",
1407 "delta": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"
1408 },
1409 "summary": "Two sentences carry two new ideas each.",
1410 "notes": [
1411 {
1412 "side": "after",
1413 "path": "docs/guide.md",
1414 "blob": "git-sha1:5555555555555555555555555555555555555555",
1415 "lines": { "start": 12, "end": 14 },
1416 "body": "Split this sentence."
1417 }
1418 ],
1419 "provenance": {
1420 "harness": "agent-runner 0.9.1",
1421 "model": "claude-opus-5-5",
1422 "settings": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
1423 "inputs": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
1424 "input_tokens": 1200,
1425 "output_tokens": null
1426 }
1427}
1428```
1429
1430- **Strict JSON rules:** The change record's: valid UTF-8, no duplicate keys in any object, no
1431 unknown fields (a key in another case is unknown), every field present with its exact type, no
1432 trailing tokens, and plain digit integers only. The whole file is `<= 64 KiB` (`MaxRecord`).
1433- **Fields:**
1434 - `schema` (`string`): Must be `"the-valley/review/v1"`.
1435 - `review_id` (`string`): 32 lowercase hex digits, unique within the history (`review.NewID`).
1436 - `change_id` (`string`): `[k-z]{32}`, matching the ref's `<change-id>`.
1437 - `target` (`string`): Valid UTF-8 branch name matching the ref's `<target>`.
1438 - `review` (`string`): The review's name, `^[a-z][a-z0-9-]*$`, `1..64` bytes.
1439 - `reviewer` (`string`): Principal name (`^[a-zA-Z0-9][a-zA-Z0-9._-]*$`).
1440 - `verdict` (`string`): `"approve"`, `"request-changes"`, or `"withdraw"`.
1441 - `withdraws` (`string` or `null`): The `review_id` a withdrawal takes back; `null` for any other
1442 verdict. A review never withdraws itself.
1443 - `binding` (`object` or `null`): Required for `approve` and `request-changes`; `null` for
1444 `withdraw`. Its fields are `record`, `head`, `target_tip` and `base`, each
1445 `"git-sha1:<40-hex>"`; `version` (`int`, `1..1000`); and `delta`, 64 lowercase hex digits.
1446 - `summary` (`string`): `1..8192` bytes of UTF-8 with no control characters but newline and tab.
1447 - `notes` (`array` of objects): `0..256` items; always empty for `withdraw`. Each has `side`
1448 (`"before"` or `"after"`), `path` (`1..4095` bytes of UTF-8, no empty, `.`, `..` or `.git`
1449 component, no component over 255 bytes, no control character), `blob` (`"git-sha1:<40-hex>"`),
1450 `lines` (`null` or `{ "start": <int>, "end": <int> }` with `1 <= start <= end <= 16777216`), and
1451 `body` (`1..8192` bytes, as `summary`).
1452 - `provenance` (`object` or `null`): `null` for a human's review. Otherwise `harness` and `model`
1453 (`1..256` bytes, no control characters), `settings` and `inputs` (64 lowercase hex digits, the
1454 SHA-256 of the generation settings and of the input manifest), and `input_tokens` and
1455 `output_tokens` (`null` or an `int` in `0..1000000000000`).
1456- **Binding:** `record` is the change record commit the reviewer read, and it names `version` with
1457 `head`. `target_tip` is the commit the version was judged against. `base` is the one merge base of
1458 `target_tip` and `head`. `delta` is the SHA-256 of the `valley-delta-v1` encoding from `base` to
1459 `head`. When `target_tip` and `head` have no merge base, or more than one, no binding exists and
1460 no review is made (`review.ErrNoBase`, `review.ErrAmbiguousBase`).
1461- **Verification (`review.Verify`):** Recomputes every part of the binding: the record names the
1462 version and head, and is the record of its own `seq` on the change's record ref when that ref is
1463 given; `target_tip` is a commit, on the target's history when the target's tip is given; `base` is
1464 the one merge base; the delta has the bound digest; and each note's `path` holds its `blob` on its
1465 side (`base` for `before`, `head` for `after`), with `lines` inside the file. It reads within a
1466 `delta.Budget` of bytes, tree entries and a deadline. An error wrapping `delta.ErrBudget` means
1467 the budget ran out, not that the binding is wrong. That includes a note's file larger than the
1468 budget's bytes, and a deadline that passes after the last read from git.
1469- **History and parents:** The ref points at the newest review commit. The first review commit's
1470 parents are `[record]`; a later review that judges a version has `[previous, record]`; a
1471 withdrawal has `[previous]`. `previous` is the history's head when the review was appended, and
1472 `record` is `binding.record`. A history holds at most 512 reviews (`MaxHistory`). A withdrawal
1473 names an earlier review of the same history and review name that is neither a withdrawal nor
1474 withdrawn already.
1475- **Appending (`review.Build`, `review.Publish`, `review.CheckAppend`):** `Build` writes the commit
1476 that appends a review to a given head, and returns `review.ErrRecorded` with the existing commit
1477 when the history holds the review already. `Publish` pushes it with
1478 `--force-with-lease=<ref>:<old>` and returns `review.ErrStale` when another append came first.
1479 `CheckAppend` decides one ref update for the push hook, which does not call it (`not built`). It
1480 admits exactly one new review commit on the old head, whose `reviewer` is the pusher. A review
1481 that judges a version must be under a review name the caller says the pusher may write, must be
1482 about a change the repository records, and its binding must verify. A withdrawal needs no grant of
1483 its name. It must be of the pusher's own review, or the pusher an operator, who may withdraw any
1484 review. It refuses every delete.
1485
1486### Signed notes and attestation statement (`the-valley/attestation/v1`)
1487
1488An attestation note wraps canonical line-oriented `the-valley/attestation/v1` statement text in a
1489signed note envelope (`golang.org/x/mod/sumdb/note` format) and is stored at
1490`refs/the-valley/attestations/<64-hex-tree-digest>/<8-hex-key-hash>`
1491([`note/note.go`](../note/note.go), [`attest/text.go`](../attest/text.go),
1492[`schema/attestation.cue`](../schema/attestation.cue)).
1493
1494```text
1495the-valley/attestation/v1
1496subject.primary valley-tree-v1
1497subject.digest.git-sha1 99b5f2f7c1d2e3f4a5b6c7d8e9f0a1b2c3d4e5f6
1498subject.digest.valley-tree-v1 73847e0b8c5a1e2f3d4b5a6c7d8e9f0a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e
1499predicateType the-valley/check/pure/v1
1500predicate.check.name prose-format
1501predicate.check.runner nix
1502predicate.check.attribute prose-format
1503predicate.result passed
1504predicate.inputs.valley-inputs-v1 a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2
1505predicate.derivation.sha256 b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3
1506predicate.output.sha256 c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3d4
1507
1508— operator WhFo+DGb1c/Fk6x7y8z9A0B1C2D3E4F5G6H7I8J9K0L1M2N3O4P5Q6R7S8T9U0V1W2X3Y4Z5a6b7c8d9e0f1g2h3i4g=
1509```
1510
1511- **Note envelope, key hash, and verifier key:**
1512 - The signed payload (`text`) is valid UTF-8 with no ASCII control characters except `\n`
1513 (`0x0a`), ending with `\n`.
1514 - A blank line (`\n\n`; the parser splits at the last `\n\n` in the note) separates the statement
1515 text from one or more signature lines.
1516 - Each signature line has the form
1517 `— <signer-name> <base64(4-byte-key-hash || 64-byte-ed25519-signature)>\n`, opening with
1518 `U+2014 EM DASH` followed by a space (`"— "`). `<signer-name>` is non-empty valid UTF-8 with no
1519 whitespace, no control characters, and no `+`.
1520 - **Key hash (`KeyHash`):** The first 4 bytes (big-endian `uint32`, written as 8 lowercase hex
1521 digits in ref names and verifier keys) of
1522 `SHA-256(<signer-name> + "\n" + 0x01 + <32-byte-ed25519-pubkey>)`. Because `<signer-name>` is
1523 inside the key hash, the same Ed25519 public key under two different names produces two distinct
1524 verifier keys.
1525 - **Verifier key line (`known-signers`):**
1526 `<signer-name>+<8-hex-key-hash>+<base64(0x01 || 32-byte-ed25519-pubkey)>`.
1527- **Statement written form (`the-valley/attestation/v1`):**
1528 - Line 1 is `the-valley/attestation/v1`.
1529 - Every subsequent line is `<dot.separated.key> <value>\n`. There are no escape sequences; every
1530 leaf value is a non-empty string without ASCII control characters; empty objects and empty
1531 arrays are rejected; array indices are dense decimal integers starting at `0`.
1532 - Lines appear in the fixed `statementOrder`:
1533 1. `subject.primary` (always `valley-tree-v1`)
1534 2. `subject.digest.<scheme>` (sorted by `<scheme>`: `git-sha1`, `git-sha256`, `sha256`,
1535 `valley-inputs-v1`, `valley-tree-v1`)
1536 3. `predicateType` (`the-valley/check/pure/v1`, `the-valley/check/effectful/v1`, or
1537 `the-valley/integration/transfer/v1`)
1538 4. `predicate.*` (ordered per `predicateType` below)
1539 5. `provenance.*` (optional: `provenance.harness`, `provenance.model`,
1540 `provenance.prompt.<scheme>`, `provenance.context.<scheme>`,
1541 `provenance.delegation.<i>.principal`, `provenance.delegation.<i>.grant`)
1542- **Pure check predicate (`the-valley/check/pure/v1`; stored at `<check>/statement.note`):**
1543 - `predicate.check.name`, `predicate.check.runner` (`nix`), `predicate.check.attribute`
1544 - `predicate.result` (`passed` or `failed`)
1545 - `predicate.inputs.valley-inputs-v1` (64-hex SHA-256)
1546 - `predicate.derivation.sha256` (64-hex SHA-256 of the `.drv` file)
1547 - `predicate.output.sha256` (64-hex `valley-tree-v1` digest of the Nix build output path)
1548- **Effectful check predicate (`the-valley/check/effectful/v1`; stored at
1549 `<check>/statement.note`):**
1550 - `predicate.check.name`, `predicate.check.runner` (`command`), `predicate.check.command`
1551 - `predicate.environment` (default `"local"`)
1552 - `predicate.observedAt` (`YYYY-MM-DDTHH:MM:SSZ`)
1553 - `predicate.result` (`passed` or `failed`)
1554
1555### Canonical digest manifests (`valley-tree-v1`, `valley-inputs-v1`, `valley-delta-v1`)
1556
1557the-valley uses three canonical SHA-256 manifest formats for trees, pure check inputs, and
1558version-to-version file deltas, plus a 16-hex evidence fingerprint
1559([`attest/digest.go`](../attest/digest.go), [`delta/delta.go`](../delta/delta.go),
1560[`change/id.go`](../change/id.go)).
1561
1562```text
1563valley-tree-v1
1564100644 e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 12 greeting.txt
1565```
1566
15671. **`valley-tree-v1`:**
1568 - **Purpose:** Content-addressed 64-hex SHA-256 digest of a git tree or filesystem output tree,
1569 independent of commit metadata.
1570 - **Encoding:** Header `"valley-tree-v1\n"`, followed by one line per file or symlink entry
1571 across the tree, sorted ascending by raw `<path>` bytes:
1572 `<mode> <64-hex-sha256-of-content> <decimal-byte-length-of-path> <path>\n`
1573 - **Modes and content:** `100644` (regular file), `100755` (executable file), or `120000`
1574 (symlink, whose hashed content is the symlink target bytes). Directory entries are omitted
1575 (implied by file paths), and submodules (`160000`) are refused.
15762. **`valley-inputs-v1`:**
1577 - **Purpose:** 64-hex SHA-256 digest of the set of Nix store paths referenced by a pure Nix
1578 check's `.drv` (`nix-store --query --references <drv>`).
1579 - **Encoding:** Header `"valley-inputs-v1\n"`, followed by one line per input name, sorted
1580 bytewise ascending and deduplicated: `<decimal-byte-length-of-name> <name>\n`
15813. **`valley-delta-v1`:**
1582 - **Purpose:** 64-hex SHA-256 digest of the whole-file changes between a pre-tree `T` and a
1583 post-tree `R`, used by `valley review` (`valley-go compare`) to check whether two versions of a
1584 change make the exact same modifications to their respective merge bases.
1585 - **Encoding:** Header `"valley-delta-v1\n"`, followed by one line per path whose entry differs
1586 between `T` and `R`, sorted bytewise ascending by `<path>`:
1587 `<decimal-byte-length-of-path> <path> <pre-image> <post-image>\n` Each image is `-` when the
1588 path is absent on that side, or `<mode> <64-hex-sha256>` (`100644`, `100755`, or `120000`).
1589 Both trees are validated for Linux checkout safety (modes in `{100644, 100755, 120000, 40000}`,
1590 no empty/`.`/`..`/case-insensitive `.git` segments, component names `<= 255` bytes, non-empty
1591 symlink targets `<= 4,095` bytes without NUL).
1592 - **Bounded reading:** `delta.BetweenWithin` gives the same delta as `delta.Between` within a
1593 `delta.Budget`: bytes read and paths built, tree entries visited (a shared subtree once per
1594 path that names it), and a deadline, all required. It asks for each object's type and size
1595 before its content, kills git at the deadline, and fails with an error wrapping
1596 `delta.ErrBudget` at the first bound crossed. `review.Verify` recomputes a review's binding
1597 with it.
15984. **Evidence fingerprint:**
1599 - **Purpose:** 16-hex-character fingerprint of all attestation refs in a repository, recorded in
1600 outcome records so the integrator and `valley status` know whether new evidence has arrived
1601 since the last pass.
1602 - **Encoding:** First 16 lowercase hex characters (8 bytes) of `SHA-256` over `<ref> <oid>\n` for
1603 every ref under `refs/the-valley/attestations/`, sorted by `<ref>` (`e3b0c44298fc1c14`, the
1604 SHA-256 prefix of the empty string, when no attestation refs exist).
1605
1606### Integrator transfer statement (`the-valley/integration/transfer/v1`)
1607
1608When a change lands, the integrator signs a transfer statement
1609(`predicateType: "the-valley/integration/transfer/v1"`) before advancing `main`. It stores the
1610statement under `refs/the-valley/attestations/<landed-tree-digest>/<integrator-key-hash>`, at a path
1611split from the landed commit's 40-hex ID: its first two hex digits, its next two, and the rest. For
1612a landing as `88a4e1f0…d6e7` the path is `transfer.d/88/a4/e1f0…d6e7.note`. Countersigned
1613`<check>/statement.note` copies go under
1614`refs/the-valley/attestations/<attested-tree-digest>/<integrator-key-hash>`
1615([`change/evidence.go`](../change/evidence.go),
1616[`integrator/transfer.go`](../integrator/transfer.go),
1617[`integrator/refs.go`](../integrator/refs.go),
1618[`schema/attestation.cue`](../schema/attestation.cue)). Both refs move in the landing's one ref
1619transaction.
1620
1621A tree that lands more than once keeps one statement per landing. Storing a landing adds its notes
1622to the ref and keeps every note already there that the landing does not write: the statements of
1623other landings, and every other path. The two levels of directories keep each tree small.
1624`valley status` and `valley changes` read the statements at these paths, and a single
1625`transfer.note` at the top of the tree, where the integrator kept one statement before it kept one
1626per landing.
1627
1628Before the landing's transaction, the integrator checks every tree it would write against every
1629bound in [the ref layout](#project-storage-ref-layout-and-bounds): the depth, the entries in one
1630tree and in all the ref's trees, the bytes of each tree object, the bytes of each note, and the
1631bytes of all of them together. A tree past any bound refuses the landing with an error naming that
1632bound, and nothing lands. So another host's hook can read every tree the integrator writes. The hook
1633and the integrator take the bounds from one place, [`change/evidence.go`](../change/evidence.go).
1634
1635The bounds also limit how often one tree can land. `transfer.d` is one tree, so it holds at most 64
1636first-byte directories. A landing that would add a 65th is refused, which takes 65 or more landings
1637of one identical tree. When the landed tree is also the attested tree, its ref holds the
1638countersigned notes as well, and the bound of 256 entries in all can refuse a landing sooner.
1639
1640```text
1641the-valley/attestation/v1
1642subject.primary valley-tree-v1
1643subject.digest.git-sha1 88a4e1f0b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7
1644subject.digest.valley-tree-v1 73847e0b8c5a1e2f3d4b5a6c7d8e9f0a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e
1645predicateType the-valley/integration/transfer/v1
1646predicate.change c-nxvpwlkmqtsrzyoukklnpmqrstuvwxyz
1647predicate.target refs/heads/main
1648predicate.base.valley-tree-v1 73847e0b8c5a1e2f3d4b5a6c7d8e9f0a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e
1649predicate.policy.git-sha1 55d1c2b3a4f5e6d7c8b9a0f1e2d3c4b5a6f7e8d9
1650predicate.policy.sha256 d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c3d4e5
1651predicate.checks.0.name prose-format
1652predicate.checks.0.rule unmoved
1653predicate.checks.0.evidence.sha256 f1e2d3c4b5a6f7e8d9c0b1a2f3e4d5c6b7a8f9e0d1c2b3a4f5e6d7c8b9a0f1e2
1654
1655— integrator R7S8T9U0V1W2X3Y4Z5a6b7c8d9e0f1g2WhFo+DGb1c/Fk6x7y8z9A0B1C2D3E4F5G6H7I8J9K0L1M2N3O4P5Q6h3i4g=
1656```
1657
1658- **Subject and predicate fields:**
1659 - `subject.primary`: `"valley-tree-v1"`.
1660 - `subject.digest.git-sha1`: The landed commit SHA-1 on `refs/heads/main`.
1661 - `subject.digest.valley-tree-v1`: The 64-hex `valley-tree-v1` digest of the landed commit's tree.
1662 - `predicateType`: `"the-valley/integration/transfer/v1"`.
1663 - `predicate.change`: Request name (`c-<change-id>` or `<branch-request-name>`).
1664 - `predicate.target`: Full target ref name (`refs/heads/main`).
1665 - `predicate.base.valley-tree-v1`: The 64-hex `valley-tree-v1` digest of the attested commit's
1666 tree (equal to `subject.digest.valley-tree-v1` when `main` did not move or merged to the
1667 identical tree).
1668 - `predicate.policy.git-sha1` and `predicate.policy.sha256`: The target tip commit SHA-1 from
1669 which the project policy was read and the 64-hex SHA-256 digest of the composed policy
1670 rendering.
1671 - **Either `predicate.checks.<i>.*` (when >= 1 check was required) or `predicate.required none`
1672 (when 0 checks were required; never both):**
1673 - `predicate.checks.<i>.name`: Check name (`^[a-z0-9][a-z0-9-]*$`).
1674 - `predicate.checks.<i>.rule`: `"unmoved"` (landed tree equals attested tree), `"closure"` (pure
1675 check whose `valley-inputs-v1` and derivation `sha256` on the landed tree matched the attested
1676 note's), or `"untouched"` (effectful check whose requiring path classes were untouched by
1677 `base..tip` on `main` and whose `observedAt` age is within `validity`).
1678 - `predicate.checks.<i>.evidence.sha256`: 64-hex SHA-256 of the signed statement text in the
1679 contributor's attestation note.
1680 - `predicate.checks.<i>.inputs.valley-inputs-v1`: Present when `rule == "closure"`; the
1681 recomputed 64-hex `valley-inputs-v1` digest on the landed tree.
1682
1683### Integrator outcome record (`refs/the-valley/integration-outcomes/<target>/<request>`)
1684
1685After judging an integration request, the integrator writes a single-line blob at
1686`refs/the-valley/integration-outcomes/main/<request>` recording the head, target tip, evidence
1687fingerprint, and decision ([`integrator/refs.go`](../integrator/refs.go),
1688[`rebase/outcome.go`](../rebase/outcome.go)). For a landing, it writes the record in the landing's
1689ref transaction, with the landing record beside it.
1690
1691```text
16922222222222222222222222222222222222222222 3333333333333333333333333333333333333333 9a8b7c6d5e4f3a2b land
1693```
1694
1695- **Format:**
1696 `<head-oid> <target-tip-oid> <16-hex-evidence-fingerprint> <decision>[ <failed-at-rfc3339>]\n`
1697 - `<head-oid>` and `<target-tip-oid>`: 40-hex SHA-1 (or 64-hex SHA-256) commit object IDs.
1698 - `<16-hex-evidence-fingerprint>`: First 16 hex digits of SHA-256 over sorted `<ref> <oid>\n`
1699 lines under `refs/the-valley/attestations/`.
1700 - `<decision>`: One of:
1701 - `land`: The change landed on `<target>`, and its integration request ref was consumed.
1702 - `stale`: The change conflicted with `<target>` or required check evidence was missing,
1703 expired, or did not transfer; the request ref remains standing.
1704 - `reject`: Attestation note or statement failed cryptographic or schema verification; the
1705 request ref remains standing.
1706 - `refused-not-ready`: The change record (or a change whose version head is brought by the
1707 request) is not `ready`, or a `c-<id>` request's head is not listed in the change's
1708 `versions`; the request ref remains standing and is reconsidered on every integrator pass.
1709 - `refused-merge`: The commits between the merge base with `<target>` and `<head-oid>` include a
1710 merge commit; the request ref remains standing and is reconsidered on every integrator pass.
1711 - `voided-withdrawn`: The change record was `withdrawn` when the integrator pass ran, and the
1712 integrator deleted the pending request ref.
1713 - `failed`: An internal error occurred during the pass. Requires the 5th field
1714 `<failed-at-rfc3339>` (`YYYY-MM-DDTHH:MM:SSZ`). The integrator retries a `failed` request on
1715 the same `(head, tip, evidence)` tuple and the same inputs after `retryFailedAfter = 10m`. Any
1716 unparseable outcome blob is treated by readers as `decision: "unknown"` (`outcome-unreadable`
1717 in `valley status`).
1718
1719### Integrator inputs record (`refs/the-valley/integration-inputs/<target>/<request>`)
1720
1721The inputs record says what the integrator read of the floor and the accepted signers when it wrote
1722the outcome record of the same name ([`integrator/inputs.go`](../integrator/inputs.go)). Only the
1723integrator reads it. The outcome record keeps its format, so its readers are unaffected.
1724
1725```text
1726cd6862621ba641adedb7d0ca1d86316d9b512de8c0f5c5225c1ad27d59a5e4aa d93a2e26f9a94ab4ddeeaef61a375784cc5df95d
1727```
1728
1729- **Format:** `<inputs-digest> <outcome-blob-oid>\n`.
1730 - `<inputs-digest>`: 64 lowercase hex digits of SHA-256 over these lines, or `unread` when an
1731 input did not read:
1732 - `floor <name> <sha256>` for each `*.cue` document of the floor, the documents the verdict
1733 composes, in name order;
1734 - `known-signers <sha256>` of the known-signers file, read at the start of the pass;
1735 - `signer-projects <sha256>` of the signer projects file as read when the integrator started, or
1736 `signer-projects none` when it was given none;
1737 - `project <name>` and `signer <name>`, the project a signer counts in and the integrator's own
1738 signing name.
1739 - `<outcome-blob-oid>`: the object ID of the outcome record blob written in the same ref
1740 transaction.
1741- **Standing answer** (`implemented`): a `land`, `stale` or `reject` outcome stands only while the
1742 head, the target tip, the evidence fingerprint and the inputs digest all match the pass. A
1743 `failed` outcome stands on the same match for `retryFailedAfter`. Refusals and voidings never
1744 stand.
1745- **An unread input** (`implemented`): when the floor or the known-signers file does not read, the
1746 integrator judges no request that no rule refuses. It records `failed` with `unread` as the
1747 digest. That failure stands for `retryFailedAfter`, and once the input reads, the digest differs
1748 and the request is judged again at once.
1749- **When the record does not match:** an inputs record that is missing, does not parse, or names
1750 another blob matches no digest, so the request is judged again. A landing and a voiding write the
1751 outcome record without one, and so does an integrator from before inputs records existed. Each
1752 pending request with such a record is judged, and reported, once more.
1753- **Over-invalidation:** any change to the known-signers file judges every pending request again,
1754 including a change to a key that verifies none of their notes. So does any change to a floor
1755 document.
1756- **The signer projects file** (`implemented`): it is read once, at start. A change to it takes
1757 effect when the integrator restarts. The host passes it as a store path on the command line, so a
1758 changed list restarts the controllers (`implemented`, in the host module), and the first pass
1759 after the restart judges every pending request again.
1760
1761### Integrator landing record (`refs/the-valley/integration-landings/<target>/<head>`)
1762
1763For every head it lands, the integrator writes a commit with no parent at
1764`refs/the-valley/integration-landings/main/<head>`, in the landing's ref transaction
1765([`change/landing.go`](../change/landing.go), [`integrator/refs.go`](../integrator/refs.go)). Its
1766tree holds one blob, `landing`:
1767
1768```text
1769landed 88a4e1f0b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7
1770request c-nxvpwlkmqtsrzyoukklnpmqrstuvwxyz
1771head 2222222222222222222222222222222222222222
1772```
1773
1774- **Format:** exactly three lines, in this order, each `<key> <value>\n`.
1775 - `landed`: the commit the head landed as on `<target>`, as a full lowercase object ID.
1776 - `request`: the request name it landed under (`c-<change-id>` or `<branch-request-name>`).
1777 - `head`: the head that landed, as a full lowercase object ID. It is the ref's last segment too.
1778- **Commit:** the integrator's signing name is author and committer, at
1779 `integrator@the-valley.invalid`, dated as the landed commit's committer, so a retried landing
1780 writes the identical commit. The message is `<request> landed as <landed>`.
1781- **Readers:** a client binds a transfer statement to the exact head that landed with this record
1782 when origin holds one for the head, and with the outcome record otherwise (see
1783 [Listing changes](./architecture.md#listing-changes)). A record that does not parse binds nothing.
1784
1785The outcome record is kept per request name, so the next version of a change to land under the same
1786name replaces it. The landing record is kept per head, so that later landing leaves it in place.
1787
1788### Plan graph and knots (`refs/the-valley/knots`)
1789
1790The plan graph lives at the exact ref `refs/the-valley/knots` as a linear chain of commits (`P = []`
1791on create, `P = [old]` on update) whose tree holds canonical Markdown files with YAML frontmatter
1792for knots and comments ([`knot/contract.go`](../knot/contract.go),
1793[`knot/canon.go`](../knot/canon.go), [`knot/model.go`](../knot/model.go)). Knots take their name
1794from the knotted cords used to keep records before writing.
1795
1796```markdown
1797---
1798type: outcome
1799id: oc-c12d4ed
1800status: open
1801title: "Publish the CLI reference"
1802created: 2026-10-19
1803created_by: "operator"
1804parent: oc-7654321
1805owner: "operator"
1806blocked_by: ["app:oc-0123456", bd-89abcde]
1807changes: ["valley:the-valley/nxvpwlkmqtsrzyoukklnpmqrstuvwxyz"]
1808---
1809
1810Write `docs/reference.md` and link it from [[oc-7654321]].
1811```
1812
1813- **Tree layout and filenames:**
1814 - Knot files (`100644`, `<= 64 KiB`, `<= 5,000` knots total):
1815 - `outcomes/oc-<7-hex>-<slug>.md` (`type: outcome`, statuses: active `open`, `in-progress`;
1816 terminal `done`, `abandoned`)
1817 - `bugs/bd-<7-hex>-<slug>.md` (`type: bug`, statuses: active `open`; terminal `closed`)
1818 - `ideas/ida-<7-hex>-<slug>.md` (`type: idea`, statuses: active `raw`, `exploring`, `adopted`;
1819 terminal `graduated`, `superseded`, `discarded`)
1820 - `questions/qn-<7-hex>-<slug>.md` (`type: question`, statuses: active `open`; terminal
1821 `answered`, `dropped`)
1822 - `<slug>` matches `^[a-z0-9]+(-[a-z0-9]+)*$` (`1..48` bytes, `MaxSlug = 48`), and `<id>` is
1823 `<prefix>-` followed by the first 7 lowercase hex digits of `SHA-256(<slug>)`. Every knot must
1824 have `created > "2026-08-05"` (`IDRuleCutoff`).
1825 - Comment files (`100644`, `<= 16 KiB`, `<= 20,000` comments total):
1826 - `comments/<knot-id>/<YYYYMMDDTHHMMSSZ>-<16-hex-op>.md`. A comment's ID is its filename without
1827 `.md` (`<YYYYMMDDTHHMMSSZ>-<16-hex-op>`). Because comment files are never moved or deleted, a
1828 comment's ID never changes.
1829 - Frontmatter between `---` fences starts with `author: "<principal>"`. An edited comment
1830 follows `author` with `edited: "<YYYY-MM-DDTHH:MM:SSZ>"` and `edited_by: "<principal>"`, in
1831 that order. Each value is a JSON string. `edited` and `edited_by` must appear together or not
1832 at all (`RuleProvenance`); an unedited comment has only the `author` line. A blank line and a
1833 required non-empty Markdown body follow the closing `---`.
1834
1835 ```markdown
1836 ---
1837 author: "alice"
1838 edited: "2026-10-25T15:00:00Z"
1839 edited_by: "operator"
1840 ---
1841
1842 Moved to bd-89abcde.
1843 ```
1844
1845- **Canonical text and body rules:**
1846 - Every knot and comment file must be valid UTF-8 with no control characters except `\n` (`0x0a`)
1847 and `\t` (`0x09`), and no `U+FFFE` or `U+FFFF` (`RuleText`).
1848 - Frontmatter opens with `---\n` on line 1 and closes with `---\n`. When a knot has a non-empty
1849 body, the body is separated from the closing `---\n` by exactly one blank line (`\n`), has no
1850 leading or trailing blank lines, and ends with a single `\n`; when the body is empty, the file
1851 ends immediately after the closing `---\n` (`RuleCanonical`).
1852- **Commit rules:**
1853 - Commit size `<= 16 KiB`, `<= 32` changed paths per commit, `Committer` name must equal the
1854 pushing principal, and the commit message must end with the trailer
1855 `Valley-Op: <16-lowercase-hex>`.
1856 - No knot or comment file may be deleted, and a knot's `id`, `type`, `created`, and `created_by`
1857 are immutable after creation. On a newly created knot or comment, `created_by` / `author` must
1858 equal the pushing principal, and a new comment may not include `edited` or `edited_by`.
1859 - A push that modifies an existing comment file is an edit. The edited comment must keep its
1860 original `author`, include both `edited` and `edited_by`, and set `edited_by` to the pushing
1861 principal. The hook admits an edit only from the comment's `author` or from a principal holding
1862 the `approve` grant (also accepted as `request`)
1863 ([`valleyhook/knots.go`](../valleyhook/knots.go)). Neither the hook nor the CLI compares
1864 `edited` against a clock or against the comment's previous `edited` value.
1865- **Canonical frontmatter fields in required order:**
1866
1867| Order | Field | Allowed types | Encoding | Required / rules |
1868| :---- | :--------------- | :--------------------------- | :---------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1869| 1 | `type` | all | bare token | Always (`outcome`, `bug`, `idea`, `question`). |
1870| 2 | `id` | all | bare token | Always (`^(oc\|bd\|ida\|qn)-[0-9a-f]{7}$`). |
1871| 3 | `status` | all | bare token | Always (must belong to `type`'s status list). |
1872| 4 | `title` | all | JSON string | Always (`1..200` bytes, no newlines/tabs). |
1873| 5 | `created` | all | bare token | Always (`YYYY-MM-DD`, `> 2026-08-05`). |
1874| 6 | `created_by` | all | JSON string | Always (principal name, `<= 64` bytes). |
1875| 7 | `source` | all | JSON string | Optional (`1..200` bytes). |
1876| 8 | `parent` | all | bare token | Optional; must name a local `outcome` (`oc-<7-hex>`) in the same graph; `parent` edges may not form a cycle. |
1877| 9 | `owner` | all | JSON string | Optional (principal name, `<= 64` bytes). |
1878| 10 | `blocked_by` | `outcome`, `bug` | flow list `[...]` | Always written on `outcome` and `bug` (`[]` when empty); up to 64 sorted, deduplicated items: bare local `<id>` (must exist in graph; local `blocked_by` edges may not form a cycle) or quoted `"<project>:<id>"`. |
1879| 11 | `claimed_by` | `outcome`, `bug` | JSON string | Optional (`<= 64` bytes); must be paired with `claimed_at`. |
1880| 12 | `claimed_at` | `outcome`, `bug` | JSON string | Optional (`YYYY-MM-DDTHH:MM:SSZ`); must be paired with `claimed_by`. |
1881| 13 | `changes` | `outcome`, `bug`, `question` | flow list `[...]` | Optional (omitted when empty); up to 64 sorted, deduplicated JSON strings (`<= 256` bytes each) matching `valley:<project>/<32-letter-change-id>` or `https://github.com/<org>/<repo>/pull/<n>`. |
1882| 14 | `target` | `outcome`, `bug` | JSON string | Optional (`<project>` or `<project>:<id>`). |
1883| 15 | `graduated_into` | `idea` | bare token | Required when `status == "graduated"` and forbidden otherwise; must name an existing local `outcome` (`oc-*`) or `question` (`qn-*`) in the live plan graph. |
1884
1885### CLI JSON outputs
1886
1887Five `--json` commands emit versioned JSON documents for scripts and front ends.
1888
1889#### `valley-status/v1`
1890
1891`valley status --json <change>` emits one `valley-status/v1` object on a single line.
1892
1893```json
1894{
1895 "schema": "valley-status/v1",
1896 "change": "greeting",
1897 "request_name": "c-nxvpwlkmqtsrzyoukklnpmqrstuvwxyz",
1898 "target": "main",
1899 "target_tip": "3333333333333333333333333333333333333333",
1900 "head": "2222222222222222222222222222222222222222",
1901 "request": {
1902 "ref": "refs/the-valley/integration-requests/main/c-nxvpwlkmqtsrzyoukklnpmqrstuvwxyz",
1903 "commit": "2222222222222222222222222222222222222222"
1904 },
1905 "outcome": null,
1906 "state": "awaiting-decision",
1907 "change_id": "nxvpwlkmqtsrzyoukklnpmqrstuvwxyz",
1908 "handle": "nxvp",
1909 "version": 2,
1910 "title": "Add greeting helper",
1911 "owner": "operator",
1912 "landing": "not-landed",
1913 "restack": null,
1914 "knots": [
1915 {
1916 "id": "oc-c12d4ed",
1917 "type": "outcome",
1918 "status": "open",
1919 "title": "Publish the CLI reference"
1920 }
1921 ]
1922}
1923```
1924
1925- **Fields:**
1926 - `schema`: `"valley-status/v1"`.
1927 - `change` (`string`): Branch name (from the active version's `branch`, or the queried branch
1928 name).
1929 - `request_name` (`string`): `c-<change_id>` for a recorded change, or `<branch>` with `/`
1930 replaced by `-`.
1931 - `target` (`string`): `"main"`.
1932 - `target_tip` (`string`): Current commit OID of `refs/heads/main` on `origin`.
1933 - `head` (`string` or `null`): Active version head OID (or remote branch tip / request / outcome
1934 head for an unrecorded branch).
1935 - `request` (`object` or `null`): `{ "ref": <string>, "commit": <oid> }` when a request ref exists
1936 on `origin`.
1937 - `outcome` (`object` or `null`):
1938 `{ "decision": <string>, "head": <oid or null>, "tip": <oid or null>, "failed_at": <rfc3339 or null> }`
1939 when an outcome ref exists on `origin`.
1940 - `state` (`string`): One of `integrated`, `integrated-recorded`, `outdated-request`,
1941 `outcome-unreadable`, `voided-withdrawn`, `not-requested`, `awaiting-decision`,
1942 `awaiting-new-decision`, `stale`, `rejected`, `refused-not-ready`, `refused-merge`, or `failed`.
1943 - `change_id`, `handle`, `title`, `owner`, `landing` (`string` or `null`) and `version` (`int` or
1944 `null`): Populated for a recorded change (`landing` is `"landed"`, `"landed-recorded"`,
1945 `"uncertain"`, or `"not-landed"`); `null` for an unrecorded branch.
1946 - `restack` (`object` or `null`):
1947 `{ "ref": <string>, "commit": <oid>, "current": <bool>, "report": <RestackReport> }` when the
1948 change has a valid restack report on `origin`.
1949 - `knots` (`array` of `{ "id", "type", "status", "title" }`): Knots in `refs/the-valley/knots`
1950 whose `changes` field links `valley:<project>/<change_id>`, active knots first (`[]` when none
1951 or for an unrecorded branch).
1952
1953#### `valley-changes/v1` and `valley-pending/v1`
1954
1955`valley changes --json` emits `valley-changes/v1`, and `valley pending --json` emits
1956`valley-pending/v1` using the same repository and change structure.
1957
1958```json
1959{
1960 "schema": "valley-pending/v1",
1961 "host": "git@valley.example",
1962 "repos": [
1963 {
1964 "repo": "demo",
1965 "url": "git@valley.example:demo",
1966 "error": null,
1967 "changes": [],
1968 "drafts": [],
1969 "branches": [
1970 {
1971 "branch": "scratch",
1972 "head": "5555555555555555555555555555555555555555"
1973 }
1974 ]
1975 }
1976 ]
1977}
1978```
1979
1980- **Top-level fields:**
1981 - `schema`: `"valley-changes/v1"` or `"valley-pending/v1"`.
1982 - `host` (`string`): Host prefix derived from `origin`'s URL (URL minus the final `/<repo>` or
1983 `:<repo>` segment).
1984 - `repos` (`array` of repository objects):
1985 - `repo` (`string`), `url` (`string`), `error` (`string` or `null`). When `error` is non-null,
1986 `changes` and `branches` are `[]` (and `drafts` is `[]` in `valley-pending/v1`).
1987 - `changes` (`array` of `jsonChange`): In `valley-changes/v1`, all recorded changes in every
1988 state (ordered by Change ID). In `valley-pending/v1`, only `ready` changes whose active
1989 version is not landed (`not-landed` or `uncertain`).
1990 - `drafts` (`array` of `jsonChange`, **present only in `valley-pending/v1`**): Changes whose
1991 recorded `state` is `"draft"`. Omitted (`omitempty`) in `valley-changes/v1`.
1992 - `branches` (`array` of `{ "branch": <string>, "head": <oid> }`): Remote branches on `origin`
1993 (other than `main`) not reachable from `main`, not equal to any recorded change's active
1994 version head, and not reachable from the head of any landed version.
1995- **`jsonChange` fields:**
1996 - `change_id`, `handle`, `target`, `owner`, `state`, `record` (record commit OID), `seq`,
1997 `active`.
1998 - `versions` (`array` of
1999 `{ "n", "head" (40-hex OID without git-sha1: prefix), "title", "branch", "uploader", "landing" ("landed"|"landed-recorded"|"uncertain"|"not-landed"), "landed_commit" (<oid or null>), "request" ({"ref","commit"} or null), "outcome" ({"decision","head","tip"} or null) }`).
2000 - `includes` (`array` of `string`): Change IDs of other changes in the candidate set (all changes
2001 in `valley-changes/v1`; unlanded changes in `valley-pending/v1`) whose active version head is a
2002 strict ancestor of this change's active version head in `main..head`.
2003 - `restack` (`jsonRestack` or `null`) and `knots` (`array` of
2004 `{ "id", "type", "status", "title" }`).
2005
2006#### `valley-plan/v1`
2007
2008`valley plan --json` emits one indented `valley-plan/v1` JSON document.
2009
2010```json
2011{
2012 "schema": "valley-plan/v1",
2013 "now": "2026-10-19T12:00:00Z",
2014 "operator": "operator",
2015 "projects": [
2016 {
2017 "project": "demo",
2018 "error": null,
2019 "tip": "6666666666666666666666666666666666666666",
2020 "roots": ["oc-c12d4ed"],
2021 "knots": [],
2022 "waiting_on_you": {
2023 "knots": ["oc-c12d4ed"],
2024 "changes": [],
2025 "changes_error": null
2026 },
2027 "in_flight": [],
2028 "open_residuals": []
2029 }
2030 ]
2031}
2032```
2033
2034- **Fields:**
2035 - `schema`: `"valley-plan/v1"`.
2036 - `now` (`string`): UTC evaluation timestamp (`RFC 3339`).
2037 - `operator` (`string` or `null`): Principal from `--owner` or `git config valley.principal`.
2038 - `projects[]`: Each element has:
2039 - `project` (`string`), `error` (`string` or `null`), `tip` (`string`, commit OID of
2040 `refs/the-valley/knots` or `""` when the project has no graph).
2041 - `roots` (`array` of `string`): Root `outcome` knot IDs in tree order (`created`, `title`,
2042 `id`).
2043 - `knots` (`array` of `planKnot`): Every knot in tree walk order. Each `planKnot` embeds
2044 [`jsonKnot`](#valley-knot---json-valley-knotv1-valley-knotsv1-valley-knot-opv1-valley-knot-logv1-valley-knot-schemav1)
2045 (without `body` or `comments`, with `children` ordered in tree order and `progress` counted
2046 over all descendants) plus:
2047 - `state` (`string`): `"ready"`, `"in-progress"`, `"blocked"`, `"active"`, `"done"`, or
2048 `"abandoned"`.
2049 - `edges` (`array` of `planEdge`): Resolved cross-project references from `blocked_by` and
2050 `target`, each
2051 `{ "field": "blocked_by"|"target", "ref": "<project>:<id>", "project": <string>, "id": <string>, "state": "resolved"|"dangling", "why": "missing"|"unreadable"|null, "status": <string or null>, "title": <string or null> }`.
2052 - `waiting_on_you` (`object` or `null`):
2053 `{ "knots": [<id>...], "changes": [{ "repo", "handle", "change_id", "version", "title", "head" }...], "changes_error": <string or null> }`
2054 (`null` when `error != null`). `knots` is `null` when `operator` is `null`, and otherwise
2055 lists active `outcome`/`bug` and open `question` knots owned by `operator`.
2056 - `in_flight` (`array` of `string` or `null`): Claimed active knot IDs ordered by oldest
2057 `claimed_at` first.
2058 - `open_residuals` (`array` of `{ "parent": <id or null>, "bugs": [<id>...] }` or `null`): Open
2059 `bug` knots grouped by `parent`.
2060
2061#### `valley knot --json` (`valley-knot/v1`, `valley-knots/v1`, `valley-knot-op/v1`, `valley-knot-log/v1`, `valley-knot-schema/v1`)
2062
2063`valley knot <verb> --json` emits one of five indented JSON schemas depending on the subcommand:
2064
2065```json
2066{
2067 "schema": "valley-knot-op/v1",
2068 "project": "demo",
2069 "op": "0123456789abcdef",
2070 "commit": "7777777777777777777777777777777777777777",
2071 "knot": {
2072 "id": "oc-c12d4ed",
2073 "type": "outcome",
2074 "status": "open",
2075 "active": true,
2076 "title": "Publish the CLI reference",
2077 "created": "2026-10-19",
2078 "created_by": "operator",
2079 "blocked_by": [],
2080 "changes": [],
2081 "path": "outcomes/oc-c12d4ed-publish-the-cli-reference.md",
2082 "body": "",
2083 "comment_count": 0,
2084 "ready": true,
2085 "waiting_on": [],
2086 "cleared_by_ending": [],
2087 "dangling": [],
2088 "unresolved": [],
2089 "children": [],
2090 "blocks": []
2091 }
2092}
2093```
2094
2095- **Envelope by subcommand:**
2096 - `valley knot show <id> [--at <commit>] --json`:
2097 `{ "schema": "valley-knot/v1", "project": <string>, "tip": <oid>, "at": <oid>, "knot": <jsonKnot with body & comments> }`.
2098 `tip` is the current tip of `refs/the-valley/knots`. `at` is the full commit OID that `--at`
2099 resolved to, and is omitted when `--at` is not passed.
2100 - `valley knot log <id> --json`:
2101 `{ "schema": "valley-knot-log/v1", "project": <string>, "tip": <oid>, "id": <knot id>, "path": <knot file path>, "commits": [<logEntry>...] }`,
2102 newest first. Each `logEntry` is
2103 `{ "commit": <oid>, "at": <RFC 3339 UTC committer time>, "committer": <string>, "op": <16-hex-op-id>, "subject": <string>, "files": [{ "path": <string>, "change": "added"|"changed"|"deleted", "comment": <comment id> }...] }`,
2104 where `comment` is present only for files under `comments/<id>/`.
2105 - `valley knot list --json`:
2106 `{ "schema": "valley-knots/v1", "project": <string>, "tip": <oid>, "knots": [<jsonKnot without body & comments>...] }`.
2107 - `valley knot (new|set|link|unlink|edit|comment|claim|unclaim) --json`:
2108 `{ "schema": "valley-knot-op/v1", "project": <string>, "op": <16-hex-op-id>, "commit": <oid>, "knot": <jsonKnot with body & comments> }`.
2109 When a write subcommand is a no-op (for example, `set` or `claim` leaves the knot unchanged), it
2110 prints a note to `stderr`, pushes nothing, and emits no JSON on `stdout`.
2111 - `valley knot schema --json`:
2112 `{ "schema": "valley-knot-schema/v1", "ref": "refs/the-valley/knots", "types": [...], "fields": [...], "edges": [...], "limits": { "knots": 5000, "comments": 20000, "knot_bytes": 65536, "comment_bytes": 16384, "changed_paths_per_commit": 32, "title_bytes": 200, "list_items": 64 } }`.
2113- **`jsonKnot` fields:**
2114 - Stored fields: `id`, `type`, `status`, `active` (`bool`), `title`, `created`, `created_by`,
2115 `source` (`omitempty`), `parent` (`omitempty`), `owner` (`omitempty`), `blocked_by`
2116 (`[]string`), `claimed_by` (`omitempty`), `claimed_at` (`omitempty`), `changes` (`[]string`),
2117 `target` (`omitempty`), `graduated_into` (`omitempty`), `path`, `comment_count` (`int`).
2118 - Full-only fields (included in `show` and write ops, omitted in `list` and `plan`): `body`
2119 (`string`), `comments` (`array` of
2120 `{ "id" (<YYYYMMDDTHHMMSSZ>-<16-hex-op>), "author", "at" (RFC 3339), "op" (16-hex), "edited" (RFC 3339, omitempty), "edited_by" (omitempty), "body" }`,
2121 `omitempty` — omitted when the knot has `0` comments). `edited` and `edited_by` are included
2122 only on edited comments.
2123 - Derived `knot.View` fields: `ready` (`bool`), `waiting_on` (`[]string`), `cleared_by_ending`
2124 (`[]string`), `dangling` (`[]string`), `unresolved` (`[]string`), `children` (`[]string`),
2125 `blocks` (`[]string`), `progress` (`{ "done": <int>, "of": <int> }`, `omitempty`), `claim`
2126 (`{ "by": <string>, "at": <rfc3339>, "age_seconds": <int64>, "stale": <bool, true when age > 24h> }`,
2127 `omitempty`).
2128
2129### Web export (`the-valley/web-export/v2`)
2130
2131A web export is the snapshot of exported projects that a valley host sends to a read-only web
2132server. It includes every project that at least one reader may read at that server, and one shared
2133export serves all of the server's readers. It consists of `export.json`, one git bundle of `main`
2134for each exported project, and a signed manifest that authenticates both. A separate signed
2135document, the [authorization](#web-authorization-the-valleyweb-authorizationv1), states who may read
2136which project. The export carries no reader and no visibility, so a content upload never grants or
2137restores access. A publisher on the valley host pushes both over HTTP to a receiver on the web
2138server, and the web server never connects back to the host. Package `export` of the `web` module
2139([`web/export/`](../web/export/)) implements the types, the verification checks below, and the
2140receiver's store. `valley-web-publish` is the publisher,
2141[`valley-web-receive`](#web-export-receiver-valley-web-receive) is the receiver, and the web server,
2142[`valley-web`](#web-server-valley-web), reads the receiver's store with the package.
2143
2144#### `export.json` (`valley-web-export/v2`)
2145
2146`export.Build` builds `export.json` from the valley CLI's JSON output and the publisher's
2147configuration. It reads `valley plan --all --json`, `valley pending --all --json`, and
2148`valley knot show --project <project> <id> --json` for every knot in every exported project. The
2149publisher also gives it each exported project's publication identity, each exported project's `main`
2150commit (`source_tip`), and a display mapping for principal names. `Export.Encode` writes the export
2151as compact JSON ending with a newline.
2152
2153```json
2154{
2155 "schema": "valley-web-export/v2",
2156 "collected": "2026-10-25T12:00:00Z",
2157 "groups": [{ "group": "core", "name": "tools", "aliases": ["t"] }],
2158 "projects": [
2159 {
2160 "project": "app",
2161 "identity": "9da6809f038df92138c131cd16bed76d",
2162 "group": "core",
2163 "aliases": ["app"],
2164 "graph_tip": "3f6a0c1d9e8b7a6f5e4d3c2b1a0f9e8d7c6b5a49",
2165 "source_tip": "ff4ea8a16ee7db8ebda8169da1ce9d6cc2a2ede1",
2166 "roots": ["oc-a000001"],
2167 "knots": [],
2168 "in_flight": [],
2169 "open_residuals": [],
2170 "changes": []
2171 }
2172 ]
2173}
2174```
2175
2176- **What is exported:** `export.Build` exports the projects its `Identities` map names, each with
2177 the publication identity given. The publisher names a project when both consents authorize some
2178 reader, `anyone` or a named principal, to read it at the destination (see
2179 [Read policy](#read-policy-schemareadcue)) and the host declaration places it in a group. Every
2180 knot and every comment of an exported project is included. The authorization alone decides whether
2181 a server shows the project.
2182- **Top-level fields:** `schema` (`"valley-web-export/v2"`), `collected` (`string`, the plan's
2183 `now`), `groups`, and `projects` (sorted by project name).
2184- **`groups[]` fields:** The groups of the exported projects, sorted by identifier. Only groups with
2185 at least one exported project are included. `groups` is omitted when empty.
2186 - `group` (`string`): The group's identifier, which follows the project-name pattern. No URL shows
2187 it.
2188 - `name` (`string`): The group's web name, used as the first URL segment for its projects.
2189 - `aliases` (`array` of `string`, omitted when empty): Additional first-segment names that
2190 redirect to the same path under `name`.
2191- **`projects[]` fields:**
2192 - `project` (`string`): The project's identifier (`^[a-zA-Z0-9][a-zA-Z0-9._-]*$`, at most 64
2193 bytes). The pattern forbids `/` and dot segments (`.` and `..`), so the name is safe to use as a
2194 file name.
2195 - `identity` (`string`): The project's publication identity, 32 lowercase hex digits, as its
2196 `policy/read` declares it. An authorization names the project by this identity and its name.
2197 - `group` (`string`, omitted when empty): The identifier of the project's group. A project without
2198 a `group` has no URL, and `valley-web` treats it as absent from the export.
2199 - `name` (`string`, omitted when empty): The project's web name, used as the second segment of its
2200 URLs. It is unique within its group and may differ from `project`. Every project with a `group`
2201 has a `name`.
2202 - `former_names` (`array` of `string`, omitted when empty): The project's former web names within
2203 its group, which redirect to the same path under `/<group name>/<name>`.
2204 - `aliases` (`array` of `string`, omitted when empty): The project's short aliases, used as first
2205 URL segments that redirect to the same path under `/<group name>/<name>`.
2206 - `graph_tip` (`string`): Commit object ID of `refs/the-valley/knots` where the knots were read,
2207 or `""` when the project has no plan graph.
2208 - `source_tip` (`string`): Commit object ID of `refs/heads/main` carried by the project's bundle.
2209 - `roots` and `open_residuals`: Same as in [`valley-plan/v1`](#valley-planv1).
2210 - `knots` (`array`): Every knot in the project, in tree order. Each item carries the `planKnot`
2211 fields of `valley-plan/v1` plus `body` and `comments` from the knot's detail JSON. It omits
2212 `path`, `claimed_by`, and `claimed_at`; claim details live in the `claim` object. Each comment
2213 carries `author`, `at`, `op`, and `body`. An edited comment also carries `edited` (when it was
2214 last edited) and `edited_by` (who edited it); a comment never edited has neither field.
2215 - `in_flight` (`array` of `string`): Active claimed knots ordered from oldest claim to newest,
2216 followed in tree order by active unclaimed knots whose status is `in-progress`.
2217 - `changes` (`array`): Ready changes whose active version has not landed. Each item carries
2218 `change_id`, `handle`, `target`, `owner`, `includes`, `knots`, and the active version alone as
2219 `version`:
2220 `{ "n", "head", "title", "uploader", "landing", "request": { "commit" } or null, "outcome": { "decision", "head", "tip" } or null }`.
2221 `includes` lists only changes that are also in `changes`.
2222- **What is left out:** `export.Build` reads only the fields it knows, so any field added to the
2223 CLI's JSON is ignored until the projection names it. From the plan, it omits `operator`,
2224 `waiting_on_you`, and each project's `error`. From the pending listing, it omits `host` and each
2225 repository's `url`, `error`, `drafts`, and `branches`. From each change, it omits `record`, `seq`,
2226 `state`, `restack`, and every version except the active one; from the active version, it omits
2227 `branch`, `landed_commit`, and `request.ref`. From each knot, it omits `path`, `claimed_by`, and
2228 `claimed_at`. From each comment, it omits `id`.
2229- **Principal names:** The display mapping (`export.Principals`) rewrites `created_by`, `owner`,
2230 `claim.by`, each comment's `author` and `edited_by`, a change's `owner`, and a version's
2231 `uploader` to configured display names such as `operator` or `agent`. Each display name is 1 to 64
2232 bytes of UTF-8 with no control characters. An empty field stays empty, and any unmapped name
2233 becomes `contributor`. Free-text fields (`title`, `body`, comment bodies, and `source`) are
2234 exported as written.
2235- **References to hidden projects:** When a knot's `blocked_by` or `target` refers to a project that
2236 is not exported, the knot's `blocked_by` and `target` fields keep the `"<project>:<id>"` string as
2237 written. The corresponding entry in `edges` has `"state": "hidden"` and `null` for `why`,
2238 `status`, and `title`. The reference is removed from `waiting_on`, `cleared_by_ending`,
2239 `dangling`, and `unresolved`, because those lists reflect the hidden knot's status. The referring
2240 knot's `state` and `ready` are unchanged, so a blocker in a hidden project still blocks it. When
2241 the export removes at least one reference from the knot's `waiting_on`, the knot carries
2242 `"waiting_on_hidden": true`. `waiting_on` lists each reference that remains a blocker: one that
2243 names an open knot, a missing knot, or a knot in a graph that could not be read. The field omits
2244 the hidden knots' IDs and count. Other knots omit `waiting_on_hidden`, and `export.Decode` accepts
2245 exports without it (see [Unpublished blockers](./architecture.md#unpublished-blockers) for what a
2246 reader can infer when `blocked_by` names a single hidden knot).
2247- **Refusals (`export.Build`):** `export.Build` fails rather than build a partial export. It fails
2248 when an exported project is missing or has an `error` in the plan or the pending listing, or when
2249 a knot in an exported project is missing its detail, appears twice, or has no `body`. It fails
2250 with `export.ErrInconsistent` when a knot's detail was read at a different graph `tip` than the
2251 plan or its comment count disagrees with `comment_count`. On `ErrInconsistent`, the publisher
2252 reads its inputs again. It also fails when an exported project has no group, or when the groups
2253 and placements fail `export.CheckNames`.
2254- **Strict reading (`export.Decode`):** `export.Decode` rejects unknown JSON fields and any
2255 non-whitespace token after the root JSON object. It decodes with `exactjson`: every key must match
2256 its field name in exact case (without ASCII or Unicode case folding), and duplicate keys in one
2257 object are refused. An array or object for a scalar field is refused before its contents are read,
2258 and arrays or objects nested more than 1000 levels deep (`exactjson.MaxDepth`) are refused. It
2259 requires `schema` to be `"valley-web-export/v2"`, projects to appear once in ascending name order
2260 with valid project names and an `identity` of 32 lowercase hex digits, and knot IDs to be valid
2261 and unique within each project. Groups must appear once in ascending identifier order, and every
2262 group must be referenced by at least one project. Every group a project names must appear in
2263 `groups`. A project with a `group` must have a web `name`, and a project with `name`,
2264 `former_names`, or `aliases` must have a `group`. Every group identifier, group name, web name,
2265 former name, and alias must follow the project-name rule. Group names, group aliases, and project
2266 aliases must be distinct from one another and from `-`, ignoring ASCII case. Within each group,
2267 project web names and former names must be distinct from one another, ignoring ASCII case. An
2268 export without `groups` is valid when no project names a group. Each project's `source_tip`,
2269 non-empty `graph_tip`, and each change's `version.head` must be a 40- or 64-hex lowercase object
2270 ID. Every knot's `title`, `body`, `source`, `created_by`, and `owner`, and every comment's `body`,
2271 `author`, `edited`, and `edited_by`, must be valid UTF-8 with no control characters other than
2272 `\n` and `\t`.
2273- **Content digest (`Export.Digest`):** `Export.Digest` is the 64-hex SHA-256 of the export's JSON
2274 with `collected` cleared and each claim's `age_seconds` and `stale` zeroed. Those fields change
2275 with the clock rather than with the valley, so two exports of the same valley state have the same
2276 digest. A reader computes a claim's age from `claim.at`.
2277
2278#### Web export manifest
2279
2280The manifest is a [signed note](#signed-notes-and-attestation-statement-the-valleyattestationv1)
2281signed by the publisher's export key:
2282
2283```text
2284the-valley/web-export/v2
2285instance valley-host
2286destination example.org
2287sequence 1792929630000000000
2288file export.json 2a841dd0581200e7ecc0443fe0a39ab502cd884c09f9232bc372ca108a0e2a99 5108
2289project app 9da6809f038df92138c131cd16bed76d 3f6a0c1d9e8b7a6f5e4d3c2b1a0f9e8d7c6b5a49 ff4ea8a16ee7db8ebda8169da1ce9d6cc2a2ede1
2290bundle app fffb1ae32f18c72dae5ee91ed0bcd14f5462cc10900db4d1cf7abc480975443b 1133
2291
2292— valley-host/web-export e7kLV5lThaGSbsBUVC2cJ8I1vn6XJWS9+L0wwWmdRAYL827G/au5kE5OidGXMH+ofpnTprs+o4GgPNuTwqOexf8zrgw=
2293```
2294
2295- **Records:** Line 1 is `the-valley/web-export/v2`. Each remaining line in the note body is a
2296 keyword and its fields, separated by single spaces:
2297 - `instance <name>`: Name of the valley instance that signed the manifest.
2298 - `destination <name>`: Name of the target receiver, matching the receiver's configuration.
2299 - `sequence <decimal>`: Signing time in Unix nanoseconds. There is no separate sequence counter.
2300 - `file export.json <sha256> <size>`: SHA-256 digest and byte size of `export.json`.
2301 - `project <name> <identity> <graph-tip> <source-tip>` and `bundle <name> <sha256> <size>`: One
2302 pair for each exported project. `<identity>` is the project's publication identity, 32 lowercase
2303 hex digits. A project with no plan graph writes `-` for `<graph-tip>`. No record names a reader.
2304- **Grammar rules (`export.ParseManifest`, `Manifest.Text`):** `instance`, `destination`,
2305 `sequence`, and `file` appear once each. Each exported project has one `project` record and one
2306 `bundle` record; no project may appear twice, and no `bundle` record may name a project without a
2307 `project` record. Names in `instance`, `destination`, `project`, and `bundle` follow the
2308 project-name rule (`^[a-zA-Z0-9][a-zA-Z0-9._-]*$`, at most 64 bytes). Tips (other than `-`) are
2309 40- or 64-hex lowercase object IDs. Hashes are 64 lowercase hex digits. Sizes and `sequence` are
2310 positive 64-bit decimal integers with no sign and no leading zero. If two declared bodies share a
2311 hash, they must declare the same size. `ParseManifest` accepts records in any order;
2312 `Manifest.Text` writes them in the order shown above, with projects sorted by name.
2313- **Admission (`export.VerifyManifest`):** The receiver verifies a manifest in six separate steps,
2314 in this exact order:
2315 1. Read the manifest. The receiver reads up to 65,537 bytes so that it can tell when the manifest
2316 is too long. It accepts at most 64 KiB (`MaxManifest = 65,536` bytes) and refuses a longer one
2317 as `too-large`.
2318 2. Open the signed note under the receiver's pinned verifier keys.
2319 3. Check the `the-valley/web-export/v2` header line and parse the records.
2320 4. Require `instance` and `destination` to match the receiver's configured instance and
2321 destination.
2322 5. Require `sequence` to be strictly greater than the receiver's `high-water` mark.
2323 6. Require the signing time (`sequence`) to be at most 72 hours (`MaxAge`) behind and at most 1
2324 minute (`MaxAhead`) ahead of the receiver's clock.
2325
2326 The signing-time window bounds how old a manifest can be replayed if the receiver loses its
2327 `high-water` file. It never expires an export after the receiver has accepted it.
2328
2329- **Agreement (`Manifest.CheckExport`):** `Manifest.CheckExport` checks that `export.json` has the
2330 SHA-256 and byte size declared in the `file` record, passes `export.Decode`, and lists the same
2331 projects as the manifest with the same `identity`, `graph_tip`, and `source_tip`.
2332
2333#### Web authorization (`the-valley/web-authorization/v1`)
2334
2335An authorization is a signed note that states who may read which project at one destination. The
2336publisher's policy path is its only writer, and it signs with the same export key as content
2337manifests. The receiver stores the newest authorization it admits. `valley-web` serves a project
2338only while the stored authorization names that project by name and identity and grants access to the
2339request's reader (`implemented`).
2340
2341```text
2342the-valley/web-authorization/v1
2343instance valley-host
2344destination example.org
2345sequence 42
2346checked 2026-10-29T01:03:00Z
2347basis 41
2348project app 9da6809f038df92138c131cd16bed76d
2349reader app anyone
2350binding lk-0123456789abcdef alice 3a6eb0790f39ac87c94f3856b2dd2c5d110e6811602261a9a923d3bb23adc8b7
2351
2352— valley-host/web-export e7kLV5lThaGSbsBUVC2cJ8I1vn6XJWS9+L0wwWmdRAYL827G/au5kE5OidGXMH+ofpnTprs+o4GgPNuTwqOexf8zrgw=
2353```
2354
2355- **Records:** Line 1 is `the-valley/web-authorization/v1`. Each remaining line in the note body is
2356 a keyword and its fields, separated by single spaces:
2357 - `instance <name>` and `destination <name>`: As in the manifest.
2358 - `sequence <decimal>`: The publisher's authorization counter. It uses no clock. Each
2359 authorization the publisher signs carries a greater sequence than every earlier one.
2360 - `checked <time>`: When the publisher last finished a complete policy check, in RFC 3339 UTC to
2361 the second. Pages display this time. Access never depends on it.
2362 - `basis <decimal>` (optional): The sequence of the authorization the receiver must hold for this
2363 one to be stored. The publisher writes it only when a project keeps access that an incomplete
2364 policy check could not confirm, and the basis is the authorization the receiver last
2365 acknowledged. It is less than `sequence`.
2366 - `project <name> <identity>`: One project the authorization names, with its publication identity.
2367 - `reader <name> <principal>`: One effective reader of the project `<name>`. Every named project
2368 has at least one reader. The publisher writes one line for each effective reader, `anyone` or a
2369 named principal, of each project that the host declaration places in a group.
2370 - `binding <id> <principal> <verifier>`: One active read link (see
2371 [Web read links](#web-read-links)). `<id>` is the credential ID, `lk-` and 16 lowercase hex
2372 digits. `<principal>` is the registry principal the link identifies, never `anyone`.
2373 `<verifier>` is the lowercase hex SHA-256 of the link's 32 secret bytes. A credential with no
2374 binding is revoked. `valley-web` redeems a link only while an authorization binds it, and keeps
2375 a session valid only while the stored binding matches the principal and verifier the link was
2376 redeemed under (see [Reader sessions](#reader-sessions)).
2377- **Grammar rules (`export.ParseAuthorization`, `Authorization.Text`):** `instance`, `destination`,
2378 `sequence`, and `checked` appear once each, and `basis` at most once. Each project appears once,
2379 each reader of a project appears once, and every `reader` record names a project that has a
2380 `project` record. Names and principals follow the project-name rule. `ParseAuthorization` accepts
2381 records in any order; `Authorization.Text` writes them in the order shown above, with projects
2382 sorted by name and readers sorted, and bindings after them sorted by ID. Each credential ID
2383 appears in at most one binding, and an authorization carries at most 1,000 bindings
2384 (`export.MaxBindings`).
2385- **Size limit (`export.MaxAuthorization`):** A signed authorization is at most 256 KiB, the most a
2386 receiver reads. `Authorization.Sign` refuses a larger one as `too-large` before it signs. A pass
2387 signs the full authorization only when its signed size is at most 256 KiB minus 64 bytes
2388 (`export.FallbackRoom`). Those 64 bytes reserve room for a longer `sequence` and an added `basis`
2389 in a later fallback. Otherwise the pass builds a bounded fallback (`export.Narrow`) from the last
2390 authorization the receiver acknowledged, keeping only the projects, readers, and bindings that
2391 both the acknowledged authorization and the current check allow, with the current check's
2392 `instance`, `destination`, `sequence`, `checked`, and `basis`. Because the acknowledged
2393 authorization may have been signed without that 64-byte reserve, the fallback can itself exceed
2394 256 KiB. The pass measures the fallback and, if it exceeds 256 KiB, restricts it further
2395 (`export.Fit`) one step at a time, signing the first result that fits:
2396 1. Drop whole projects kept only on the `basis`, one at a time in name order. Once no project kept
2397 on the `basis` remains, drop the `basis` record too.
2398 2. Drop one reader at a time from the project with the most remaining readers (breaking ties by
2399 the earliest project name), removing the reader whose name sorts last. Dropping a project's
2400 last reader drops its `project` record as well.
2401 3. Drop one `binding` record at a time, in credential ID order.
2402
2403 After the last step, the authorization grants nothing: it has no `project`, `reader`, `binding`,
2404 or `basis` record. It always fits.
2405
2406- **Admission (`export.VerifyAuthorization`):** The receiver admits an authorization in six separate
2407 steps, in this exact order:
2408 1. Read at most 256 KiB (`MaxAuthorization`), and refuse a longer one as `too-large`.
2409 2. Open the signed note under the receiver's pinned verifier keys.
2410 3. Check the `the-valley/web-authorization/v1` header line and parse the records. A content
2411 manifest fails here as `bad-manifest`, as does an authorization posted as a manifest.
2412 4. Require `instance` and `destination` to match the receiver's configuration.
2413 5. Require `sequence` to be strictly greater than the stored authorization's sequence.
2414 6. Require `basis`, when present, to equal the stored authorization's sequence. Otherwise refuse
2415 it as `stale-basis`, with the stored sequence as `high_water`.
2416
2417 Admission checks no age window. An authorization above the stored sequence is admitted regardless
2418 of how old its `checked` time is or how far the clocks disagree. If the stored authorization
2419 cannot be read, step 5 fails with an error rather than treating the stored sequence as 0, so no
2420 replay is admitted over it.
2421
2422- **Storing (`Store.Authorize`):** The receiver takes `authorization.lock`, checks the sequence and
2423 the basis again, and writes the signed note to `<payload>/authorization` durably: it syncs a
2424 temporary file, renames it over the old one while it holds `<payload>/serving.lock` exclusively,
2425 releases that lock, and syncs the directory. It takes no activation lock, reads no graph, checks
2426 no repository, and runs no sweep, so a stalled upload or commit never holds it up. The receiver
2427 replies once the note is on disk and `serving.lock` is released.
2428
2429| Request | Reply |
2430| :------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
2431| `POST /web-export/v2/authorization` with the signed note | `200` and `valley-web-authorized/v1`: the `sequence` stored, `active` (the served export's `sequence` and content `digest`, or `null`), and `missing` (projects of the active export the authorization names whose repositories the receiver deleted when an earlier authorization withdrew them, or `[]`) |
2432
2433- **Withdrawal:** A project omitted from the stored authorization is hidden starting with the next
2434 request. The publisher omits a project once it has no effective reader left. After replying, the
2435 receiver deletes the project's repository from the active generation once no reader holds the
2436 generation (`Store.Prune`). It retries with a backoff that doubles up to five seconds for up to
2437 five minutes, and logs any prune it could not finish. The next authorization, activation, or
2438 receiver start tries again. `export.json` keeps its signed bytes, so it still holds the withdrawn
2439 project's plan text until a later activation replaces the generation and deletes the old one. A
2440 prune selects the withdrawn repositories, then takes `authorization.lock`, reads the authorization
2441 again, and renames away only the repositories it still does not name. So a repository that an
2442 authorization names again is never deleted after the receiver replies to that authorization. If a
2443 prune deleted it first, the reply lists the project in `missing`, and the next content upload
2444 sends its bundle again.
2445- **Refusals:** Uses the same refusal format and codes as the upload. `replayed` and `stale-basis`
2446 carry the stored sequence as `high_water`.
2447
2448#### Web read links
2449
2450A read link is a bearer credential for reading at the edge. It identifies one registry principal,
2451and it authorizes what that principal may read there and nothing more (`implemented`). The edge
2452redeems each read link once and starts a browser session (see [Reader sessions](#reader-sessions)).
2453
2454```text
2455valley-web-link issue --principal alice --note laptop
2456valley-web-link list
2457valley-web-link revoke lk-0123456789abcdef
2458valley-web-link revoke --principal alice
2459valley-web-link revoke --all
2460valley-web-link prune
2461```
2462
2463- **The wrapper (`valley-web-link`, `deployment choice`):** The web publisher module installs it,
2464 and the operator runs it as root. It runs `valley-web-publish link` with the module's paths, sets
2465 `ulimit -c 0`, and gives git the unit's exact `safe.directory` entries, because root owns no
2466 repository. After every `issue` or `revoke`, whether or not it changed anything, it starts
2467 `valley-web-publish-policy.service`, a oneshot that runs the publisher's pass with `--policy-only`
2468 in the same sandbox as `valley-web-publish.service`. It then runs `link list --check` over every
2469 credential. A policy pass that was already running when the command started may have signed before
2470 the change, and `systemctl start` returns when that pass ends. So while a credential is still
2471 `pending`, the wrapper starts the policy pass and runs the check once more, without repeating the
2472 change. It prints each credential still `pending`, and exits 1 while any is. Running a `revoke`
2473 again therefore retries its delivery. The wrapper runs `list` and `prune` alone, as root, and
2474 starts no pass.
2475- **`valley-web-publish link issue --principal NAME [--note TEXT]`:** Reads the registry and the
2476 projects' `policy/read` the way a policy pass does, into a temporary cache it removes. It refuses
2477 unless the principal may read at least one project at `--destination` that the host declaration
2478 places in a group. It also refuses when the file it would write is larger than 1 MiB less 64 KiB
2479 (`linksHeadroom`), with a message to run `prune`. It then makes its process non-dumpable
2480 (`prctl(PR_SET_DUMPABLE, 0)`), generates the secret, adds a credential to the file, and prints the
2481 link once on stdout. The note is at most 100 characters, with no control characters.
2482- **`valley-web-publish link list [--check] [ID...]`:** Shows each credential's ID, principal, state
2483 (`active` or `revoked`), delivery, issue time and note. It reads the publisher's state and never
2484 contacts the edge, and it does not know whether a link was redeemed. Delivery is one of:
2485 - `enforced`: the receiver acknowledged an authorization that carried the links of the revision
2486 that set the credential's state, or of a later revision.
2487 - `pending`: the receiver has acknowledged no such authorization, or the publisher has no delivery
2488 record. When a pass sends a bounded fallback, the delivery record records the credential-file
2489 revision from the acknowledged authorization that the fallback narrowed. Any link issued or
2490 revoked in a later revision therefore stays `pending` in `link list`, even though the fallback
2491 delivers the revocation. A fallback that drops a binding to fit within the size limit is
2492 recorded as carrying no links from the credential file, so every credential stays `pending`
2493 until an authorization fits.
2494
2495 With `--check`, it exits 1 when a credential it shows is `pending`.
2496
2497- **`valley-web-publish link revoke (ID | --principal NAME | --all)`:** Records a revocation time on
2498 each matching active credential. A revocation is permanent. It does not change the registry. It
2499 writes the file only when it revoked a credential. A revoke is never refused for the file's size:
2500 the 64 KiB `issue` leaves free fits a revocation of all 1,000 active credentials, each adding at
2501 most 59 bytes.
2502- **`valley-web-publish link prune`:** Removes each revoked credential whose revocation is
2503 `enforced`, and keeps each one still `pending`. It writes the file at the next revision when it
2504 removes any. Removing a record loses nothing: the edge accepts only a credential the stored
2505 authorization binds, so an absent credential is as revoked as a revoked one. Each ID has 64 random
2506 bits, and `issue` never issues an ID that the file already holds.
2507- **Flags:** `--links FILE` (required) is the credential file. It may not be named `lock`.
2508 `--state DIR` is the publisher's state directory, whose delivery record every verb reads.
2509 `--instance-repo`, `--destination` and `--host` are required for `issue`, and `issue` alone
2510 accepts them, `--registry-ref`, `--registry-dir` and the schemas.
2511- **The link:** `https://<destination>/-/redeem#<id>.<secret>`. `<destination>` is the publisher's
2512 `--destination`. `<secret>` is 32 random bytes from `crypto/rand`, in base64url without padding,
2513 43 characters. The part after `#` stays in the browser and is not sent in the request line.
2514- **The credential file (`--links`):** JSON, read strictly: unknown or misspelled keys, repeated
2515 keys, a repeated ID, a malformed field, or more than 1,000 active credentials fail it. A missing
2516 or empty file holds no credentials. Reads and writes hold it to 1 MiB (`maxLinksFile`). Every
2517 change takes the links lock, then reads the file, writes a temporary file, syncs it, and renames
2518 it over the file. The file has mode 0640, in the group of its directory. The module keeps it at
2519 `/var/lib/valley-web-links/links`, owned by root and the group `valley-web-links`, in a directory
2520 of mode 0750 with the same owners (`deployment choice`). Because the edge also holds the
2521 verifiers, the verifiers are not secret; the file needs integrity, and only root can write it.
2522
2523 ```json
2524 {
2525 "revision": 4,
2526 "links": [
2527 {
2528 "id": "lk-0123456789abcdef",
2529 "principal": "alice",
2530 "note": "laptop",
2531 "verifier": "3a6eb0790f39ac87c94f3856b2dd2c5d110e6811602261a9a923d3bb23adc8b7",
2532 "issued": "2026-10-29T12:00:00Z",
2533 "revoked": "2026-10-30T08:00:00Z",
2534 "changed": 4
2535 }
2536 ]
2537 }
2538 ```
2539
2540 `verifier` is the lowercase hex SHA-256 of the 32 secret bytes. A 256-bit random secret needs no
2541 slow hash. `revoked` is absent while the credential is active. `changed` is the file's revision
2542 that set the credential's current state: the revision its issue wrote, or its revocation. The file
2543 never holds a secret.
2544
2545- **The links lock (`lock` beside `FILE`):** An exclusive `flock` on the file named `lock` in the
2546 credential file's directory. A change (`issue`, `revoke`, `prune`) holds it alone, and takes no
2547 lock in `--state`. A pass takes it inside the authorization lock, just before it reads the file,
2548 and holds it until it has signed. Each waits at most 60 seconds for it and says on stderr that it
2549 is waiting. If the wait runs out, a change fails without writing, whereas a pass signs and sends
2550 an authorization with no bindings and then fails. The lock is opened with `O_NOFOLLOW` and
2551 `O_NONBLOCK`, so a symbolic link or a FIFO there is refused without following or blocking.
2552 Anything but a regular file owned by root, or by the user who runs the command, is refused. A
2553 missing lock is made, mode 0640. The module's tmpfiles makes it, owned by root and the group
2554 `valley-web-links`, mode 0640, so the publisher can open and lock it but can make, replace or
2555 remove nothing in the directory (`deployment choice`).
2556- **The revision only moves forward:** Every change writes revision one more than the greater of the
2557 file's revision and the greatest revision a pass has signed from, which the publisher records in
2558 its state. So a change to a file restored from an older copy still writes past every revision
2559 already signed.
2560- **In the pass (`--links FILE` on `valley-web-publish`):** On its first signing attempt and on
2561 every retry after a refusal, the pass reads the file under the links lock, after it checks the
2562 policy and immediately before it signs. Every change to the file holds the same lock, so once a
2563 revoke has finished, no pass signs the revoked credential. The pass signs one `binding` record for
2564 each active credential into every authorization it signs, including an authorization that keeps
2565 access because a project's policy could not be read. Under the module, the pass reads the file
2566 directly through the group `valley-web-links`. A file that cannot be read or does not parse fails
2567 the pass closed: the pass signs and sends an authorization with no bindings, then exits non-zero
2568 and says why. If the file is missing or empty, the pass treats it as holding no credentials and
2569 succeeds; if the file's directory is missing, the pass takes no lock and also succeeds with no
2570 credentials. A pass that can sign nothing, such as when the instance repository cannot be read,
2571 delivers nothing, and a revocation waits for the next pass that signs. Bindings never appear in a
2572 content manifest or in the export.
2573- **Delivery record (`links-delivery` in `--state`):** Records the greatest credential file revision
2574 a pass has signed from (written under the links lock before the authorization is signed), along
2575 with the sequence of the last authorization the receiver acknowledged and the file revision whose
2576 links it carried (`0` when it carried none read from a file). The pass and every verb read it
2577 without following a symbolic link or waiting on a FIFO, and refuse anything but a regular file of
2578 at most 4 KiB.
2579- **Restore:** Restoring the host from a backup restores the credential file and the publisher's
2580 state as they were at the backup. The next pass carries the restored file's links, so a credential
2581 revoked after the backup is active again. To cut off every link after a restore, or after the edge
2582 loses its state, follow the recovery steps in [the guide](./guide.md). The order matters: revoke
2583 everything, deliver an authorization with no bindings, confirm that `browser/state` exists, and
2584 only then issue new links. `valley-web` creates the browser state only under a stored
2585 authorization that carries no link binding (`implemented`, `web/readerstate/state.go`), so issuing
2586 replacements first can prevent initialization. While the state is unavailable, `valley-web` serves
2587 a request without the session cookie as `anyone`. It answers `503` to a `GET` or `HEAD` request
2588 that carries the session cookie, whether the cookie is malformed, revoked, or valid, and to a
2589 redemption or a logout that passes the request checks, because it checks that the state is usable
2590 before it validates the token (`implemented`, `web/readerstate/state.go`, `web/server/reader.go`).
2591 Once the state is usable, a request with an invalid session is served as `anyone` (`implemented`,
2592 `web/server/reader.go`). `web-push-e2e` checks this recovery.
2593
2594#### Web export upload
2595
2596The publisher uploads an export to the receiver in three steps. Every response body is JSON. A full
2597upload is two requests plus one `PUT` for each needed body. Package `export` defines the paths,
2598reply schemas, and checks for each step, and `valley-web-receive` serves them.
2599
2600- **The token:** Every request carries `Authorization: Bearer <token>` with the receiver's
2601 configured token (`export.BearerHeader`). If a request does not carry that exact header, the
2602 receiver refuses it before reading the body with status `401`, `WWW-Authenticate: Bearer`, and
2603 refusal code `unauthenticated` (`export.CarriesToken`). Both the publisher and the receiver read
2604 the token file with `export.ReadToken`, which requires one line of 32 to 256 visible ASCII
2605 characters (`0x21` to `0x7e`) with an optional trailing newline.
2606- **Caps at step 1:** After `export.VerifyManifest` admits a manifest, `Manifest.CheckSizes` refuses
2607 it as `too-large` when any declared body exceeds the receiver's single-body cap or when the unique
2608 declared bodies together exceed the receiver's upload cap. A body declared twice under one SHA-256
2609 counts once.
2610
2611| Step | Request | Reply |
2612| :--- | :---------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
2613| 1 | `POST /web-export/v2/manifest` with the signed manifest | `200` and `valley-web-inventory/v2`: `active` (the served export's `sequence` and content `digest`, or `null`), `holds` (each project's `source_tip` with a verified repository), and `needs` (bodies to send, `export.json` first) |
2614| 2 | `PUT /web-export/v2/<sequence>/<sha256>` for each needed body, with its bytes | `204` once the body has been verified and staged |
2615| 3 | `POST /web-export/v2/<sequence>/commit` with an empty body | `200` and `valley-web-committed/v2`: the `sequence` activated |
2616
2617- **Named projects:** The inventory requests a bundle only for a project that the stored
2618 authorization names, and a commit builds a repository only for such a project. When no
2619 authorization is stored, the inventory requests no bundle and a commit builds no repository.
2620- **Held repositories:** When the receiver's active generation still holds a project's repository at
2621 the manifest's `source_tip`, the inventory lists that project in `holds` and omits its bundle from
2622 `needs`. On commit, the new generation copies `refs/heads/main` from the held repository
2623 (`export.CarryRepo`). If `active.digest` matches the publisher's `Export.Digest` and `needs`
2624 includes no bundles, the receiver already serves the same content and repositories. The publisher
2625 may then stop after step 1 without sending `export.json` or committing, and the next manifest it
2626 posts replaces the staged upload.
2627- **Retries:** Posting the same manifest again keeps the staging directory and returns the same
2628 inventory minus any bodies already staged. This works only while the manifest is still admissible.
2629 A retried manifest is refused as `replayed` if the receiver has since accepted its sequence, as
2630 `superseded` if a staged upload has a later sequence, and as `out-of-window` if its signing time
2631 is more than 72 hours behind the receiver's clock. A body that is already staged still passes the
2632 size cap, the `Content-Encoding` check, and the `Content-Length` check. After those, the receiver
2633 returns `204` without reading the request body again.
2634- **Body check (`export.StageBody`):** Before reading the request body, the receiver refuses a body
2635 whose declared `size` exceeds the receiver's cap (`too-large`), a request with a
2636 `Content-Encoding` header (`content-encoding`), or a request whose `Content-Length`, when given,
2637 does not equal the declared `size` (`size-mismatch`). A request with no known length skips that
2638 comparison. The receiver then counts the streamed bytes and refuses a body that is shorter or
2639 longer than `size` (`size-mismatch`). While reading, it hashes the stream with SHA-256, reads at
2640 most `size + 1` bytes, and writes to a temporary file inside the upload's `bodies/` directory.
2641 Once the byte count and SHA-256 match the manifest, it syncs and renames the temporary file to
2642 `bodies/<sha256>`. Nothing is written outside the upload's staging directory. The temporary file
2643 and the staged body have mode `0600`.
2644- **Bundle acceptance (`export.AcceptBundle`):**
2645 1. Read the bundle header. The receiver reads at most 64 KiB + 1 byte of the file, so that it can
2646 tell when the header is too long, and never buffers a line past that bound. Require a v2 or v3
2647 git bundle header with no prerequisite commits.
2648 2. Require the header to list exactly one ref, `refs/heads/main`, at the project's declared
2649 `source_tip`.
2650 3. Initialize a fresh bare repository and fetch the bundle into it with the refspec
2651 `refs/heads/main:refs/heads/main`, `--no-tags`, `transfer.fsckObjects=true`, and
2652 `core.fsync=all`.
2653 4. Verify that the repository holds `refs/heads/main` at `source_tip` and no other ref.
2654 5. Write the repository's commit-graph with `git commit-graph write --reachable`.
2655
2656 A bundle that fails any of these checks is refused as `bad-bundle`. Failing to open the bundle
2657 file, to initialize the repository, or to list its refs is an operational error, not a refusal of
2658 the bundle. Either way, no repository is left behind.
2659
2660- **Reachability (`export.Reachable`):** A git bundle can contain objects that `refs/heads/main`
2661 does not reach. When serving a repository, browsing serves a commit only when `export.Reachable`
2662 confirms that it is a commit reachable from `source_tip` and that its object ID has the same
2663 length as `source_tip`.
2664- **Commit outcome:** A commit has succeeded once `Store.Activate` has written the upload's sequence
2665 to `high-water` and swapped the `current` symlink to the new generation. The receiver then replies
2666 `200` with `valley-web-committed/v2`. A later failure while syncing the swap to disk or deleting
2667 old generations, stale staging directories, and `trash/` does not change the `200` reply. `Store`
2668 passes that failure to the `report` callback given to `export.OpenStore` for the receiver to log.
2669 The next sweep retries failed deletions, but it does not retry a failed directory sync. Recovery
2670 at `OpenStore` returns at once when `current` already names the `high-water` generation. It
2671 restores the swap after a crash only when the two differ. A commit that fails before `current` is
2672 swapped leaves the previous export active. If it failed after `high-water` was written, its
2673 sequence is accepted, and retrying the commit is refused as `replayed`. The publisher's next
2674 manifest, signed later, replaces the upload.
2675- **Refusals:** A refused request returns the code's HTTP status and a `valley-web-error/v1` JSON
2676 object:
2677 `{ "schema": "valley-web-error/v1", "error": <code>, "message": <string>, "high_water" (with replayed), "needs" (with incomplete) }`.
2678 The `error` code is stable for programs to act on; `message` is human-readable text.
2679
2680| Code | HTTP | Step | Meaning |
2681| :-------------------- | :---- | :--- | :-------------------------------------------------------------------------------------------------------- |
2682| `unauthenticated` | `401` | 1-3 | The request does not carry the receiver's token. |
2683| `too-large` | `413` | 1, 2 | A manifest over 64 KiB, a body declared larger than the receiver's cap, or bodies over its upload cap. |
2684| `bad-signature` | `403` | 1 | The manifest does not open under the pinned key. |
2685| `bad-manifest` | `400` | 1 | The manifest's text is not a valid manifest. |
2686| `wrong-instance` | `403` | 1 | The manifest is from another instance. |
2687| `wrong-destination` | `403` | 1 | The manifest is for another receiver. |
2688| `replayed` | `409` | 1, 3 | The sequence is not greater than the high-water mark. The publisher waits for its clock to pass the mark. |
2689| `out-of-window` | `403` | 1 | The manifest was signed more than three days ago, or more than a minute ahead. |
2690| `superseded` | `409` | 1-3 | A newer manifest is staged. |
2691| `no-manifest` | `404` | 2, 3 | Nothing is staged for the sequence. |
2692| `not-declared` | `404` | 2 | The manifest declares no body with that hash. |
2693| `content-encoding` | `415` | 2 | The body was sent with a `Content-Encoding`. |
2694| `size-mismatch` | `400` | 2 | The body's size is not the declared size. |
2695| `hash-mismatch` | `422` | 2, 3 | The body's SHA-256 is not the declared one. |
2696| `unreadable` | `400` | 1, 2 | The request body could not be read. |
2697| `incomplete` | `409` | 3 | A needed body has not verified; `needs` lists what is still needed. |
2698| `bad-export` | `422` | 3 | `export.json` is not a valid export, or disagrees with the manifest. |
2699| `bad-bundle` | `422` | 3 | A bundle fails acceptance. |
2700| `stale-basis` | `409` | auth | An authorization whose `basis` is not the stored authorization's sequence. |
2701| `unsupported-version` | `410` | any | A request under `/web-export/v1/`, from a publisher older than the receiver. |
2702
2703A refused upload leaves the active export as it was.
2704
2705#### Web export publisher
2706
2707`valley-web-publish` ([`web/cmd/valley-web-publish/`](../web/cmd/valley-web-publish/)) builds an
2708export of every project on a valley host that has an effective reader at the destination, and
2709uploads it. One run is one pass.
2710
2711```sh
2712valley-web-publish --instance-repo /srv/git/valley.git --instance valley-host \
2713 --destination example.org --host valley-config.json --receiver https://example.org \
2714 --receiver-token receiver-token --principals principals.json
2715```
2716
2717- **Before a pass:** The publisher reads `--host` and checks its groups and placements with
2718 `export.CheckNames` (see [Groups and web URLs](./architecture.md#groups-and-web-urls)). If the
2719 declaration fails any check, the publisher exits with status `1` before taking the lock.
2720- **The policy path:** Every pass starts with the policy path, which is the only writer of
2721 authorizations. In order, it:
2722 1. takes an exclusive `flock(2)` lock on `<state>/authorization.lock`;
2723 2. reads the export key, or creates one on first start;
2724 3. fetches the instance repository and reads the read grants (as steps 3 and 4 of the content pass
2725 describe) into its own caches under `$XDG_CACHE_HOME/valley-web-publish/policy/`;
2726 4. for each project in a group that a read grant of any principal covers, reads `main` and
2727 `policy/read` from the project's repository beside `--instance-repo`;
2728 5. allocates the next sequence from `<state>/authorization-sequence` (written durably before use)
2729 and signs an authorization naming each project that has an effective reader, with those
2730 readers;
2731 6. releases the lock and posts the authorization to the receiver. Once the receiver stores it, the
2732 publisher records it in `<state>/authorization` as the last authorization acknowledged.
2733
2734 The policy path runs no `valley` command and reads no plan, knot, or bundle, so no project's graph
2735 holds it up. When a project's `main` or `policy/read` cannot be read, the project keeps only the
2736 readers from the last acknowledged authorization that a current grant still covers under that
2737 authorization's publication identity, and it gains no reader. The authorization then carries that
2738 acknowledged authorization's sequence as its `basis`, so the receiver stores it only while it
2739 still holds that exact sequence. With no acknowledged authorization recorded, the project keeps
2740 nothing. That check is incomplete: the authorization keeps the `checked` time of the last complete
2741 check, the publisher still signs and sends it, and the pass then fails before doing any content
2742 work. If the instance repository or registry cannot be read, the policy path fails and signs
2743 nothing. With `--policy-only`, the pass ends after the policy path and takes no other lock.
2744
2745- **Sending the authorization:** On a failure in transit, a status with no refusal, or `unreadable`,
2746 the publisher retries sending the same authorization (pausing 2 seconds and doubling the pause
2747 each time, for up to five attempts). A `replayed` or `stale-basis` refusal means the receiver
2748 holds an authorization the publisher's record does not match, such as after the publisher's state
2749 is restored from an older backup. The policy path then rechecks the policy and signs a new
2750 authorization above the refusal's `high_water` (up to three times), never resending an earlier
2751 authorization. That new authorization keeps no access an incomplete check could not confirm, and
2752 carries no `basis`. A `404` means the receiver is older than the publisher, and the pass fails
2753 with instructions to upgrade the edge first. Any other refusal fails the pass.
2754- **The content pass:** In order, the content pass:
2755 1. takes an exclusive `flock(2)` lock on `<state>/lock`, waiting for a pass that holds it;
2756 2. checks the state and the caches against `--max-storage`;
2757 3. fetches the instance repository's `main`, `refs/the-valley/projects` and `--registry-ref` into
2758 the publisher's own bare repository, `$XDG_CACHE_HOME/valley-web-publish/origin.git`, whose
2759 `origin` is `--instance-repo`. It fetches them once for the whole pass. It requires that `main`
2760 carry `policy/instance` and no `policy/valley`;
2761 4. reads the read grants at `--destination` from the identity registry in `--registry-dir` at the
2762 commit of `--registry-ref` it fetched;
2763 5. runs `valley plan --all --json` and `valley pending --all --json` in the pointer repository,
2764 `$XDG_CACHE_HOME/valley-web-publish/_pointer.git`, so the CLI discovers the projects through
2765 `refs/the-valley/projects` and the signers through `refs/the-valley/signers`.
2766 `VALLEY_KNOWN_SIGNERS` and `VALLEY_INTEGRATOR_SIGNER` are removed from the CLI's environment.
2767 Each listing must name exactly the projects the fetched `refs/the-valley/projects` lists;
2768 6. for each project that the host declaration places in a group and that a read grant of any
2769 principal covers (by project name or `"all"`), fetches `main` from the URL in the pending
2770 listing into a mirror, `$XDG_CACHE_HOME/valley-web-publish/repos/<project>.git`, and reads the
2771 project's own `policy/read` at that `main`;
2772 7. runs `valley knot show --project <project> <id> --json` in the publisher's own bare repository,
2773 for every knot of every exported project;
2774 8. builds the export with `export.Build`, and checks the state and the caches against
2775 `--max-storage` again;
2776 9. makes the bundles, each within what `--max-bundles` and `--max-storage` leave;
2777 10. uploads the export, or writes it to `--out`.
2778- **One instance:** A pass fetches the instance repository's `main` once in step 3 and reads only
2779 the instance that `--instance-repo` names (see
2780 [One pass, one instance](./architecture.md#one-pass-one-instance)).
2781- **Visibility:** A project is exported when it has an effective reader at the destination and the
2782 host declaration places it in a group. An effective reader is a principal that the project's own
2783 `policy/read` names and that a read grant at an `edge-read` boundary for `--destination` covers
2784 with the identity the policy declares, including `anyone`. `--host` gives the project its `group`.
2785 The authorization names each exported project with its effective readers. Every other project is
2786 not exported: one that no grant covers, one in no group, one with no `main`, one with no
2787 `policy/read`, one whose policy `schema/read.cue` rejects or that names another project, and one
2788 whose policy names no principal a grant covers. When a read grant names a project that has no
2789 group in `--host`, the publisher warns on `stderr` and skips reading its `policy/read`. An invalid
2790 policy or registry is reported on `stderr`. A missing or invalid registry grants nothing, so the
2791 pass builds an empty export.
2792- **Read failures:** A failure to read aborts the pass. The pass then writes no output export and
2793 uploads nothing, though it may already have written the caches it reads through. The pass fails if
2794 either schema fails to load, if the instance repository or its project list cannot be fetched, or
2795 if `valley plan` or `valley pending` lists a different set of projects than
2796 `refs/the-valley/projects` (which happens when project discovery falls back to the pointer
2797 repository alone). For any project a read grant selects, the pass also fails if the pending
2798 listing reports a read error or gives no URL, if `main` cannot be fetched, or if `git` or `cue`
2799 fails to run on its `policy/read`. When reading the registry or a project policy, any `cue`
2800 failure other than exit status 1 — failing to start, crashing, being killed, or exceeding the
2801 1-minute timeout — aborts the pass. `export.Build` also fails if the plan listing could not read
2802 an exported project, so a transient read error never drops one from the export.
2803- **Reading a policy or the registry:** Before reading any document, the pass runs
2804 `cue vet -c=false` on each schema file alone and fails if either schema does not load. It then
2805 reads documents through [`readaccess`](../readaccess/read.go). It walks the path in the commit
2806 (`policy/read/` or `--registry-dir`) with `git ls-tree` and reads each regular `*.cue` file with
2807 `git cat-file`, without a checkout. If a directory entry's name contains a slash, is `.` or `..`,
2808 or appears twice, the document is invalid and no files are copied. Otherwise, the reader writes
2809 the files into a temporary directory with no `cue.mod` (so `cue` resolves only standard-library
2810 imports), strips `CUE_*` environment variables, and runs `cue export --out json` with the schema
2811 and the files. A document is invalid if `cue` exits with status 1. After `cue export` succeeds,
2812 the Go reader decodes the exported JSON with [`exactjson`](../exactjson/exactjson.go). The decode
2813 refuses a key that is not a field of the struct it is read into, spelled exactly, a key that
2814 appears twice in one object, and a value of the wrong JSON type. So a document that redeclares a
2815 schema definition cannot add a field, such as `Grants` beside `grants`, that the reader would take
2816 for the schema's. The registry's `keys`, `external`, `genesisGovernance`, `externalGovernance` and
2817 `readScopes` are kept as raw JSON, checked only for a key repeated in one object. The reader then
2818 checks again the values it acts on. For `policy/read`, it checks the project name against the
2819 repository, the publication identity, and every reader name. For the registry, it checks every
2820 principal name and `expires` date. For each grant of an unexpired principal and of `anyone`, it
2821 checks that the boundary is declared, that `anyone`'s grants are at `edge-read` boundaries, and
2822 that a grant at another boundary names no `projects`. At an `edge-read` boundary, it checks the
2823 boundary's `destination` and the grant's project names and identities. The Go reader does not
2824 check boundary names, grant names, other boundary kinds, principal kinds, keys, or what `genesis`
2825 must be: those rest on `cue` and `schema/identity.cue`. A policy is also invalid if it has more
2826 than 32 files, a file over 64 KiB, or more than 1 MiB of exported JSON; a registry is invalid if
2827 it has more than 64 files, a file over 1 MiB, or more than 8 MiB of exported JSON.
2828- **Output bounds:** The pass holds at most 64 MiB of what a `valley` command prints on stdout, and
2829 4 MiB of the `git` output it captures. A command that prints more aborts the pass. A git bundle is
2830 not captured output: `git bundle create` writes into a file that may grow only into the room
2831 `--max-bundles` and `--max-storage` leave, and a larger bundle makes the pass send nothing.
2832 `readaccess` holds `cue vet` to 4 MiB of stdout, `cue export` to 1 MiB for a read policy and 8 MiB
2833 for the registry, and its own `git` commands to 4 MiB. `git ls-tree` output or `cue export` output
2834 past its bound makes that policy or registry invalid instead of aborting the pass. The pass keeps
2835 the first 64 KiB of what `git` and `cue` print on stderr, for its messages. What a `valley`
2836 command prints on stderr passes through to the pass's own stderr.
2837- **Bundles:** Each exported project's bundle is what `git bundle create - refs/heads/main` prints
2838 in its mirror. The pass writes it to a temporary file, and keeps it as
2839 `$XDG_CACHE_HOME/valley-web-publish/bundles/<project>/<source-tip>.bundle`. A bundle is made once
2840 per source tip, so the body a manifest declares for a tip is the same in every pass. The pass
2841 checks with `git bundle list-heads` that the bundle carries `refs/heads/main` at the source tip.
2842 Before it makes any bundle, it deletes the bundles of a project's earlier tips, the bundles of
2843 projects the export does not hold, and any partial bundle an earlier pass left.
2844- **Size bounds:** A bundle carries the whole history of `main`, as the export requires.
2845 `--max-bundles` bounds the bundles of one export together. `--max-storage` bounds the state
2846 directory, `$XDG_CACHE_HOME/valley-web-publish`, and the CLI's `$XDG_CACHE_HOME/valley` together.
2847 - Every pass checks `--max-storage` before fetching anything, before writing or replacing a
2848 repository cache, before and after each `valley` command, and after reading the valley. That
2849 final check runs even when the export digest matches the last acknowledgement and the pass skips
2850 uploading.
2851 - The pass writes each bundle only into the room that both bounds leave. When a bundle is larger,
2852 the pass stops writing at that room. It deletes what it wrote of that bundle and every bundle it
2853 made in the pass, and fails.
2854 - The publisher's repository caches and the CLI's caches borrow objects from absolute local
2855 repository paths through Git alternates. They copy no history. Before replacing each cache, the
2856 publisher checks that its complete metadata fits alongside the existing storage. It checks
2857 storage again before installing the replacement and removes partial replacements on failure.
2858 - The pointer repository is built in memory and staged within the same storage budget. Collection
2859 reserves room for the CLI's ref metadata before each command and checks storage afterward.
2860 - Before collection, the publisher reads the read grants, stages a CLI cache for each project in a
2861 group that a read grant of any principal selects, and removes all other CLI caches. During each
2862 CLI command, the cache parent directory is made read-only (`0500`). Existing caches remain
2863 usable, while project discovery and foreign knot references cannot create unstaged caches. The
2864 CLI therefore reports unselected projects as unreadable without touching their repositories, and
2865 the publisher does not export them; an unreadable repository for an unselected project never
2866 fails a pass. The next pass restores write permissions on the cache parent before staging,
2867 including after an interrupted run.
2868
2869 A pass that fails on a bound sends and writes nothing.
2870
2871- **Skipping an unchanged export:** The pass computes `Export.Digest`. It sends no content when the
2872 last acknowledgement names the same receiver, destination, and digest, is newer than `--recheck`,
2873 and the receiver's reply to the authorization reports the same `active` digest and an empty
2874 `missing` list. Otherwise, the pass posts a manifest. When the inventory's `active.digest` matches
2875 the export's digest and `needs` lists no bundle, the pass stops after step 1 of the upload. Either
2876 way, the acknowledgement records the sequence the receiver reported (the inventory's active
2877 sequence or the committed sequence). A refused upload attempt records nothing. When a receiver has
2878 lost its state, its authorization reply reports `active` as `null`, and the pass uploads the full
2879 export.
2880- **Sequence:** A manifest's sequence is the clock in Unix nanoseconds when it is signed. It must be
2881 greater than the greatest sequence the receiver is known to have accepted: the acknowledged one,
2882 or the `high_water` of a `replayed` refusal. When the clock is behind that mark by at most two
2883 minutes, the pass waits for the clock to pass it. Otherwise the pass fails, and the next pass
2884 tries again.
2885- **Retries:** A pass makes at most five upload attempts.
2886
2887 | Reply | What the pass does |
2888 | :-------------------------------------------------------------- | :------------------------------------------------------------------------------------- |
2889 | A failure in transit, a status with no refusal, or `unreadable` | Pauses, 2 seconds and then twice as long each time, and posts the same manifest again. |
2890 | `incomplete` | Posts the same manifest again and sends what the inventory still needs. |
2891 | `replayed` | Signs a new manifest once the clock has passed `high_water`. |
2892 | `superseded`, `no-manifest` | Pauses, and signs a new manifest. |
2893 | `out-of-window` | Fails the pass, naming the signing time, without a retry. |
2894 | Any other refusal | Fails the pass without a retry. |
2895
2896- **Requests:** Each body is sent with its declared byte size in `Content-Length` and without
2897 `Content-Encoding`. The HTTP client connects directly to `--receiver`, ignores proxy environment
2898 variables (`HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY`), and refuses HTTP redirects. A manifest post
2899 times out after 2 minutes, and a body upload or commit times out after 30 minutes. Any response
2900 body over 1 MiB fails the request.
2901- **`--out`:** The pass writes what it would send to `<dir>`: `authorization` (the signed
2902 authorization), `manifest` (the signed manifest), `export.json`, and `bundles/<project>.bundle`.
2903 It writes them in a temporary directory beside `<dir>` and renames it into place, so a reader
2904 never sees a partial directory. A pass with `--out` signs with the same key, allocates a sequence
2905 from the authorization counter, and neither reads nor writes the acknowledgement.
2906- **State directory:**
2907
2908 ```text
2909 <state>/lock flock(2) lock held for the whole of a content pass
2910 <state>/authorization.lock flock(2) lock held while the policy path checks the
2911 policy, allocates a sequence and signs
2912 <state>/authorization-sequence the greatest authorization sequence allocated, in decimal
2913 <state>/authorization the last authorization the receiver acknowledged, as its
2914 signed note
2915 <state>/key the export key: Ed25519, PKCS #8 in PEM, mode 0400
2916 <state>/verifier the key's verifier line, <instance>/web-export+<hash>+<base64>
2917 <state>/acknowledged valley-web-publish-acknowledged/v1: receiver, destination,
2918 digest, sequence, and when the receiver replied
2919 ```
2920
2921 An unreadable counter fails the pass rather than resetting to zero. If the counter file alone is
2922 lost, the counter starts at 1, and the receiver's first `replayed` refusal advances it above the
2923 receiver's `high_water`. If the whole state directory is lost, the export key is lost with it: the
2924 next pass makes a new key, and the receiver refuses its authorizations and manifests as
2925 `bad-signature` until the receiver pins the new verifier line.
2926
2927 The key is made under a temporary name and renamed into place, so a start that is killed leaves no
2928 key, and the next start makes one. Every pass compares the key's verifier line with
2929 `<state>/verifier`. When the line differs, for a new key or a new `--instance`, the pass writes it
2930 there and prints `valley-web-publish: the export key's verifier line is <line>`. The receiver pins
2931 that line. The private key is never printed.
2932
2933#### Web export receiver (`valley-web-receive`)
2934
2935`valley-web-receive` ([`web/cmd/valley-web-receive/`](../web/cmd/valley-web-receive/)) receives
2936uploads from `valley-web-publish` into a state directory using the three-step protocol in
2937[Web export upload](#web-export-upload), and `valley-web` serves the activated export. The flake
2938builds it as the `valley-web-receive` package with its `git` binary path fixed at build time.
2939
2940```sh
2941valley-web-receive --state /var/lib/valley-web/store --listen 192.0.2.10:8081 \
2942 --instance valley-host --destination example.org \
2943 --verifiers /etc/valley-web/verifiers --token-file /run/keys/valley-web-receiver-token
2944```
2945
2946- **Flags:**
2947 - `--state FILE` (required): The store's descriptor file. When `FILE` does not exist,
2948 `export.OpenStore` creates it and the payload directory `v2/` beside it, and completes any
2949 activation interrupted by a crash (see [Web export receiver state](#web-export-receiver-state)).
2950 It refuses a directory. The receiver is the store's only writer.
2951 - `--listen ADDR` (required): TCP listen address. Port `0` picks a free port.
2952 - `--instance NAME`, `--destination NAME` (required): Instance name and destination name required
2953 in every manifest.
2954 - `--verifiers FILE` (required): File of publisher verifier lines, one per line, with blank lines
2955 and `#` comments skipped. The publisher writes its verifier line to `<state>/verifier`. Every
2956 manifest must open under one of these keys.
2957 - `--token-file FILE` (required): File holding the bearer token required on every request, read
2958 with `export.ReadToken` (matches the file passed to the publisher's `--receiver-token`).
2959 - `--max-body SIZE` (default `1G`): Maximum declared byte size of a single body.
2960 - `--max-upload SIZE` (default `2G`): Maximum total declared byte size of the unique bodies in a
2961 single manifest.
2962 - `--max-storage SIZE` (default `8G`): Best-effort cap on disk bytes used by the state directory,
2963 including held generations, the staged upload's bodies, and a built repository for each project
2964 in the upload. A manifest whose upload would exceed this cap is refused as `too-large` at step
2965 1, and a commit whose built repositories exceed it is refused as `too-large` at step 3. The hard
2966 bound on disk usage is the filesystem the state directory lives on (see
2967 [Bounds](./architecture.md#bounds)).
2968
2969 A `SIZE` is a positive byte count, optionally suffixed with `K`, `M`, `G`, or `T` for KiB, MiB,
2970 GiB, or TiB.
2971
2972- **Running:** Once listening, the receiver prints `valley-web-receive: listening on <addr>` on
2973 `stderr`. It logs each refusal and failure with the request's method, path, and remote address,
2974 each activated sequence, and any error passed to `export.OpenStore`'s report callback. It never
2975 logs the token, and an unreadable or invalid token file or verifier file is reported without its
2976 contents. On `SIGINT` or `SIGTERM`, the receiver stops accepting new connections, gives in-flight
2977 requests 10 seconds to finish, then closes their connections, which kills the process group of any
2978 running commit's `git`. It waits up to 5 seconds more for those requests and their `git`
2979 subprocesses to exit. A commit stopped while it waits for the store lock, builds or checks
2980 repositories, or waits for body writers leaves the active export unchanged. Once a commit passes
2981 its last check of the request's context, after every repository is built and checked, it does not
2982 stop: it moves the generation into `generations/`, writes `high-water`, and swaps `current`. A
2983 receiver that exits during those steps leaves what a crash leaves: the next start activates the
2984 generation if `high-water` names it, and discards it otherwise. The receiver exits `0` after a
2985 clean stop, `1` on a runtime failure, and `2` on invalid flags. `--help` prints usage on `stderr`
2986 and exits `0`.
2987- **Routes:** The receiver checks the bearer token first on every request. Authenticated requests
2988 use four routes:
2989
2990| Route | Method | Step |
2991| :----------------------------------- | :----- | :---------------- |
2992| `/web-export/v2/authorization` | `POST` | the authorization |
2993| `/web-export/v2/manifest` | `POST` | 1, the manifest |
2994| `/web-export/v2/<sequence>/<sha256>` | `PUT` | 2, one body |
2995| `/web-export/v2/<sequence>/commit` | `POST` | 3, the commit |
2996
2997`<sequence>` is a positive decimal integer with no leading zero, and `<sha256>` is 64 lowercase hex
2998digits. Any path under `/web-export/v1/` answers `410` with `unsupported-version` and a message
2999instructing the caller to upgrade `valley-web-publish`. Any other path answers `404` with an empty
3000body, and any other method on one of these paths answers `405` with an `Allow` header and an empty
3001body.
3002
3003- **Limits:**
3004
3005| Limit | Value |
3006| :----------------------------------------- | :----------- |
3007| Upload requests running at once | 4 |
3008| Authorization requests running at once | 2 |
3009| An authorization request, from its headers | 30 seconds |
3010| Connections open at once | 32 |
3011| Request headers: time to arrive, and size | 10 s, 16 KiB |
3012| A manifest request, from its headers | 1 minute |
3013| A body request, from its headers | 30 minutes |
3014| A commit request, from its headers | 30 minutes |
3015| An idle connection | 1 minute |
3016
3017An upload request beyond 4 running at once, or an authorization request beyond 2, answers `503` with
3018`Retry-After: 5` and an empty body. Upload and authorization slots are counted separately, so
3019uploads that fill all 4 upload slots still leave room for an authorization. A body upload arriving
3020while another request is already staging the same body of the same upload also answers `503` with
3021`Retry-After: 5`. A connection beyond 32 open at once waits in the listen queue. Unauthenticated
3022requests take no request slot. `OPTIONS *` is handled like any other request, answering `401`
3023without the token and `404` with it. A manifest or commit request waiting for the store lock stops
3024waiting when its time limit expires or its client disconnects. Any internal failure that is not a
3025refusal answers `500` with an empty body; the publisher retries both `500` and `503` as failures in
3026transit.
3027
3028- **The staged upload:** The receiver tracks the newest staged upload in memory. A body or commit
3029 request for a newer sequence is refused as `no-manifest`, and one for an older sequence is refused
3030 as `superseded`. A body request still running when a newer manifest discards its upload is stopped
3031 and refused as `superseded`. A body request still running when a commit removes its upload's
3032 bodies, or arriving after a commit has already activated that upload, is refused as `no-manifest`.
3033 After a restart, the receiver holds no staged upload in memory until the publisher signs and posts
3034 a new manifest.
3035
3036- **The container image:** The `valley-web-image` package is a container image built with
3037 `dockerTools.buildLayeredImage`. It holds `valley-web` and `valley-web-receive` at `/bin`, and the
3038 `git` both run. Each program runs `git` at the Nix store path it was built with, which the image
3039 holds. The image puts no `git` at `/bin/git`.
3040
3041 | Path or setting | Value |
3042 | :--------------------- | :----------------------------------------------------------------- |
3043 | `/etc/passwd` | `valley-web-receive` (uid 990) and `valley-web` (uid 991), gid 990 |
3044 | `/etc/group` | `valley-web` (gid 990) |
3045 | `/var/lib/valley-web` | The image's one volume: owner 990, group 990, mode `0750` |
3046 | Default user | `valley-web` |
3047 | Entrypoint and command | None: each container names `valley-web` or `valley-web-receive` |
3048
3049 `nix build .#valley-web-image` writes the image as a gzipped tar archive that `docker load` and
3050 `podman load` read. The image tag is its Nix store path hash.
3051
3052#### Web export receiver state
3053
3054The receiver keeps every accepted export as a generation in one store (`export.OpenStore`). Both
3055programs take the store's descriptor file as `--state`, and the store keeps its payloads in `v2/`
3056beside the descriptor:
3057
3058```text
3059<dir>/store the descriptor: one line, the-valley/web-store/v2
3060<dir>/v2/lock flock(2) lock serialising Stage, Activate, Prune and OpenStore
3061<dir>/v2/authorization.lock flock(2) lock serialising Authorize and a prune's deletions
3062<dir>/v2/serving.lock flock(2) lock: shared by valley-web from its last check of the
3063 authorization to a response's headers, exclusive while
3064 Authorize renames the authorization into place
3065<dir>/v2/authorization the newest authorization admitted, as its signed note
3066<dir>/v2/high-water the greatest content sequence accepted
3067<dir>/v2/current symlink to generations/<sequence>
3068<dir>/v2/generations/<sequence>/ one generation: export.json and repos/<project>.git
3069<dir>/v2/staging/<sequence>/ one upload until it is committed:
3070 bodies/<sha256> verified bodies written by StageBody
3071 export.json moved from bodies/ during Activate
3072 tmp/<project>.git a repository being built
3073 repos/<project>.git a repository once accepted and synced
3074<dir>/v2/trash/ generations and repositories renamed away before deletion
3075```
3076
3077- **The descriptor:** `OpenStore` refuses a `--state` path that is a directory or a file whose
3078 contents differ from `the-valley/web-store/v2`. When the descriptor does not exist, `OpenStore`
3079 creates `v2/` first and writes the descriptor last, durably. `OpenReadOnly` enforces the same
3080 checks and requires both the descriptor and `v2/` to exist. Binaries from the first store layout
3081 expect a directory for `--state`: a first-layout `valley-web` exits `1` reporting that the
3082 descriptor is not a directory, and a first-layout `valley-web-receive` exits `1` when it cannot
3083 create a directory there. Pointed at `v2/`, first-layout binaries find no `active` symlink and no
3084 `exports/` directory, so they serve nothing from the store. In addition, each generation holds
3085 repositories only for projects that the authorization named when the generation was built, so a
3086 rollback cannot expose unauthorized repositories.
3087- **Nothing outside the store:** The receiver writes and deletes nothing outside the descriptor and
3088 `v2/`. `OpenStore` refuses a `--state` that is a directory before it creates anything. State of
3089 the first store layout in the descriptor's directory stays there until the operator deletes it
3090 (see [Upgrading the edge and the host](#upgrading-the-edge-and-the-host)).
3091
3092- **Activation (`Store.Activate`):** Holding an exclusive `flock(2)` on `<dir>/v2/lock`, `Activate`
3093 runs these steps in order:
3094 1. Refuse the upload if its `sequence` is not greater than `high-water` (`replayed`), if a newer
3095 manifest is staged (`superseded`), or if any needed body is missing (`incomplete`, with
3096 `needs`).
3097 2. Move `export.json` from `bodies/<sha256>` to `<staging>/<sequence>/export.json`, set its mode
3098 to `0644`, and check it against the manifest with `Manifest.CheckExport`. If `CheckExport`
3099 fails, remove `export.json` from staging so `Inventory` lists it as needed again.
3100 3. Build `repos/<project>.git` for each project named in the stored authorization that is not
3101 already in `repos/`, and remove any staged repository for any other project. For each project
3102 to build, it removes any leftover `tmp/<project>.git`, then builds the repository in
3103 `tmp/<project>.git` from the staged bundle with `AcceptBundle` or from the active generation's
3104 repository at the same `source_tip` with `CarryRepo`. It sets the file and directory modes in
3105 `tmp/<project>.git` (see **Modes** below), syncs every file and directory to disk, and renames
3106 the repository to `repos/<project>.git`. If `AcceptBundle` fails, the staged bundle is removed
3107 from `bodies/` so `Inventory` lists it as needed again. A build interrupted by a crash stays in
3108 `tmp/` and is rebuilt on the next commit.
3109 4. Stop any in-flight body writers for the upload (`Store.Writer`) and wait until each has closed
3110 and removed its partial file. Remove `bodies/` and `tmp/`, and verify that the staging
3111 directory holds only `export.json` and `repos/`, with a repository at `refs/heads/main` =
3112 `source_tip` for each project named in the authorization and no others.
3113 5. Set the mode of `repos/` and the staging directory to `0755`. Sync `export.json`, `repos/`, and
3114 the staging directory, rename `<staging>/<sequence>` to `generations/<sequence>`, and sync
3115 `generations/` and `staging/`.
3116 6. Write `<sequence>\n` durably to `high-water`.
3117 7. Swap `current` by renaming a new symlink (`generations/<sequence>`) over it.
3118 8. Sync `v2/`, sweep inactive generations that no reader holds, sweep staging directories with
3119 `sequence <= high-water` and `trash/`, and prune the repositories of any projects that the
3120 authorization withdrew while the commit ran.
3121- **Durability:** Every file and directory of a generation is synced to disk before `high-water`
3122 names its sequence. Git's `core.fsync=all` syncs what `git fetch` writes, but not the files
3123 `git init` creates beforehand, so `Activate` recursively syncs each repository before renaming it
3124 into `repos/`.
3125- **Modes:** The store sets the modes of the paths below explicitly, independent of the receiver's
3126 umask (see [Reading the state directory](./architecture.md#reading-the-state-directory)).
3127 - `staging/`, each upload directory inside it, and the upload's `bodies/` and `repos/` have mode
3128 `0700`.
3129 - `v2/` and `generations/` have mode `0755`. Inside each generation, every directory has mode
3130 `0755` and every file has mode `0644`, or `0444` when git wrote the file read-only.
3131 - The descriptor, `high-water`, and `authorization` have mode `0644` regardless of the umask. The
3132 store creates `trash/` with mode `0755`, the locks with mode `0644`, and each staged body with
3133 mode `0600`. The receiver's umask can narrow these creation modes.
3134 - `Activate` leaves any repository already in an upload's `repos/` unchanged. Each repository that
3135 the receiver builds gets the generation modes before it enters `repos/`. A repository staged by
3136 an earlier build of the receiver keeps the modes that build gave it. Whether any upload holds
3137 such a repository is a `deployment choice`.
3138 - The mode of the descriptor's parent directory is a `deployment choice`: `OpenStore` creates the
3139 directory if needed and leaves its mode unchanged. That directory's mode decides who can reach
3140 the store.
3141- **Reading (`Store.Open`):** A reader calls `Store.Open` once per request. `Open` resolves
3142 `current` and holds a shared `flock(2)` (`LOCK_SH`) on `generations/<sequence>` until the caller
3143 releases it (`export.ErrNoExport` if no export has been activated yet). Because a request serves
3144 everything from that single opened generation, a concurrent activation never mixes two generations
3145 in one response. An old generation is deleted only when a sweep can acquire a non-blocking
3146 exclusive `flock(2)` (`LOCK_EX | LOCK_NB`) on its directory, which fails while any reader holds
3147 it. Under that exclusive lock, the sweep renames the generation into `trash/` before removing its
3148 files. `Store.Prune` takes the same exclusive lock on the active generation before it renames a
3149 withdrawn project's repository into `trash/`.
3150- **Recovery (`export.OpenStore`):** When `OpenStore` opens the store, it locks `v2/lock`, recovers
3151 any interrupted activation, sweeps leftover directories, and prunes withdrawn repositories:
3152 - A crash before `high-water` is written leaves the previous generation at `current`, and the next
3153 `OpenStore` deletes the unactivated generation and any staging directory with
3154 `sequence <= high-water`.
3155 - A crash after `high-water` is written and before `current` is swapped is finished by the next
3156 `OpenStore`. Before swapping `current` to `generations/<high-water>`, `OpenStore` checks that
3157 generation: `export.json` must pass `export.Decode`, each project named in the stored
3158 authorization must have a repository, and each repository must pass `git fsck` and hold
3159 `refs/heads/main` at its `source_tip` and no other ref. If the check passes, `OpenStore` swaps
3160 `current` to that generation and syncs `v2/`.
3161 - If the generation fails the check, `OpenStore` passes the error to `report` and does not
3162 activate the generation. The previous generation keeps serving, the sweep deletes the damaged
3163 generation, and the publisher's next manifest replaces it.
3164 - A repository fails `git fsck` only when `git` exits on its own with a non-zero status and its
3165 output names a problem (`error: `, `missing `, `broken link from `,
3166 `fatal: not a git repository`, or `fatal: ... is corrupt`). Any other `git fsck` failure means
3167 the check did not finish: `git` was killed by a signal, failed to start, or exited without
3168 naming a problem (as when it runs out of memory). `OpenStore` then returns the error without
3169 running the sweep and deletes nothing, so the receiver can try again.
3170- **Fixture (`exporttest`):** Package `exporttest` builds a complete, valid export from a synthetic
3171 valley with a public project `app` and a hidden project `site`. It yields the export directory,
3172 the bundles, the signed manifest, and its verifier key, so tests for the publisher, the receiver,
3173 and the web server share the same bytes.
3174
3175#### Upgrading the edge and the host
3176
3177This release uses a v2 store layout and upload protocol and reads nothing from the first version.
3178Upgrading starts the edge on a new, empty store, and the publisher uploads the full export on its
3179next pass. Upgrade in this order:
3180
31811. **The edge first.** Upgrade `valley-web-receive` and `valley-web`, passing `--state <dir>/store`
3182 to both, where `<dir>` is the state directory. The receiver NixOS module sets this path
3183 automatically. Stop the first layout's receiver, then start the new one. On its first start, the
3184 receiver creates the descriptor and `v2/` and touches nothing else in `<dir>`. Until the host is
3185 upgraded, the edge serves nothing (every page shows "Nothing published yet") and the old
3186 publisher on the host fails each pass with `unsupported-version`.
31872. **Then the host.** Upgrade `valley-web-publish`. On its next pass, the publisher sends an
3188 authorization and then uploads the full export, because the receiver's authorization reply
3189 reports no active export. To publish immediately, run
3190 `systemctl start valley-web-publish.service`.
3191
31923. **Then delete the first layout by hand.** Once the new receiver runs, delete the first layout's
3193 state from `<dir>`, beside the descriptor: `active`, `high-water`, `exports/`, `staging/`,
3194 `trash/` and `lock`. On NixOS:
3195
3196 ```sh
3197 sudo sh -c 'cd /var/lib/valley-web && rm -rf active high-water exports staging trash lock'
3198 ```
3199
3200 Leaving them is harmless: the first layout held public projects only, because its exports carried
3201 nothing else, and the new binaries never read them. The receiver deletes nothing outside its
3202 descriptor and `v2/`, so this step is the operator's.
3203
3204If the host is upgraded before the edge, each pass fails when sending its authorization: the old
3205receiver answers `404`, and the publisher reports that the edge must be upgraded first. The edge
3206continues serving its existing export until upgraded.
3207
3208Rolling the edge back to first-layout binaries serves nothing from the v2 store: those binaries
3209refuse the descriptor file, and find no first-layout state in `v2/`. Pointed at `<dir>` before step
32103, they serve the first layout's last export, which held public projects only. After step 3, a
3211rolled-back deployment serves nothing until a first-protocol publisher uploads a full export to a
3212first-layout directory.
3213
3214#### Web server (`valley-web`)
3215
3216`valley-web` serves the active export in a receiver's store over HTTP, as the stored authorization
3217allows. For the projects the request's reader may read, it serves a projects page and a knots page
3218of all of them. For each of those projects, it serves the project's own knots page, one page per
3219knot, and a source browser over `main`, including a gzipped tar archive for each reachable commit.
3220When started with `--origin`, `valley-web` serves a request that carries a valid session cookie as
3221that session's principal, and serves every other request as `anyone` (see
3222[Reader sessions](#reader-sessions)). Without `--origin`, it serves every request as `anyone`.
3223Package `server` of the `web` module ([`web/server/`](../web/server/)) implements the HTTP handler,
3224and [`web/cmd/valley-web/`](../web/cmd/valley-web/) is the command. The flake builds it as the
3225`valley-web` package.
3226
3227```sh
3228valley-web --state /var/lib/valley-web/store --listen 127.0.0.1:8080 --origin https://example.org
3229```
3230
3231- **Flags:** `--state` and `--listen` are required.
3232 - `--state FILE` names the receiver's existing store descriptor. `valley-web` opens the store
3233 read-only with `export.OpenReadOnly` (see
3234 [Reading the state directory](./architecture.md#reading-the-state-directory)). It refuses a
3235 directory.
3236 - `--listen ADDR` sets the TCP address to listen on. Port `0` picks a free port.
3237 - `--origin URL` sets the public HTTPS origin readers reach, formatted as a browser sends it in an
3238 `Origin` header: `https://`, a lowercase host, and a port only when the port is not `443`. Any
3239 other `--origin` value exits `2`. Every `POST` to a reader page must carry this `Origin` header.
3240 Before opening the browser state, `valley-web` marks its process non-dumpable with
3241 `prctl(PR_SET_DUMPABLE, 0)` and refuses to start if that call fails (such as outside Linux). It
3242 then opens `browser/` beside the store descriptor, and refuses to start if that directory is
3243 missing, is a symbolic link, is owned by another user, grants any group or other permissions, or
3244 is locked by another running `valley-web`.
3245- **Running:** Once listening, `valley-web` prints `valley-web: listening on <addr>` on `stderr`. It
3246 logs runtime errors on `stderr`. On `SIGINT` or `SIGTERM`, it stops accepting new requests and
3247 gives in-flight requests up to 5 seconds to finish. It exits `0` after a clean stop and `1` on a
3248 runtime failure. On invalid flags, it prints usage on `stderr` and exits `2`. `--help` prints
3249 usage on `stderr` and exits `0`.
3250- **Routes:** The server answers `GET` and `HEAD`. Any other method answers `405` with
3251 `Allow: GET, HEAD`. When `--origin` is set, `/-/redeem` and `/-/logout` also answer `POST`, and
3252 their `405` responses carry `Allow: GET, HEAD, POST`. `/-/session` answers only `GET` and `HEAD`.
3253
3254| Route | Page |
3255| :------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------- |
3256| `/` | `302` redirect to `/-/projects`, or to the root tree of the one project the reader may read |
3257| `/-/projects` | The projects page: every project the reader may read, by group |
3258| `/-/knots` | The knots page of every project the reader may read |
3259| `/<group>/` and `/<group>` | The projects page of one group: the group's projects the reader may read |
3260| `/<group>/<project>/` and `/<group>/<project>` | `302` redirect to the root tree at the project's `source_tip` |
3261| `/<group>/<project>/knots` | The project's knots page |
3262| `/<group>/<project>/knots/<id>` | One knot |
3263| `/<group>/<project>/source/` | `302` redirect to the root tree at the project's `source_tip` |
3264| `/<group>/<project>/source/tree/<commit>/<path>/` | One directory and its README |
3265| `/<group>/<project>/source/blob/<commit>/<path>` | One file |
3266| `/<group>/<project>/source/log/<commit>` | Up to 50 commits of history ending at `<commit>`, newest first |
3267| `/<group>/<project>/source/log/<commit>?from=<ids>` | The next older page of that history, starting from the commits in `<ids>` |
3268| `/<group>/<project>/source/archive/<commit>.tar.gz` | The tree of `<commit>` as a gzipped tar archive, sent as an attachment |
3269| `/<group>/<project>/source/archive/main.tar.gz` | `302` redirect to the archive of the project's `source_tip` |
3270| `/<group>/<former name>` and `/<group>/<former name>/…` | `308` redirect to the same path under `/<group>/<project>` |
3271| `/<alias>` and `/<alias>/…` | `308` redirect to the same path under the group's name, or under `/<group>/<project>` |
3272| `/-/redeem` and `/-/logout` | Reader sign-in and sign-out pages, served only when `--origin` is set (see [Reader sessions](#reader-sessions)) |
3273| `/-/session` | JSON reporting the credential ID of the current session's link, served only when `--origin` is set |
3274| `/-/…` | The server's own routes: `/-/projects`, `/-/knots` and the reader routes. Every other path under `/-/` answers `404` |
3275
3276- **Groups:** `<group>` is the group's `name` in the export, and `<project>` is the project's web
3277 `name` in the export. Routes match the group's `name` and the project's web `name` rather than
3278 their identifiers. Names are matched in exact case. A project in the export without a group has no
3279 route. `/<group>` and `/<group>/` list the group's projects that the reader may read. When a group
3280 has none, `/<group>` and `/<group>/` answer `404`, the same as a path that does not exist, so the
3281 page never shows that a group exists. The server reads a path's first segment as an alias before
3282 it reads it as a group's `name`. If a group's `name` were also an alias, the alias would win.
3283 Package `export` refuses an export in which a group's `name` and an alias collide.
3284- **Aliases and former names:** A group's alias redirects to the same path under the group's `name`,
3285 and a project's short alias redirects to the same path under `/<group>/<project>`. A project's
3286 former name redirects to the same path under `/<group>/<project>`. These alias and former-name
3287 redirects are permanent (`308`) with no response body. Its `Location` header preserves the
3288 remainder of the path and the raw query string as sent, including percent-escapes, dot segments,
3289 and a trailing `?` with an empty query.
3290- **Landing:** When the reader may see exactly one project, `/` redirects to the root tree at that
3291 project's `source_tip`. When the reader may see more than one project, or none, `/` redirects to
3292 `/-/projects`. Because the target depends on the reader's view, the redirect carries the same
3293 headers and passes the same final authorization check as any rendered page.
3294- **Reserved paths:** Every path other than `/` and the server's own routes under `/-/` starts with
3295 a group's name or an alias. Names match `^[a-zA-Z0-9][a-zA-Z0-9._-]*$`, which always starts with a
3296 letter or digit. A group or a project may be named `source`, `knots`, `web-export`, or
3297 `robots.txt` and is served on every route (see
3298 [Groups and web URLs](./architecture.md#groups-and-web-urls)).
3299
3300- **Authorization on every request:** Each request reads `v2/authorization` when it arrives, and
3301 re-parses it only when its bytes have changed. It serves only the projects its reader may see (see
3302 **One project-view filter**). Once the response is rendered, the request takes `v2/serving.lock`
3303 shared, reads the authorization again, and writes the response's headers (including for redirects)
3304 before it releases the lock and writes the body. A request waits for the lock only until its
3305 15-second deadline, or until its reader goes away. It then writes nothing it rendered: it answers
3306 `503`, or nothing to a reader that went away. If the authorization bytes changed, the server
3307 discards the rendered response and renders it again under the new authorization (up to three
3308 renders total, after which the request answers `503`). The receiver renames a new authorization
3309 into place under the same lock, exclusively, and replies only after it releases it. So a response
3310 whose headers are written after the receiver replies was checked against the new authorization. A
3311 response whose headers were written before continues to completion. A missing, unreadable, or
3312 invalid authorization serves no project: every `GET` and `HEAD` answers `503` with the page
3313 "Nothing published yet", and any other method answers `405`.
3314- **One project-view filter:** Every view is built through a single filter that takes the export,
3315 the authorization, and the request's reader, and returns the projects that reader may see. A
3316 reader sees a project when it belongs to one of the export's groups and the authorization grants
3317 read access to `anyone` or to the reader's own principal under the project's identity in the
3318 export. The server copies those projects for the reader, removing derived information about knots
3319 in other projects (see [Each reader's view](./architecture.md#each-readers-view)). From those
3320 copies it builds the projects page, the group pages, the knots pages, navigation, groups,
3321 cross-project references, the redirect from `/`, all alias and former-name redirects, and the
3322 source routes. Any project excluded by the filter answers `404` as if it did not exist and takes
3323 no `git` slot. A group with no remaining project has no alias.
3324- **One generation per request:** Each request renders its entire response from one generation's
3325 export. A source route that reads a repository opens the active generation with `Store.Open` after
3326 taking a `git` slot, and releases the generation once rendering finishes, before writing the
3327 response. If another generation has become active before `Store.Open`, the request releases its
3328 `git` slot, generation, and index, and starts again from the new generation. Activating a new
3329 export during a request does not change that request's response, and a sweep cannot delete the old
3330 generation until the request releases it. Before the first activation, every route answers `503`.
3331- **One read per generation:** Requests waiting for the same generation share one read, and the
3332 server keeps the newest generation's decoded `export.json`. A read that every waiting request
3333 abandons is cancelled, so a later request may read that generation again, as it may after the
3334 reserved slot's cancellation described below. A request opens its generation on disk only after
3335 the server has decoded that generation.
3336 - Each read runs in its own worker. The worker opens the active generation, holds it while reading
3337 and decoding `export.json`, and releases it when the read finishes. A request waiting for a read
3338 holds no generation.
3339 - At most 2 reads run at once (`server.MaxLoads`), using two worker slots: one general slot and
3340 one slot reserved for anonymous requests. A worker starts only when a waiting request takes a
3341 worker slot. The server never queues a read without a waiting request.
3342 - The reserved slot runs a read only while at least one anonymous request waits for that read, so
3343 reads that only named readers wait for use the general slot alone. If the last anonymous request
3344 stops waiting for a read on the reserved slot while named readers still wait for it, the read
3345 moves to the general slot when that slot is free. When the general slot is busy, the server
3346 cancels the read, frees the reserved slot at once, and lets the named readers wait for the
3347 general slot within their own deadlines. A stopped worker holds no slot while it exits.
3348 - A request stops waiting for a read if its reader disconnects or its 15-second deadline runs out.
3349 When no request is left waiting for a read, the worker stops reading and the server discards the
3350 unfinished read.
3351- **Indexes:** After decoding a generation's export, the server builds an index, including the knots
3352 page's structure, for each view it serves: one generation, one revision of the authorization, and
3353 one set of projects. Readers who see the same projects share one index. Each index is built in its
3354 own worker without holding a loader slot.
3355 - Anonymous requests have 2 index places of their own for the `anyone` view: the current
3356 generation's index and the one replacing it or being replaced. No named reader's request ever
3357 takes an anonymous place.
3358 - Named readers' requests share 8 index places (`server.MaxViews`), counting cached, building, and
3359 pinned indexes. A named reader who sees no more than `anyone` serves from the same index object
3360 as anonymous requests, while occupying a named place for it.
3361 - While pinned by active or waiting requests, an index occupies a place in each pool that has
3362 requests pinning it, and releases a pool's place as soon as only the other pool's requests pin
3363 it. When the last request unpins an index, the index keeps the single place of that last
3364 request's pool. The server evicts only an index that no request is currently serving from.
3365 - When all 8 named places are full, named readers' requests wait while anonymous requests do not.
3366 An anonymous request for the current generation always gets the current `anyone` index without
3367 waiting on any named reader's request.
3368 - When no request remains waiting for an index that is still building, the server cancels the
3369 build. The cancelled build keeps its place until its worker exits, and no new request joins it,
3370 so at most 10 workers build indexes at once.
3371 - A request waiting for its view's index to build, or for a free place in its pool, waits among
3372 the 64 view-waiting places (`server.MaxLoadWaiting`, at most 48 for named readers under
3373 `server.MaxNamedWaiting`) and answers `503` once its 15-second deadline runs out.
3374- **Projects page:** `/-/projects` lists every project the reader may see, grouped under its group's
3375 `name`. Groups and their projects follow the export's order. Each group's name links to the
3376 group's page. Each project shows `<group>/<project>`, which links to its root tree at
3377 `source_tip`, and a `knots` link to its knots page. Below the list, an `all knots` link goes to
3378 `/-/knots`. When the reader may see no project, the page has no list and no `all knots` link. It
3379 says only "No project is readable here." and answers `200`. A group's page, `/<group>/`, shows the
3380 same project entries for that group alone. Its group heading does not link to itself.
3381- **Navigation:** Pages rendered from an export show a `projects` link to `/-/projects` and the
3382 freshness line. Pages rendered for a reader with a valid session also show `Sign out`. Every page
3383 of one project also has a project header. The header names the project as `<group>/<project>` and
3384 has two tabs: `source`, which links to the project's root tree at `source_tip`, and `knots`, which
3385 links to `/<group>/<project>/knots`. The tree, file, and history pages mark the `source` tab with
3386 `aria-current="page"`. The project's knots page and each of its knot pages mark the `knots` tab
3387 with `aria-current="page"`.
3388- **Knots pages:** `/-/knots` shows the knots across every project the reader may see, and
3389 `/<group>/<project>/knots` shows the knots of one project. A project's own knots page shows only
3390 that project's knots, ready changes, and knots in flight. Its knots' references into other
3391 projects render as on every other page (see **References into unpublished projects**). Both pages
3392 have the same four sections, in this order:
3393 1. **Waiting on you:** Always empty.
3394 2. **In flight:** The export's `in_flight` knots, showing who claims each knot and how long ago.
3395 Beside them, a card titled "Ready changes — order not assessed" lists the export's `changes`.
3396 Each change shows its handle, its active version's title, whether an integration request
3397 approves it, and the integrator's last decision.
3398 3. **Paths:** One card per knot whose children wait on one another, grouping those children into
3399 numbered stages. A child's stage is one after the latest stage of any sibling in its
3400 `blocked_by`, whether or not that sibling is done. Children with no blocker order between them
3401 share a stage. Abandoned children are left out.
3402 4. **Milestones:** Each root knot with the tree of knots under it, ordering children at each level
3403 by state. Knots that have no parent and are not roots appear under "Unfiled". A tree shows at
3404 most 32 levels of knots (`server.MaxPlanDepth`). If a knot on the 32nd level has children, its
3405 row notes that there is more on its page. Each knot appears once in a project's trees. A
3406 milestone's count includes every knot under it, at any depth.
3407
3408 A knot whose `state` is `ready` is labeled "free to start". The legend defines this as an open,
3409 unclaimed, unblocked outcome or bug. The page's single inline script runs the milestone filters.
3410 Without the script, every knot shows and the trees still open and close.
3411
3412- **Freshness:** Every page shows the export's `collected` time alongside when the policy was last
3413 checked (the authorization's `checked` time and its age when the request is served). A page is
3414 marked `stale` when that policy check is more than five minutes old (`server.StaleAfter`). Every
3415 pass sends an authorization, so a pass whose policy check is complete advances the policy check
3416 time even when no content changed. An incomplete check keeps the `checked` time of the last
3417 complete one. The `collected` time continues to show the age of the exported content.
3418- **Knot page:** A knot page shows the knot's type, status, state, and fields, the chain of parents
3419 above it, and links to the knots that block it, the knots it blocks, and its children. The parent
3420 chain starts at the project's knots page, names the nearest 32 parents (`server.MaxPlanDepth`),
3421 and marks any parents above them with `…`. The body and each comment render as escaped
3422 preformatted text. A comment with an `edited` timestamp is marked "edited" and shows its `edited`
3423 time and `edited_by`.
3424- **References into unpublished projects:** A page never shows the name of a project the reader may
3425 not see, or the text of a reference into one, whether the export omits that project or holds it
3426 for another reader. Every such reference is replaced with fixed text and no link:
3427 - A `blocked_by` entry or a `<project>:<id>` entry in `target` that names a knot in an unpublished
3428 project is shown as "a knot in an unpublished project".
3429 - A `target` that names only an unpublished project is shown as "an unpublished project". A
3430 `target` is always a project's name or `<project>:<id>`, never a bare knot ID in the knot's own
3431 graph, so a project whose name looks like a knot ID (such as `oc-1234567`) is still treated as a
3432 project and hidden the same way.
3433 - A `changes` link `valley:<project>/<change ID>` into an unpublished project is shown as "a
3434 change in an unpublished project".
3435 - `graduated_into` is the ID of an outcome or question in the knot's own graph, which the reader
3436 sees, and is shown as written.
3437 - Before looking up any project, the server checks that the entire reference value matches a shape
3438 its field allows. A value that fails this shape check — even one that begins with a visible
3439 project name, such as `app:site:oc-b000001` or `valley:app/site/secret` — names no project the
3440 reader may see and is shown as unpublished with none of its text: a `target` as "an unpublished
3441 project", a `blocked_by` entry, `waiting_on` entry, or `graduated_into` value as "a knot in an
3442 unpublished project", and a change link as "a change in an unpublished project". In the reader's
3443 copy of the knot, any such entry is removed from `waiting_on`, `cleared_by_ending`, `dangling`,
3444 and `unresolved`, and an entry removed from `waiting_on` counts as a hidden blocker.
3445 - On the knots page, a tree row's "waits on" chip lists the knots from `waiting_on` that the
3446 reader may see. When the knot also waits on knots the reader may not see (`waiting_on_hidden`,
3447 or a reference removed from `waiting_on`), the chip ends with "a knot in an unpublished project"
3448 once, regardless of how many hidden knots block it. A blocked knot with no blocker the reader
3449 may see shows "waits on a knot in an unpublished project" alone.
3450
3451 A `blocked_by` entry that names a missing knot in a project the reader may see still shows its
3452 reference text. It is marked "not found in its graph" when its edge is `dangling`, and "not found"
3453 otherwise.
3454
3455- **Source browser:** The server reads each generation's repositories by running `git` subprocesses
3456 through `export.Git` and `export.GitStream`. It passes `git` only verified object IDs, never text
3457 from the request.
3458 - A source route serves `<commit>` only when it is a full object ID with the same length as the
3459 project's `source_tip` and `export.Reachable` finds it reachable from `source_tip`. Anything
3460 else answers `404`, including an unreachable commit, a tree or blob ID, an abbreviated ID, a ref
3461 name such as `main`, and the first 40 hex digits of a SHA-256 commit.
3462 - The server resolves `<path>` from the commit's root tree one segment at a time with
3463 `git ls-tree` on tree object IDs, without `--long`. A path answers `404` if it is deeper than 64
3464 segments (`server.MaxDepth`) or if any segment is empty, `.`, `..`, or contains `/` or NUL. The
3465 directories along `<path>` share one 4 MiB budget of `git ls-tree` output (`server.MaxRead`),
3466 read up to the entry each segment names; a path whose entry lies past that 4 MiB budget answers
3467 `404`.
3468 - Every source link names the group and the project, a full commit ID, and a path.
3469 - The server streams `git` output through `export.GitStream` and reads at most 4 MiB of a
3470 directory listing or history page (`server.MaxRead`). Once `git` prints more than 4 MiB, the
3471 server stops `git` and waits for it to exit.
3472 - A directory page lists at most 1,000 entries (`server.MaxEntries`), directories first. If a
3473 directory's `git ls-tree` output exceeds 4 MiB, the page lists only the entries from the first 4
3474 MiB and notes that the listing is partial. Below the listing, the page shows the directory's
3475 README: `README.md`, `README`, or `README.txt` in that order, or else the first file named
3476 `readme` in any case with any extension.
3477 - A Markdown file, one whose name ends in `.md` or `.markdown` in any case, renders as a document,
3478 and so does a directory's Markdown README. Each heading has an `id` made by GitHub's rule and a
3479 self-link. A heading whose text gives an empty `id` by that rule, such as `# !!!`, has no `id`
3480 and no self-link. A document with at least four headings at levels 2 to 4 starts with a
3481 collapsible Contents list. A relative link goes to the target's page at the same commit, with
3482 its fragment kept. The file page links to `?plain=1`, which shows the file as plain text, as
3483 below, and links back to the rendered view. On any other file, `?plain=1` changes nothing.
3484 - A link in a document is written only for an `http` or `https` destination that names a host
3485 (`https://…`), a `mailto` destination, or a relative one. Any other destination renders as the
3486 link's text, such as `https://`, which names no host. So does any destination that holds a
3487 backslash, such as `http\x/../y`, whether the file writes the backslash as itself, as the escape
3488 `\\` or as the entity `&#92;`.
3489 - A rendered document is at most 2 MiB (`server.MaxShown`). A document that would be larger shows
3490 the blocks that fit, and the page notes that only its start is shown. In a document, block
3491 quotes and list items nest at most 32 deep (`markdown.MaxDepth`), and so do emphasis,
3492 strikethrough, links, images and autolinks within a block. Deeper, a quote's or an item's marker
3493 and emphasis's delimiters render as text, and a link, an image or an autolink renders as its
3494 text alone. A table has at most 64 columns (`markdown.MaxTableColumns`), and a document's tables
3495 hold at most 100,000 cells between them (`markdown.MaxTableCells`). Rows past that limit render
3496 as a paragraph.
3497 - A document holds at most 65,536 blocks (`markdown.MaxBlocks`), counting quotes, lists and list
3498 items. The line that would pass that limit, and the input after it, render as one block of
3499 preformatted text. A document's inline content takes at most 262,144 nodes
3500 (`markdown.MaxInlineNodes`): one for each run of text, code span, line break, run of `*`, `_` or
3501 `~`, bracket and autolink, and one for each emphasis or link they make. The block that passes
3502 that limit, and every block after it, renders as its escaped text alone. Within a block, at most
3503 4,096 `[` or `![` wait for their `]`, and a `[` past that is text. A link label holds at most
3504 999 characters. A render looks up at most 4 MiB of labels, and a reference past that renders as
3505 text. One render allocates less than 128 MiB.
3506 - A blob route whose path names a directory redirects (302) to the tree route at the same commit
3507 and path. A tree route whose path names a file redirects (302) to the blob route.
3508 - A file page shows the file as escaped text with numbered lines, each with an anchor `#L<n>`. It
3509 shows at most 10,000 lines (`server.MaxLines`). It stops at the line that would take the escaped
3510 text and row markup past 2 MiB (`server.MaxShown`). When the file is longer, the page says "The
3511 page stops at line `<n>` of `<total>`." A README shows at most 10,000 lines and 2 MiB of escaped
3512 text, and notes when it is shown in part.
3513 - A file larger than 1 MiB (`server.MaxFile`) is not read. A file that contains a NUL byte or is
3514 not valid UTF-8 is not shown, and the page says it is binary. A symbolic link shows its target
3515 path and is not followed. A submodule is listed with its commit ID and has no link.
3516 - A log page shows the first 1 KiB of each commit's subject and author name. If a page's commits
3517 exceed 4 MiB of `git log` output, the page ends at the commit cut off by the 4 MiB bound,
3518 showing as much of that commit as was read. The page notes that it ends early and links to the
3519 older commits after it.
3520 - A log page lists commits in `git log --date-order`, which always places a child before its
3521 parents. Each page asks `git` for 50 commits, regardless of how far back in history the page
3522 starts. Its "Older" link points to the same route with `?from=` naming the frontier of remaining
3523 commits: the retained parents of the commits shown on the page, plus the commits the page
3524 started from, minus the commits shown on the page (see
3525 [A source request's git work](./architecture.md#a-source-requests-git-work)). A commit's
3526 retained parents are its first 128 parents. While every page leaves at most 64 commits in that
3527 frontier, following "Older" from the first page visits once every commit reached through
3528 retained parents, including across merges.
3529 - The `from` query parameter takes a single value of 1 to 64 full commit IDs
3530 (`server.MaxFrontier`), separated by commas, in ascending order, each appearing once. Each
3531 commit in `from` must be reachable from `<commit>`. Any other `from` value answers `404`. Every
3532 page after the first includes a "Newest" link back to the first page of that history.
3533 - When a page leaves more than 64 commits to show, its "Older" link starts from the first 64 in
3534 ascending order. Below the commit list, the page notes how many lines of history continue and
3535 links each remaining commit by its short ID to `?from=<id>` for that single commit. Together,
3536 "Older" and those individual links reach every older commit along retained parents, though two
3537 of those branches may later visit the same ancestor.
3538 - A page leaves at most 192 commits to show (`server.MaxLeftToShow`), so it renders at most 128
3539 individual branch links in addition to "Older". Before adding a commit that would push the
3540 frontier past 192 commits, the page stops early and notes why. Every page shows at least its
3541 first commit, which leaves at most 63 other starting commits plus 128 parents.
3542 - A page retains at most the first 128 parents of any commit for older pages
3543 (`server.MaxParents`). A merge with more than 128 parents still renders, with a note on that
3544 commit stating that older pages follow only its first 128 parents. `git log` still walks every
3545 parent, so a commit reachable only through later parents may appear on the same page. Commits
3546 reachable only through later parents may be omitted from older pages.
3547- **Source archives:** `/<group>/<project>/source/archive/<commit>.tar.gz` serves the tree of
3548 `<commit>` as a gzipped tar archive (see [Source archives](./architecture.md#source-archives)).
3549 Every directory page links to its commit's archive as "Download .tar.gz".
3550 - Every entry in the archive is under one top-level directory, `<project>-<12 hex digits>/`, named
3551 from the project's web `name` and the first 12 hex digits of `<commit>`.
3552 - The archive is `<commit>`'s tree byte for byte. The server does not apply the `export-ignore` or
3553 `export-subst` attributes, or any other attribute. It holds every file in the tree, including
3554 binary files and files larger than the 1 MiB a file page shows (`server.MaxFile`).
3555 - `<commit>` follows the rule of every source route: a full object ID of the project's object
3556 format that `source_tip` reaches. An abbreviated ID, a ref name, an unreachable commit, a last
3557 segment without `.tar.gz`, or any further path segment answers `404`.
3558 - `/<group>/<project>/source/archive/main.tar.gz` answers with a `302` redirect to
3559 `/<group>/<project>/source/archive/<source_tip>.tar.gz` and the same headers as
3560 `/<group>/<project>/source/`. `main` is the only name the route accepts in place of a commit ID;
3561 `HEAD`, any other ref name, or an abbreviated ID answers `404`. The redirect takes no `git`
3562 slot. A project the reader may not see answers `404`.
3563 - The server writes the tar in Go from `git ls-tree -r -t -l -z` and one `git cat-file --batch`.
3564 Entries follow the tree's order, each directory before what it holds. A file has mode `0644`, or
3565 `0755` for git mode `100755`. A symbolic link (`120000`) is a tar symbolic link to its content
3566 in git, and is never followed. A submodule (`160000`) is an empty directory. Every entry has the
3567 commit's committer time, uid and gid 0, and empty user and group names. Go's tar writer chooses
3568 USTAR or PAX for each header, whichever the header needs.
3569 - A symbolic link whose target is longer than 4,096 bytes, or holds a NUL byte, makes the archive
3570 answer `500`.
3571 - The server compresses the tar with Go's `compress/gzip` at a fixed level, with an empty file
3572 name and zero modification time in the gzip header. A commit's archive has the same bytes on
3573 every request to the same build under the same web name, whatever the time, the repository's
3574 refs, git configuration, or attributes.
3575 - The response carries `Content-Type: application/gzip` and
3576 `Content-Disposition: attachment; filename="<project>-<12 hex digits>.tar.gz"`, in addition to
3577 every header listed under **Rendering and headers** (including
3578 `Cache-Control: private, no-store`).
3579 - Before it reads any file, the server refuses an archive whose files add up to more than 32 MiB
3580 (`server.MaxArchiveInput`), whose tree holds more than 10,000 entries
3581 (`server.MaxArchiveEntries`), or whose listing is longer than 4 MiB (`server.MaxRead`). A
3582 refused archive answers `500` with the "Page too large" page.
3583 - The server streams the files through tar and gzip into the response budget within the 5-second
3584 `git` slot timeout, and writes the response once the archive is complete. A compressed archive
3585 is at most 8 MiB (`server.MaxResponse`); a larger one answers `500` with the "Page too large"
3586 page.
3587- **Time:** Every request has a 15-second deadline from when it arrives, covering waiting for its
3588 view, its `git` slot and a rendering slot, running `git` commands, and rendering the page. A
3589 request that exceeds 15 seconds answers `503` with `Retry-After: 5`. Within that deadline, a
3590 source request may hold its `git` slot for at most 5 seconds from when it takes it, covering all
3591 of its `git` commands. If 5 seconds pass while the request still holds its `git` slot, the server
3592 logs the timeout and answers `503` with `Retry-After: 5`.
3593- **Admission:** The server bounds how many requests may run `git` or wait at once. Every admission
3594 check runs before the request opens a generation.
3595 - A tree, file, log, or archive request that reads a repository for a project the reader may see
3596 needs a `git` slot. At most 8 such requests hold a `git` slot at once (`server.MaxGit`), and at
3597 most 16 more wait in a first-in-first-out queue (`server.MaxWaiting`). A request takes its slot
3598 only after its route is resolved through its view's index. Redirects (including
3599 `/<group>/<project>/source/archive/main.tar.gz`, aliases, and former names), paths that a source
3600 route refuses, and paths of hidden or nonexistent projects are answered from the index alone and
3601 take no `git` slot. When all 8 slots and 16 waiting places are full, a request that needs a slot
3602 answers `503` immediately with `Retry-After: 5`.
3603 - A source request releases its `git` slot before rendering HTML, and every request releases its
3604 generation before writing the response to the client (see
3605 [Slow readers](./architecture.md#slow-readers)).
3606 - At most 2 source requests render Markdown at once (`server.MaxRendering`). A request waits for a
3607 rendering slot while it still holds its `git` slot, within the same 5 seconds, and releases the
3608 `git` slot once it has one. Rendering stops when the request's 15 seconds run out.
3609 - Before opening a generation, any request whose generation is not yet decoded must wait for the
3610 read, and any request whose view has no ready index must wait for the index build or for a place
3611 in its pool. At most 64 requests wait for their views at once (`server.MaxLoadWaiting`).
3612 - Named readers' requests take at most 48 of those 64 waiting places (`server.MaxNamedWaiting`).
3613 Anonymous requests may take any of the 64, leaving at least 16 places for anonymous requests
3614 regardless of how many named readers wait.
3615 - A request that finds no waiting place it may take answers `503` immediately with
3616 `Retry-After: 5`: when all 64 places are full for an anonymous request, or when 48 named places
3617 or all 64 places are full for a named reader's request.
3618 - Every other limit is shared across all readers and does not grow with the number of readers:
3619 `git` slots, rendering slots, the response budget and its large-response cap, the 8 MiB response
3620 limit, and the archive limits.
3621- **Response size and memory:** Every page is rendered in full before the server writes the
3622 response.
3623 - A page or an archive is at most 8 MiB (`server.MaxResponse`) on any route. A response that
3624 exceeds 8 MiB stops at that bound. The server logs the failure and answers `500` with a short
3625 page titled "Page too large".
3626 - The server holds at most 64 MiB of rendered responses at once (`server.MaxBuffered`). A response
3627 claims this budget in 64 KiB chunks as it renders and releases them once the response has been
3628 written. A slow reader holds its response's share of the budget until the write finishes.
3629 `valley-web` stops writing a response 60 seconds after reading the request's headers.
3630 - Responses larger than 256 KiB (`server.SmallPage`) may hold at most 48 MiB of the 64 MiB budget
3631 between them (`server.MaxLarge`). Once a response grows past 256 KiB, its entire size—including
3632 the first 256 KiB—counts against that 48 MiB cap, leaving at least 16 MiB of the budget for
3633 responses of 256 KiB or smaller (see [Slow readers](./architecture.md#slow-readers)).
3634 - A request whose page needs more memory than remains in the budget answers `503` with
3635 `Retry-After: 5`.
3636 - The "Busy" (`503`), "Page too large" (`500`) and "Not found" (`404`) pages are rendered once
3637 when the server starts. They show no export data and take none of the 64 MiB budget.
3638- **Access:** Every project route checks that the request's reader may see the project (see **One
3639 project-view filter**). Every `404` serves the same page, byte for byte, whether the project is
3640 hidden or missing, the knot or path does not exist, or the commit is not served.
3641- **Not found:** The `404` page is titled "Not found" and shows a box of preformatted text in the
3642 server's stylesheet. Its last line, "Return to the source", links to `/`. The page omits
3643 navigation, the export age, and the site name:
3644
3645 ```text
3646 ╔═════════════════════════════════════╗
3647 ║ ║
3648 ║ THE WAY THAT CAN BE FOUND ║
3649 ║ IS NOT THE ETERNAL WAY ║
3650 ║ ║
3651 ║ The page you seek exists ║
3652 ║ only in non-existence. ║
3653 ║ ║
3654 ║ Return to the source ║
3655 ║ ║
3656 ╚═════════════════════════════════════╝
3657 ```
3658
3659- **Rendering and headers:** Pages are rendered on the server with Go's `html/template`, which
3660 escapes every value from the export or a repository. The stylesheet, the knots pages' script and
3661 the reader pages' script are embedded in the binary and inlined into the page; nothing else is
3662 loaded. No page serves a repository file as raw content; raw repository files are served only
3663 inside a source archive, which is gzipped and sent as an attachment. Every response, including
3664 redirects, error pages, `HEAD` responses and archives, carries these headers:
3665 - On `/-/knots` and on every path of the shape `/<group>/<project>/knots`, whether or not the
3666 reader may see the project:
3667 `Content-Security-Policy: default-src 'self'; script-src 'sha256-<script hash>'; style-src 'sha256-<stylesheet hash>'; connect-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`
3668 - On `/-/redeem` and `/-/logout`, with `--origin`:
3669 `Content-Security-Policy: default-src 'self'; script-src 'sha256-<reader script hash>'; style-src 'sha256-<stylesheet hash>'; connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`
3670 - On every other path:
3671 `Content-Security-Policy: default-src 'self'; script-src 'none'; style-src 'sha256-<stylesheet hash>'; connect-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`
3672 - `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`, `Referrer-Policy: no-referrer`,
3673 `Cross-Origin-Opener-Policy: same-origin`, `Cross-Origin-Resource-Policy: same-origin`,
3674 `Cache-Control: private, no-store`, and `Vary: Cookie`.
3675
3676 No response carries an `ETag` or a `Last-Modified`, and the server never answers `304`.
3677
3678- **Errors:** When the server cannot read the export or a repository, it logs the error on `stderr`
3679 and answers `500` with a generic error page that gives no detail. A request that runs out of time
3680 answers `503`. The timeout is logged when time runs out while the request waits for its export to
3681 be read, runs `git`, or renders the page. The server does not log a request refused at admission,
3682 a request whose time runs out while waiting for a `git` slot, or a request refused because the 64
3683 MiB response budget is full.
3684
3685#### Reader sessions
3686
3687A reader signs in by opening a read link issued on the valley host. When started with `--origin`,
3688`valley-web` redeems the link once into a session cookie for the link's principal (`implemented`,
3689[`web/server/reader.go`](../web/server/reader.go), [`web/readerstate/`](../web/readerstate/)). A
3690signed-in session sees the projects that the stored authorization lets `anyone` read, together with
3691those it lets the session's principal read (`implemented`,
3692[`web/server/plan.go`](../web/server/plan.go)).
3693
3694```text
3695https://example.org/-/redeem#lk-0123456789abcdef.<secret>
3696```
3697
3698- **The redeem page, `/-/redeem`:** `GET` and `HEAD` render this page whether or not an export is
3699 published. On load, its script copies the URL fragment after `#` into memory and clears the
3700 fragment from the address bar with `history.replaceState`. It sends nothing until the reader
3701 clicks. Without a valid session, the page shows **Continue as reader**. With a valid session, it
3702 shows **Sign out and continue with this link**, which posts to `/-/logout` and then to
3703 `/-/redeem`. Clicking the button sends one attempt and disables the button while the request is in
3704 flight. On `204`, the browser navigates to `/`.
3705 - **An unknown outcome:** If the response never arrives, or has a status other than `204`, `403`,
3706 or `409`, the page cannot tell whether the server redeemed the link. It keeps the link in
3707 memory, explains that the link may already be used and that a refused retry requires a new link,
3708 and re-enables the button so the reader can retry.
3709 - **A retry:** After an unknown outcome, the next click first reads `GET /-/session`. If the
3710 browser holds a session for this link, the earlier attempt succeeded, and the page navigates to
3711 `/` without sending another `POST`. If the browser holds no session, the retry skips
3712 `POST /-/logout` and posts only to `/-/redeem`, so it never ends a session that the earlier
3713 attempt started. If the browser holds a session from a different link, the retry signs that
3714 session out before redeeming this link.
3715- **The logout page, `/-/logout`:** For a reader with a valid session, every page with navigation
3716 links to `/-/logout`, and `/-/logout` shows a **Sign out** button. If the response to **Sign out**
3717 never arrives or is not `204`, the page reports that it cannot tell whether the reader was signed
3718 out and lets the reader retry. Retrying is safe because `POST /-/logout` without a valid session
3719 also answers `204`.
3720- **The session endpoint, `/-/session`:** `GET` and `HEAD` answer `200` with `application/json`.
3721 `HEAD` has no body. The body of a `GET` response is `{"link":"lk-0123456789abcdef"}` with the
3722 credential ID of the request's valid session, or `{"link":""}` when the request carries no valid
3723 session. The credential ID carries no secret and cannot redeem a link. Like every other `GET` or
3724 `HEAD` response, `/-/session` renews a valid session's cookie.
3725- **Redemption:** `POST /-/redeem` takes `{"credential":"<id>.<secret>"}`. The `credential` field is
3726 required and must be a string; `{}`, `null`, or any other value violates the `POST` contract below
3727 and answers `403` with `This request is refused.`
3728 - `204` with `Set-Cookie`: the server consumes the link and starts its session in one durable
3729 transaction.
3730 - `403` with `This link cannot be used. Request another link.`: the credential is malformed,
3731 unknown, revoked, already redeemed, or has the wrong secret. All of these cases return the same
3732 response.
3733 - `409`: the request already carries a valid session. The link is not consumed.
3734 - `503`: the browser state is unavailable, adding the redemption would exceed the 32 MiB state
3735 limit, or the request's 15-second deadline expired before the transaction began writing
3736 `state.new`; in the latter two cases the link is not consumed.
3737- **Logout:** `POST /-/logout` takes `{}`.
3738 - `204` with an empty `Set-Cookie` (`Max-Age=0`): the server removes the session's token hash from
3739 the browser state while keeping the link marked as redeemed. A request without a valid session
3740 also answers `204` and clears the cookie.
3741 - `503`: the browser state is unavailable, or the request's 15-second deadline expired before the
3742 transaction began writing `state.new` (leaving the session active).
3743- **Every reader `POST`:** A `POST` to `/-/redeem` or `/-/logout` must carry:
3744 - one `Origin` header, equal to `--origin`;
3745 - one `Content-Type` header, `application/json` (optionally with `charset=utf-8` in any case, and
3746 no other parameters);
3747 - one `X-Valley-Reader` header, equal to `1`;
3748 - no `Content-Encoding` header and no URL query (including a bare `?`); and
3749 - a body of at most 1 KiB containing a single JSON object with exact key names, no duplicate or
3750 unknown keys, and no trailing data. Any `POST` that fails these checks answers `403` with
3751 `This request is refused.` Responses never carry CORS headers.
3752- **The link:** `<id>` is `lk-` followed by 16 lowercase hex digits. `<secret>` is 32 bytes in
3753 canonical unpadded base64url. The server compares the SHA-256 of the decoded secret with the
3754 binding's verifier in constant time.
3755- **The cookie:**
3756 `Set-Cookie: __Host-valley-reader=<token>; Secure; HttpOnly; Path=/; SameSite=Lax; Max-Age=2592000`.
3757 `<token>` is `<id>.<random>`, where `<random>` is 32 bytes from `crypto/rand` in canonical
3758 unpadded base64url. The browser state stores only the SHA-256 of the full token. Logout sets the
3759 same cookie with an empty value and `Max-Age=0`.
3760- **Sessions:** A token is valid while the browser state holds its hash and the stored authorization
3761 binds its link to the principal and verifier under which the link was redeemed. A request that
3762 carries the cookie more than once, or carries a malformed, unknown, signed-out, or revoked token,
3763 is served as `anyone` without renewing the cookie. A request that carries the cookie while the
3764 browser state is unavailable answers `503`. A request without the cookie is always served as
3765 `anyone`.
3766- **Renewal:** Every `GET` and `HEAD` response for a valid session, including `404` and error pages,
3767 sends `Set-Cookie` again with `Max-Age=2592000` after the final check confirms the session is
3768 still valid. If the request's 15-second deadline has expired by the final check, the server
3769 answers `503` without `Set-Cookie`. Renewal extends how long the browser keeps the cookie; the
3770 server stores no expiry timestamp.
3771- **The final check before writing headers:** After rendering a `GET` or `HEAD` response, the server
3772 re-checks both the stored authorization and the request's session before writing headers. If
3773 either changed while the page was rendering, the server discards the rendered response and renders
3774 again, up to three renders in total.
3775
3776The browser state lives in `browser/` beside the store's descriptor:
3777
3778| File | Purpose |
3779| :----------- | :----------------------------------------------------------------------- |
3780| `owner.lock` | `flock(2)` lock held by the single `valley-web` process for its lifetime |
3781| `lock` | `flock(2)` lock held during each state transaction |
3782| `state` | Committed state file (`the-valley/web-reader-state/v1`) |
3783| `state.new` | Temporary file written during a transaction and removed on startup |
3784
3785```text
3786the-valley/web-reader-state/v1
3787link lk-0123456789abcdef alice <verifier> <SHA-256 of the session token, or ->
3788```
3789
3790- **Records:** `state` contains one `link` line per redeemed link, sorted by credential ID. Each
3791 line records the credential ID, principal, and verifier under which the link was redeemed,
3792 followed by the lowercase hex SHA-256 of the active session token or `-` after logout. Link
3793 records are never deleted.
3794- **Limits:** `state` is at most 32 MiB (`readerstate.MaxState`). A redemption that would exceed 32
3795 MiB answers `503` and leaves the link unconsumed.
3796- **Modes:** Every file in `browser/` has mode `0600`. `valley-web` refuses symbolic links,
3797 non-regular files, and any `state` file that grants group or other permissions.
3798
3799---
3800
3801## CUE configuration schemas
3802
3803Seven CUE schemas under `schema/` validate host declarations, verification policies, read policies,
3804attestation statements, identity registries, knowledge/plan nodes, and bus events. What an instance
3805writes in its CUE files is a `deployment choice`; the schema constraints below are `implemented`.
3806
3807### Host configuration (`schema/valley.cue`)
3808
3809[`schema/valley.cue`](../schema/valley.cue) (`package valley`) defines `#Host`, the declaration of
3810projects, the groups they belong to, ref protection, ref grants, mirrors, and offsite backup for a
3811valley host.
3812
3813```sh
3814cue vet -c schema/valley.cue valley.cue
3815```
3816
3817| Definition / field | Type / default | Rules |
3818| :--------------------------------------------- | :--------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
3819| `projects.<name>` (`#Project`) | `[=~"^[a-zA-Z0-9][a-zA-Z0-9._-]*$"]: #Project` | Top-level map of hosted projects, keyed by each project's identifier. Only `projects`, `groups` and `backup` are permitted at top level. |
3820| `projects.<name>.git.enable` | `bool \| *true` | Whether the host serves `<name>.git`. Disabling leaves existing data on disk untouched. |
3821| `projects.<name>.mirrors` | `[...string] \| *[]` | Push-mirror URLs receiving `refs/heads/main` and `refs/tags/*` on updates. |
3822| `projects.<name>.protection` (`#Protection`) | optional | When omitted, no refs in `<name>` are protected. When present: `refs` (`[#RefPattern, ...#RefPattern] \| *["refs/heads/main"]`, where `#RefPattern` is `=~"^refs/[^ ~^:?\\\\[]+$"`) and `writers` (`[...#PrincipalName] \| *[]`). |
3823| `projects.<name>.grants.<grant>` (`#RefGrant`) | `[#GrantName]: #RefGrant` | Opens ref patterns outside `refs/heads/`, `refs/replace/`, `refs/notes/`, and `refs/the-valley/` (`#GrantPattern`: `#RefPattern & !~"^refs/(heads\|replace\|notes\|the-valley)/"`) to `writers: [#PrincipalName, ...#PrincipalName]`. |
3824| `projects.<name>.group` | optional `#GroupID` | The identifier of the project's group, which `groups` must declare. A project in no group has no web URL. |
3825| `projects.<name>.name` | `#ProjectName \| *<name>` | The project's web name, used as the second segment of its web URLs (`/<group name>/<web name>/…`). It defaults to `<name>` and is constrained to `#WebName` when `group` is set. Setting `name` to another value requires `group`. |
3826| `projects.<name>.formerNames` | `[...#WebName] \| *[]` | Former web names within the group: `/<group name>/<former>/…` redirects to `/<group name>/<web name>/…`. A nonempty `formerNames` requires `group`. |
3827| `projects.<name>.aliases` | `[...#WebName] \| *[]` | Short aliases: `/<alias>/…` redirects to `/<group name>/<web name>/…`. A nonempty `aliases` requires `group`. |
3828| `groups.<id>` (`#Group`) | `[#GroupID]: #Group` | Top-level map of groups, keyed by each group's permanent identifier. `#GroupID` and `#WebName` match `=~"^[a-zA-Z0-9][a-zA-Z0-9._-]*$"` with at most 64 runes. |
3829| `groups.<id>.name` | `#WebName` | The group's web name, used as the first segment of its projects' web URLs. |
3830| `groups.<id>.aliases` | `[...#WebName] \| *[]` | Additional first-segment names that redirect to the same path under `name`. |
3831| `backup` (`#Backup`) | optional | Host-level backup policy: `enable` (`bool \| *true`), `target` (`"restic-sftp"`), `cadence` (`"nightly"`), `retention` (`{ daily: int & >0 \| *7, weekly: int & >0 \| *4, monthly: int & >0 \| *6 }`). |
3832
3833`cue vet` refuses a project whose `group` is undeclared in `groups`, or a project without a `group`
3834that sets a custom `name`, a nonempty `formerNames`, or a nonempty `aliases`. It refuses any two
3835group names, group aliases, or project aliases that match ignoring ASCII case, including a group
3836alias that matches the group's own `name`. Within each group, it refuses any two project web names
3837or former names that match ignoring ASCII case. Projects in different groups may share a web name.
3838Each check evaluates a hidden field (`_groupless`, `_firstSegments`, or `_secondSegments`), which
3839appears in the CUE error on failure (see
3840[Groups and web URLs](./architecture.md#groups-and-web-urls)).
3841
3842A former name redirects only while it remains in `formerNames`. Removing it frees the name within
3843that group: while no project claims it, `/<group name>/<former>/…` answers `404`, and if another
3844exported project in the group that is visible to the reader later takes it as its `name` or in
3845`formerNames`, those URLs resolve to that project.
3846
3847### Verification policy (`schema/verification.cue`)
3848
3849[`schema/verification.cue`](../schema/verification.cue) (`package verification`) defines `#Policy`
3850and composes the instance `floor`, optional project-type `templates`, and the `project` layer into
3851`policy: floor & templates[type] & project`.
3852
3853```sh
3854cue vet -c schema/verification.cue policy/instance/*.cue policy/project/*.cue
3855```
3856
3857| Definition / field | Type / default | Rules |
3858| :------------------------------------- | :------------------------------------------------ | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
3859| Top-level fields | `floor`, `templates`, `type`, `project`, `policy` | `floor: #Policy`, `templates: [#Name]: #Policy` (with `templates: none: {}` built in), `type: #Name \| *"none"`, `project: #Policy`, and derived `policy: floor & templates[type] & project` (`#Name` is `=~"^[a-z0-9][a-z0-9-]*$"`). |
3860| `#Policy.checks.<name>` (`#Check`) | `[#Name]: #Check` | Check catalogue. Every check required by any class or `unclassified` in the composed `policy` must be defined in `policy.checks`. |
3861| `#Check` | `runner: "nix" \| "command"` | When `runner == "nix"`: requires `attribute: #Name`, forbids `command` and `validity`. When `runner == "command"`: requires `command: =~"^[^\\x00-\\x1f\\x7f]+$"`, forbids `attribute`, and accepts optional `validity?: =~"^[1-9][0-9]*(s\|m\|h\|d)$"` (`#Duration`). Both accept `cost: *"quick" \| "slow"`. |
3862| `#Policy.classes.<class>` (`#Class`) | `[#Name]: #Class` | Path classes: `paths` (`[#Pattern]: bool`, where `#Pattern` is relative to repo root with no leading `/`, `..` segment, or control characters), `requires` (`[#Name]: bool`), and `carry` (`["same-class" \| "exact"]: bool`, resolving to strictest of `exact`, `same-class`, or default `same-paths`). Concrete `true` in `floor` is mandatory; `bool \| *true` in `templates` is an overridable default. |
3863| `#Policy.unclassified` | `[#Name]: bool` (`#Requires`) | Checks required when a changed path matches no class in `policy.classes`. |
3864| `#Policy.restack.maxAutomaticVersions` | `int & >=1 \| *64` | Cap on the versions of one change uploaded by the principal `valley-restacker` is configured to push as (`valley-restacker` holds any change that has reached this count). |
3865| `#Policy.approval.hardware` | optional `bool` | Whether an approval must be signed with a hardware key. Left out, it is not required. See [Requiring a hardware approval key](#requiring-a-hardware-approval-key-approvalhardware). |
3866
3867#### Requiring a hardware approval key (`approval.hardware`)
3868
3869The floor writes this to require that approvals be signed with a hardware key:
3870
3871```cue
3872floor: approval: hardware: true
3873```
3874
3875A hardware key is an approval key that the identity registry enrolled with proof that the key is
3876held on a device and that every signature takes a touch. The identity compiler lists those keys in
3877`approval-signers-hardware` ([Approval signers files](#approval-signers-files)).
3878
3879- **What it decides.** It decides which keys may sign an approval. It does not decide whether a
3880 change needs an approval.
3881- **Left out.** Any enrolled approval key may sign. A policy that leaves the field out exports no
3882 `approval` field, so the field adds nothing to its policy digest.
3883- **The floor** writes `true`, and no project can remove it. A project that writes `hardware: false`
3884 makes the policy fail to compose, and `cue vet` names `policy.approval.hardware`. A project cannot
3885 edit the floor either: the integrator reads the floor from the instance repository or a host
3886 directory, never from the project's tree ([Policy](./architecture.md#policy)).
3887- **A template** may write `bool | *true`. That is a default, and a project may turn it off with
3888 `false`.
3889- **A project** may write `true`, which requires a hardware key even where the floor does not.
3890- **A floor's `false`** would stop every project from writing `true`. A floor writes `true` or
3891 leaves the field out.
3892- **Unknown fields and other types** are refused: `approval` holds only `hardware`, and `hardware`
3893 is a boolean. A document may reopen a schema definition to add a field, such as `Hardware` beside
3894 `hardware`. The Go reader refuses any composed policy with a field the schema does not give it, a
3895 key that appears twice in one object, or a value of the wrong type.
3896
3897The schema rule and its Go reader, `HardwareApproval` in
3898[`composed/composed.go`](../composed/composed.go), are `implemented`. Nothing acts on the value.
3899Enrolling hardware keys in the identity registry is `implemented`: the compiler verifies each key's
3900attestation and writes `approval-signers-hardware`. The approval gate that would check approvals
3901against that file alone is `not built`. Whether a floor writes the field is a `deployment choice`.
3902
3903The schema travels with the tools: `valley`, the integrator, the check worker and the restacker each
3904compose under their own packaged copy. A tool with an older schema refuses a policy that writes
3905`approval`, and derives no checks for it. Deploy the tools before a policy writes the field.
3906
3907### Read policy (`schema/read.cue`)
3908
3909[`schema/read.cue`](../schema/read.cue) (`package read`) defines a project's consent to read access,
3910stored in `policy/read/*.cue` on the project's `main`. `readaccess` evaluates two consents: this
3911policy and a read grant in the instance's identity registry
3912([Identity registry](#identity-registry-schemaidentitycue)). A principal is authorized in
3913`readaccess` only when both consents match. `valley-web-publish` exports every project with an
3914authorized reader, and its authorization names each project's readers. When started with `--origin`,
3915`valley-web` serves a request that carries a valid session cookie as that session's principal, and
3916serves every other request as `anyone`.
3917
3918```cue
3919// policy/read/read.cue in app
3920package read
3921
3922project: "app"
3923identity: "9da6809f038df92138c131cd16bed76d"
3924readers: {
3925 anyone: true
3926 operator: true
3927}
3928```
3929
3930```cue
3931// identity/registry.cue in the instance repository, in part
3932boundaries: web: {kind: "edge-read", destination: "example.org"}
3933principals: operator: grants: read: {boundary: "web", projects: "all"}
3934anyone: grants: read: {boundary: "web", projects: app: "9da6809f038df92138c131cd16bed76d"}
3935```
3936
3937```sh
3938cue vet -c schema/read.cue policy/read/*.cue
3939```
3940
3941| Field | Type | Rules |
3942| :--------------- | :--------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------- |
3943| `project` | `#ProjectName` | Required. The project the policy is for: the name the instance lists it under, by the project-name rule, at most 64 characters. |
3944| `identity` | `#Identity` (`=~"^[0-9a-f]{32}$"`) | Required. The project's publication identity: 32 random lowercase hex digits, chosen when the policy is first written and never changed. |
3945| `readers` | `close({[#Principal]: true})` | Required. The set of principals the project lets read it, by the principal-name rule. `{}` lets no one read. A key that is not a principal name is refused. |
3946| Top-level fields | `project`, `identity`, `readers` | Any other top-level field conflicts with a sentinel string and fails vet, naming the field. |
3947
3948- **Two consents:** `readaccess` authorizes a principal for a project at a destination when the
3949 project's `readers` names that principal and a read grant for that principal at an `edge-read`
3950 boundary for that destination covers the project. A grant covers a project when its `projects` is
3951 `"all"`, or when it maps the project's name to the `identity` declared in the project's
3952 `policy/read`. Authorization for any principal, `anyone` or a named principal, causes
3953 `valley-web-publish` to export a project that the host declaration places in a group. A missing or
3954 invalid policy or registry consents to nothing.
3955- **`anyone`:** `anyone` represents a reader who presents no credential. A project is public at a
3956 destination when both consents authorize `anyone` there.
3957- **Named principals and the operator:** The schema and `readaccess` evaluate every named principal
3958 the same way, including the operator: the project's `readers` must name the principal and an
3959 instance grant must cover the project. A project a named principal may read reaches the edge with
3960 that principal in its authorization, and a reader signed in with that principal's read link reads
3961 it there (`implemented`; see [Reader sessions](#reader-sessions)). The starter policy for a new
3962 project,
3963 [`examples/policy/read/new-project/read.cue`](../examples/policy/read/new-project/read.cue), names
3964 only `operator`; copying it is a `deployment choice`. `valley-read-coverage` reports which
3965 projects lack either consent for a given principal (see the host helpers in the
3966 [CLI reference](#cli-reference)).
3967- **Identity:** A grant that names a specific project binds both its name and its `identity`. If a
3968 new project reuses an old project's name with a new identity, grants for the old identity do not
3969 cover it. A policy whose `project` field does not match the repository it was read from is
3970 invalid.
3971- **Redeclared definitions:** In CUE, a policy file can redeclare a schema definition, and
3972 unification can reopen a closed struct. `readers` is closed with `close()`, which a redeclaration
3973 cannot reopen. The Go reader in `readaccess` decodes the exported JSON with `exactjson`, which
3974 refuses a key that is not one of the schema's fields spelled exactly, and then checks the project
3975 name, identity, and reader names again.
3976- **Beside the verification policy:** `policy/read/` sits beside `policy/instance/` and
3977 `policy/project/`. Those two directories are verification-policy layers, whose top level
3978 `schema/verification.cue` closes to its own fields.
3979- **the-valley's own:** [`policy/read/read.cue`](../policy/read/read.cue) declares this repository's
3980 project consent for `anyone` and `operator` (`deployment choice`). Publishing or authorizing read
3981 at an edge still requires a matching `edge-read` grant in the hosting instance's identity
3982 registry.
3983
3984### Attestation statement (`schema/attestation.cue`)
3985
3986[`schema/attestation.cue`](../schema/attestation.cue) (`package attestation`) validates the JSON
3987representation of `the-valley/attestation/v1` statements before rendering or during `attest verify`.
3988
3989```sh
3990cue vet -c schema/attestation.cue statement.json
3991```
3992
3993- **Top-level fields:** `statementType: "the-valley/attestation/v1"`, `subject: #Subject`
3994 (`primary: "valley-tree-v1"`, `digest: #DigestSet`), `predicateType: #PredicateType`, `predicate`
3995 (`#PureCheck`, `#EffectfulCheck`, or `#Transfer` selected by `predicateType`), and optional
3996 `provenance?: #Provenance`.
3997- **Definitions:**
3998 - `#DigestSet`: `"valley-tree-v1"?`, `"valley-inputs-v1"?`, `sha256?` (`=~"^[0-9a-f]{64}$"`),
3999 `"git-sha1"?` (`=~"^[0-9a-f]{40}$"`), `"git-sha256"?` (`=~"^[0-9a-f]{64}$"`).
4000 - `#Line`: `=~"^[^\\x00-\\x1f\\x7f]+$"`; `#Name`: `=~"^[a-z0-9][a-z0-9-]*$"`; `#KeySegment`:
4001 `=~"^[A-Za-z][A-Za-z0-9-]*$"`.
4002 - `#CheckRun`: `name: #Name` and `runner: "nix" | "command"`. When `runner == "nix"`, requires
4003 `attribute: #Name` and forbids `command`. When `runner == "command"`, requires `command: #Line`
4004 and forbids `attribute`.
4005 - `#Result`: `"passed" | "failed"`; `#CheckTransfer`: `rule: "closure" | "untouched" | "unmoved"`.
4006 - `#Provenance`: optional `harness?: #Line`, `model?: #Line`, `prompt?: #DigestSet`,
4007 `context?: #DigestSet`, and `delegation?: [...{ principal: #Line, grant?: #Line }]`.
4008
4009### Identity registry (`schema/identity.cue`)
4010
4011[`schema/identity.cue`](../schema/identity.cue) (`package identity`) validates an instance's
4012governed identity registry (`identity/*.cue`), which `valley-identity compile` renders into
4013`known-signers`, `authorized_keys`, `grants`, and the two
4014[approval signers files](#approval-signers-files) ([`identity/render.go`](../identity/render.go)).
4015
4016```sh
4017cue vet -c schema/identity.cue examples/identity/registry/*.cue
4018```
4019
4020| Definition / field | Type / default | Rules |
4021| :--------------------------------- | :-------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
4022| `boundaries.<name>` (`#Boundary`) | `[#Name]: #Boundary` | Enforcement boundaries run by the instance (`#Name`: `=~"^[a-zA-Z0-9][a-zA-Z0-9._-]*$"`). Every boundary has `kind: "git-push" \| "registry" \| "approve" \| "request" \| "restack" \| "edge-read"`. A boundary of kind `edge-read` requires `destination: #Name`, and boundaries of other kinds forbid it (`readScopes`). Every `boundary` referenced by a grant must exist in `boundaries`. |
4023| `principals.<name>` (`#Principal`) | `[#Name]: #Principal` | Named principals: `kind: "human" \| "machine" \| "service"`, `keys: [#Key, ...#Key]`, `grants: [#Name]: #Grant` (`{ boundary: #Name, projects?: #Scope }`), `external: #External \| *null` (`{ kind: "domain" \| "did", handle: =~"^[^\\s]+$" }`), and `expires?: =~"^[0-9]{4}-[0-9]{2}-[0-9]{2}$"`. `expires` is **required** whenever `kind != "human"` or `external != null`. Principal names cannot be `anyone`. |
4024| `#Scope` | `"all" \| close({[#ProjectName]: #Identity})` | The projects a read grant covers: `"all"` for every project, or a map from project name to the publication identity declared in that project's `policy/read` ([Read policy](#read-policy-schemareadcue)). `{}` covers no projects. Every grant at an `edge-read` boundary requires `projects`, and grants at other boundaries forbid it (`readScopes`). |
4025| `anyone` (`#Anyone`) | `{ grants: [#Name]: #Grant }` | Optional. The read grants for a reader who presents no credential. `anyone` has no keys, no external identity, and no expiry, can hold grants only at `edge-read` boundaries (`readScopes`), and cannot be `genesis`. |
4026| `#Key` | `class: "ssh-ed25519"` | `bound: "hardware" \| "host"`, `public: =~"^ssh-ed25519 [A-Za-z0-9+/]+={0,2}( [^\\n]*)?$"`, and optional `signs?: =~"^[^\\s+]+$"` (when set, `identity compile` emits a verifier key in `known-signers`), and optional `attestation?: #Attestation`. A key with an `attestation` must be `bound: "hardware"`. |
4027| `#Attestation` | `slot`, `f9` | A YubiKey PIV attestation of the key: `slot`, the certificate the YubiKey wrote for the PIV slot holding the key, and `f9`, the YubiKey's own attestation certificate, which signed it. Each is one PEM certificate and nothing else (`#Certificate`). `identity compile` checks what they say; see [Approval signers files](#approval-signers-files). |
4028| `genesis` and governance checks | `genesis: #Name & !="anyone"` | `genesis` must be a key in `principals` that holds at least one grant at a boundary with `kind == "registry"` (`genesisGovernance: [_, ...]`), and no principal with `external != null` may hold a `registry` boundary grant (`externalGovernance`). At compile time, `identity compile` omits principals with `expires <= now` and fails if no unexpired principal holds a `registry` grant, if two principals holding `git-push` grants share a public key, if a `git-push` key conflicts with a host-declared `authorizedKeys` tag, if a key that approves is also listed under another principal, if an `attestation` does not verify, or if the export holds a key that does not spell a schema field exactly (such as `Grants` beside `grants`) or a key twice in one object. |
4029
4030#### Approval signers files
4031
4032An approval signers file lists the keys whose signed approvals count. `identity compile` writes two
4033of them, each only when its flag names a path:
4034
4035```sh
4036identity compile --repo /srv/git/instance.git --known-signers known-signers \
4037 --authorized-keys authorized_keys --grants grants \
4038 --approval-signers approval-signers --approval-signers-hardware approval-signers-hardware
4039```
4040
4041Each line is a verifier key in the `known-signers` format, named by the principal who approves with
4042that key. For the example key of `example-operator`:
4043
4044```text
4045example-operator+3649fd12+AT/3+vgQhY5cdQ4AqspQ1A2yW60nn4j1FOyx04WfuQjc
4046```
4047
4048- **`approval-signers`** lists every key of every unexpired `human` principal holding the approve
4049 grant, at a boundary of kind `approve` or `request`. Software keys are listed too.
4050- **`approval-signers-hardware`** lists the hardware approval keys: the keys from `approval-signers`
4051 whose entry carries an `attestation` that verifies and says the touch policy is `always`. The
4052 YubiKey then asks for a touch before every signature.
4053- No gate reads either file, and the host module does not write them (`not built`).
4054- [`examples/identity/attested/`](../examples/identity/attested/registry.cue) is an example registry
4055 enrolling a YubiKey key for `example-operator`. Its keys are examples, and its attestation chains
4056 to a test-only root, "the-valley example attestation root, not Yubico". The compiler refuses it,
4057 so an entry copied from it compiles only with the enrolling YubiKey's own certificates.
4058
4059An `attestation` verifies when all of these hold:
4060
40611. The `slot` certificate chains through the entry's `f9` certificate and Yubico's PIV intermediates
4062 to Yubico Attestation Root 1, on the day the compilation is for (`--now`, default today).
40632. The `f9` certificate is the one that signed the `slot` certificate.
40643. The key in the `slot` certificate is the entry's `public` key.
40654. The `slot` certificate states a PIN and touch policy, in two bytes of Yubico's extension
4066 `1.3.6.1.4.1.41482.3.8`. The first byte is the PIN policy: 1 never, 2 once per session, 3 always.
4067 The second byte is the touch policy: 1 never, 2 always, 3 cached. These are the values Yubico
4068 specifies. An extension of any other length, or a byte with any other value, fails the
4069 compilation.
4070
4071The compiler carries that root and those intermediates, in
4072[`identity/yubico/`](../identity/yubico/attestation-root-1.pem), and a registry cannot add others.
4073The root is Yubico's `yubico-ca-1.pem`, with the SHA-256 fingerprint Yubico publishes:
4074
4075```text
407662:76:0C:6A:6E:F9:16:79:F4:54:C8:90:2B:80:FD:00:98:25:B3:F2:5D:A9:0F:1F:BA:CE:2E:C6:58:6C:D5:A8
4077```
4078
4079The compiler reports each attestation that verifies on stderr, with the YubiKey's serial number,
4080firmware, PIN policy and touch policy. Whoever reviews an enrollment checks them there. For a
4081YubiKey with serial number 12345678, enrolled as the first key of `example-operator`:
4082
4083```text
4084identity: example-operator: key 0 is on YubiKey serial 12345678, firmware 5.7.4, PIN policy always, touch policy always; it approves as a hardware key
4085```
4086
4087Who can do what, and what stops them:
4088
4089- **Whoever can land a registry change can enroll a key and its attestation.** The registry's own
4090 governance decides who that is.
4091- **Only Yubico's chain makes a key a hardware approval key.** A registry entry cannot add a root or
4092 an intermediate. It needs an attestation that Yubico's chain signs, for that exact key, with touch
4093 policy `always`. `bound: "hardware"` without an attestation does not make a hardware approval key.
4094- **Evidence that does not verify stops the compilation.** An attestation naming another key,
4095 altered, missing its `f9` certificate, chaining to another root, or stating a policy Yubico does
4096 not specify fails the whole compilation, and the last good files stay as they were. The key is
4097 never compiled as a software key instead.
4098- **A cached or never touch policy is not hardware.** Such a key is in `approval-signers` and not in
4099 `approval-signers-hardware`. With a cached policy, one touch allows further signatures for 15
4100 seconds.
4101- **One approval key belongs to one principal.** A key that approves and is also listed under
4102 another unexpired principal fails the compilation. A line in either file therefore names the only
4103 principal holding its key.
4104- **Enrolling someone else's attested key gains nothing.** An approval still needs a signature from
4105 the device that holds the key.
4106
4107Limits:
4108
4109- The compiler trusts Yubico's root, and the YubiKey's firmware, to state the touch policy
4110 truthfully.
4111- An attestation chaining to Yubico's older PIV root, used before firmware 5.7.4, does not verify.
4112- The PIN policy is reported, and nothing requires one.
4113- The files hold keys, not serial numbers. The compile report and the attestation link a key to its
4114 device.
4115
4116### Node frontmatter and bus events (`schema/node.cue`, `schema/events.cue`)
4117
4118Two additional CUE schemas validate knot frontmatter and NATS bus payloads:
4119
4120```sh
4121cue vet -c -d '#Node' schema/node.cue frontmatter.yaml
4122cue vet -d '#RefUpdated' schema/events.cue payload.json
4123```
4124
4125- **[`schema/node.cue`](../schema/node.cue) (`package knowledge`):** Defines `#Node`, `#Graph`, and
4126 `#Directories`. The `knot-agree` flake check verifies that `#Node` and `knot/` enforce the same
4127 frontmatter rules (note that `#GraduationTarget` in `schema/node.cue` also admits `*.md` paths for
4128 tree-based test graphs, whereas the live plan graph in [`knot/graph.go`](../knot/graph.go)
4129 requires `graduated_into` to name a local `oc-*` or `qn-*` knot; historical nodes under
4130 `archive/.the-valley/` are frozen read-only history and are not checked against today's schema).
4131- **[`schema/events.cue`](../schema/events.cue) (`package valley`):** Defines the three NATS event
4132 payloads published under `valley.git.<repo>.<event>` when the optional host event bus is enabled
4133 (`services.valley.bus.enable`, a `deployment choice`; publication is best-effort and never blocks
4134 a push or landing):
4135 - `#RefUpdated`: `{ event: "ref-updated", repo, ref, old, new }` (published by the host's
4136 post-receive publisher hook, by the integrator on landing, and by `valley replay`).
4137 - `#IntegrationSucceeded`:
4138 `{ event: "integration-succeeded", repo, change, target, old, new, transferred: [...#CheckName] }`
4139 (published by the integrator when a request lands).
4140 - `#RequestStale`:
4141 `{ event: "request-stale", repo, change, target, tip, reason: "conflict" | "evidence", checks: [...#CheckName] }`
4142 (published by the integrator when a request cannot land because of a merge conflict or
4143 non-transferring check evidence).