# The valley restacker — rev 2 The restacker keeps ready, unsubmitted changes based on the current `main`. It runs as a separate Go service and principal, and pushes through the host’s hook. A 15-second polling loop reconciles Git state; bus delivery is optional. It prepares each connected stack family together and publishes its branches atomically. A shared lower layer is rebased once. A conflict moves no branch and adds no version. Reports live at `refs/the-valley/restack/main/<change-id>`; recovery journals stay local. A potentially landable request holds its family still. A current stale outcome releases it. Every automatic version names the restacker as uploader. Review computes `valley-delta-v1` to distinguish unchanged files from a changed resolution. Approval carry remains part 3, with checks required on the prepared result. ## Changes from rev 1 - Replace the part 1 assumptions with its landed implementation and the remaining API work. - Remove hook replay, the restricted service role, operation refs, and receive serialization. - Allow restacking past a current stale request, including the evidence-fingerprint test. - Use one report namespace and a local recovery journal. - Add the clean-restack review signal, project carry modes, and explicit check-set pinning. - Correct the threat model: a compromised restacker retains ordinary pushing-principal permissions. Source baseline: the-valley `d776ee7`. Statements below describe proposed behavior unless identified as current behavior. Attachment citations refer to the design's working papers. External klaus citations name their full paths. ## 1. Trigger and placement **Decision: reconcile at startup and every 15 seconds, in one Go controller per enabled project.** Each pass reads the target, branches, change records, requests, outcomes, and attestation fingerprint. Reconcile even when `main` has not moved: a newly ready change or a fresh integrator outcome can release work. The existing bus is a notification path. Post-receive publication is detached and tolerates failure. The integrator publishes its own landing events because local ref updates do not invoke post-receive; it does not consume the unauthenticated bus. These are reasons to retain polling as the authority path. (`nix/valley-host.nix:305`, `nix/valley-host.nix:430`, `integrator/bus.go:3`, `integrator/bus.go:12`, `integrator/bus.go:62`.) A later bus subscription may wake the same loop early. It must fetch Git state rather than act on event-supplied heads. Do not consume the mirror publisher’s queue: its drain deletes entries after publishing them. (`nix/valley-host.nix:397`.) Run `valley-restacker@<project>.service` as the system user `valley-restacker`, with its own group and state directory. Give it a private checkout, scratch directory, recovery journal, SSH key, and pinned host key. It has no membership in the git group, no writable access to served repositories, and no integrator or check-signing credentials. The current integrator deliberately belongs to the repository’s group; that arrangement would let the restacker bypass the hook. (`nix/valley-host.nix:1414`.) Fetch and push over the host’s SSH endpoint, including on localhost. The existing login shell derives the principal from the authenticated key and removes a client-supplied principal. (`valleyhook/shell.go:95`, `valleyhook/shell.go:139`.) Use pinned binaries, bounded subprocesses, disabled Git hooks and external filters, and one active controller per repository. Go owns scheduling and recovery; Nix owns service wiring. **Rejected alternatives:** event-only triggering loses convergence after missed events. Running inside the integrator enlarges its trusted responsibilities. Direct repository writes bypass the chosen permission boundary. ## 2. Principal and grant ### The additional permission **Decision: add `restack` for a narrow record transition and `restack-report` for reports.** The `restack` grant permits appending exactly one version to another principal’s existing ready change. It permits no other record transition. The hook requires: - The old and new states are both ready. - The record’s first parent is the previous record commit; its second parent is the new head. - All previous versions, ownership, target, and change ID remain unchanged. - The new version becomes active, and `seq` increases by one. - The new version retains the branch locator and title. - Its uploader equals the authenticated pushing principal. Most structural checks already exist. The new authorization path adds the old-state requirement and restricts this grant to that transition. Today updates require ownership or `request`; the existing version check already preserves history and authenticates the uploader. (`valleyhook/record.go:223`, `valleyhook/record.go:284`.) Do not grant `request`. It also authorizes filing, replacing, and deleting integration requests, and permits deleting change records. (`valleyhook/policy.go:142`, `valleyhook/record.go:165`.) ### What this does not restrict There is **no restricted service role**. The new grant is narrow; the principal’s total authority is broader. Unprotected topic branches are already open to admitted pushers. The restacker therefore needs no new branch grant. Ordinary named principals may also create their own records and write the project plan within its validation rules. These permissions remain. (`valleyhook/policy.go:130`, `valleyhook/record.go:170`, `valleyhook/main.go:68`.) The controller limits itself to eligible existing branches and leased updates. Those are service behavior, not a hook-enforced restriction on a compromised key. Its project enable list is likewise a scheduling choice, not a new repository access boundary. ### What the hook proves The hook proves the record transition and uploader attribution. It does **not** prove that the proposed head: - Is a rebase of the old head. - Contains only the old change’s content. - Preserves messages or author fields. - Descends from the target tip. There is no replay, patch-id comparison, or delta comparison in pre-receive. Hook work remains bounded object and record validation. This accepts arbitrary **unapproved** replacement content from a compromised restacker. Current requests name exact heads, and records supply restrictions rather than landing authority. Independently computed review comparisons protect re-approval now; part 3’s output verification protects carry later. (`bin/valley:1530`, `integrator/records.go:5`; `change-identity-design.md:139`.) ### Grant source and attribution Use the identity registry as the normal source. Add boundary kinds and explicit compiler emission for `restack` and `restack-report`. The current schema and renderer handle `request` specifically; arbitrary new boundary names do not automatically become hook grants. (`schema/identity.cue:126`, `identity/render.go:96`.) Support corresponding declared host grants for bootstrap. Declared and compiled grants are additive today, so remove bootstrap declarations after the registry takes over. (`nix/valley-host.nix:622`.) Every automatic version names `valley-restacker` as uploader. Preserve earlier uploaders. Conflict-resolution versions name the authenticated resolving principal. Part 3’s rule 6 applies without an exemption for mechanical uploads: the restacker cannot independently review a change it uploaded, and a human or agent who resolves a conflict may lose independence for that change. (`change-identity-design.md:150`.) **Rejected alternatives:** `request` grants excessive authority. Hook replay adds a second rebase engine at the trust boundary. Attribution to the owner would falsify the upload history. ## 3. What gets restacked **Decision: ready, unsubmitted changes whose active heads do not descend from current `main`.** Use the status implementation’s landing rules, including evidence for integrator merges. Ready state alone is insufficient to establish that work remains unsubmitted. Leave uncertain landing cases for inspection. (`status/inventory.go:258`.) Leave drafts and withdrawn changes alone. Leave plain branches alone because they express no readiness decision. If an ineligible layer lies within a proposed family, report it and hold that family. This is narrower than the manual stack command, which discovers plain branches, drafts, and withdrawn changes as layers. (`status/stack.go:4`.) ### What part 1 now provides Part 1 is implemented in `status/rebase.go`. Both manual rebase and review’s base action use it, including a single change. (`status/rebase.go:1`.) It provides: - Capture and preflight for one chain of layers. - Refusal of missing or mismatched branches, duplicate branch locators, merges, and historical version heads belonging to unready or outside changes. - Bottom-up preparation in a throwaway worktree. - Removal of lower work already proven submitted through an integrator merge. - Record revalidation, an atomic leased branch push, and conditional record appends. - Human-readable partial-result manifests and notification of other stacks left on old heads. These behaviors are implemented, rather than future interface assumptions. (`status/rebase.go:231`, `status/rebase.go:297`, `status/rebase.go:389`, `status/rebase.go:482`, `status/rebase.go:594`, `status/rebase.go:630`, `status/rebase.go:664`, `status/rebase.go:702`.) A conflict prevents publication. An empty rebased layer is also refused; the host must report that case rather than silently retire the change. (`status/rebase.go:438`.) ### What part 2 still needs The implementation remains in `package main`, with private methods and a prose manifest. Preparation’s signal handler can exit the process. It is not yet an importable, cancellable family API. (`status/rebase.go:47`, `status/rebase.go:155`, `status/rebase.go:406`, `status/rebase.go:664`.) Extract shared Go interfaces for: 1. Capturing and validating a family. 2. Preparing without publishing. 3. Reusing a prepared lower layer. 4. Publishing the union of branch updates. 5. Appending versions individually. 6. Returning structured results at every publication boundary. Use context cancellation instead of process exit in the shared code. Preserve the manual CLI’s output. Add capacity and request checks in the host caller; do not parse its prose or repeatedly invoke the human command. ### Connected families Build the dependency graph from one captured snapshot, retaining every old base and head. For `A → B → C`, prepare and publish once. For `A → B` and `A → C`, prepare A once, then prepare both children onto that same new A. Publish all three branches in one atomic push. Append A’s version once, followed by the children. A conflict anywhere holds that family; independent families continue. A shared layer cannot appear in two publication operations in the same pass. This requires extending the current chain model. Current discovery follows active heads, and manual rebase only reports outside stacks that contain rewritten heads. Rediscovering siblings after publishing A would lose the original planning context. (`status/stack.go:110`, `status/rebase.go:702`.) ### Requests that hold a family still **Decision: hold a family while a related request might still land. A current stale outcome does not hold it.** Enumerate every ref under `refs/the-valley/integration-requests/main/`. Associate a request with the family through: - `c-<full-change-id>`. - Every historical version’s branch name, with `/` replaced by `-`. - An exact match to any historical version head. - A request’s incoming commit range containing a family version head. The first two are current naming conventions. The range test also covers an approved upper layer outside the selected family. Treat lossy branch-name collisions conservatively. (`status/inventory.go:226`, `status/status.go:184`, `integrator/records.go:15`.) For each related request at head **H**, read its corresponding outcome: `refs/the-valley/integration-outcomes/main/<request-name>` An outcome is current only when all three match: 1. Its head equals H. 2. Its target tip equals the captured current `main`. 3. Its evidence fingerprint equals the current attestation-namespace fingerprint. The integrator uses precisely those inputs for memoization. The fingerprint covers every attestation ref and object ID, not just this change’s evidence. Reuse the existing parser and fingerprint logic. (`integrator/refs.go:130`, `integrator/refs.go:547`, `integrator/refs.go:568`, `status/status.go:340`, `status/status.go:395`.) Apply these rules: | Observation | Restacker action | |---|---| | Current `stale` outcome | Proceed; retain the request unchanged. | | Current `reject` outcome | Also cannot land on those inputs; permit mechanical restacking, retaining the rejection warning. | | Missing, malformed, or mismatched outcome | Hold for an integrator decision. | | Failure or readiness/merge refusal | Hold; these are not durable assurances that the request will remain unable to land. | | Landing evidence | Re-run selection and exclude submitted work. | Current stale and reject decisions are cached on those inputs. Refusals are reconsidered, and failures have a retry window. A new attestation—even for another change—invalidates the stale exemption. (`integrator/refs.go:220`, `status/status.go:434`.) Recheck before publication and recovery. Never delete or retarget the old request. Before part 3, the operator approves the new version explicitly. **Rejected alternatives:** independently rebasing each record duplicates shared work. Moving plain branches invents readiness. Blocking every stale request preserves the manual work this service is intended to remove. ## 4. Conflicts and reporting **Decision: one durable report ref per change:** `refs/the-valley/restack/main/<change-id>` The ref points to the latest report commit. Its first parent is the previous report, preserving history. The first report has no parent. The hook allows only the designated `restack-report` holder to write this namespace. It validates the target and ID, requires a fixed single-file layout, bounds JSON to 64 KiB, bounds commit and tree sizes, and refuses deletion or history replacement. These are new permissions; current miscellaneous `refs/the-valley/` namespaces reject every push. (`valleyhook/policy.go:121`.) A report contains: - Observed record commit, version, branch, and head. - Captured target tip and a local operation identifier. - Result: conflict, blocked, partial, complete, or superseded. - Failing layer and bounded conflict-path details. - Branch and version publication results. - Blocking request refs or the exact preflight refusal. Reports are observations, not evidence that content is unchanged or approved. Clients must recompute the review comparison. A client reads the current target, record, branch, and report to distinguish pending work, a current conflict, a request hold, and partial publication. A report applies only while its relevant input identities match. When an author uploads a version or `main` moves, the old conflict becomes historical. The next pass tries the new inputs and appends a replacement report. Success clears the actionable conflict; draft or withdrawn state removes it from the work queue. Do not repeatedly retry unchanged conflicts. Extend the status inventory and JSON output to expose this report. The existing inventory already enumerates branches, records, requests, outcomes, and attestations; the report prefix is an addition. (`status/inventory.go:63`.) Use existing `ref-updated` events as refresh notifications. No new bus event is necessary. (`nix/valley-host.nix:322`.) **Rejected alternatives:** bus-only reporting loses observations during disconnects. A change-record field mixes operational observations with readiness transitions. Direct-write reports would require repository access like the integrator’s outcome writer. Project storage is the appropriate location for observations about versions. (`change/record.go:124`, `integrator/refs.go:559`, `docs/architecture.md:44`.) There are no shared operation-descriptor refs. Recovery belongs in the service’s local journal. ## 5. Races, review, and bounds ### Author and request races Retain explicit branch leases and one atomic branch push. Retain record leases and `ready --if-active <captured-head>`. The conditional append checks both readiness and the active head. (`status/rebase.go:594`, `status/ready.go:184`, `status/changes.go:513`.) A record can change after revalidation but before branch publication. Part 1 documents that window: the branch may move while the record remains a draft at its old head. The manifest identifies the unfinished record write. (`status/rebase.go:473`.) Do not add a receive lock. A request can likewise arrive after the last check. If observed before branch publication, hold the family. If observed between phases, pause remaining record appends and report the partial result. If the request arrives after the final check, it still names exactly the approved head. The same is true if fresh evidence makes an old stale request eligible again. These races cost freshness and may require reconciliation; they do not authorize the new version. The current integrator already documents a comparable last-read window for readiness. (`integrator/records.go:31`.) ### An operator mid-review A restack does not necessarily force another review. Current bound approval accepts the exact displayed head while it remains a version of a ready change, even when another version becomes active. Only an unbound operation requires the active head to remain unchanged. (`bin/valley:1530`, `bin/valley:1568`.) Keep that path. Never substitute the new active head. Part 1 still refuses approval of a stale head that brings another unsubmitted change, before running checks. A stale single change or bottom layer remains approvable. This is an implemented policy distinction. (`bin/valley:1129`.) ### What counts as an approved reference version **Decision: use observable request history, and describe its limits.** For the review comparison, a reference version must have an exact head named by: - An extant integration request unambiguously associated with this change; or - A recognized `land`, `stale`, or `reject` outcome associated with this change and head. Use the ID name or an unambiguous historical branch name. Do not infer separate approval of every lower version merely because an approved upper head contains it. Current status already associates requests and outcomes with exact version heads. (`status/inventory.go:226`.) “Approved” here means approval through the current request protocol. It does not identify a human signer or prove an unexpired part 3 approval. Request writes are grant-authorized; the request ref names the head. (`valleyhook/policy.go:142`, `bin/valley:1125`.) Choose the greatest version number with this evidence below the displayed version. Name it explicitly. Do not search backward until some older version happens to produce a matching delta. This is not a complete approval history: outcome refs are overwritten blobs. Versions store no approved base or approval timestamp. If evidence is missing or ambiguous, show ordinary review rather than inventing a baseline. (`integrator/refs.go:559`, `change/record.go:105`.) ### Compute the clean signal independently Implement `valley-delta-v1` in a shared Go package during part 2. The trusted review client computes it directly from Git objects. The restacker may use the same package for reports, but its reported answer is never trusted by review. Implement the supplied encoding exactly: whole-file pre- and post-images, raw byte-length-prefixed paths, bytewise ordering, SHA-256 content hashes, supported modes, and deletion-plus-addition for renames. Reject unsupported entries and malformed encodings. No external diff driver, filter, or checkout is involved. (`change-identity-design.md:97`, `change-identity-design.md:105`, `change-identity-design.md:114`.) For the current protocol, define the comparison base precisely: - Freeze the target T and both version heads H₀ and H₁. - For each head, use its unique merge-base with T. - Require those bases B₀ and B₁ to lie in order on the target’s linear landing history. - Compare `delta(B₀, H₀)` with `delta(B₁, H₁)`. This follows the existing approval’s target-relative base calculation. For an upper layer, the comparison includes the lower work that approving that head would bring. Existing layer-by-layer paging remains available. (`bin/valley:1121`, `bin/valley:1954`, `bin/valley:1982`.) These are reconstructed bases, not a claim that today’s request recorded the original reviewed destination. If reconstruction is ambiguous, withhold the clean label. Part 3 will instead supply the signed tip and prepared result. When the digests match, display: ```text <change> v<N> at <head>: clean restack of approved v<M> at <old-head>. File delta unchanged. Base <old-base> -> <new-base>. Landings between bases: <commit> <subject> ``` List the target’s first-parent commits in `(B₀, B₁]`, oldest first. Include every commit; group them into named submissions only where landing evidence supports that grouping. When the digests differ, display: ```text <change> v<N> at <head>: changed since approved v<M> at <old-head>. Review the range-diff before approving. ``` Show `git range-diff B₀..H₀ B₁..H₁`, with the full current diff available. Binary and mode changes must remain visible even where range-diff is insufficient. Compare messages and author fields separately and prominently disclose changes; file equality does not establish their equality. The single-change prompt is: ```text [a]pprove <change> at <head>, [v]iew full diff, [s]top? ``` Within a stack, retain the existing next-layer and “approve up to here” meanings, adding the full-diff option. Existing prompts already distinguish approval of a layer from progression to the next one. (`bin/valley:2011`.) A clean label never files a request automatically, skips checks, or claims that all carry rules pass. Whole-file equality is deliberately stricter than a conflict-free Git rebase across different edits in one file. (`change-identity-design.md:172`.) ### Coalescing landings Capture one target per preparation. Maintain one active worker and one pending reconciliation, not a queue of passes for every landing. Refresh the target before preparing another family and before publishing. Discard an unpublished plan if the target has moved. A move after that read is accepted; the next pass restores freshness. The 15-second cadence coalesces ordinary bursts. ### Capacity Current records permit 1,000 versions, 100,000 updates, and 64 KiB of JSON. The byte bound can bind first. (`change/record.go:64`.) Before moving any family branch, require each prospective record to satisfy: - At most 64 automatic versions over the change’s lifetime by default. - At most 900 total versions. - At most 99,000 record updates. - At most 48 KiB of encoded JSON. Count authenticated restacker uploads across the retained version history. Author uploads do not reset the count. Retry of an already-added version does not increment it. Put the default in project policy as `restack.maxAutomaticVersions: 64`, beside the carry settings. A host may impose lower operational ceilings. Raising the project limit requires an ordinary policy change. These are controller limits, not a security boundary against a compromised service. The hook’s format bounds remain the enforced ceiling. Do not skip rebases solely because landing paths are disjoint: that does not repair ancestry or establish unchanged check inputs. Current approval runs checks on its selected head, while the integrator can judge a merged candidate. (`bin/valley:1193`, `integrator/git.go:158`.) Do not compact version history. Existing appends preserve it, and future independence checks require it. (`valleyhook/record.go:288`; `change-identity-design.md:152`.) ### Partial publication and recovery Persist and flush a local journal before phase 1. Record captured refs, old and new bases and heads, branch leases, and per-layer publication results. Keep prepared objects reachable in the private checkout until recovery completes. On restart or an unknown push result: 1. Read remote branches and records. 2. Determine which branches actually moved. 3. Recognize versions already appended. 4. Retry only missing appends whose branch still equals the prepared head and whose record remains ready at the captured head. 5. Recheck requests and landing evidence. 6. Stop on author movement, withdrawal, submission, or incompatible target history. Use bounded backoff for transient failures. A moved target does not by itself prevent finishing an already-published operation if it remains a descendant of the captured target. Part 1 already distinguishes rejected pushes from unknown transport outcomes and continues record appends after an individual failure. Its manifest supplies repair commands. (`status/rebase.go:594`, `status/rebase.go:630`, `status/rebase.go:664`.) Automatic recovery uses conditional appends, not unconditional execution of those commands. If the journal is lost, report the mismatch for explicit repair; do not infer permission to record arbitrary branch content. **Rejected alternatives:** receive serialization adds no exact-head protection. Path-based skipping leaves stale ancestry. Unconditional recovery can reactivate paused work. A clean label cannot substitute for approval. ## 6. The klaus side **Decision: klaus consumes current conflict reports and dispatches resolution only for changes it owns.** Extend its valley reader with the report. Ownership comes from the record, not the latest uploader: automatic versions belong to the restacker. The current reader already exposes owners, versions, uploaders, requests, and outcomes. (`klaus/internal/valley/changes.go:61`.) Before dispatch, re-read the target, readiness, active head, and report inputs. Deduplicate by repository, family, head, and target. Do not execute commands supplied by a report. Dispatch: ```text klaus launch --repo <project> --change <full-change-id> <resolution-prompt> ``` The prompt identifies the failing layer and captured inputs. Resolve the lowest conflicted owned layer first. Do not take over another author’s lower layer. Mirror the GitHub conflict handler: avoid an active worker, apply cooldown, count failed attempts, and stop after the retry limit. Its current defaults include three conflict-resolution attempts and a 60-second cooldown. (`klaus/internal/pipeline/transitions.go:198`, `klaus/internal/pipeline/pipeline.go:441`.) Keep the two required adaptations: - Permit rebase pushes with explicit leases in the conflict-resolution `--change` workflow; its current instructions require fast-forward pushes. - Confirm the intended change is draft before launching edits; current launch only warns when unreadying fails. Preserve its existing running-worker and unpushed-work protections. (`klaus/internal/cmd/launch.go:75`, `klaus/internal/cmd/launch.go:97`, `klaus/internal/cmd/launch.go:817`.) **Rejected alternative:** host-dispatched resolution agents would put author-specific content decisions in the mechanical service. ## 7. Tests **Decision: test through real pushes, rendered host hooks, and a real integrator.** Extend the existing hook harness and add a NixOS restacker test for SSH identity and service isolation. Existing tests provide both patterns. (`nix/checks/valley-ready.sh:2`, `nix/checks/ssh-e2e.nix:1`, `nix/checks/publish-e2e.nix:1`.) Part 1 already has an integrator scenario proving whole-stack rebasing, removal of previously submitted lower work, and landing every remaining layer after approving the top. Preserve it and extend it for host-driven preparation. (`integrator/e2e/run.sh:1330`, `integrator/e2e/run.sh:1390`, `integrator/e2e/run.sh:1402`.) Required scenarios: 1. **Convergence without the bus.** A real landing causes eligible changes from several owners to restack. Newly ready work is found without another landing. 2. **Linear and shared stacks.** Verify ancestry and trees, not patch-ids alone. A shared lower layer gains one version, and both children descend from its new head. 3. **Conflict isolation.** A middle-layer conflict moves no family branch or record. Independent families progress. 4. **Selection.** Leave drafts, withdrawn changes, plain branches, submitted changes, uncertain landings, and families with ineligible layers untouched. 5. **Record permission.** The new grant allows only the specified append to another owner’s ready record. Reject state changes, changed history, forged uploaders, record deletion, and request writes. 6. **Actual principal authority.** Demonstrate that ordinary topic-branch and plan writes remain possible. Protected targets and integrator outcomes remain closed. Do not retain rev 1’s false branch-restriction assertions. 7. **Untrusted replacement content.** An arbitrary structurally valid restacker version can pass the hook. Independent review must detect its changed delta or metadata; an old request must still name the old head. 8. **Request classification.** Cover ID names, historical branch names, collisions, arbitrary-name heads, and upper-layer ranges. A matching stale memo releases work; wrong head, tip, or evidence fingerprint does not. Cover current rejection and retryable failures separately. 9. **Races.** Move branches, records, readiness, requests, evidence, and `main` at controlled boundaries. Verify leases and partial reports without receive serialization. 10. **Review.** Test clean comparison, changed resolution, altered authorship/message, missing or ambiguous baseline, historical-head approval, and part 1’s stale-stack refusal. 11. **Delta conformance.** Use fixed independent vectors for empty deltas, binary files, renames, modes, symlinks, deletions, CRLF, final newlines, and paths containing spaces or newlines. Reject duplicate paths, noncanonical lengths, invalid modes and hashes, unsupported entries, and unmaterializable trees. 12. **Recovery.** Restart before publication, after branch publication, and after each append. Lose a push response. Verify idempotent completion and safe refusal after author movement or journal loss. 13. **Reports and bounds.** Test report ownership, append history, size limits, supersession, capacity preflight, the lifetime cap, and absence of duplicate reports for unchanged inputs. 14. **Policy.** Test mode composition, overlapping classes, unchanged required-check selection, cap configuration, and policy-digest changes when modes or check declarations change. 15. **Klaus.** Dispatch once for a current owned conflict; honor draft confirmation, worker guards, cooldown, and retry limits. 16. **Isolation.** Verify that the Unix user cannot modify served repositories directly or read integrator credentials. The existing integrator harness substitutes the Nix evaluator while exercising the downstream attestation and integration machinery. Keep that limitation explicit; the VM test proves service and SSH isolation. These are acceptance scenarios, not tests run for this document. (`nix/checks/integrator.nix:18`.) ## 8. Rollout on the home network **Decision: a small additive cutover, initially for the-valley only.** 1. Land the shared family API, controller, grant handling, report reader, delta package, and review signal. 2. Extend the identity schema/compiler and declared-grant fallback. 3. Register an expiring service principal with push admission, `restack`, and `restack-report`. Give it no `request`, protected-ref writer, or signing authority. 4. Provision its private SSH key outside the Nix store. 5. Activate the hook and client support with the service disabled. 6. Run a reporting-only pass and inspect families, requests, conflicts, and capacity. 7. Enable the service for the-valley, then expand after observing convergence. Service identities already require expiry, and a key without `signs` can push without becoming an evidence signer. (`schema/identity.cue:58`, `schema/identity.cue:82`.) The deployment project's checked-in host configuration enables the valley host. Whether the inspected files are currently activated is **unconfirmed**. Rollback stops the service and revokes its key and grants. Removing only `restack` does not remove ordinary push permissions. Remove duplicate declared grants when compiled grants take over. Retain reports and local recovery data; do not automatically rewind branches authors may have continued. **Rejected alternative:** no record migration, new privileged repository writer, or receive wrapper is needed. ## Threat model **Decision: trust the restacker to perform useful work, not to establish approval or unchanged content.** A compromised restacker can: - Rewrite or delete unprotected branches using ordinary push access. - Add arbitrary versions to other owners’ ready records through `restack`. - Create and manage its own records, and write valid project-plan updates. - Publish misleading reports, consume storage, exhaust record capacity, or withhold work. The first and third capabilities already follow from ordinary principal permissions. The operational cap of 64 does not constrain a compromised implementation. The attachment’s “worst case is denial of service” claim is therefore too narrow after removing the restricted role. (`valleyhook/policy.go:130`, `valleyhook/record.go:170`, `valleyhook/main.go:68`; `restacker-carry-threats.md:27`.) With the proposed grants and host isolation, it cannot directly write protected `main`, file or replace requests, rewrite integrator outcomes, or forge check signatures. It may relay valid signed evidence; lacking a signing identity is not a prohibition on pushing someone else’s valid attestation. (`valleyhook/policy.go:121`, `valleyhook/policy.go:134`, `valleyhook/policy.go:142`, `valleyhook/policy.go:172`.) Before part 3, the operator approves an exact displayed head. Review independently computes the delta and shows changed content. After part 3, the integrator independently checks the approved delta against the actual prepared result. Neither trusts a report’s “clean” assertion. The remaining content threats are: - **Cross-file meaning and symlinks.** Unchanged files can behave differently because surrounding code moved. Checks and stricter carry modes limit this; delta equality does not eliminate it. - **Split payloads.** Two changes can become harmful together. `same-class` forces fresh review when the intervening landing touches any relevant class; cross-class interactions remain. - **Weakened checks.** Pinning the declared required set prevents removal through policy. Changing a check’s implementation is a separate issue addressed below. - **Overtaken intent and old approvals.** List intervening landings. Part 3’s expiry bounds authority; the restack cap limits churn, not elapsed approval age. - **Routine re-approval.** A conflict resolution must show its range-diff. “Restacked” is never a reason to hide changed content. These threats and semantic limits are explicit in the supplied designs. (`restacker-carry-threats.md:7`, `restacker-carry-threats.md:14`, `restacker-carry-threats.md:19`; `change-identity-design.md:166`.) Full authenticated upload history remains a part 3 prerequisite. Today a `request` holder can delete a record; append discipline alone cannot establish permanent history across deletion and recreation. Part 3 must close that gap before claiming rule 6. (`valleyhook/record.go:165`; `change-identity-design.md:152`.) ## Amendments to part 3 ### Carry modes are project policy Add a `carry` field to each verification class: ```cue carry: *"same-paths" | "same-class" | "exact" ``` Use the strictest mode among all matching classes. Preserve instance-floor restrictions through CUE constraints. This extends the existing policy framework. Classes contain path globs and required-check sets; all matching classes contribute. Effective policy composes the instance floor, project-type template, and project layer. The-valley’s layer is `policy/project/policy.cue`. (`schema/verification.cue:42`, `schema/verification.cue:69`, `schema/verification.cue:237`, `policy/project/policy.cue:12`.) Initial declarations: | Scope | Mode | |---|---| | `valleyhook/**`, `integrator/**`, `sigverify/**`, identity compiler and identity-schema code | `same-class` | | Policy, authoritative registry/grant data, and secrets | `exact` | | Other classes and unmatched paths | `same-paths` | Use existing classes where possible. Adding a class must preserve the checks previously required for its paths, including unclassified requirements. The existing identity class covers compiler code and fixtures; it must not be confused with an instance’s authoritative registry directory. (`policy/project/policy.cue:149`, `policy/project/policy.cue:194`, `schema/verification.cue:64`, `nix/valley-host.nix:1235`.) The deployment project should declare `same-class` for its access-enforcing host modules: for example, its account and key declarations, the agent guest's account and SSH restrictions, and the valley host's SSH restrictions. The deployment project owns its complete classification. The project’s `restack.maxAutomaticVersions`, default 64, belongs in the same effective policy. Both additions enter its snapshot digest. ### Pin the declared required check set Rule 5’s policy snapshot must mean the **complete composed policy**, using the existing catalogue digest. That code hashes the entire exported policy JSON, not only check names. It therefore covers class paths, requirements, check declarations, runner attributes or commands, and cost. (`integrator/policy.go:333`.) Required checks are the union selected by matching classes. Cost groups or filters CLI output; it does not exempt slow checks from approval or integration. (`schema/verification.cue:163`, `integrator/policy.go:358`, `policy/project/policy.cue:67`.) No additional digest of the declarative check set is needed. Check implementation files behind an unchanged attribute are **not** covered by that policy hash. Input-closure verification detects changed computation for evidence reuse, but does not itself pin the implementation to an earlier approval. (`attest/inputs.go:8`.) ### Reuse the delta code and record intervening landings Part 3’s rule 2 must reuse the part 2 delta package, evaluating the actual prepared result against its destination tip. The advisory version comparison is not the acceptance predicate. Every carried-approval decision records the ordered landing interval `(T₀, T₁]`, including commit IDs and the effective policy and registry inputs. An empty interval is explicit. Intermediate authority changes must remain visible even when later reverted. (`change-identity-design.md:139`, `change-identity-design.md:144`, `change-identity-design.md:149`.) All other acceptance rules remain unchanged, including upload independence, blocking verdicts, trains, and checks on the new result. Carry remains sequenced with M1-C after the M4 preparation/check flow. (`change-identity-design.md:150`, `change-identity-design.md:157`, `change-identity-design.md:188`.) ## Open questions for the operator **Should changing a check’s implementation also invalidate carried approvals?** Recommend yes. The declared required set is already pinned, but weakening a script behind an unchanged Nix attribute leaves that policy digest unchanged. Before enabling carry, define a separate digest of check-definition sources and runner identities, or include those definitions in the policy snapshot. Keep it distinct from the full check input closure: ordinary changes to application inputs should require new evidence without automatically defeating approval carry. This decision need not delay part 2. ## Risks - The restacker retains broad ordinary branch permissions. Its key can cause substantial disruption even without approval authority. - Branch publication and record publication remain separate. Partial states require reliable recovery and clear reports. - A stale request can become eligible again when the target or evidence changes. It still names the old approved head. - A conflict in one shared family delays its healthy siblings. - Current approval history is incomplete. The clean signal must fall back to ordinary review when its reference is uncertain. - Whole-file equality can preserve content while surrounding changes alter meaning. - Version capacity and report-history storage remain finite; operational caps are not protection against a compromised service. - Part 1 needs a family API and durable recovery integration before unattended publication is enabled.