gunk-dev/the-valley
the-valley:oc-c0db2b0outcomeopen

Landing is one crash-safe transaction with a decision ledger

State
free to start
Created
2026-10-17 by contributor
Source
2026-10-04, plan.md decision 5 and M4 item 3

Body

Each landing writes one versioned decision record (request, previous and resulting state, policy revision, approvals, build results) to an append-only ledger ref. The same ref transaction moves the target and consumes the request with a leased compare-and-swap. A write-ahead intent and idempotent recovery cover crashes. Backups include the decision namespaces.

Today landing is several separate ref updates, and the integrator moves `main` before it stores evidence.

Done when interruption tests kill the integrator at every persistence step and both the decisions and the requests survive.

Source: `plan.md` decision 5 and M4 item 3; the-valley `docs/roadmap.md`, "Further work".

---

Design revision 2, 2026-10-21: authored by Astra (Codex gpt-6-astra), reviewed cross-family by Claude against e3fdc96; every review finding adopted (see the final section). The review of revision 1 is a comment on this knot.

# Landing ledger (design, revision 2)

Each landing or withdrawal that consumes a request appends one durable decision.
The decision retains the approved head, target state, policy snapshot, approvals and evidence.
One leased ref transaction publishes the decision, updates the target and consumes the request.
An intent retains the decision until recovery and post-commit work finish.
Recovery derives its writes from the decision; it executes no stored operation list.
Each pass pins the instance commit and a copy of known-signers.
Failed registry compilation leaves integration using the last good signers file.
Transfer v2 and the extended outcome memo ship before the ledger.
Readers retain support for older outcomes and transfer statements.
There is no host guard, registry-generation writer or new publisher.
Five slices deliver the work, with readers deployed before new formats are written.

## Basis

**Implemented** claims cite HEAD `e3fdc96a4964906eb42c9dbbfe7040268ba47d5c`, which equals the local `origin/main`. Knot paths refer to `refs/the-valley/knots` at `11eac11fa7f6304f8096b52bd3749d927181aee9`. Remote freshness and deployed versions are **unconfirmed**.

All proposed mechanisms below are **not built**. Host configuration is labelled **deployment choice**. This is a source review and design, not a report of executed tests.

The required scope comes from the landing transaction, snapshot and source-binding knots: `outcomes/oc-c0db2b0-landing-is-one-crash-safe-transaction-with-a.md:13`, `outcomes/oc-e527f0b-the-outcome-records-the-policy-and-registry.md:13` and `outcomes/oc-4018719-the-transfer-statement-binds-the-source-head.md:13`.

## 1. The decision record

### Decision — not built

A decision records a request-consuming action and the evidence used to authorize it. Append decisions only for `land` and `voided-withdrawn`. Staleness, rejection, readiness refusal and failure continue to use the outcome memo.

Use strict JSON with `schema: "the-valley/decision/v1"`. A Go codec rejects duplicate keys, unknown fields, malformed identities and oversized records. Its encoding is deterministic.

The record contains:

| Field | Contents |
| --- | --- |
| `schema` | `the-valley/decision/v1`. |
| `kind` | `land` or `voided-withdrawn`. |
| `project` | The configured project name. |
| `request` | Request name, exact head and target stream. The Git adapter derives the request ref from these fields. |
| `version` | Source head and source tree digest; merge base for a landing. Change ID, version number and change-record commit are nullable for requests without a change record. |
| `target` | Previous and resulting target revisions, plus the resulting tree digest. A voiding leaves the target unchanged. |
| `snapshot` | Instance source identity, composed-policy digest, signers digest and snapshot digest, as defined in §3. It identifies the retained policy and signers artifacts. |
| `approvals` | The integration request relied on. Each entry names its kind, exact subject and durable record when one exists. Unavailable principal, time or signature information remains null. |
| `records` | The per-change record refs and object IDs used for final validation, including the record that justifies a voiding. |
| `reviews` | Nullable list of `{ref, commit}` pairs identifying the exact review records relied on. Null means review enforcement was not evaluated; an empty list means it was evaluated and required none. |
| `checks` | Required checks, selected evidence and build results, with the fields below. Empty for a voiding or a landing requiring no checks. |
| `evidence` | Evidence fingerprint and retained original and countersigned notes. Includes the signed transfer for a landing. |
| `memo_before` | Previous outcome-memo object ID, or null. Used only for the memo lease. The new memo is derived from the decision. |
| `timings` | Decision start and completion time, elapsed decision work, and per-check evaluation durations. Reported build timings are nullable and identify their producer. |

Each check entry records its name, requiring classes, runner and definition, evidence object and signed-text digest, signer, claimed result, transfer rule and reason. Pure checks include attested and recomputed input and derivation digests, and the claimed output digest. Effectful checks include the observation time, environment, validity window and touched classes.

The integrator records results it verified; it does not claim to have built them. **Implemented:** evidence and transfer judgments are separate structures (`integrator/verdict/verdict.go:115`, `integrator/verdict/verdict.go:227`). Pure statements contain output digests that the current evidence reader does not retain (`schema/attestation.cue:129`, `integrator/evidence.go:93`).

A request currently preserves its head, target and name, not its approving principal or approval time (`integrator/refs.go:47`). Record that limitation. Commit authorship is not approval attribution.

### Location and retention

Use:

```text
refs/the-valley/decisions/<target>       -> latest decision commit
refs/the-valley/landing-intents/<target> -> pending decision commit
```

The ledger starts with one fixed empty root commit. Each decision’s first parent is the previous ledger tip. Additional parents retain the source head, target commits and referenced change or review commits. The decision commit’s object ID is its identity; no separate `decision_id` or `previous_decision` field is needed.

The tree contains `decision.json`, policy and signers artifacts, and the notes required to reconstruct attestation projections. Copy external policy and registry source artifacts into that tree. Retain blobs and trees through actual Git object links, not merely object IDs inside JSON.

**Deployment choice:** keep committed decisions indefinitely. There is no quota or archival subsystem in this work. Bound each JSON record to 1 MiB and its retained metadata to 16 MiB. Exclude build outputs and full logs; retain their digests and signed results. Total history grows with request-consuming actions.

Timings use UTC timestamps and integer elapsed durations with explicit units. Missing data is null, not zero. The immutable decision cannot include the measured duration of writing itself. Persistence and recovery timings remain structured journal entries keyed by decision commit.

The timing knot currently specifies local approval logs and structured integrator logs without changing evidence formats (`outcomes/oc-214f38f-approval-and-the-integrator-record-check-and.md:16`). The ledger does not invent unavailable build timings.

### Relationship to existing records

The ledger supplements the outcome memo and retains the transfer statement. It replaces neither reader interface.

- The memo remains the latest answer for a request.
- The transfer statement remains the landing proof used by `rebase` and `valley changes`.
- Attestation refs remain projections written after the landing transaction.
- Change records continue to describe readiness and versions. They are not landing decisions.

**Implemented:** change records can refuse a request but cannot authorize one (`integrator/records.go:5`). The existing landing reader depends on transfer evidence and treats the memo alone as insufficient proof (`rebase/snapshot.go:16`, `rebase/snapshot.go:32`).

### Reason and rejected alternatives

Only request-consuming actions need this durable transaction history. Recording every polling result would enlarge the ledger without meeting an additional done-when criterion.

Reject a second outcome namespace, duplicate identity fields and embedded build logs. Retain the existing memo and transfer interfaces so ordinary readers need no ledger walk.

## 2. The transaction

### Decision — not built

Write the complete decision object first. Publish an intent pointing to it. Then move the ledger, target, memo and request through one leased `git update-ref --stdin` transaction.

**Implemented:** the current sequence moves the target before storing evidence, deleting the request and writing the memo (`integrator/refs.go:491`, `integrator/refs.go:498`, `integrator/refs.go:511`, `integrator/refs.go:170`). Voiding similarly deletes the request before writing its memo (`integrator/records.go:433`, `integrator/records.go:438`).

### Atomicity and concurrency

Git prepares a transaction by locking its refs and checking the supplied old values. Failure to prepare applies none of its updates. Individual ref writes are atomic, but readers may see a subset of the transaction. [Git update-ref documentation](https://git-scm.com/docs/git-update-ref).

The inspected upstream files backend writes updates before deletions: `refs/files-backend.c:2812` and `refs/files-backend.c:2863`. Thus its normal commit ordering writes the target and ledger before deleting the request. This ordering is **unconfirmed for the deployed Git** and is not a substitute for recovery. [Git files backend](https://github.com/git/git/blob/v2.47.0/refs/files-backend.c#L2812).

There is no host lock or fetch guard. Pushes continue during decisions and recovery. Leases and `verify` operations resolve collisions.

**Deployment choice:** run one integrator per served repository. Stop its service before manual recovery or a one-shot integrator run. The host already supplies one service instance per project (`nix/valley-host.nix:1655`). Its unit leaves systemd’s default control-group termination in place; recovery must begin after that unit’s previous children have exited (`nix/valley-host.nix:1731`; [systemd termination semantics](https://www.freedesktop.org/software/systemd/man/latest/systemd.kill.html#KillMode=)).

### Final validation

Keep the current final readiness read. Preserve the object IDs returned by that read, rather than resolving the ref names again afterward.

Add a `verify` operation for every relevant existing per-change record the decision used. Always verify the request’s own change record when applicable. Review enforcement later adds verification of its exact review-history ref, including verification that the ref is absent when absence was evaluated.

A different change’s newly created record can still appear after the final index read. Accept that race. The source explicitly accepts records written after the last read because the landed head is still the head approved by the operator (`integrator/records.go:31`, `integrator/refs.go:476`).

Policy and signer changes during a pass take effect on a later pass. This transaction does not lock another repository or a host file.

### Intent and allowed writes

The intent is simply:

```text
refs/the-valley/landing-intents/<target> -> D
```

Here `D` is the fully constructed decision commit. Creating the ref requires that it be absent. The intent retains all recovery material and stays until post-commit work finishes.

Recovery validates `D` and derives the permitted refs from its typed fields:

- The target from `target`.
- The request and outcome from the target and request name.
- The ledger and intent from the target.
- Record and review dependencies from validated namespace-specific entries.

For a landing, the decision must agree with the signed transfer’s project, target, source head, result and snapshot. A voiding must carry the withdrawal record it read. Reject symbolic refs, invalid targets, missing objects and unexpected namespaces.

There is no executable transaction string or arbitrary operation array in project storage.

### Exact transaction

Let:

- `T` and `L` be the previous and resulting target commits.
- `H` be the approved head.
- `P` and `D` be the previous and new ledger commits.
- `M` and `B` be the old and derived new outcome blobs.
- `0` mean the repository’s all-zero object ID.

For a landing, run `git update-ref --no-deref --stdin` with:

```text
start
verify refs/the-valley/landing-intents/<target> D
verify <each relevant change-record ref> <observed commit>
verify <each evaluated review ref> <observed commit or 0>
update refs/the-valley/decisions/<target> D P
update refs/heads/<target> L T
update refs/the-valley/integration-outcomes/<target>/<request> B M
delete refs/the-valley/integration-requests/<target>/<request> H
prepare
commit
```

Use `create` when the outcome is absent. Emit each ref only once. If an update would leave a value unchanged, emit `verify` instead.

For a voiding, replace the target update with `verify <target> T`. Derive `B` as `voided-withdrawn`. Its request deletion has the same head lease.

Neither attestation projections nor the publish queue is in this transaction.

Preparation failures caused by a changed lease or active lock contention retry on the next tick. They must bypass the current ten-minute failed-memo backoff (`integrator/refs.go:216`, `integrator/refs.go:229`).

### Persistence and recovery

Recovery runs before ordinary reconciliation, even if the request namespace is empty. The current early return for no requests must move after recovery (`integrator/refs.go:108`).

| Persistence step | Interruption rule |
| --- | --- |
| Initialize the empty ledger root, if absent. | Retry its create. No request or target is involved. |
| Write landing, snapshot, notes, memo and decision objects. | Without an intent, leave refs alone and recompute. Unreferenced objects are disposable. |
| Create the intent ref pointing to `D`. | Read and validate `D` on restart. Never regenerate its signatures or timestamps. |
| Prepare the ref transaction. | If no decision effect is visible, discard the uncommitted intent and reconsider the current request and dependencies. |
| Commit the ref transaction. | Inspect actual refs. Complete a partially published decision using the rules below. |
| Write attestation projections. | Rebuild them from the retained decision. Repeating an identical write is harmless. |
| Queue the target move. | Re-queue a confirmed landing. Repeating the handoff is harmless. |
| Attempt bus notices. | Best effort. A crash can lose or repeat a notice. |
| Delete the intent, leased on `D`. | If it remains, recovery repeats the completion work. If absent, reconciliation proceeds. |

A transaction attempt is uncommitted when its ledger, target and memo have no attributable change. A missing or replaced request alone is not proof of a landing: the operator may have withdrawn or replaced it.

Once a decision effect is visible, roll forward:

| Observed state | Action |
| --- | --- |
| Landing target remains at `T`. | Complete `T → L` with a lease. |
| Target is `L`, or a later target contains `L`. | The target move is complete. Never rewind it. |
| Target has another value that does not contain `L`. | Stop recovery for this target and report the conflict. |
| Voiding target has moved. | Leave it alone. A voiding has no target update to recover. |
| Request still equals `H`. | Delete it with an `H` lease. |
| Request is absent. | Consumption is complete. |
| Request equals another head. | Leave the fresh approval intact and complete the remaining decision writes. |
| Ledger is `P`. | Append `D` with a `P` lease. |
| Ledger already contains `D` on its decision chain. | Do not append again. |
| Memo is `M`. | Write the derived `B` with a lease. |
| Memo is already `B`. | Do nothing. |

Rebuild each remaining transaction from these observations and the decision. A concurrent request change can fail preparation; reread and retry without that deletion if it now names another head.

Do not reapply readiness or review requirements to an action already partly committed. Those requirements governed its original transaction. Rechecking them during roll-forward could strand a landing after its target moved.

An unrelated ledger rewrite, a malformed decision or missing retained objects is storage damage, not an ordinary push race. Report it and preserve the intent rather than guessing.

Never automatically remove `.lock` files. Retry ordinary contention. If a lock remains after its writer has exited, stop that target and name the lock. The runbook has the operator stop the integrator, establish that no Git process owns the lock, remove only the stale file and restart recovery.

A ref containing `H` cannot distinguish an old request from a newly filed approval of the same head. Preserve different-head approvals; do not claim occurrence-level protection for identical-head reapproval. The current code itself treats a refiling after voiding as fresh approval (`integrator/refs.go:225`).

### Post-commit work

Write attestation projections after the transaction, using the retained notes. A replayed valid note must not make a landing fail a projection lease. **Implemented:** the hook deliberately permits evidence relaying and does not equate pusher with signer (`valleyhook/attestation.go:38`).

Keep the intent while a projection or queue handoff needs retry. The landing remains committed; failures do not become failed landing memos. New decisions on that target wait for completion, but pushes and fetches remain available.

Reuse the existing publish queue. Its drain retries failures and pushes current `main`, regardless of the queued old move (`nix/valley-host.nix:369`). Bus notices remain best effort (`integrator/refs.go:519`). Add no ledger-scanning publisher or dispatch cursor.

### Reason and rejected alternatives

The transaction prevents ordinary partial publication caused by separate commands. The intent covers interrupted publication and post-commit work.

Reject a host guard, automatic lock deletion and rollback of a partly published landing. Reject attestation leases in the landing transaction and free-form recovery operations.

## 3. Policy and registry snapshots

### Decision — not built

Pin the instance source and effective signer bytes once per pass. A snapshot records what the integrator actually used, including any lag between registry source and compiled signers.

At pass start:

1. Resolve the instance ref to commit `I`.
2. Read the floor through `I`, never through the mutable ref.
3. Record the registry source at `I`. Reading or retaining those source bytes does not require successful registry compilation.
4. Open known-signers once, copy its bytes, compute SHA-256 digest `S`, and give that copy to every verifier.
5. Pin target `T`, compose its project policy with the pinned floor and obtain digest `P`.
6. Keep those inputs for the pass. End the pass after a landing changes the target.

The policy digest remains SHA-256 over the exact complete CUE export. **Implemented:** this already includes checks, classes, carry modes and restack settings (`composed/composed.go:191`, `composed/composed.go:227`).

Fix both mutable-ref extraction gaps. Floor extraction currently reads files through its supplied tree-ish (`composed/composed.go:64`, `composed/composed.go:134`, `composed/composed.go:152`). Registry compilation resolves a commit but then reads through the original ref (`identity/registry.go:78`, `identity/registry.go:83`). The compiler should likewise use its resolved commit for every source read.

For a materialized floor, copy its documents once and use a content identity instead of `I`. Do not invent registry-source provenance when none is available.

### Keep the last good signers file

Known-signers is the only registry artifact the integrator currently reads (`integrator/evidence.go:127`). It is replaced as a whole by rename (`identity/compile.go:137`, `identity/compile.go:164`).

If registry compilation fails, keep using the existing readable signers file. Do not require it to match `I`. This preserves the deliberate host behavior that lets controllers run after a failed compilation (`nix/valley-host.nix:1669`).

The snapshot states:

- Registry source observed: `I`.
- Effective verifier input: digest `S`.
- Registry commit that produced `S`: unknown unless independently supplied.

This is not a claim that `S` was compiled from `I`. Signer publication can provide that provenance later. Missing or unreadable known-signers remains an error; there is no invented trust fallback.

### Extended memo

Keep the existing outcome namespace. Add an explicit suffix understood by the deployed reader:

```text
H T E outcome [failed-at] snapshot-v1 I P S
```

`E` remains the existing evidence fingerprint. `I` is a typed Git commit identity or materialized-floor content identity. `P` and `S` are full SHA-256 digests.

The parser accepts exactly the legacy forms and this versioned extension. Unknown suffixes, malformed fields and extra lines remain unreadable. **Implemented:** the current parser rejects a sixth field (`rebase/outcome.go:22`).

Define the snapshot digest as SHA-256 over a fixed, versioned encoding of project, target, `T`, `I`, `P` and `S`. Use that digest in transfer v2 and in decisions. The ledger retains the corresponding bytes for landings and voidings.

The integrator compares `H`, `T`, `E`, `I`, `P` and `S` before suppressing a repeated answer. A legacy memo has no snapshot and therefore needs a fresh decision. A changed instance commit, composed policy or signers file triggers reconsideration.

**Implemented:** the current key contains only `H`, `T` and `E`, before policy materialization (`integrator/refs.go:146`, `integrator/refs.go:329`). Refusals and voidings continue to be reconsidered as today (`integrator/refs.go:234`).

Expiry affects integration when the compiler publishes changed signer bytes. The compiler removes expired principals’ keys and grants (`identity/render.go:90`). This work does not create a second expiry evaluator.

### Boundaries

Approval verifies intent. It does not refresh a check result. Preserve the pure-check input and derivation comparisons and the effectful-check scope and age rules (`integrator/verdict/verdict.go:406`, `integrator/verdict/verdict.go:413`, `integrator/verdict/verdict.go:425`).

Update status and restacker parsing in the readers slice, but defer their snapshot-currency behavior. Status continues comparing tip and evidence; the restacker continues its existing currency rule (`status/status.go:403`, `restack/plan.go:177`). This can permit an avoidable restack while the integrator reconsiders changed authority. No hard count bound is claimed.

### Reason and rejected alternatives

The snapshot makes retry behavior sensitive to the policy and signer inputs actually used. It does not require a new identity publication protocol.

Reject generation directories, coordinated activation of all identity artifacts and refusing integration until the latest registry compiles. That refusal could prevent landing the registry repair.

## 4. Transfer statement v2

### Decision — not built

Keep envelope `the-valley/attestation/v1`. Add predicate type `the-valley/integration/transfer/v2`.

Keep the v1 fields. Add:

- `project`: the configured project identity.
- `source`: a binding, typed revision identity for the approved head.
- Optional `snapshot`: the snapshot digest from §3.

For example:

```text
predicateType the-valley/integration/transfer/v2
predicate.project the-valley
predicate.source.scheme git-sha1
predicate.source.id <approved-head>
```

`source` is not an advisory member of a digest set. The existing schema treats Git members of ordinary digest sets as advisory (`schema/attestation.cue:26`, `schema/attestation.cue:65`).

The existing subject already carries the landed commit and resulting tree (`integrator/transfer.go:76`). Do not add another result identity. The reader checks that commit’s actual tree against the signed subject, as it already does (`rebase/snapshot.go:461`, `attest/verify.go:111`).

The snapshot field is optional in the deployed v2 schema so the transfer writer can ship before snapshot pinning. The snapshot slice starts filling it. Absence means unrecorded; it must not be filled with a digest of unpinned inputs.

Update the canonical rendering order with the schema. A new field otherwise has no written form (`attest/text.go:25`, `attest/text.go:132`).

### Classification and compatibility

Write v2 only at the existing `transfer.note` after readers deploy.

For v2, `landed-recorded` requires:

1. A valid signature from the trusted integrator.
2. Matching project, target, request identity and exact source head.
3. Matching source-tree digest.
4. The named landed commit on the target’s accepted first-parent history.
5. Its actual tree matching the signed subject.

No outcome memo or recomputed merge is needed to establish the source-to-result association. Retain the current target-history safeguards (`rebase/snapshot.go:164`).

Keep the full v1 classification rule, including its memo and merge checks (`rebase/snapshot.go:280`). Leave stored v1 statements unchanged.

No inventory pattern or ledger walk is required; readers already scan attestation refs (`rebase/origin.go:34`). A lagging reader skips v2 (`rebase/snapshot.go:384`). It may show `uncertain` when the corresponding consumed-request memo is readable; other incomplete states can show `not-landed` (`rebase/snapshot.go:257`). Deployment must update supported clients first.

### Reason and rejected alternatives

Binding the approved head closes `oc-4018719` independently of the ledger. Trust keys and target history are still needed; “statement alone” removes the memo and merge reconstruction, not signature verification.

Reject dual v1/v2 writing, new statement namespaces and a ledger-dependent landing classifier.

## 5. Hook and authority

### Decision — not built

Add no push-hook mechanism for the ledger. Preserve the existing namespace boundary.

| Namespace | Writer |
| --- | --- |
| `decisions/*`, `landing-intents/*` | Local integrator and its recovery path. No push. |
| `integration-outcomes/*` | Local integrator. No push. |
| `integration-requests/*` | Request-grant holders through the hook; leased consumption by the integrator. |
| `attestations/*` | Existing authenticated, create-only push path; local integrator projections. |
| `changes/*`, `restack/*` | Existing owner, request-grant and narrow restack rules. |
| `reviews/*` | The separately deployed review contract and review grant. |
| Signer publication | Its separately deployed host publisher. |

**Implemented:** unknown project-storage namespaces are closed before configurable grants are considered (`valleyhook/policy.go:129`). A push cannot publish, rewrite or delete a decision ref. Local `update-ref` does not run pre-receive (`valleyhook/main.go:96`). No reference-transaction hook is installed by this host module; its discussion is about an alternative to the existing publish queue (`nix/valley-host.nix:379`).

A legitimate request push and the landing transaction contend through Git’s ref locks and old-value checks. An extra policy decision in the hook is unnecessary.

The restack grant gains no ledger, request or review authority. Its existing scope is a restricted version append and restack reports (`valleyhook/policy.go:48`).

### Reviews and trust

Reserve `reviews` as `{ref, commit}` references. Retaining those commits preserves the review records without copying their full contract into the decision schema.

When review enforcement connects, its evaluator contributes the review refs to the transaction’s verification set. Verify absence too. This gives it atomic final validation without designing review selection, carry or model execution. That boundary follows the recorded review direction (`comments/oc-5b0e87c/20261019T131924Z-cbb1dc64a14d953e.md:10`).

The current `oc-0fb4426` contract and signer-publication implementation are **unconfirmed in this checkout**. Keep their interfaces explicit and do not infer a signer’s authority from keys included in a decision. Readers retain their independent trusted signer configuration (`status/inventory.go:35`).

Namespace validation also limits damage from malformed intents in repositories served without the hook. It does not make such repositories trustworthy. The integrator already acknowledges that an unhooked repository permits arbitrary request writes (`integrator/refs.go:59`).

### Reason and rejected alternatives

Existing push policy already closes the new namespaces. The ledger needs validated local writes, not a new grant.

Reject changes to the login-shell lifecycle, a production reference-transaction hook and arbitrary recovery ref names. Arbitrary local filesystem access remains outside the remote-push guarantee.

## 6. Backups and restore

### Decision — not built

Keep the existing whole-data-directory backup. It includes every new decision and intent namespace without additional ref selection.

**Deployment choice, implemented configuration:** restic backs up `cfg.dataDir` (`nix/valley-host.nix:1850`). Decisions retain their signers and policy artifacts inside the served repository, so those historical inputs are included.

A consistent capture uses the existing push hold:

1. Create the hold, preserving any pre-existing operator hold.
2. Let already-running receive-pack processes and their maintenance finish.
3. Stop the integrators and other local repository writers.
4. Run the backup.
5. Restart only the services stopped for this capture; remove only its own hold.

The hold rejects new pushes but does not drain existing ones (`valleyhook/shell.go:82`). Its path is already configured (`nix/valley-host.nix:602`). Put this orchestration in the backup prepare and cleanup path, implemented in Go or Nix with thin shell glue. Abort capture if writers cannot be quiesced.

The isolated restore drill checks:

- Source, requests, outcomes, decisions, intents, attestations, changes, reviews and plan storage are present.
- `git fsck` succeeds and retained decision objects remain reachable.
- Pending recovery finishes or reports the documented target conflict or stale lock.
- Consumed heads remain retained; different-head fresh approvals survive.
- Projections can be rebuilt and confirmed landings re-queued.
- Legacy and new outcomes and transfers remain readable through changes, status and review.

Keep outbound publication disabled during the drill. Host secrets and live identity-state restoration remain the existing host recovery responsibility; their deployed coverage is **unconfirmed**.

### Reason and rejected alternatives

The existing backup scope is sufficient. It needs a consistent capture and a restore check, not a new backup namespace mechanism.

Reject treating source mirrors or bus events as backups of decisions.

## 7. Interruption tests

### Decision — not built

Use real Git, the real rendered pre-receive hook and the real integrator. Publish ordinary requests and evidence through receive-pack.

The existing integrator fixture uses real valley and attestation binaries with a stand-in Nix evaluator (`integrator/e2e/run.sh:2`). Hook tests already exercise rendered hooks against real repositories (`nix/checks/hooks.nix:51`).

Add a Go driver with barriers at every persistence step in §2. Kill the integrator with `SIGKILL`, wait for the writing children to exit under the test’s service-equivalent cleanup, and restart it.

Use a test-only reference-transaction hook to stop at `prepared` and `committed`. The repository already uses a committed-state blocker in tests (`rebase/rebase_test.go:657`).

Construct intermediate ref states directly for recovery tests: target moved without ledger, ledger moved without target, memo moved with request retained, all updates present before request deletion, and completed transactions with an uncleared intent. Include stale `.lock` files. These tests exercise recovery’s observable inputs without a syscall-level Git driver.

Assert:

- A completed landing or voiding has exactly one ledger decision.
- An uncommitted attempt leaves the request available for reconsideration.
- A different-head fresh approval survives recovery.
- An advanced target containing `L` is never rewound; an unrelated target stops recovery.
- Repeated recovery leaves the same decision object and final state.
- Readiness and review-ref lease failures land nothing.
- A replayed valid integrator note cannot abort the landing transaction.
- Projection and queue failures leave a recoverable intent, without changing the committed outcome to `failed`.
- Ordinary lock contention retries next tick; stale locks are reported and never deleted automatically.
- Policy or signers changes trigger a fresh decision; failed registry compilation still allows a repair under the last good signer file.
- Wrong-head v2 statements fail even when source trees match.
- v1 and legacy memo fixtures remain readable.
- Garbage collection after completion retains every consumed head and decision artifact.
- All pushing principals are refused when attempting decision or intent writes.

**Deployment choice:** configure `core.fsync=objects,reference` and an actual fsync method in valley-init. These settings harden the named components; they do not establish a tested power-loss guarantee. [Git fsync configuration](https://git-scm.com/docs/git-config#Documentation/git-config.txt-corefsync).

### Reason and rejected alternatives

The done-when requires interruption of the integrator and survival of requests and decisions. Barriers, real hooks and constructed partial states cover that contract.

Reject the syscall-level driver and VM-reset gate. Defer power-loss claims rather than implying these tests prove them.

## 8. Slices and rollout

### Decision — not built

Use five slices and one reader deployment gate. Each slice brief and change description carries a claim-to-code checklist, with claim kind and citations verified against its HEAD (`AGENTS.md:77`).

| Slice | Scope and acceptance |
| --- | --- |
| **1. Readers and formats** | Add transfer v2 schema, rendering and verification; v1/v2 landing classification; extended memo parsing; decision codec and intent-ref validation. Add fixtures and bounds tests. No production writer uses a new format. Baselines: `attest/text.go:132`, `rebase/snapshot.go:280`, `rebase/outcome.go:22`. |
| **Deploy readers** | Deploy host tools, operator clients, review, restacker and klaus. Check their actual entry points against mixed-format fixtures. Whether klaus reads memo blobs directly is **unconfirmed** and must be checked here. Update that reader rather than adding a second outcome namespace by default. |
| **2. Transfer writer** | Write v2 only at `transfer.note`, initially without the optional snapshot field. Demonstrate a re-parented landing as `landed-recorded` with its memo absent. This closes `oc-4018719`. Baseline: `integrator/transfer.go:59`. |
| **3. Snapshot** | Pin instance commit and signers copy per pass; fix source extraction; write the extended memo and fill transfer v2’s snapshot field. Test policy and signer changes and failed registry compilation. This closes `oc-e527f0b`. Baselines: `composed/composed.go:134`, `identity/registry.go:83`, `nix/valley-host.nix:1669`. |
| **4. Ledger and transaction** | Write landing and voiding decisions, create intents, apply the leased transaction and recover from constructed partial states. Reuse projection and queue code. Ship disabled. Baselines: `integrator/refs.go:491`, `integrator/records.go:433`, `integrator/bus.go:105`. |
| **5. Interruption suite and enable** | Add both barrier kinds, concurrent-push tests, stale-lock handling, fsync configuration and the restore runbook. Complete security review, then enable one project. This closes `oc-c0db2b0`. Baselines: `rebase/rebase_test.go:657`, `nix/checks/hooks.nix:51`, `nix/valley-host.nix:1850`. |

The ledger codec belongs in slice 1, not beside its first production writer in slice 4. This preserves the explicit staging requirement without adding a sixth slice. The recorded schema failure supports deploying tools before format use (`bugs/bd-5859932-a-policy-that-uses-a-new-schema-field-blocks.md:12`).

Slices 2 and 3 may be developed independently after the gate. Both ship before enabling the ledger.

Activation needs no historical conversion. Drain the active pass, enable one project and inspect a real decision and restore. To roll back, disable new ledger writes only after resolving its intents. Keep the recovery-capable tool until no pending intent remains.

### Reason and rejected alternatives

The first two knots deliver value before the ledger. Five slices keep each writer change reviewable while preserving format staging.

Reject a combined transfer/snapshot/ledger cutover and an exception to schema staging merely because the integrator is initially the only ledger reader.

## Open questions for the operator

1. **Is identical-head reapproval during recovery required to be distinguishable?**  
   Recommendation: keep the current head-valued request model. Avoid reapproving the same head while its intent is pending. Distinct approval-occurrence identities are separate work.

2. **Is indefinite retention of compact decisions acceptable?**  
   Recommendation: yes. Retain metadata and signed results, omit full logs and outputs, and defer quota and archival mechanisms until measured growth warrants them.

3. **What establishes completion of the deployment gate for klaus?**  
   Recommendation: run its actual status and review paths against legacy and extended memos before enabling either new writer. Do not assume its parser contract.

## Risks

- **Readers can observe partial state.** There is no host-wide read snapshot. Not every partial state displays as `uncertain`; classification depends on the memo and refs present.
- **Recovery has no ten-second bound.** Ten seconds is the configured restart delay, not a completion deadline (`nix/valley-host.nix:1734`).
- **New records can race final validation.** Verified refs are protected; a newly created record belonging to another change remains the accepted race.
- **Signer compilation can lag or fail.** Integration uses the last readable signer file and records its digest. Its source registry commit remains unknown until publication supplies it.
- **Same-head requests have no occurrence identity.** Leases preserve different-head approvals, but cannot distinguish an identical-head refiling.
- **Operational damage needs intervention.** Stale locks, missing retained objects and unrelated target rewrites are reported rather than repaired speculatively.
- **Power-loss safety is unconfirmed.** This work establishes integrator-interruption recovery, with fsync configuration but no power-loss claim.
- **Projection history remains limited.** A `transfer.note` projection can be replaced for the same tree and signer; the ledger retains the original decision, but ordinary readers do not walk it.

## Changes from revision 1

1. **Finding 1 — adopted.** Corrected the voiding memo citation to `integrator/records.go:438`; tightened the memo-key, namespace and shared-repository references.

2. **Finding 2 — adopted, with factual qualifications.** Removed the host guard and added per-change `verify` operations. The accepted race is explicit at `integrator/records.go:31`. Disputed the blanket `uncertain` claim: `rebase/snapshot.go:257` also permits `not-landed`. The restart delay at `nix/valley-host.nix:1734` is not a recovery bound.

3. **Finding 3 — adopted.** Removed registry generations. Pin the instance commit and one signers copy; verification consumes only known-signers (`integrator/evidence.go:127`). Preserve whole-file replacement (`identity/compile.go:137`).

4. **Finding 4 — adopted.** Write v2 only at the existing projection; extend the memo in place; append only landings and voidings; exclude attestation refs from the transaction. Existing discovery and relay behavior support these cuts (`rebase/origin.go:34`, `valleyhook/attestation.go:38`).

5. **Finding 5 — adopted.** Removed the new publisher and cursor. Recovery reuses the queue; its drain pushes current `main` (`nix/valley-host.nix:369`). Bus notices remain best effort (`integrator/refs.go:519`).

6. **Finding 6 — adopted.** Use Go barriers, reference-transaction barriers and constructed partial states. The existing blocker is at `rebase/rebase_test.go:657`. Removed syscall and VM-reset tests.

7. **Finding 7 — adopted, with one qualification.** Removed quotas, duplicate IDs, duplicate predecessor fields and expanded review data. Deferred client currency changes and reused the backup hold. The “at most one” restack cost is **unconfirmed**: this HEAD contains a report-only planner (`restack/main.go:5`), not evidence of that execution bound.

8. **Finding 8 — adopted.** Keep running on the last good signers file after compilation failure, as required by `nix/valley-host.nix:1669`.

9. **Finding 9 — adopted.** Preserve different-head requests, accept targets containing the landing, leave stale-lock removal to the operator and retry contention without the failed-memo backoff. Existing request preservation and backoff are at `integrator/refs.go:505` and `integrator/refs.go:216`. Identical-head refiling remains an explicit limitation.

10. **Finding 10 — adopted within verified scope.** Upstream files-backend update-before-delete ordering is verified; deployed behavior remains unconfirmed. No reftable migration or compatibility claim is required.

11. **Finding 11 — adopted.** No ledger hook changes. Local writes bypass pre-receive and new namespaces are already closed (`valleyhook/main.go:96`, `valleyhook/policy.go:129`).

12. **Finding 12 — adopted.** The intent points to the decision. Recovery derives a fixed set of writes and rejects arbitrary namespaces; no operation list is executed. Unhooked repositories remain outside the push-authority guarantee (`integrator/refs.go:59`).

**Five-slice shape — adopted.** The only staging adjustment moves the decision codec into slice 1. Combining its format and first writer is rejected under the brief’s staging requirement and the recorded failure at `bugs/bd-5859932-a-policy-that-uses-a-new-schema-field-blocks.md:12`.

Comments

  1. contributor2026-10-21 09:58 UTC
    Cross-family review (Claude) of the landing-ledger design revision 1, 2026-10-21. Revision 2 (the body) adopts every finding.
    
    # Review: landing ledger design
    
    Cross-family review, against `wt-valley-ledger` at e3fdc96 and the knots at 11eac11.
    
    **Verdict.** The diagnosis is right and the citations are nearly flawless. But the design is about twice what the three done-when criteria need. Its host guard mostly closes a race the code accepts on purpose, and its registry rule creates a lockout. Cut the guard, the generation writer, the dual transfer write and the ledger-driven publisher. Ship the transfer and snapshot knots before the ledger. Five slices are enough.
    
    ## Citations
    
    I checked 46 citations: every one into `integrator/`, `rebase/`, `status/`, `restack/plan.go`, `valleyhook/`, `identity/`, `composed/`, `attest/`, `schema/attestation.cue` and `nix/`, plus the knot files. All but one support their claims, including the two real gaps the design found:
    - the floor is read through a mutable ref (`composed/composed.go:64,134,152`);
    - the registry is resolved, then read through the ref (`identity/registry.go:78,83`).
    
    1. **P3: one wrong citation.** `records.go:425` is the tip read in `void`. The memo written after the leased delete is at `:438`. Three other citations sit a few lines early but point at the right code: `refs.go:136` (the code is at `:146`), `policy.go:124` (`:129`) and `valley-host.nix:150` (`:152`).
    
    ## Simplification
    
    2. **P2: cut the host guard.** This covers transport supervision, the shared read lock, maintenance coordination and the intent check on fetch. Beyond what the leased transaction gives, it buys three things:
       - **It closes the records race.** The code accepts that race on purpose: "what lands is always a head the operator approved" (`records.go:31-34`, `refs.go:476-482`). That is approval as intent.
       - **It hides partial state from readers.** Readers already show this state as `uncertain` (`snapshot.go:26-29`). The window is milliseconds, or 10 s after a crash (`valley-host.nix:1734`).
       - **It proves no git child is still writing.** systemd already does: the unit keeps the default control-group kill.
    
       **Simpler:** add a `verify` line for each per-change ref the decision read. Today that is the request's change record; later it is `refs/the-valley/reviews/<target>/<change-id>`, verified as absent when it doesn't exist. That gives reviews the atomic final validation the review direction asks for (`comments/oc-5b0e87c/…131924Z…:10`, item d), with no lock.
    
       **Risk accepted:** a different change's newly created record can still race the landing, as today.
    
       The cut also removes liveness hazards. A stalled push holding the host lock stops every landing, and a stuck intent fails every fetch, including the operator's diagnostic tools. The guard would also require turning the login shell, which `exec`s git-shell today (`shell.go:105`), into a supervising parent.
    
    3. **P2: cut the registry generation writer.** The integrator reads exactly one registry artifact, known-signers (`evidence.go:127`). `authorized_keys` and `grants` never enter a landing decision, and each file is replaced whole by rename (`compile.go:137-140`).
    
       **Simpler:** once per pass, copy known-signers, hash it, and pass the copy to every `attest verify`. Resolve the instance tip once and read the floor and the registry through that commit, which fixes both gaps.
    
       **Risk accepted:** the outcome names the digest of the signers file, not the registry commit it came from, until signer publication (oc-ecd6173) carries that commit.
    
    4. **P2: shrink the compatibility projections.**
       - **Transfer.** Once readers are deployed, write v2 only, at the existing `transfer.note`. Old readers skip an unknown predicate type (`snapshot.go:384`) and show `uncertain`. `valley changes` then needs no ledger walk and no new inventory pattern (`rebase/origin.go:34`). This decouples oc-4018719 from the ledger; in the design it closes only at slice 8. v1 already carries the landed commit, bound by tree (`transfer.go:80`, `snapshot.go:461`). So the source head is the one binding field v2 must add.
       - **Outcome.** Once readers accept the longer line, extend the memo with the policy and signer digests (`ParseOutcome` rejects a sixth field, `outcome.go:32`). Don't add a `decision-outcomes` namespace. Keep the legacy memo beside a new one only if klaus parses memo blobs itself (unconfirmed).
       - **Ledger.** Append only the decisions that consume a request: landings and voidings. The knot says "each landing", and the design also appends refusals and repeated failures.
       - **Attestation projections.** Take them out of the transaction. Anyone holding a validly signed integrator note can create these refs (`valleyhook/attestation.go:41-80`), so a lease on one lets a replayed note abort a landing. Write them after the commit, as today, and let recovery rebuild them from the ledger.
       - **Risk accepted:** a lagging client shows new re-parented landings as `uncertain`.
    
    5. **P2: cut the ledger-driven publisher and the dispatch cursor.** The publish queue is durable, and the drain pushes the current main whatever the queue says (`valley-host.nix:369-372`). Recovery re-queues the move when it confirms a landing. The bus stays best effort (`refs.go:519-521`).
    
    6. **P2: trim the tests.** Cut the syscall-level git driver and the VM reset test: the done-when says kill the integrator, not git.
       - Kill at Go barriers in the integrator.
       - Kill from a `reference-transaction` hook at the prepared and committed states. The restacker tests already block there (`rebase_test.go:657`).
       - Build the mid-commit states by hand, with some refs moved and stale `.lock` files left behind. Recovery reads only refs and lock files, so how a state arose doesn't matter.
       - Set `core.fsync` in valley-init, and defer any power-loss claim.
    
    7. **P3: smaller cuts.**
       - Drop the storage quota, `decision_id` (the commit's OID is stable through recovery) and `previous_decision` (it duplicates the first parent).
       - Trim the decision record to what a landing needs, plus a nullable `reviews` list of {ref, record commit}.
       - Defer the restacker and status currency changes. The cost is at most one avoidable restack.
       - For backups, `paths = [ cfg.dataDir ]` already covers every namespace (`valley-host.nix:1850`). For a consistent capture, use the existing push hold (`valley-host.nix:602`) and stop the integrators in restic's prepare command.
    
    ## Gaps
    
    8. **P1: the registry rule can wedge the host.** "If the registry source changes but its matching generation is unavailable, integration waits" (design lines 273 and 512). A registry change that fails to compile never gets a matching generation. Every integrator then waits, including the one that would land the fix to the instance repository. Today a failed compilation deliberately keeps the controllers running on the last good file (`valley-host.nix:1669-1672`). Keep that behaviour, and record the digest of the file used.
    
    9. **P2: recovery needs rules that hold without a guard.**
       - **Request ref at a third value.** That is a fresh approval: leave it and complete the rest, rather than stopping writes.
       - **Target at a third value.** If it contains L, the landing is done. Otherwise stop and report; this is the only case that should stop.
       - **Stale `.lock` files.** They come only from SIGKILL or power loss, because git's handlers remove locks on SIGTERM. Stop that target and report. The operator removes the lock by hand, as a documented one-off step.
       - **Lock contention.** Pushes, and `gc --auto` run by `receive.autogc`, make prepare fail cleanly. Retry on the next tick instead of writing a `failed` memo with its 10-minute backoff (`refs.go:216-246`).
    
    10. **P3: the atomicity claim is correct, and one fact strengthens it.** One `update-ref --stdin` transaction is all-or-nothing at prepare, not on disk with the files backend, and bare repositories behave the same. The design misses that the files backend commits every update before any deletion ("perform updates first", `files-backend.c`; unconfirmed for the deployed git). So a kill inside git can't consume a request before the target and ledger are written. Reftable would make the commit atomic on disk. Whether it supports the integrator's linked worktrees is unconfirmed.
    
    11. **P3: the hook interaction needs no code.**
        - A local `update-ref` runs no pre-receive hook (`valleyhook/main.go:96-97`).
        - No reference-transaction hook is installed (`valley-host.nix:379-383`).
        - New `refs/the-valley/*` namespaces are closed to pushes by default (`policy.go:129-132`).
        - Receive-pack locks refs after pre-receive, so a push and the transaction collide only at lock time, and one of them fails cleanly.
    
    12. **P3: recovery shouldn't execute a free-form operation list.** Derive the roll-forward from the decision instead: the target T→L, matching the signed statement; the request delete, leased on H; the ledger; the memo. Refuse an intent that names any other ref. This defends repositories served without the hook (`refs.go:59-61`).
    
    ## Proposed shape
    
    Five slices and one deployment gate.
    
    1. **Readers.**
       - Transfer v2: a binding `predicate.source` (the head commit), a snapshot digest and the project, with render order and verification.
       - `rebase` classifies v2 at `transfer.note` from the statement alone, and keeps the v1 rule.
       - `ParseOutcome` accepts the extended memo.
    
       **Deploy readers** to the host, the clients and klaus.
    2. **Transfer writer.** The integrator writes v2. This closes oc-4018719.
    3. **Snapshot.** Pin the instance commit and the signers copy once per pass, read the floor and registry through that commit, and write the extended memo. This closes oc-e527f0b.
    4. **Ledger and transaction.**
       - The decision codec and its writer. No other tool reads the ledger yet, so the staging rule doesn't split them.
       - A trimmed intent: the decision commit plus the literal transaction.
       - One transaction with `verify` lines, and the recovery rules from finding 9.
    
       It ships behind a flag, tested against hand-built partial states.
    5. **Interruption suite and enable.** Real hook, real integrator, both barrier kinds and `core.fsync`. Enable one project, with a restore check in the runbook. This closes oc-c0db2b0.
    
    After the gate, slices 2 and 3 and slice 4 can proceed in parallel.