gunk-dev/the-valley
the-valley:ida-d86bb7aidearaw

Design: a change moves toward main by events, and every gate is a check

State
question or idea
Created
2026-11-09 by contributor

Body

Use one journal per project and one shared derivation of the work still due. Every durable write carries its transition into that journal. Controllers and clients wake, reread the relevant state, and act on obligations identified by their inputs.

Delivery is at least once. A client gets exactly one logical dispatch by committing a durable intent before advancing its cursor and passing that intent’s identity to an idempotent launcher. Persisting a cursor alone cannot provide that guarantee.

Everything described below as proposed is **not built**. References to current behavior name its source. The design belongs on the question knot; landed slices describe their implemented mechanisms in the architecture and security docs.

**1. The parts and the next step**

The public model keeps four independent parts.

| Part | Durable data | Reading |
| :--- | :--- | :--- |
| Change and versions | The change record at `refs/the-valley/changes/<target>/<id>`; immutable version heads; verified landing evidence | Read the record, then establish whether any version lands the current round. Keep the active version and the version that landed distinct. |
| Checks and integration | Signed build notes, signed reviews, signed approvals, attempt records, and integrator outcomes | Derive required checks from trusted policy; verify each result’s signer, binding and applicability; retain outcomes per version and input set. |
| Restack condition | The report at `refs/the-valley/restack/<target>/<id>` and the refs it names | A conflict matters only while its observed inputs still match. |
| Main health | Main’s tip, follow-check requirements, applicable results and attempts | Derive clear, clearing or muddy separately from whether a change landed. |

The stored change record currently has `ready`, `draft` and `withdrawn`, an active version, and an ordered version list. Landing is established separately. The existing landing calculation handles an earlier version landing while a later version remains active, and a later round descending from that landing. Preserve that distinction rather than introducing a second authoritative “landed” flag. (`change/record.go:59`, `change/record.go:96`, `rebase/snapshot.go:319`, `rebase/snapshot.go:345`.)

Draft records do exist. Klaus finalize calls `valley ready`, then calls `valley unready` when configured to leave the work awaiting review. The host admits initial records as ready, and `pending` separately lists recorded drafts. This is a two-write workflow, not an absence of drafts. ([Klaus finalize](klaus: internal/cmd/hidden.go:397), `valleyhook/record.go:243`, `status/pending.go:140`.)

Under the chosen direction, a successfully finished agent leaves its work ready. The coordinator’s review is a check on that ready work. Returning the change to draft remains an explicit pause.

The current restack report already defines applicability by comparing the target, requests, records and work refs it observed. Reuse that test. (`rebase/report.go:131`.) Main health currently combines signed passing evidence with worker telemetry, so its failure and running states are not yet durable project state. (`status/mainstate.go:25`.) The proposed attempt and failure records replace that dependency.

The checks model uses the existing policy distinction between a named requirement and the runner that supplies its evidence. A proposed declaration is:

```cue
checks: {
    build: {
        runner:    "nix"
        attribute: "build"
    }
    coordinator-review: {
        runner: "review"
    }
    human-approval: {
        runner: "approval"
    }
}

classes: source: {
    paths: {"**": true}
    requires: {
        build:              true
        coordinator-review: true
        human-approval:     true
    }
}

approval: hardware: true
```

These runner additions are proposed. The `review` field in a review record names the corresponding policy check. The trusted identity configuration says which principals and keys may answer that check. Policy does not contain an agent command or a prompt.

`approval.hardware` selects acceptable approval keys; it does not decide whether approval is required. That distinction already exists in the current schema. (`schema/verification.cue:80`.) The approval check itself is required by policy, normally by the instance floor.

The approval work needs careful reuse. `origin/approval/v1` introduces a `presence` runner and approval evidence bound to a tree, change and destination; it refuses transfer across a changed tree. (`origin/approval/v1:schema/verification.cue:126`, `origin/approval/v1:attest/approve.go:3`.) HEAD also contains a newer approval statement binding instance, project, target, change, version, head, record and principal. (`approval/statement.go:77`.) Use the runner model from the former and the scoped statement from HEAD. Do not import an unconditional hardware requirement or treat the two encodings as interchangeable.

| Runner | Who supplies the result | Binding | Carry to another version |
| :--- | :--- | :--- | :--- |
| `nix` | Host worker | Tree digest and check definition | Reuse for the same tree and definition under current signer policy. Any existing evidence-transfer rule remains a separate verification, not a claim that the new tree was built. |
| `command` | The runner declared for that effectful check | Tree, check definition, environment and observation | Only under its declared applicability and validity rules. |
| `review` | Authorized client reviewer or coordinator | Project, check definition and the verified delta; record, version and head retain provenance | Carry both pass and fail while the delta and check definition remain equal and the reviewer remains authorized. |
| `approval` | A person holding an enrolled approval key | The signed scope and the recorded head it names | Carries to a later version, and to the landing tree the integrator builds on a newer main, as far as the composed `carry` mode of the changed path classes allows (`same-paths`, `same-class` or `exact`; `docs/concepts.md:87`, `schema/verification.cue`). `exact` keeps it on its named version. A carried approval records the version it was signed for; it is never reattributed as a signature over another head. |

A check definition includes the fields that determine what the check means. Changing only an unrelated policy requirement does not invalidate every result. Changing a runner, review requirement or accepted signer set causes the affected applicability tests to run again.

A review verdict maps as follows:

- `approve` is a passing review check.
- `request-changes` is a failed review check.
- `withdraw` removes the named review from consideration.

For one applicable review check, an authorized, unwithdrawn failure keeps the check failed. A later pass does not silently erase it. A changed delta needs a fresh review. This matches the semantics described with the existing record, although host evaluation is not built. (`review/review.go:5`, `docs/architecture.md:2034`.)

Readiness, stack coherence and landing eligibility are also named checks in the internal model. They are reserved mechanical checks, not policy entries that a submitted change can disable. The author satisfies readiness; the restacker satisfies automatic restacking; the integrator satisfies the final landing conditions.

The derivation is a dependency graph with a fixed meaning, not an ordered rule table:

- Readiness enables work on the version.
- Independent build, review and approval checks can proceed together.
- Integration depends on applicable passing evidence and the mechanical conditions.
- Follow checks depend on the landing.

The result contains one `next` answer. For a ready version this is “satisfy the unmet checks,” with the checks and their runners. Several independent checks can be due in that answer. Each is one next move; sorting them for display does not establish execution order.

This is necessary for the worker to start immediately while a coordinator reviews. A scalar “current actor” would hide one of those moves.

The following table describes contributions to that answer. Its rows are not tested top to bottom.

| Unmet check or condition | Actor | Durable event announcing it |
| :--- | :--- | :--- |
| Recorded draft | Author | `change.drafted` |
| Ready version lacks applicable build evidence | Worker | `check.due`, runner `nix` |
| Ready version lacks an applicable review | Authorized client reviewer | `check.due`, runner `review` |
| Required review fails | Author, using the review’s feedback | `check.failed`, runner `review` |
| Required build fails | Author | `check.failed`, runner `nix` |
| Required approval is absent or inapplicable | Person holding an approval key | `check.due`, runner `approval` |
| Automatic restack is possible and needed | Restacker | `restack.due` |
| A current restack has a conflict | Author or a client acting for the author | `restack.conflicted` |
| A stack’s prerequisite change has not landed | Valley controllers | `integration.blocked`, naming the prerequisite |
| All applicable checks pass and mechanical conditions hold | Integrator | `integration.due` |
| A runner cannot execute or publish its work | Operator or runner recovery | `check.blocked`, reason class `infrastructure` |
| Landing commits | Follow-check worker; clients handling completion | `version.landed`, followed by applicable `check.due` events |
| A follow check fails | Client or operator deciding the repair | `main.muddy` |
| Change is withdrawn | Nobody progresses it | `change.withdrawn` |
| Landing evidence is incomplete or inconsistent | Integrator reconciliation or operator | `integration.uncertain` |

Every due obligation has a stable identity derived from its scope, check definition, binding and retry generation. The event ID is not its identity. Repeated observations, reconnects and equivalent restacks must name the same obligation.

The four required cases follow directly.

A stack is represented by dependencies between recorded changes. The valley discovers and handles the order. Builds and reviews may run before lower changes land, but integration waits for the prerequisite landings and coherent restacked inputs. A lower landing wakes the restacker, worker and evaluator. The client neither sequences the stack nor waits a guessed amount of time.

There is a binding limit worth keeping explicit: the existing review binding uses the merge base of the version head and target tip. It does not define a delta containing only one stack layer. (`review/binding.go:77`, `review/binding.go:121`.) Therefore, a review of an upper version can include unlanded lower changes. When a lower change lands, that comparison can change and the upper review can become due again. This design does not silently redefine the existing delta to avoid that consequence.

An approval standing on v1 while v2 is active remains an approval of v1. The view shows both facts. The integrator can consider the approved v1, subject to readiness, current policy and the approval’s content binding. It cannot relabel the signature as approval of v2. If integration requires a different tree, approval is due. If v1 lands and satisfies the current round, the restacked v2 is not independently dispatched for another landing; a later version descending from the landing can begin another round.

A review started on v1 can finish after a restack publishes v2. Admission verifies the v1 binding against the durable history. Applicability then compares its delta and check definition with v2. If both match, the result satisfies—or fails—the same obligation. The client keeps the same review dispatch identity. If the delta changes, the v1 result remains historical and a new obligation is due.

Main muddy after a landing does not undo that landing. It creates a project repair obligation naming the failed follow check, its tree and the landings it covers. This design adds no implicit freeze on all further integration. A project that wants a main-health gate declares one explicitly and must allow a useful repair path.

Put this derivation in a stdlib-only `flow` package:

```go
func Derive(inputs Inputs) View
```

`Inputs` contains normalized, verified facts. Loading Git objects, composing CUE, verifying signatures and computing deltas happen outside the pure function. Status, controller adapters and the web server call the same function. Unknown or unreadable inputs produce a blocked or unknown result, never an empty requirement set.

The host stores a derived report at `refs/the-valley/flow/<target>`. It contains the independent parts, the next obligations and the exact input fingerprint. Updating that report and emitting its changed obligations is one journaled transaction.

The report is a cache and a durable announcement. It grants no authority. A controller verifies its inputs and guards before acting. An integrator evaluation pass computes it for ready changes even when no approval has arrived, so reviews become due alongside builds. Direct consumers can derive the same view before that pass finishes.

**2. The journal**

The journal belongs in **project storage**, because it describes project activity and versions rather than the contents of a source version. This follows the existing source/project-storage boundary. (`docs/architecture.md:44`.)

Use one logical journal ref per repository:

```text
refs/the-valley/events
```

Use two supporting refs:

```text
refs/the-valley/event-transaction   # crash-recovery intent, normally absent
refs/the-valley/flow/<target>       # derived report
```

Attempt records, reviews, approvals and ordinary change records remain their own state. They are not replaced by the journal.

Choose one journal rather than one per writer. A project gets one sequence and one cursor, and snapshots get a meaningful watermark. Per-writer logs would require a vector cursor and a rule for snapshots across independently advancing writers. That complexity buys little because only the short publication transaction is serialized; builds, reviews, signatures and restacking computation remain concurrent.

Each journal commit holds one transaction record. One transaction can announce several facts, so a landing and its request consumption share a cursor.

The proposed `valley-transition/v1` fields are:

| Field | Meaning |
| :--- | :--- |
| `schema` | `valley-transition/v1` |
| `project_id` | Stable project identity, not merely its mutable display name |
| `generation` | Random identity for this journal’s history |
| `sequence` | Increasing integer, encoded as a decimal string |
| `transaction_id` | Stable identity retained when an ambiguous publication is retried |
| `previous` | Digest of the preceding logical record |
| `writer` | Authenticated principal and controller role, established by admission |
| `causes` | Input transaction IDs or obligation IDs where known |
| `updates` | Ref names and their exact old and new object IDs |
| `facts` | Typed transitions, with change/version/check identities where applicable |
| `inputs` | Relevant policy, signer and external-input identities |
| `observed_at` | Diagnostic time; never ordering or authority |

Facts contain reason codes, evidence object IDs and obligation IDs. They contain no raw build logs, prompts, private paths or credentials. Review text remains in review records, where its format and access are explicit.

Do not let clients submit arbitrary journal facts. The receiving machinery derives facts from admitted writes. A review push can cause `review.recorded`; it cannot claim `version.landed`.

The cursor identifies project, generation, sequence and logical record digest. It is opaque to clients. Including the digest detects a cursor aimed at a different history rather than accepting a coincidentally equal sequence.

Sequence advances only for a committed journal transaction. Normal retention does not reset sequence or generation. A deliberate history replacement or restoration that loses accepted history starts a new generation. Ordinary service restarts do neither.

The transaction boundary is the essential implementation choice.

The integrator currently uses a leased `git update-ref --stdin` transaction and sends notifications afterward. (`integrator/refs.go:591`, `integrator/refs.go:624`, `integrator/refs.go:750`.) The restacker publishes through pushes in several recoverable phases. (`restack/publish.go:12`.) Both need the journal included at their actual publication boundaries.

Introduce a shared Go transaction package used by all hosted writers. It performs:

1. Admission and expensive preparation against pinned input objects.
2. Acquisition of a per-project publication lock.
3. Recovery of any interrupted accepted transaction.
4. Revalidation of the relevant ref and configuration leases.
5. Construction of the next journal record from the current journal head.
6. Durable preparation of the transaction’s old values, new values and journal record.
7. One Git ref transaction containing the state writes and journal advance.
8. Confirmation of that transaction, followed by removal of its recovery intent.
9. Advisory wakeups after publication.

A preparation losing its input leases is recomputed. Losing only the journal lease requires rebuilding the append against the new journal head; it does not require rebuilding the change.

Client pushes enter through a Go `proc-receive` implementation in `valleyhook`. It owns publication of all accepted commands in the receive operation and adds the journal update. Existing push-policy checks remain admission checks. Any additional configured admission hook still runs before acceptance. There is no fall-through path that moves relevant refs outside the journaled transaction.

The hook reports success only after publication. It never writes an event later from `post-receive`. The latter remains suitable for advisory notifications.

For an accepted push, the commands form one transaction even if the client did not request atomic push semantics. A failed admission or lease refuses that transaction. This gives the receiver one unambiguous result to journal.

Local integrator writes call the same package directly. A landing includes the target move, evidence, landing receipt, outcome, request handling and journal append. Record-state and authorization inputs read by the landing become transaction guards too. That closes the current readiness race, where a pause between the last record read and landing can be missed. (`docs/security.md:129`.)

The restacker continues to publish its phases through the receiver. Each accepted phase gets its own journal transaction. It emits completion only when the corresponding version or report is actually published; a work-ref movement alone is not a completed restack.

The worker publishes an attempt completion, its signed result and the journal transition together through the receiver. A network failure after acceptance is resolved by the attempt and transaction identities, not by running the check again.

Signer publication, administrative ref changes and other host writers whose refs feed the model use this transaction path as well. An unjournaled local mutation is a detected administrative inconsistency, not an ordinary supported write path.

There is a further crash detail. Git documents atomic updates of individual refs while permitting a concurrent reader to observe a subset of a multi-ref update. A multi-ref command must not be treated as a complete storage crash protocol. ([Installed Git documentation](/nix/store/mb5kkl4yar0i9m20f6bglah9l7a28fcs-git-2.56.0-doc/share/doc/git/git-update-ref.html:967).)

The recovery intent closes that gap without requiring a ref-backend migration:

- Before publication, persist an accepted transaction record under `event-transaction`. It retains the objects and the exact old/new ref set, including the proposed journal advance.
- Objects and the recovery record are made durable before any state ref moves.
- Coherent readers take the publication lock long enough to capture their ref map. They first settle an interrupted transaction.
- After a crash, values must be either the recorded old value or the recorded new value. Recovery completes the accepted transaction.
- An unexplained value stops recovery and reports the inconsistency. It never guesses.
- A prepared transaction is not streamed as a completed event.

Thus, killing the writer during the multi-ref update cannot leave a state transition permanently absent from the journal. This is recovery of an already admitted transaction, not a second authorization decision. An ambiguous connection failure after preparation must not be reported as a definite refusal.

The process performing Git writes holds the lock for its lifetime, including when its parent dies. Recovery removes only lock artifacts attributable to that interrupted transaction.

The journal retains objects through real Git reachability, not merely object IDs embedded in JSON. Commit objects need commit-parent reachability; trees and blobs need tree entries. In particular, a gitlink is not an adequate retention root.

Retention is bounded by declared storage, not a fixed number of days or events.

Expose a host event-storage allocation, divided among projects with equal weights by default. A project may override its share. Reserve room for its current checkpoint and one maximum admitted transaction before allocating retained history. Size the retained portion from measured event bytes per unit of activity and the intended disconnected period. Report the resulting retained sequence range and observed history span.

If a checkpoint and an admitted transaction cannot fit, refuse further mutation with a capacity error before accepting it. Do not silently drop the transition. Actual repository storage also needs room for retained object roots; metadata size alone is not a complete disk limit.

Compaction runs when an append reaches the declared retention boundary, not on a timer. It:

- builds a checkpoint at sequence K;
- retains the complete state map at K and the object roots needed to read it;
- copies the logical records K+1 through H into a new physical chain;
- preserves their sequence numbers, transaction IDs and record digests;
- swaps the journal ref with a lease on H.

The replacement chain has no parent link into the discarded journal prefix. Otherwise compaction retains the history it claims to remove. Normal Git object reclamation handles unreachable objects afterward.

A cursor preceding K is expired. A cursor in the retained suffix remains valid even though the containing Git commits have changed.

| Crash or race | Guarantee |
| :--- | :--- |
| Rejected push | Neither state nor committed transition changes. |
| Two writers prepare against the same journal head | Publication serializes them; the second appends after rereading the head. |
| Author updates a record while a controller prepares | The controller’s record lease fails; it cannot publish an obsolete action. |
| Writer dies before durable preparation | No accepted transaction exists. |
| Writer dies during ref publication | Recovery completes the admitted state-and-journal transaction before coherent readers proceed. |
| Publication succeeds but reply is lost | Retrying the same transaction or result identity discovers acceptance and does not duplicate it. |
| Bus publication or wake marking fails | The journal remains complete. |
| Compaction races with an append | Its journal lease fails; it incorporates the new suffix before trying again. |
| Journal storage cannot accept the next transaction | The proposed state change is refused with capacity information. |
| Administrative mutation violates the recorded ref set | Recovery blocks visibly; no fabricated transition or inferred success. |

No journal signing key is introduced. Journal admission records facts; landing and check evidence retain their own verification. The receiving Git user and existing local controller users acquire only the publication rights their roles need. Agent and restacker credentials cannot write arbitrary journal contents, integration receipts or main.

**3. Failure notes, attempts and review admission**

A required check that runs and fails produces a signed negative result.

The existing attestation schema already admits `passed` and `failed`, and coverage deliberately selects a trusted note regardless of whether it passes. The integrator then refuses a result other than `passed`. (`schema/attestation.cue:272`, `status/coverage.go:18`, `integrator/verdict/verdict.go:417`.) The missing behavior is production and publication: `attest run` currently returns before publishing when checks fail, and the worker records its failure and wait locally. (`attest/run.go:245`, `status/worker.go:1370`.)

Keep the existing check-note vocabulary:

```text
statementType: the-valley/attestation/v1
subject: the checked tree
predicateType: the-valley/check/pure/v1
predicate.check: the check name, runner and attribute
predicate.result: failed
predicate.inputs: measured input digests
predicate.derivation: the evaluated derivation digest
predicate.output: {}
```

A failed build has no successful output digest. Do not invent one. The digest-set schema permits an empty set; the failure path must preserve that through rendering, parsing and verification. (`schema/attestation.cue:51`, `schema/attestation.cue:129`.) A failure before inputs or a derivation can be established needs a classified attempt result, not fabricated pure-check evidence.

Publish each completed check independently. If one check fails, passing siblings remain useful evidence. A batch’s aggregate exit code is not enough to classify every check it contains.

The worker reports three distinct outcomes:

| Outcome | Meaning | Result |
| :--- | :--- | :--- |
| Pass | The check executes successfully | Signed passing note |
| Check failure | Execution or attributable source evaluation establishes that the check fails | Signed failed result, with structured evidence |
| Infrastructure failure | The runner cannot establish a check verdict | Durable blocked attempt; no failed-check claim |

Examples of infrastructure failure include exhausted host capacity, an unavailable daemon, interrupted execution and inability to publish. An arbitrary nonzero child exit does not establish which category applies. Unclassified errors remain infrastructure failures with an explicit unknown cause.

Use an append-only attempt history at:

```text
refs/the-valley/check-runs/<work-key>
```

For a build, the work key contains project, tree and check-definition identities. Versions sharing those inputs can share work.

An attempt record names:

- the work key and generation;
- an attempt ID;
- the triggering ready versions or main obligation;
- requested, running or terminal state;
- runner identity and relevant execution inputs;
- terminal result and reason code;
- the signed note’s object ID when there is one.

The worker signs a terminal attempt statement that binds the attempt identity to the result note. This prevents an old passing note from being presented as completion of a newly requested retry. The note still states the check result in its established format.

A successful transition to running is durable before execution begins. A process that disappears leaves a running attempt to reconcile. On restart, the worker checks its recorded execution identity; if that execution is gone, it records interruption. A timeout alone does not prove that a check failed.

Infrastructure failure waits for a relevant input change: capacity, worker configuration, daemon availability, signer availability, publication availability, or an explicit retry. A completed signed result awaiting publication is kept in a durable local outbox and republished without rerunning its check. If the repository itself is unavailable, immediate project publication is impossible; the result remains pending locally and becomes visible when publication succeeds.

Explicit retry is a durable operation:

```text
valley retry <change> --check <name>
```

It names the current failed or blocked generation and a stable retry ID. Admission allows the change owner or an authorized operator to request it. It cannot publish evidence or clear an approval requirement.

A retry advances the attempt generation under compare-and-swap. Duplicate requests with the same retry ID have one effect. A new tree creates different work. Neither is driven by elapsed time.

Evidence selection must change with this mechanism. Today, publishing another note does not necessarily replace the first trusted failure selected for the same check. (`status/coverage.go:60`, `integrator/evidence.go:46`.)

For attempt-aware work:

- Only the selected attempt generation can complete the current obligation.
- An earlier failure remains a failure in history.
- An authorized retry can produce a later pass.
- Late results from an older generation cannot overwrite the selected one.
- While an explicit retry is running, the earlier pass or failure does not masquerade as the retry’s result.
- Coverage, status, worker scheduling and the integrator use the same selection function.

Existing notes without attempt identities remain legacy evidence. Introduce readers and selection rules before enabling attempt-aware publication. Do not let old readers and new writers silently disagree.

For reviews, retain the existing history layout:

```text
refs/the-valley/reviews/<target>/<change-id>
```

The current package already provides unique review IDs, leased appends, withdrawal history and a recomputable delta binding. Host admission is explicitly absent. (`review/history.go:14`, `review/history.go:29`, `review/binding.go:121`, `docs/architecture.md:2013`.)

Add a signed review format that preserves those fields and adds instance/project scope and the check-definition identity. Version the format rather than inserting fields into the strict v1 parser.

A signed Git commit can hold the review JSON as its sole tree entry, preserving the existing parent structure. Its signature covers the record and history position. A client retry that needs another parent signs another commit containing the same review ID and judgment.

Admission verifies:

1. The signature belongs to an enrolled review key.
2. The signer is the named reviewer and may answer this project’s named check.
3. The signed scope identifies this instance and project.
4. The append follows the history and introduces no duplicate review ID.
5. The bound record is an actual historical record of this change.
6. The bound version, head, target tip, base, delta and note anchors reproduce.
7. A withdrawal is authorized by the original reviewer or the declared operator role.
8. The write cannot alter any approval, integration or protected source ref.

The target or active version moving does not by itself reject a valid historical review. Admission verifies what was reviewed; evaluation decides whether it still applies.

Verification uses byte, entry and execution budgets derived from declared verification capacity. The existing binding API already distinguishes budget exhaustion from a false binding. (`review/binding.go:131`.) Surface that distinction.

A coordinator that signs an agent’s review is the accountable reviewer. Its provenance identifies the agent run. The valley does not pretend that an unsigned agent held the coordinator’s key.

Review keys and approval keys have separate grants and custody. A review can satisfy a review requirement but grants no landing authority. Approval remains a person’s signed act; no worker or agent runner acquires that key.

**4. `valley events`**

The client command is:

```text
valley events --repo app --after <cursor> --follow
```

JSON lines are the protocol, not an optional rendering mode. Diagnostics go to stderr.

The corresponding closed SSH verb is handled by `valleyhook shell`, for example:

```text
valley-events app --after <cursor> --follow
```

The shell parses it directly, resolves `app` through the host’s project registry, and invokes the event reader without a shell expansion. It derives the principal from the authenticated key, as it already does for its own commands. (`valleyhook/shell.go:27`, `valleyhook/shell.go:103`.)

Authorization asks the same question as source reading: may this principal read this project through this transport?

Do not substitute telemetry’s `observe` grant. That grant reads every host source, and telemetry deliberately discards older records. (`telemetry/protocol.go:42`, `telemetry/store.go:3`.)

There is an existing access distinction to preserve honestly: SSH currently admits every accepted Git key to fetch every project; the narrower read-consent mechanism governs web exports. (`docs/architecture.md:4952`.) Factor source-read authorization into a shared entry point for upload-pack and events. Initially, where SSH source reading remains broad, events are equally broad. Any later per-project SSH restriction must apply to both together. An event-only restriction would violate the agreed contract.

For deployments using project read consents, reuse the existing two-consent decision: project consent and an instance grant for that project identity. (`readaccess/access.go:3`, `readaccess/access.go:94`.) Read-grant changes wake streams and revoke access before another authorized batch is released.

Following has no read/subscribe gap:

1. Establish the local journal/ref watch.
2. Recover an interrupted transaction and capture the journal head under the publication lock.
3. Read and emit complete transactions after the supplied cursor.
4. Read the head again.
5. Continue immediately if it advanced; otherwise wait on the already established watch.
6. On every wake, reread the durable head rather than trusting notification contents.

The watch covers ref-file replacement and the relevant ref-storage directory, including packed-ref or backend changes. Overflow means “reread,” not “events lost.”

NATS may wake the reader sooner. It never supplies the cursor or proves that replay is complete.

The stream emits these JSON-line types:

- `transition`: one complete journal transaction and its cursor;
- `watermark`: all transactions through this cursor have been emitted;
- `reset`: the supplied cursor cannot be continued, with a reason;
- `snapshot-begin`, snapshot entries, and `snapshot-end`.

A missing, expired or foreign-generation cursor produces a snapshot, not an empty replay.

To create it, capture a coherent ref map and watermark H under the publication lock. Read immutable objects from that map after releasing the lock. The snapshot includes recorded drafts, ready and withdrawn work, relevant completed rounds, standing older approvals, attempts, restack conditions, main health and current obligations. It is not restricted to active ready changes.

The client installs the snapshot only after `snapshot-end`, which carries H. It then consumes transitions after H. A landing or review arriving while the snapshot is serialized therefore appears in the suffix.

A snapshot is a statement of current state at H, not a replay of every expired event. It announces current obligations even on first observation. It does not suppress a failed check merely because the client has never seen the change before.

The server never holds the publication lock while waiting for a slow socket. It uses bounded pages and one bounded output buffer per connection. Stream capacity derives from declared memory and descriptor capacity; admission reports exhaustion. If retention overtakes a slow reader, it receives a reset and another snapshot.

Multiple projects have separate cursors. A client convenience command may multiplex them, but no global sequence or cross-project ordering is promised.

**5. Wakeups and intervals**

Every completion is published before any wake is sent. Controllers use the journal to discover changes and durable refs to decide what to do.

| Input movement | Readers awakened |
| :--- | :--- |
| Change records and version work refs | Worker, restacker, flow evaluation |
| Main | Worker follow checks, restacker, integrator, flow evaluation |
| Build notes and attempt records | Integrator, worker scheduling, flow evaluation |
| Reviews and approvals | Integrator and flow evaluation |
| Requests, outcomes and landing receipts | Restacker, integrator reconciliation, flow evaluation |
| Restack reports | Flow evaluation and affected clients |
| Retry records | The named runner and flow evaluation |
| Policy floor, project policy and signer changes | Every controller whose input set includes them |
| Read authorization | Event readers and source-read admission |
| Capacity/configuration changes and child completion | The affected worker scheduler |

A journal wake does not automatically run every expensive evaluation. Controllers compare input identities and process only affected work. Their own report writes do not create an endless evaluation loop.

External inputs need durable fan-out. A controller consuming instance-policy or signer changes remembers the consumed input identity only after publishing the affected project’s new report and journal transition. Restart reconciliation compares those identities again. There is no claim of an atomic transaction across repositories.

The restacker gains the same event-driven behavior as the other controllers. It arms its watch before reading, reconciles at startup, and runs again when a relevant input changes or one of its own recoverable phases enables another.

Its current loop waits on a 15-second interval and applies time-based failure backoff. (`restack/main.go:212`, `restack/main.go:312`.) Those are removed from normal operation.

The worker’s one-second wake-mark polling and repeated scans while batches run become waits on ref events and child completion. Its build and push retry waits, including the special two-second convergence retry, are replaced by durable blocked inputs and explicit retry. The current constants are in `status/worker.go:212` and `status/worker.go:229`.

Retain one configurable **recovery interval** for degraded observation:

- It is armed while a watch is unavailable, a remote event connection is down, or notification recovery cannot establish continuity.
- It rereads durable state and attempts to restore observation.
- It does not rerun a failed check whose inputs and retry generation are unchanged.
- It is disarmed when continuous observation is restored.

Default it to the declared recovery setting, using the existing worker interval as the compatibility default. Its meaning is the maximum additional discovery delay during degraded observation, not scheduling cadence or a capacity limit.

This interval remains because a disconnected observer has no usable event channel reporting the remote service’s return. Healthy observation has no periodic scan.

Execution deadlines, connection deadlines and check validity deadlines are distinct from polling. They are one-shot bounds or declared expiry events. Compaction wakes on storage consumption. Output expiry can use its actual next expiry deadline. No new periodic maintenance job is introduced.

**6. The client contract**

A client subscribes to each project it manages, retains a cursor per project, and receives both transitions and snapshots.

It treats events as durable reasons to reconsider work. Before dispatching, it rereads the relevant view and confirms that the obligation still exists. A delayed failure event must not launch a fix after a later version has already resolved it.

| Event or current obligation | Client response |
| :--- | :--- |
| Version published or change readied | Refresh the view; dispatch any due client-run review. Builds start independently. |
| Review due | Launch or resume the authorized review using its obligation ID. |
| Review failed | Present the feedback or dispatch author work, subject to client policy. |
| Build failed | Dispatch diagnosis/fix work once for the applicable failure obligation. |
| Infrastructure blocked | Surface the runner problem; do not automatically ask an author to change source. |
| Restack conflict | Dispatch conflict resolution against the current report’s inputs. |
| Approval due | Notify the person who can approve. Never manufacture approval. |
| Integration blocked on another change | Display it; let the valley manage ordering. |
| Version landed | Complete local tracking and enqueue idempotent cleanup. |
| Main muddy | Consider a project repair under client policy; retain the successful landing. |
| Withdrawn, superseded or obligation removed | Cancel obsolete queued work. Preserve evidence of already completed dispatches. |

Client budgets, reviewer choice, diagnosis and decisions to stop remain client policy. The valley does not infer an agent spending limit by counting versions or uploaders.

The client stores cursor and intents transactionally:

1. Receive a transaction or complete snapshot.
2. Derive the applicable local actions.
3. Persist an intent for each action, keyed by project and obligation identity.
4. Commit those intents and the consumed cursor in one local transaction.
5. Have a separate dispatcher deliver the intents.

A failed local write leaves the cursor unchanged. A duplicate event finds the same intents.

An intent contains the input identity, action type, stable action ID and delivery state. Advancing the cursor means the client has durably accounted for the event, not necessarily finished its action.

The launcher must support the equivalent of:

```text
EnsureRun(action_id, inputs) -> durable run_id
```

Repeated calls with the same identity return the same logical run. Reusing an identity with different inputs is refused. The launcher’s accepted-run record survives lost replies and process restarts.

This is the boundary that makes “exactly once” meaningful. If the launcher exposes only “start a process” and cannot determine whether an earlier call succeeded, the client cannot guarantee both no duplicate and no dropped dispatch. The journal does not solve that ambiguity.

On restart, the client resumes pending intents before or alongside replay. An intent whose obligation is obsolete is recorded as cancelled. A review carried through an equivalent restack keeps its action identity; a changed delta creates another one.

Klaus can then delete its valley snapshot-transition inference: `ChangeSnap`-style comparisons, marks that guess transitions from listings, and first-sight suppression. The supplied ledger currently records first observations without emitting their transitions. ([Klaus ledger](klaus: internal/pipeline/changeledger.go:146).)

It retains durable run state, budgets, cursor state and the intent outbox. A snapshot remains useful for initial synchronization and cursor recovery. What disappears is periodic snapshot diffing as the source of events.

**7. Slices**

Each slice below is one behavior change. New check names are identified as proposed. Existing check names come from the flake’s check catalog. (`nix/checks.nix:17`.)

Tests use real Git at publication boundaries, fault injection at named persistence points, and event synchronization. They do not sleep to hope that a controller has run.

The first slice is deliberately a complete vertical path.

| Slice | Acceptance and crash/race cases | Flake checks |
| :--- | :--- | :--- |
| **1. Durable publication and catch-up** | Add the common transaction boundary, journal, SSH read verb, replay and snapshot watermark. Interpret version/readiness facts; retain generic ref transitions for other writers. A small contract client disconnects, misses a ready version, reconnects, persists its intent and dispatches once. Kill it before intent commit, after intent commit, after launcher acceptance and before reply. Kill the writer before preparation, during ref publication and after commit. Race two writers and a stale record update. Every accepted mutation is recoverable with its transition. | Proposed `events-unit` for cursor/record/recovery logic; proposed `events-e2e` for the actual receiver, CLI and durable test consumer. Extend `valleyhook-unit`, `protect-e2e`, `integrator-e2e` and `module-eval` only for their changed boundaries. |
| **2. Continuous following** | Add watch-before-read follow, authorization rechecks and bounded streaming. Commit at the replay/live boundary; overflow a watch; replace its directory; revoke access; block a reader; disconnect the bus. The reader either continues from its cursor or receives an explicit reset. No event-only authority broader or narrower than source access. | Extend `events-e2e`; focused watch tests in `events-unit`; `valleyhook-unit` and `module-eval`. |
| **3. Shared parts and obligations** | Add `flow.Derive`, stable obligation IDs and journaled flow reports. Status, controller adapters and web use the same normalized model. Exercise concurrent build/review obligations, a stack, active v2 with a standing v1 request, withdrawn work, stale reports and uncertain landing evidence. Changing an unrelated input does not create a new dispatch identity. | Proposed `flow-unit`; `valley-go-unit`, `integrator-unit`, `restack-unit`, `web-server-unit`, and one cross-component scenario in `events-e2e`. |
| **4. Approval as a required check** | Add runner/schema support and verify the scoped person-signed approval at the integration gate. A review key cannot satisfy approval. A v1 approval is not attributed to v2. A landing tree or later version outside the composed carry mode fails applicability; one within it keeps the approval. Unready races are caught by transaction guards; withdrawal invalidates standing authorization for a later round. Software approval remains usable only where hardware is not required. | `approval-unit`, `sigverify-unit`, `sigverify-e2e`, `identity-e2e`, `cue-vet`, `valley-request`, `integrator-e2e`. |
| **5. Signed review admission and evaluation** | Add the scoped signed format, host admission and review runner. Refuse wrong project, wrong check, unauthorized signer, forged record, invalid delta and unauthorized withdrawal. Race two appends. Accept an old-version review after an equivalent restack without redispatch. A changed delta creates a fresh obligation. An unwithdrawn failure survives a later pass. | `review-unit`, `valleyhook-unit`, `derive-unit`, `integrator-e2e`; extend `events-e2e` for the client review round trip. |
| **6. Attempt-aware readers and retry** | Add attempt records, signed completion envelopes and the shared selection rule before enabling worker writes. Retry a failed tree; duplicate the retry request; deliver an older completion after the new attempt starts. Legacy notes remain readable, and every consumer agrees which result applies. | `attest-unit`, `attest-conformance`, `valley-go-unit`, `integrator-unit`, `valleyhook-unit`, `cue-vet`. |
| **7. Worker failure publication** | Enable durable starts and per-check terminal results. Publish one failure and passing siblings from a mixed batch. Kill the worker after execution and before publication; lose the push reply; exhaust capacity; interrupt evaluation. A check failure is signed; infrastructure remains blocked. Restart republishes a stored result without rebuilding. An unchanged failure does not run again without an input change or retry. | `attest-e2e`, `valley-go-unit`, `integrator-e2e`; extend the worker boundary scenario in `events-e2e`. Use `worker-e2e` only for changed host isolation or capacity behavior. |
| **8. Controller wakeups and durable main health** | Replace restacker polling and worker mark polling with event waits; record follow-check outcomes durably. Land a lower stack change and observe automatic restacking. Land a change, disconnect the client, fail a follow check, reconnect and receive a muddy-main repair obligation while the change remains landed. Exercise degraded-watch recovery with an injected clock, not wall-clock waits. | `restack-e2e`, `integrator-e2e`, `valley-go-unit`, `events-e2e`, `module-eval`; `restack-host-e2e` only if service isolation changes. |
| **9. Retention and compaction** | Add declared storage allocation, checkpoint compaction and continued cursors across rewritten physical history. Race compaction with append. Expire a cursor; commit while its snapshot is streaming. Kill compaction before and after the swap. Verify discarded journal ancestry is unreachable and insufficient space refuses the proposed mutation visibly. | `events-unit`, `events-e2e`, `module-eval`. |

The first slice does not claim that an unchanged Klaus automatically consumes the new protocol. Its test consumer proves the contract, including the launcher requirement. Klaus adopts that contract in its own repository before deleting its ledger.

Schema and reader support land before policy requires a new runner or writers publish a newly interpreted format. Capability checks make mixed-version incompatibility explicit.

For every slice, list added claims, their kinds and verified source citations in its brief and head commit message. Update architecture and security only for behavior that lands. Run `prose-format` when those docs change.

**8. What not to build, and the remaining owner question**

Do not build:

- A single stored stage that replaces the independent parts.
- An ordered first-match client pipeline inside the valley.
- A post-receive journal append that can lose a completed transition.
- Per-writer journals and a vector-clock merge protocol.
- A journal derived from sampled telemetry or NATS delivery.
- Automatic approval, shared review/approval keys, or approval carried beyond the policy's composed carry mode.
- A host agent launcher, agent budget counter or inferred reviewer judgment.
- A timer that repeatedly retries an unchanged failed check.
- An unbounded event history or subscriber acknowledgements that let one abandoned client retain everything.
- A new runtime, database or message broker.
- A claim that a stored cursor alone makes external effects happen exactly once.
- A silent change from the existing review delta to a stack-layer-only delta.

The one direction question that materially changes this design is:

**After retention expires, must a client still perform an action for every historical transition, even when that transition leaves no current obligation?**

This design guarantees replay within retention and reconciliation of current obligations from a snapshot afterward. Durable client intents survive independently once accepted. It does not promise to reconstruct every expired notification.

If historical actions must survive arbitrary disconnection, their pending obligations need durable acknowledgement and retention of their own. That is a larger contract than resumable observation; it should be added only for a named action that needs it.

Comments

  1. contributor2026-11-09 01:15 UTC
    Coordinator review, 2026-11-09: approval carry corrected to follow policy's composed carry mode (same-paths, same-class, exact; docs/concepts.md:87), as decided earlier: an approval carries as far as policy allows, exact for sensitive classes. The authored text forbade any carry to a later version or a different landing tree, which contradicted the declared carry modes and the integrator's existing landing of an approved version's delta onto a newer main. Rows changed: the approval runner, slice 4's acceptance, and the do-not-build list.