From 4f6eda4e7836d1201be4480b96e3ed18784f3a6f Mon Sep 17 00:00:00 2001 From: Daniel Hanold Date: Thu, 22 Oct 2026 06:30:05 -0400 Subject: [PATCH 1/7] Add design spec: Retire claim reclaim and its lease --- ...tire-claim-reclaim-and-its-lease-design.md | 217 ++++++++++++++++++ 1 file changed, 217 insertions(+) create mode 100644 docs/superpowers/specs/2026-10-22-retire-claim-reclaim-and-its-lease-design.md diff --git a/docs/superpowers/specs/2026-10-22-retire-claim-reclaim-and-its-lease-design.md b/docs/superpowers/specs/2026-10-22-retire-claim-reclaim-and-its-lease-design.md new file mode 100644 index 000000000..e7b6016df --- /dev/null +++ b/docs/superpowers/specs/2026-10-22-retire-claim-reclaim-and-its-lease-design.md @@ -0,0 +1,217 @@ +# Retire claim reclaim and its lease — design + +Change 0575 — Retire claim reclaim and its lease + +## Why + +Claim reclaim returns an `in-progress` change to `proposed` when all of these hold: its `claimed_at` stamp is strictly older than `reclaim.lease_ttl` (72h by default); neither the recorded `branch:` nor the conventional `/` branch exists locally or on the remote; and no live workspace exists. It runs only when typed (`docket change reclaim`), or from the maintenance sweep when `reclaim.auto: true` (off by default). It arrived with #89 (2026-07-17), borrowed from a competitor's lease-and-reclaim feature, and was ported to Go in #316. + +It has never fired, and its one window is already covered: + +- No change record has ever carried a `## Reclaim log`. That holds for this repository's full metadata history, checked 2026-10-21, and for the other local repositories using docket. No saved session ran a real `docket change reclaim`, and `reclaim.auto` is set in no config layer. +- In every saved session the sweep reported a stale claim for exactly one change, #422, six times. It had halted with a feature branch, so reclaim would have refused it anyway, and the board already showed it as halted. +- The building clone has a local branch from `workspace.prepare` onward, minutes after the claim, which blocks reclaim. A run that dies before then is recovered by resuming the change by id (which works without a workspace since #368), with the run tracker's verdict deciding any retry. +- From another clone, reclaim is a risk. A live run's branch is invisible there until `workspace.publish`, so a reclaim after the TTL could hand back a change that is still being built. ADR-0159 records this as an accepted risk. + +The lease has no other job. `claimed_at` is read only by lease evaluation (reclaim, the sweep's reclaim pass, and the `lease` value echoed in the claim result) and by validation that insists the stamp exists. Nothing else reads it: not the board, `docket status`, `context.implementation`, `change.relink`, or the run tracker, which has bound a dispatch to its claim through claim proofs since #407 (ADR-0111). + +The docs describe reclaim wrongly in several places. The guides say it rescues a run that "crashed before pushing a branch", but a local branch or workspace also blocks it. The convention's `halt` fallback says "the reclaim lease self-heals an abandoned claim", which has never been true in Go: every halt in that row happens after `workspace.prepare`, so a branch exists. The convention also says `claimed_at` is "cleared on leaving in-progress", but the code keeps it through blocked, implemented, and stacked-merged and clears it only at kill, done, and complete. + +## Goals + +- No operation, sweep pass, config key, body section, or doc returns an `in-progress` change to `proposed`. +- `claimed_at` is never written, cleared, required, or read. Records that already carry the line keep loading unchanged. +- **Upgrade together (decided at grooming).** No compatibility step for older binaries. Today's validation treats a missing `claimed_at` on an in-progress, implemented, or stacked-merged record as an error. So a pre-change binary reading a record the new binary claimed reports `change-state-incoherent`, and refuses that change's reconcile, mark-implemented, and finalize writes until it upgrades. On one machine there is no gap, because the binary is rebuilt right after the merge. The results file's human-actions section and the PR body carry an upgrade note for the next release's notes: every machine sharing a repository's docket metadata must upgrade before its next claim. +- An old config carrying `reclaim.lease_ttl` or `reclaim.auto` loads in every layer with one warning per key and never blocks anything. +- Every maintained doc describes the recovery of a stranded run as: resume the change by id, with the run tracker deciding. + +## Non-goals and anti-goals + +- **No replacement stale-claim signal.** Accepted at grooming. The sweep's skipped-reclaim entries were the only place a stale claim showed up, and the one change they ever named was already flagged as halted. A crashed coordinator surfaces at the next `docket run start implement-next --resume ` (`resume-active-run`). +- **No new way back to `proposed`.** After this change, nothing moves `in-progress` to `proposed` (#568 already refuses deferring an in-progress change). A stranded change is resumed, blocked, or killed. +- **No `schema_version` bump.** `SchemaVersion` versions the schema surface's own format, not each operation's fields. #360 removed a whole operation without a bump, and a bump would make installed skills refuse to run. +- **Anti-goal:** a `reclaim:` block in `.docket.yml`, `.docket.local.yml`, the global config, or a private repository's config must never make an operation refuse. Deleting the schema rows outright would do exactly that: `reclaim:` would become an `unknown-key` error, and every operation would fail with `ErrInvalidConfig`. +- **Unchanged:** resume, `change.resume-halted`, the run tracker, `## Run halted`, `reconciled:`, claim eligibility, and `branch:`. +- **Unrelated uses of the word stay:** `docket install collect` reclaiming version trees, `transaction/cleanup.go`'s `PruneAbandoned`, gate-drive claims, and `claim_eligible`. +- **Point-in-time records stay as written:** archived change records, specs, plans, results, release notes, Accepted ADR bodies, learnings war stories, and frozen fixtures (`testdata/bash-upgrade/**`, `internal/install/legacydata/**`, `testdata/repositories/documents/active-change-0158.md`). + +## Design + +**Build the removal list from a whole-repo grep, not from the lists below.** Grep for `reclaim`, `claimed_at`, `ClaimedAt`, `lease`/`Lease`, and `refreshes the claim`, then sort each hit into executable or prose. Drop the unrelated senses: git exact-lease pushes (`--force-with-lease`, `PushLease`, the transaction engine's expected-ref lease, finalize's publication lease, `lease-contended` in `run_verify.go`), `install collect`'s version trees, `PruneAbandoned`, gate-drive claims, and `claim_eligible`. Then drop the point-in-time records. The lists in each section are the sites known at grooming; the builder check found more, and there may be others. + +### 1. Delete the reclaim operation and the sweep's reclaim pass + +- **Operation.** Delete `internal/app/change_reclaim.go` whole: the `change.reclaim` op, its request, result, receipt, dispositions, proofs, and `## Reclaim log` writer. Also delete: + - the CLI subcommand (`newReclaimSubcommand` and its registration in `internal/cli/change.go`); + - the `"change reclaim"` entry in `internal/cli/install.go`'s asset-independent list; + - the `change.reclaim` schema binding (`schema_registry.go`) and the `reclaim_dispositions` vocabulary (`schema_vocab.go`). + + Reason consts whose values other operations also define (for example `workspace-probe-failed`, `unknown-change`, `ambiguous-change`) stay alive through those operations. +- **Domain.** Delete `internal/domain/lease.go` whole: `EvaluateReclaim`, `Reclaim`, `blockingBranch`, and its refusal reasons, plus `EvaluateLease` and `LeaseState`. Nothing reads them once the claim's `lease` field goes (section 2). Fix `actions.go`'s "Reclaim is declared in lease.go" comment. Reclaim has no transition enum value, so no switch needs editing. +- **Sweep** (`internal/app/maintenance.go`). Delete: + - `sweepKindReclaim`; + - `ReasonSweepReclaimAutoDisabled` and `ReasonSweepReclaimRevisionMissing`; + - the `sweepOps.reclaim` field and its closure, and the `case sweepKindReclaim` arm; + - the reclaim list in `sweepWorklist` and `sweepRunReclaim`. + + Keep the workspace service: `sweepAssessHistorical` still uses it. Only the reclaim closure's `wsErr` path goes. Drop `sweepWorklist`'s `eff` and `now` parameters if they become unused, and the `time` import with them. Delete `FCWorkspaceServiceUnavailable` if, as traced, only the reclaim closure mints it. +- **Finding-code registry** (`finding_codes.go`). Remove `branch-still-exists`, `lease-not-expired`, `malformed-claim-stamp`, `missing-claim-stamp`, and any other code only reclaim mints. Shared codes stay. +- **Dead config plumbing.** Delete: + - `context.finalize`'s `FinalizePolicy.ReclaimAuto` (`reclaim_auto`) and `ReclaimLeaseTTLHours` (`reclaim_lease_ttl_hours`). Nothing reads them. + - `domain.RepositoryPolicy.ReclaimTTLHours` and its only writer in `internal/repository/build.go`. Nothing reads them. + - `diagnostic.config`'s effective lines for both keys (`internal/app/config.go`). + - `config.Effective.Reclaim`, `type Reclaim`, its defaults, and its resolve assignments. +- **Comments that name reclaim:** fix them in `derived_views.go` (the always-board-visible op list), `change_relink.go` ("the same remote branch-facts probe reclaim gathers"), `change_claim.go`, `internal/cli/finalize.go`, and `internal/cli/maintenance.go`. +- **Help text.** `docket maintenance sweep`'s Short drops "and reclaim expired claims". `docket maintenance`'s group Short "Reclaim docket's closing half in batch", and the matching "batch driver that reclaims docket's closing half" comment in `maintenance.go`, are reworded so the word no longer appears (decided at grooming). Exact wording is the builder's call. + +### 2. Retire `claimed_at` + +Decided at grooming: stop writing it, rather than keep it as a "claimed on" date (git history already records the claim commit) or leave it as a lease nothing reads. + +- **Writers.** Delete `setClaimedAt`, `clearClaimedAt`, and `domain.RefreshClaim`: + - `change.claim` stops stamping; + - `change.reconcile` and `change.resume-halted` stop re-stamping; + - `Kill`, `MarkDone`, and `Complete` stop writing a bare `claimed_at:`. + + An existing line in a record is left exactly as it is by every write. +- **Domain and decode.** Remove `ChangeSpec.ClaimedAt` and `Change.ClaimedAt()`, and the `claimed_at` field of `changeWire` in `internal/repository/decode.go`. The decoder already treats unknown frontmatter keys as compatibility data ("Unknown keys are compatibility data and stay in the document; they are not decoded here and never fail the decode"). So an old record's `claimed_at:` line, empty, stamped, or even malformed, loads with no finding. +- **Validation** (`internal/repository/validate.go`): + - `claimFacts` stops requiring `claimed_at`. `branch` stays required for in-progress, implemented, and stacked-merged. Rename the function or fix its comment ("the claim facts a held lease requires"), since no lease exists. + - Delete the `change-final-claim-stamp` check and its finding text in `validation_text.go`. If kill, done, and complete no longer clear the stamp, an older record finishing under the new binary would keep one, and an error there would block writes to that record. +- **Repair** (`internal/reposetup/repair.go`). Delete `planClaimedAt`, `claimedAtHoldsValue`, the `drop-final-claimed-at` repair code (`RepairDropClaimedAt`), and the non-repairable "archived but not done/killed, still holds `claimed_at`" variant of `frontmatter-manual-review`. An archived record in a non-final status is still caught by validation's placement check. Other repair codes, and other `frontmatter-manual-review` cases if any exist, are untouched. Update `internal/app/testdata/finding-catalog.txt` to match. +- **Claim receipt and result** (`internal/app/change_claim.go`): + - Drop `claimed_at` and `lease` from `changeClaimReceipt` (the committed Docket-Result trailer) and from `ChangeClaimResult`. + - Drop the claim's TTL lookup (`ttlHours: eff.Reclaim.LeaseTTL.Value`). + - The human line loses its lease part. Before: `change 0575 claimed (refactor/retire-claim-reclaim-and-its-lease) lease fresh — …`. After: `change 0575 claimed (refactor/retire-claim-reclaim-and-its-lease) — …`. + + Older committed receipts that carry both keys still decode (extra keys are ignored), and `claim_proof.go` reads neither. ADR-0129's "committed state keeps its spelling" covers renames, not new receipts carrying fewer keys. +- **Comments that describe the lease.** Fix them in `change_halt.go` (header, `ChangeHalt`, `resumeHaltedOp`), `change_reconcile.go` (header and the patch-step comment), `change_implemented.go` ("never touches claimed_at"), `internal/document/document.go` and `internal/repository/decode.go` (both name "reposetup's claimed_at planner"), and `finalize_context.go`'s `FinalizePolicy` doc comment ("approval/reclaim policy"). +- **Before/after on a record.** Before, a claim leaves `claimed_at: '2026-10-22T09:14:03Z'` in the frontmatter, reconcile overwrites it, and a missing line on an in-progress record is a `change-state-incoherent` error. After, a new claim writes no `claimed_at:` line. An older in-progress record that has one keeps it untouched until it is archived, and nothing reads it. + +### 3. Tombstone the two config keys + +Decided at grooming: follow the existing retired-key path used by `finalize.skip_results_only_delta`, `runtime.bash`, and `metadata_branch`. + +- In `internal/config/schema.go`, keep `reclaim.lease_ttl` and `reclaim.auto` as `disp: dispObsolete` rows, with no `def`, the default any-layer scope, and their existing validators (`intLeaf(0)`, `boolLeaf()`). Keeping the rows also keeps `reclaim` an interior node, so a `reclaim:` block still parses. +- In `internal/config/decode.go`, add a `decodeLeaf` case per key, shaped like `finalize.skip_results_only_delta`'s. It emits an `obsolete-setting` warning with `Classification = Obsolete`, a message saying docket no longer returns claimed changes to the backlog and the value is ignored, and the remedy `remove reclaim. from `. It returns before the leaf is appended. Example: `reclaim.auto: docket no longer returns claimed changes to the backlog; it is ignored — remove reclaim.auto from .docket.yml`. +- This covers every layer: the repository `.docket.yml` (read from origin), `.docket.local.yml`, the global config, and a private repository's config. The warning shows in `diagnostic.config`, `docket status` findings, and install warnings. It never resolves into `Effective` and never blocks a mutation preflight. A malformed value (`auto: maybe`) still reports its type error first, as every tombstone's validator does today. +- Remove the `reclaim:` section from `.docket.example.yml`, then run `go generate ./internal/assets/` to refresh the embedded copy. With the rows marked obsolete, `TestLivingDocsAlignment` and `TestExampleSchemaCorrespondence` (Direction C) flag every remaining `reclaim.*` spelling in the living docs. That makes the docs pass in section 5 self-checking. +- Do **not** add `reclaim.lease_ttl` or `reclaim.auto` rows to `internal/repoguard/retired_vocabulary_test.go`. The tombstone needs those exact literals in Go, and `skip_results_only_delta` has no row for the same reason. + +### 4. Keep two defensive paths, and fix their wording + +- **Claim strips a leftover `## Run halted`** from a `proposed` record. After this change, only a record written by an older docket can reach that state (for example, one deferred while in progress before #568, then revived). Keep the code, because a stale marker on a re-claimed change would make `run.verify` report `run-halted` for a fresh run. Remove only the prose that ties it to reclaim. +- **The run tracker's `claim-replaced` verdict** fires when a newer claim proof exists for the bound change. It never read the lease. Keep it as a fail-closed ownership guard, and reword the "reclaimed and re-claimed" comments in `runtracker_verdict.go` and its two integration tests. + +### 5. Skills and docs + +Edit the authored `skills/**` files, then regenerate `internal/assets/embedded/tree/` with `go generate ./internal/assets/`; never hand-edit the mirror. For every edit below, a stranded run's recovery reads as: resume the change by id (`docket run start implement-next --resume `). If that reports `resume-active-run`, cancel the old run with `docket run cancel --key --reason ` and resume; for a halted change, use `change.resume-halted`. `skills/docket-implement-next/references/edge-paths.md`'s *Resume of an in-progress change* and `docs/concepts/run-tracker.md` already describe this; reuse their wording. + +- **`skills/docket-convention/SKILL.md`:** + - Drop the `reclaim:` lines from the config sample. + - The `halt` row loses "the reclaim lease self-heals an abandoned claim"; replace it with the resume-halted recovery, or nothing. + - Drop the `claimed_at:` manifest line, and "survives reclaim" from the `branch_prefix:` line. + - Delete the `## Reclaim log` body-section bullet. + - Delete the lifecycle diagram's `lease expired, no branch (reclaim)──▶ proposed` edge. + - Delete the *Reclaim edge* paragraph. + - Keep `## Run halted`'s "and by the claim when a halted change is claimed again", which is still accurate as behavior. +- **`skills/docket-implement-next/SKILL.md`:** + - Claim paragraph: drop "+ `claimed_at:` — the lease the `change.reclaim` operation and the maintenance sweep's reclaim key on", and "lease classification" from what the claim returns. + - Delete "A change that instead reached `proposed` through the `change.reclaim` operation carries no live claim…". + - Checkpoint row 2: drop "+ `claimed_at:`". + - Delete "`claimed_at` is stamped only by the claim, reconcile, and resume-halted transactions." + - Named-invocation paragraph: drop "or reclaim" from "another change's failing closeout, cleanup, or reclaim". + - Resume-halted paragraph and the reconcile-transaction sentence: drop "refreshes the claim" from both. + - The halt bullet: "leaving the branch, lease, workspace, and evidence untouched" drops "lease". +- **`skills/docket-implement-next/references/edge-paths.md`:** drop "and no reclaim" from the bounded dependency closeout. Review "no stolen lease": keep it if it means the claim or ownership, and reword it if it means the claim lease. +- **`skills/docket-status/SKILL.md`:** remove every reclaim mention: + - the read "never … reclaims", twice; + - implementation scope's "plus reclaim gating" and its "`reclaim.auto`-gated reclaims"; + - the full sweep's "eligible reclaims"; + - "attempts an eligible reclaim only when `reclaim.auto` is true"; + - the `reclaim-auto-disabled` example of an intentional skip (replace it with a remaining intentional skip if one exists, or drop it); + - "A stale claim surfaces as a `maintenance.sweep` reclaim entry…". +- **Guides:** + - `docs/guide/keeping-the-backlog-honest.md`: delete the intro clause about a crashed run going back to the queue, the status and sweep "reclaims" mentions, and the whole *Reclaiming expired claims* section with its YAML fence. The "crashed before pushing a branch" bullet is replaced by the single resume path above. The "crashed after pushing a branch" bullet becomes the general case and gains the `resume-active-run` → `run cancel` step. + - `docs/guide/capturing-work.md`: drop the backward-edge paragraph, the claim lease, and reclaim. A claim records which branch will carry the work. + - `docs/guide/building-without-supervision.md`: step 2 drops "and when it was taken" and the claim-lease self-heal sentence. +- **Concepts and reference:** + - `docs/concepts/change-lifecycle.md`: drop "and when it was taken". + - `docs/reference/fields.md`: drop "and when it was taken". + - `docs/reference/glossary.md`: remove `claimed_at` from the manifest field list and "Moved there by … `change reclaim`" from the `proposed` row. Delete the *Claim / claim lease / reclaim* entry, or reduce it to *Claim* without lease or reclaim. Delete the *`reclaim.auto` / `reclaim.lease_ttl`* entry, the `reclaim_dispositions` vocabulary row, the docket-status "reclaim expired claims" phrase, and both index links. + - `docs/reference/cli.md`: drop "and reclaim expired claims" from `docket maintenance`. + - `docs/reference/config-keys.md`: remove both rows. Obsolete keys are not listed there (no existing tombstone is). + - `docs/install/global-config.md`: swap the example key `reclaim.lease_ttl` for another any-layer key. +- **Indexes:** `docs/README.md` and `docs/guide/README.md` drop "reclaiming expired claims". +- **`docs/comparison/ai-native-sdlc-playbook.md`:** this is kept current (edited 2026-10-19 for trivial's retirement). Fix the two rows that list reclaim as a docket capability, and drop "and leases" from the audit-trail row's "receipts and leases" (settled at grooming: there the lease is the claim stamp; pushes leave no trail). The `reclaim-claims.sh` entry in its retired-scripts list is history and may stay. This file is outside the docs-alignment guard's roots, so no test flags a miss here. + +### 6. ADR + +Record a new ADR through `docket-adr` that **supersedes ADR-0159**, so 0159's status becomes "Superseded by ADR-N". The decision: docket keeps no claim lease and no reclaim. `claimed_at` is never written or read, and old lines are ignored. The two `reclaim.*` keys are obsolete tombstones that warn and are ignored. A stranded run recovers only by resuming it by id, with the run tracker deciding. The consequences and alternatives cover: + +- the evidence (never fired; #422 the only stale claim ever reported, already halted); +- the cross-clone risk; +- no path from `in-progress` back to `proposed` (with #568); +- no replacement stale-claim signal. + +Considered and rejected: keeping `claimed_at` as a "claimed on" date; leaving the lease in place; deleting the config keys outright; a silent tombstone. + +The ADR's context also notes three stale passages, and lists ADR-0059, ADR-0084, and ADR-0101 in `relates_to`: + +- ADR-0059's consequence "the existing reclaim lease self-heals an abandoned claim" no longer applies. +- ADR-0101's implementation-scope schedule no longer includes `reclaim.auto`-gated reclaims. +- ADR-0084's `claimed_at` attribution filters were already replaced by ADR-0111's claim proofs. + +The bodies of those three ADRs are not edited. + +### 7. Tests + +Follow the rule that a test whose subject is gone is deleted, while a test guarding a mechanism that survives is re-pointed, not re-gated to green. + +- **Delete:** + - `internal/app/change_reclaim_test.go` whole; + - the five `TestIntegrationChangeRuntimeReclaim*` functions in `change_integration_test.go`; + - `internal/domain/lease_test.go` whole, since `EvaluateLease` goes too; + - in `maintenance_test.go`: `TestSweepReclaimGatedOnAuto`, `TestDisabledReclaimPreparesNothing`, and `TestReclaimRevisionFromObservation`; + - `TestChangeReclaim*` in `internal/cli/change_test.go`; + - the `reclaim_dispositions` spec in `schema_vocab_test.go`. +- **Replace, don't just delete:** + - `TestIntegrationSweepDispatchedReclaimKeepsSetupOnce` in `maintenance_traffic_integration_test.go` is the file's only proof that a sweep-dispatched operation keeps setup to once. Re-point that proof at another dispatched sweep item, such as a closeout, and reword the header comments. + - `TestE2EHaltResumeAndReclaim` in `finalize_e2e_test.go` keeps its halt/resume half and drops the reclaim half. +- **Edit:** + - `maintenance_test.go`: the `recordingSweepOps.reclaim` field, `sweepPin`, `sweepInProgressBlob`, and the reclaim legs of the structured-report, reload, implementation-scope, integration-sync no-op, and history-growth tests. The integration-sync test used a skipped reclaim as its no-op entry, so give it another no-op item. + - The `sweepWorklist` callers in `maintenance_assess_test.go`. + - `maintenance_preflight_test.go`'s reclaim rows. + - `finding_codes_test.go`'s `reclaimSkip` constructor pattern. + - `revision_rename_test.go`'s reclaim rows. + - `build_test.go`, `transaction/loader_test.go`, and `entities_test.go` (`ReclaimTTLHours`). + - `finalize_e2e_test.go`'s `reclaim:` config block and its unsupported-config matrix row. + - `claim_proof_git_integration_test.go`'s receipt fixture fields. + - `change_integration_test.go`'s claim `Lease` assertion. +- **Claim stamp tests:** + - Remove the stamp assertions in `actions_test.go` (`TestClaimSetsBranchStampAndReconciled`, `TestRefreshClaimRestampsOnly`, and the clear checks in kill, done, and complete), plus the action-matrix fingerprint field. + - Update the same assertions in `change_claim_test.go`, `change_reconcile_test.go`, the resume-halted integration tests, `change_kill_test.go`, `change_complete_test.go`, and `finalize_closeout_integration_test.go`. + - Remove the claim-stamp cases in `validate_test.go`, `decode_test.go`, `repair_test.go`, `repair_text_test.go`, `findingtext_test.go`, `repository_repair_*_test.go`, `repair_remedy_family_test.go`, `validation_text_test.go`, `empty_value_test.go` (if its subject was only `claimed_at`), `tests/test_go_integration_app_reporepair.sh`, and the finding-catalog golden file. + - **Add** one validation case: an in-progress record with a branch and no `claimed_at:` line is coherent. **Add** one decode case: a record with a stamped or malformed `claimed_at:` line decodes with no finding. +- **Config:** + - Add `TestReclaimKeysAreObsoleteTombstones`, modeled on `TestSkipResultsOnlyDeltaIsObsoleteTombstone`. It covers both keys across the repository (block and flow), local, and global layers: not declared, exactly one obsolete warning with the exact remedy, preflight allowed, and the capability obsolete and non-blocking. + - Flip both rows to obsolete in `decode_test.go`'s acceptance table, `capability_test.go`, and `setting_paths_test.go`. + - Tests that used a `reclaim.*` key as a generic subject move to another key of the same shape and layer scope: `resolve_test.go`'s per-leaf precedence and explicit-default provenance tests, `decode_test.go`'s empty-section test, the `four-layer-collision` fixtures, `repository_set_visibility_integration_test.go` (which reads `Effective.Reclaim.Auto`, a compile break), and optionally `internal/reposetup/visibilityconfig_test.go`. + - Remove the block from `testdata/repositories/configs/example-activated`. + - Fix the tests that read `Effective.Reclaim` and stop compiling: `defaults_test.go`, `schema_test.go`'s defaults map (the obsolete rows have no default), and `fixtures_test.go`'s sparse-defaults, example-activated, and four-layer-collision assertions. +- **Run-tracker tests.** + - `runtracker_ownership_integration_test.go` re-stamps `claimed_at` as its "real reconcile edit" churn. Switch it to an edit reconcile still makes, so the test keeps proving that unrelated churn does not move ownership. + - Update `runtracker_verdict_integration_test.go`'s header, which still describes the retired `claimed_at` ≥ dispatch-time attribution filter. +- **Comment-only:** the `tests/test_go_integration_app_changeruntime.sh` header and `derived_views_guard_test.go`. +- **Retired-operation guard.** Add `TestChangeReclaimRetired` in `internal/cli/change_test.go`, in the shape of `TestChangeRefreshClaimRetired`: absent from the Cobra tree, the capability catalog, and `app.SchemaFor`, and exit 2. +- **Prose sentinels** (`internal/repoguard/prose_contracts_test.go`): + - Replace the `change_0360_revision_lookup` presence pin on "stamped by claim, reconcile, and resume-halted" with `absent:` pins on `change.reclaim`, `## Reclaim log`, `reclaim.lease_ttl`, and the `claimed_at:` manifest line in the convention and implement-next skills, plus "refreshes the claim" in implement-next. + - Mutation-test each pin: restore the removed text and watch it go red. + +## Left to the builder + +- Exact help-text and doc wording, within the rules above. +- Which key replaces `reclaim.*` in each re-pointed config test, as long as it has the same type, merge kind, and layer scope as the key it replaces. +- Whether to strip now-ignored `claimed_at:` lines from test fixtures. Either way passes, since the decoder ignores them; strip them where the test is about claim facts. +- Whether to re-point retired-vocabulary row 44a (`reclaim-version-missing` → `reclaim-revision-missing`). It names a token that no longer exists, and its `New` value is never checked. +- Whether the glossary keeps a slimmed *Claim* entry or folds it into an existing one. From b066d5264e0c53c2c2431dc2fb97996b7441ecb4 Mon Sep 17 00:00:00 2001 From: Daniel Hanold Date: Thu, 22 Oct 2026 06:56:54 -0400 Subject: [PATCH 2/7] refactor: delete change.reclaim and the maintenance sweep's reclaim pass --- internal/app/change_claim.go | 2 +- internal/app/change_integration_test.go | 228 ------- internal/app/change_reclaim.go | 632 ------------------ internal/app/change_reclaim_test.go | 178 ----- internal/app/change_relink.go | 2 +- internal/app/derived_views.go | 2 +- internal/app/derived_views_guard_test.go | 2 +- internal/app/finalize_e2e_test.go | 49 +- internal/app/finding_codes.go | 44 +- internal/app/finding_codes_test.go | 5 +- internal/app/maintenance.go | 112 +--- internal/app/maintenance_assess_test.go | 9 +- internal/app/maintenance_preflight_test.go | 6 +- internal/app/maintenance_test.go | 258 +++---- .../maintenance_traffic_integration_test.go | 133 ++-- internal/app/schema_registry.go | 1 - internal/app/schema_vocab.go | 4 - internal/app/schema_vocab_test.go | 1 - internal/cli/change.go | 42 +- internal/cli/change_test.go | 76 +-- internal/cli/finalize.go | 2 +- internal/cli/install.go | 1 - internal/cli/maintenance.go | 14 +- internal/cli/revision_rename_test.go | 3 +- internal/domain/actions.go | 4 - internal/domain/lease.go | 90 --- internal/domain/lease_test.go | 307 --------- .../test_go_integration_app_changeruntime.sh | 2 +- 28 files changed, 289 insertions(+), 1920 deletions(-) delete mode 100644 internal/app/change_reclaim.go delete mode 100644 internal/app/change_reclaim_test.go diff --git a/internal/app/change_claim.go b/internal/app/change_claim.go index 2ac6b9f86..a9f546d65 100644 --- a/internal/app/change_claim.go +++ b/internal/app/change_claim.go @@ -37,7 +37,7 @@ import ( // a lost response replays the original applied receipt as `already-claimed` // rather than allocating a second claim; a foreign edit that moved the record // fails the exact-revision expectation as `contended`. A claim never clears or -// steals an expired claim; reclaim is 0316. +// steals an existing claim. // OperationChangeClaim is the operation key the claim transition records in its // result envelope and transaction trailer. diff --git a/internal/app/change_integration_test.go b/internal/app/change_integration_test.go index 6157c6a6e..15342cb9c 100644 --- a/internal/app/change_integration_test.go +++ b/internal/app/change_integration_test.go @@ -2441,234 +2441,6 @@ func TestIntegrationChangeRuntimePRPublishThroughFakeGH(t *testing.T) { } } -// TestReclaimIndependentOfAutoPolicy proves explicit reclaim applies even when -// reclaim.auto is false — the auto policy governs only maintenance sweep. -func TestIntegrationChangeRuntimeReclaimIndependentOfAutoPolicy(t *testing.T) { - requireRealGit(t) - recPath := groomPath(3, "widget") - repo := newWorkingRepo(t, map[string]string{ - ".docket.yml": "reclaim:\n auto: false\n", - recPath: lifecycleChange(3, "widget", "in-progress"), - }) - node := planningDepsFor(t, repo.invocation) - ver := blobRevisionAt(t, repo.origin, "docket", recPath) - res := ChangeReclaim(context.Background(), node.deps, reclaimClearWorkspace, node.dir, - ChangeReclaimRequest{ID: 3, Revision: ver}) - if res.Result != ResultApplied || res.Disposition != ReclaimDispReclaimed { - t.Fatalf("explicit reclaim under reclaim.auto:false = (%q, %q) findings=%v", res.Result, res.Disposition, res.Findings) - } -} - -// TestReclaimMalformedLeaseSkips proves a record whose claim stamp is malformed -// (an unevaluable lease, hence a corpus error) is refused end-to-end with no -// mutation — the destructive leg fails closed on an unreadable lease. -func TestIntegrationChangeRuntimeReclaimMalformedLeaseSkips(t *testing.T) { - requireRealGit(t) - recPath := groomPath(3, "widget") - repo := newWorkingRepo(t, map[string]string{ - recPath: reclaimRecordWithClaim(3, "widget", "not-a-timestamp"), - }) - node := planningDepsFor(t, repo.invocation) - ver := blobRevisionAt(t, repo.origin, "docket", recPath) - before, _ := originFile(t, repo.origin, "docket", recPath) - res := ChangeReclaim(context.Background(), node.deps, reclaimClearWorkspace, node.dir, - ChangeReclaimRequest{ID: 3, Revision: ver}) - if res.Result == ResultApplied { - t.Fatalf("a malformed lease was reclaimed: %q", res.Result) - } - if res.Disposition != ReclaimDispSkipped { - t.Errorf("disposition = %q, want skipped", res.Disposition) - } - assertOriginRecordUnchanged(t, repo.origin, "docket", recPath, before) -} - -// TestReclaimRequiresProvenAbsence proves the destructive gate refuses and -// mutates NOTHING when a recorded/conventional branch is still present (locally -// or remotely), when an owned workspace is still live, or when any probe cannot -// be answered — unknown never shares the absent branch. Every refusal leaves the -// origin record byte-identical. -func TestIntegrationChangeRuntimeReclaimRequiresProvenAbsence(t *testing.T) { - requireRealGit(t) - recPath := groomPath(3, "widget") - - for _, m := range planRepoModes() { - m := m - t.Run(m.name, func(t *testing.T) { - // branch present locally. - t.Run("local-branch-present", func(t *testing.T) { - repo := m.build(t, map[string]string{recPath: lifecycleChange(3, "widget", "in-progress")}) - node := planningDepsFor(t, repo.invocation) - runGit(t, repo.invocation, "branch", "feat/widget") - ver := blobRevisionAt(t, repo.origin, m.branch, recPath) - before, _ := originFile(t, repo.origin, m.branch, recPath) - res := ChangeReclaim(context.Background(), node.deps, reclaimClearWorkspace, node.dir, - ChangeReclaimRequest{ID: 3, Revision: ver}) - assertReclaimSkipped(t, res, ReasonReclaimBranchPresent) - assertOriginRecordUnchanged(t, repo.origin, m.branch, recPath, before) - }) - - // the fresh-mint candidate is /, not the fixed feat/ - // prefix: a type-fix change probes fix/ alongside its recorded - // name. Here the recorded feat/widget is absent, so the block can only - // come from the minted fix/widget candidate. - t.Run("mint-candidate-probes-type", func(t *testing.T) { - rec := strings.Replace(lifecycleChange(3, "widget", "in-progress"), "type: feat", "type: fix", 1) - repo := m.build(t, map[string]string{recPath: rec}) - node := planningDepsFor(t, repo.invocation) - runGit(t, repo.invocation, "branch", "fix/widget") - ver := blobRevisionAt(t, repo.origin, m.branch, recPath) - before, _ := originFile(t, repo.origin, m.branch, recPath) - res := ChangeReclaim(context.Background(), node.deps, reclaimClearWorkspace, node.dir, - ChangeReclaimRequest{ID: 3, Revision: ver}) - assertReclaimSkipped(t, res, ReasonReclaimBranchPresent) - assertOriginRecordUnchanged(t, repo.origin, m.branch, recPath, before) - }) - - // branch present remotely (local absent). - t.Run("remote-branch-present", func(t *testing.T) { - repo := m.build(t, map[string]string{recPath: lifecycleChange(3, "widget", "in-progress")}) - node := planningDepsFor(t, repo.invocation) - runGit(t, repo.invocation, "push", "-q", "origin", "HEAD:refs/heads/feat/widget") - ver := blobRevisionAt(t, repo.origin, m.branch, recPath) - before, _ := originFile(t, repo.origin, m.branch, recPath) - res := ChangeReclaim(context.Background(), node.deps, reclaimClearWorkspace, node.dir, - ChangeReclaimRequest{ID: 3, Revision: ver}) - assertReclaimSkipped(t, res, ReasonReclaimBranchPresent) - assertOriginRecordUnchanged(t, repo.origin, m.branch, recPath, before) - }) - - // an owned workspace still holds live work. - t.Run("workspace-active", func(t *testing.T) { - for _, kind := range []workspace.StateKind{workspace.StateReady, workspace.StateDirty, workspace.StateResumable, workspace.StateMismatch} { - repo := m.build(t, map[string]string{recPath: lifecycleChange(3, "widget", "in-progress")}) - node := planningDepsFor(t, repo.invocation) - ver := blobRevisionAt(t, repo.origin, m.branch, recPath) - before, _ := originFile(t, repo.origin, m.branch, recPath) - res := ChangeReclaim(context.Background(), node.deps, - WorkspaceDeps{Service: fakeReclaimWorkspace{kind: kind}}, node.dir, - ChangeReclaimRequest{ID: 3, Revision: ver}) - assertReclaimSkipped(t, res, ReasonReclaimWorkspaceActive) - assertOriginRecordUnchanged(t, repo.origin, m.branch, recPath, before) - } - }) - - // a proven cleanly-absent workspace names no owned live work: it - // must not raise the workspace-active refusal (change 0368 — absent - // is foreign-equivalent for reclaim, never in the active set). - // Adding StateAbsent to reclaimActiveWorkspaceStates reddens this. - t.Run("absent-workspace-does-not-block", func(t *testing.T) { - repo := m.build(t, map[string]string{recPath: lifecycleChange(3, "widget", "in-progress")}) - node := planningDepsFor(t, repo.invocation) - ver := blobRevisionAt(t, repo.origin, m.branch, recPath) - res := ChangeReclaim(context.Background(), node.deps, - WorkspaceDeps{Service: fakeReclaimWorkspace{kind: workspace.StateAbsent}}, node.dir, - ChangeReclaimRequest{ID: 3, Revision: ver}) - if res.Reason == ReasonReclaimWorkspaceActive { - t.Fatalf("an absent workspace raised the workspace-active refusal; reason=%q", res.Reason) - } - }) - - // a workspace probe that cannot be answered fails closed. - t.Run("workspace-probe-error", func(t *testing.T) { - repo := m.build(t, map[string]string{recPath: lifecycleChange(3, "widget", "in-progress")}) - node := planningDepsFor(t, repo.invocation) - ver := blobRevisionAt(t, repo.origin, m.branch, recPath) - before, _ := originFile(t, repo.origin, m.branch, recPath) - res := ChangeReclaim(context.Background(), node.deps, - WorkspaceDeps{Service: fakeReclaimWorkspace{err: errors.New("inspect boom")}}, node.dir, - ChangeReclaimRequest{ID: 3, Revision: ver}) - assertReclaimSkipped(t, res, ReasonReclaimWorkspaceProbe) - assertOriginRecordUnchanged(t, repo.origin, m.branch, recPath, before) - }) - }) - } -} - -// TestReclaimTransaction proves the applied path end-to-end: the landed Reclaim -// action returns the record to proposed, clears branch/claim, sets -// reconciled:false, appends one dated ## Reclaim log entry, and rerenders the -// board — all in one atomic commit; and that an exact-revision contention refuses. -func TestIntegrationChangeRuntimeReclaimTransaction(t *testing.T) { - requireRealGit(t) - recPath := groomPath(3, "widget") - - for _, m := range planRepoModes() { - m := m - t.Run(m.name, func(t *testing.T) { - t.Run("reclaims", func(t *testing.T) { - repo := m.build(t, map[string]string{recPath: lifecycleChange(3, "widget", "in-progress")}) - node := planningDepsFor(t, repo.invocation) - ver := blobRevisionAt(t, repo.origin, m.branch, recPath) - res := ChangeReclaim(context.Background(), node.deps, reclaimClearWorkspace, node.dir, - ChangeReclaimRequest{ID: 3, Revision: ver}) - if res.Result != ResultApplied || res.Disposition != ReclaimDispReclaimed { - t.Fatalf("reclaim = (%q, %q) reason=%q findings=%v", res.Result, res.Disposition, res.Reason, res.Findings) - } - if res.Revision == "" { - t.Fatalf("applied reclaim carried no committed revision") - } - rec, ok := originFile(t, repo.origin, m.branch, recPath) - if !ok { - t.Fatalf("record vanished after reclaim") - } - for _, want := range []string{"status: 'proposed'", "reconciled: false", "## Reclaim log", "2026-08-02T00:00:00Z", "lease strictly expired"} { - if !strings.Contains(rec, want) { - t.Errorf("reclaimed origin record missing %q:\n%s", want, rec) - } - } - if strings.Contains(rec, "branch: feat/widget") { - t.Errorf("branch not cleared on origin:\n%s", rec) - } - if strings.Contains(rec, "claimed_at: 2026-08-02") { - t.Errorf("claim stamp not cleared on origin:\n%s", rec) - } - // The board is refreshed to a fresh render of the committed corpus. - assertBoardMatchesCommitted(t, repo.origin, m.branch, repo.invocation) - }) - - t.Run("revision-drift-contends", func(t *testing.T) { - repo := m.build(t, map[string]string{recPath: lifecycleChange(3, "widget", "in-progress")}) - node := planningDepsFor(t, repo.invocation) - before, _ := originFile(t, repo.origin, m.branch, recPath) - res := ChangeReclaim(context.Background(), node.deps, reclaimClearWorkspace, node.dir, - ChangeReclaimRequest{ID: 3, Revision: strings.Repeat("b", 40)}) - if res.Result != ResultContended { - t.Fatalf("revision drift = %q, want contended", res.Result) - } - assertOriginRecordUnchanged(t, repo.origin, m.branch, recPath, before) - }) - }) - } -} - -// TestReclaimUnreachableRemoteFailsClosed proves the destructive leg fails closed -// when the remote is unreachable: nothing is reclaimed and the origin record is -// untouched. An unreachable origin is caught while pinning authoritative context -// (which fetches origin before any probe), so a reclaim can never proceed on -// state it could not authoritatively read — unknown never shares the clean-read -// branch on a destructive operation. -func TestIntegrationChangeRuntimeReclaimUnreachableRemoteFailsClosed(t *testing.T) { - requireRealGit(t) - recPath := groomPath(3, "widget") - repo := newWorkingRepo(t, map[string]string{ - recPath: lifecycleChange(3, "widget", "in-progress"), - }) - node := planningDepsFor(t, repo.invocation) - ver := blobRevisionAt(t, repo.origin, "docket", recPath) - before, _ := originFile(t, repo.origin, "docket", recPath) - // Break the remote so no origin state can be authoritatively read or probed. - runGit(t, repo.invocation, "remote", "set-url", "origin", testsupport.TempDir(t)+"/nonexistent.git") - res := ChangeReclaim(context.Background(), node.deps, reclaimClearWorkspace, node.dir, - ChangeReclaimRequest{ID: 3, Revision: ver}) - if res.Result == ResultApplied { - t.Fatalf("an unreachable remote was reclaimed: %q", res.Result) - } - if res.Disposition != ReclaimDispSkipped { - t.Errorf("disposition = %q, want skipped", res.Disposition) - } - assertOriginRecordUnchanged(t, repo.origin, "docket", recPath, before) -} - // TestChangeReconcileAppliedResult proves the app layer submits the exact // expected revision and metadata target ref, carries NO idempotency key (a // non-allocating edit of an existing record), and decodes the applied receipt. diff --git a/internal/app/change_reclaim.go b/internal/app/change_reclaim.go deleted file mode 100644 index 8e98894b0..000000000 --- a/internal/app/change_reclaim.go +++ /dev/null @@ -1,632 +0,0 @@ -package app - -import ( - "context" - "encoding/json" - "fmt" - "path" - "strings" - - "github.com/danielhanold/docket/internal/config" - "github.com/danielhanold/docket/internal/document" - "github.com/danielhanold/docket/internal/domain" - "github.com/danielhanold/docket/internal/gitcli" - "github.com/danielhanold/docket/internal/render" - "github.com/danielhanold/docket/internal/repository" - "github.com/danielhanold/docket/internal/repository/transaction" - "github.com/danielhanold/docket/internal/workspace" -) - -// This file is `change reclaim`: the proof-gated, exact-revision return of one -// strictly-expired `in-progress` claim to `proposed`. Reclaim is destructive -// metadata surgery — it clears the branch and the claim stamp and marks the -// record unreconciled — so its destructive leg FAILS CLOSED on any probe it -// cannot answer. Every external observation has three outcomes: present, cleanly -// absent, and unknown; `unknown` never shares the "absent" branch, so a probe -// error is a retained skip, never a licence to reclaim (learning -// `probe-error-is-not-clean-absence`). -// -// The gate requires ALL of: a strictly-expired lease (missing, empty, malformed, -// future, exactly-at-boundary, and non-in-progress stamps are NOT expiry); the -// recorded AND conventional feature branch cleanly absent both locally and -// remotely; no owned live feature workspace (allocating/ready/dirty/ambiguous); -// and every Git and workspace probe succeeding. The workspace inspection is the -// ownership + live-gate/process-liveness probe: a live gate run keeps its owned -// workspace registered/dirty/allocating, exactly the states this refuses on — -// the same reading `change resume-halted` and `finalize clear-block` take of a -// workspace whose writer may still be live. -// -// Only when every condition holds does the exact-revision transaction apply the -// landed `domain.Reclaim` action, append ONE dated `## Reclaim log` entry (the -// previous claim plus a proof summary), return the record to `proposed`, clear -// branch/claim, set `reconciled: false`, rerender the artifact block and inline -// board, validate the whole repository, commit exactly those paths, and push -// under the exact-ref lease. The lease and branch-fact re-evaluation happens on -// the transaction's own fresh state (decide-and-act-on-the-same-copy): the -// pre-transaction probes are the destructive gate, the in-transaction action is -// the authority. A record whose fresh status moved out from under the exact -// revision maps to `contended`; every retained refusal is `skipped` and touches -// nothing (no cleanup, delete, reset, or marker removal). -// -// Explicit reclaim is available regardless of `reclaim.auto`: the auto policy -// governs only whether `maintenance sweep` attempts reclaim, never this command. - -// OperationChangeReclaim is the operation key `change reclaim` records in its -// result envelope and its transaction trailer. -const OperationChangeReclaim = "change.reclaim" - -// reclaimLogHeading is the exact H2 heading of the appended reclaim log. -const reclaimLogHeading = "## Reclaim log" - -// The closed set of `change reclaim` dispositions a result may carry. -const ( - // ReclaimDispReclaimed: the claim was reclaimed to proposed. - ReclaimDispReclaimed = "reclaimed" - // ReclaimDispSkipped: a retained precondition refusal — the lease is not - // strictly expired, a branch/workspace still holds the work, or a probe could - // not be answered. Nothing was cleaned, deleted, reset, or removed. - ReclaimDispSkipped = "skipped" - // ReclaimDispContended: the exact-revision transaction lost to a fresh - // incompatible state (the record moved out from under the submitted revision). - ReclaimDispContended = "contended" - // ReclaimDispFailed: a transaction failure; the cause is in the envelope's - // failure field. - ReclaimDispFailed = "failed" -) - -// The stable machine reasons `change reclaim` reports. Message text is -// explanatory and must not be parsed. -const ( - // ReasonReclaimUnknownChange: an id names no record in the corpus. - ReasonReclaimUnknownChange = "unknown-change" - // ReasonReclaimAmbiguousID: an id is claimed by more than one record. - ReasonReclaimAmbiguousID = "ambiguous-change" - // ReasonReclaimBranchPresent: the recorded or conventional feature branch is - // still present locally or remotely — unfinished work whoever left it. - ReasonReclaimBranchPresent = "branch-still-present" - // ReasonReclaimBranchProbe: a Git branch-existence probe could not be - // answered; the destructive leg fails closed rather than assume absence. - ReasonReclaimBranchProbe = "branch-probe-failed" - // ReasonReclaimWorkspaceActive: an owned feature workspace is - // allocating/ready/dirty/ambiguous — the work still exists. - ReasonReclaimWorkspaceActive = "workspace-active" - // ReasonReclaimWorkspaceProbe: the owned workspace could not be inspected. - ReasonReclaimWorkspaceProbe = "workspace-probe-failed" - // reclaimReasonIllegalSource is the domain's stable token for a non-in-progress - // source status; the result mapper folds it onto `contended`. - reclaimReasonIllegalSource = "illegal-source-status" -) - -// reclaimActiveWorkspaceStates is the set of inspected workspace states that -// prove the work still exists and so block a reclaim. A ready, dirty-owned, -// allocating, or path/registration/manifest-mismatched (ambiguous ownership) -// workspace is a live holder; a cleaned tombstone, a missing feature branch, a -// foreign/malformed/unowned manifest, or a proven cleanly-absent slot -// (workspace.StateAbsent — a run halted before allocation, change 0368) is not -// this change's live work and does not block. StateAbsent is deliberately absent -// from this set: pre-0368 it inspected as StateForeign, which was likewise -// non-blocking, so its omission preserves that behavior. Keyed on the workspace -// layer's own state spellings. -var reclaimActiveWorkspaceStates = map[string]bool{ - string(workspace.StateReady): true, - string(workspace.StateDirty): true, - string(workspace.StateResumable): true, - string(workspace.StateMismatch): true, -} - -// ChangeReclaimRequest is the closed, caller-supplied request for one reclaim. -// ID and Revision pin the exact submitted record; the reclaim generates its own -// dated log entry, so there is no authored input. -type ChangeReclaimRequest struct { - ID int `json:"id" docket:"required"` - Revision string `json:"revision" docket:"required"` -} - -// ChangeReclaimResult is the protocol-v1 document `change reclaim` returns. It -// names identity and the closed disposition; a refusal carries a stable reason -// and message. Findings marshals as [] on every path. -type ChangeReclaimResult struct { - Envelope - ID int `json:"id,omitempty"` - Disposition string `json:"disposition,omitempty" docket:"enum=reclaim_dispositions"` - Revision string `json:"committed_revision,omitempty"` - Reason string `json:"reason,omitempty"` - Message string `json:"message,omitempty"` - Findings []StatusFinding `json:"findings"` -} - -// HumanText renders a one-line summary naming identity and disposition only. -func (r ChangeReclaimResult) HumanText() string { - if r.Result == ResultApplied || r.Result == ResultNoOp { - return fmt.Sprintf("%s: change %04d %s — %s", r.Operation, r.ID, r.Disposition, r.Revision) - } - if r.Reason != "" { - return fmt.Sprintf("%s: %s (%s)", r.Operation, r.Result, r.Reason) - } - return fmt.Sprintf("%s: %s", r.Operation, r.Result) -} - -// newChangeReclaimResult stamps the envelope and normalizes Findings so the -// array marshals as [] on every path. -func newChangeReclaimResult(result Result, out ChangeReclaimResult) ChangeReclaimResult { - out.Envelope = NewEnvelope(OperationChangeReclaim, result) - if out.Findings == nil { - out.Findings = []StatusFinding{} - } - return out -} - -// reclaimSkip builds a retained-refusal result: disposition skipped, a stable -// reason, and an explanatory message. A skip mutates nothing. -func reclaimSkip(result Result, reason, message string, id int) ChangeReclaimResult { - return newChangeReclaimResult(result, ChangeReclaimResult{ - ID: id, Disposition: ReclaimDispSkipped, Reason: reason, Message: message, - }) -} - -// changeReclaimReceipt is the canonical receipt persisted with a reclaim commit. -// Field order is alphabetical for the engine's canonical-form validator. -type changeReclaimReceipt struct { - ID int `json:"id"` - Op string `json:"op"` -} - -// ChangeReclaim proof-gates a reclaim and, when every condition holds, drives one -// atomic exact-revision transaction that returns the record to proposed. The -// branch and workspace probes run first, before any effect: any present branch, -// any live workspace, or any unanswerable probe is a retained skip that mutates -// nothing. The authoritative lease and branch-fact decision re-runs inside the -// transaction on fresh state via the landed domain.Reclaim action. -func ChangeReclaim(ctx context.Context, deps PlanningDeps, wdeps WorkspaceDeps, repoDir string, req ChangeReclaimRequest) ChangeReclaimResult { - if findings := validateReclaimShape(req); len(findings) > 0 { - return newChangeReclaimResult(ResultInvalidInput, ChangeReclaimResult{ID: req.ID, Findings: findings}) - } - - pin, err := deps.Reader.PinContext(ctx, repoDir) - if err != nil { - result, reason := classifyStatusError(ctx, err) - return reclaimSkip(result, reason, err.Error(), req.ID) - } - if decision := config.PreflightMutation(&pin.Config); !decision.Allowed { - return newChangeReclaimResult(ResultUnsupportedConfig, ChangeReclaimResult{ - ID: req.ID, Reason: ReasonDeferredCapRequested, - Message: "configuration actively requests a deferred capability docket does not ship in this version (" + - strings.Join(blockerPaths(decision.Blockers), ", ") + "); withdraw it before any mutation", - }) - } - eff := pin.Config.Effective - - inline, err := resolveBoardSurface(eff) - if err != nil { - if pe, ok := asPlanningError(err); ok { - return reclaimSkip(pe.Result, pe.Reason, pe.Message, req.ID) - } - return reclaimSkip(ResultInternalError, ReasonStatusInternalError, err.Error(), req.ID) - } - - // Resolve the record's canonical path and read the recorded branch/slug the - // branch probes consult. This pre-read is a supporting observation; the - // authoritative lease + branch-fact decision re-runs fresh in the transaction. - c, refusal := reclaimResolveChange(ctx, deps, pin, eff, req.ID) - if refusal != nil { - return *refusal - } - recPath := c.Path() - - repo, err := deps.Client.Discover(ctx, gitcli.DiscoverOptions{InvocationPath: repoDir}) - if err != nil { - result, reason := classifyStatusError(ctx, classifyGitFailure(err)) - return reclaimSkip(result, reason, err.Error(), req.ID) - } - - // Destructive gate — branch absence. Both the recorded and the conventional - // feature branch must be cleanly absent locally AND remotely. A present branch - // blocks; an unanswerable probe blocks (unknown never shares absent). - if refusal := reclaimProveBranchesAbsent(ctx, deps, repo, c); refusal != nil { - return *refusal - } - - // Destructive gate — workspace/ownership/live-gate. The inspection's typed - // error is a probe failure (skip); a live-holder state is active work (skip). - if refusal := reclaimProveWorkspaceClear(ctx, deps, wdeps, repoDir, req.ID); refusal != nil { - return *refusal - } - - // Every condition held. The transaction re-decides on fresh state: it applies - // domain.Reclaim (which re-evaluates the strict-expiry lease and the proven - // branch facts), appends the reclaim log, and rerenders the derived views. - op := reclaimOp{ - id: req.ID, - ttlHours: eff.Reclaim.LeaseTTL.Value, - facts: domain.NewBranchFacts(nil), // branches proven absent above - proofSummary: reclaimProofSummary(eff.Reclaim.LeaseTTL.Value), - eff: eff, - clock: deps.Clock, - inline: inline, - link: linkContextOf(pin), - changesDir: eff.ChangesDir.Value, - } - res, execErr := deps.Engine.Execute(ctx, transaction.Request{ - Repository: repo, - Remote: metadataRemote(pin.Layout), - TargetRef: metadataRef(pin.Layout), - Expected: []transaction.EntityExpectation{{ - Path: gitcli.RepoPath(recPath), - Revision: transaction.ExpectedRevision{Kind: transaction.RevisionBlob, ObjectID: gitcli.ObjectID(req.Revision)}, - }}, - Loader: newPlanningLoader(eff), - Operation: op, - }) - return reclaimResultFromOutcome(res, execErr) -} - -// reclaimResolveChange reads the metadata corpus once and resolves the target -// change. An id that names no single record is refused here, before any probe or -// engine call, with a typed unknown/ambiguous reason. -func reclaimResolveChange(ctx context.Context, deps PlanningDeps, pin StatusPin, eff config.Effective, id int) (domain.Change, *ChangeReclaimResult) { - blobs, err := deps.Reader.ReadCorpus(ctx, pin) - if err != nil { - result, reason := classifyStatusError(ctx, err) - r := reclaimSkip(result, reason, err.Error(), id) - return domain.Change{}, &r - } - inputs, _ := parseCorpus(blobs) - build, err := repository.BuildSnapshot(repository.BuildInput{Config: eff, Documents: inputs}) - if err != nil { - r := reclaimSkip(ResultInternalError, ReasonStatusInternalError, err.Error(), id) - return domain.Change{}, &r - } - c, out := build.Snapshot.Change(domain.ChangeID(id)) - switch out { - case domain.LookupFound: - return c, nil - case domain.LookupAmbiguous: - r := newChangeReclaimResult(ResultInvalidState, ChangeReclaimResult{ - ID: id, Disposition: ReclaimDispSkipped, Reason: ReasonReclaimAmbiguousID, - Message: fmt.Sprintf("more than one record claims change id %04d; refusing to choose", id), - }) - return domain.Change{}, &r - default: - r := newChangeReclaimResult(ResultInvalidInput, ChangeReclaimResult{ - ID: id, Disposition: ReclaimDispSkipped, Reason: ReasonReclaimUnknownChange, - Message: fmt.Sprintf("no change %04d is present in the corpus", id), - }) - return domain.Change{}, &r - } -} - -// reclaimProveBranchesAbsent proves the recorded and conventional feature -// branches are cleanly absent both locally and remotely. It returns a retained -// skip on any present branch or any unanswerable probe, and nil only when every -// candidate branch is proven absent on both sides. Duplicate candidates (the -// recorded branch often equals the conventional one) are probed once. -func reclaimProveBranchesAbsent(ctx context.Context, deps PlanningDeps, repo gitcli.Repository, c domain.Change) *ChangeReclaimResult { - seen := map[string]bool{} - candidates := make([]string, 0, 2) - if recorded := c.Branch(); recorded.State == domain.FieldPresent && recorded.Value != "" { - candidates = append(candidates, recorded.Value) - } - candidates = append(candidates, domain.MintBranch(c.Type(), c.BranchPrefix(), c.Slug())) - - id := int(c.ID()) - for _, branch := range candidates { - if branch == "" || seen[branch] { - continue - } - seen[branch] = true - ref := gitcli.RefName(branchRefPrefix + branch) - - // Local: a resolvable ref is present; a ref-unavailable failure is a clean - // absence; any other failure is an unanswerable probe (fail closed). - if _, err := deps.Client.ResolveRef(ctx, repo, ref); err == nil { - return reclaimResultPtr(reclaimSkip(ResultBlocked, ReasonReclaimBranchPresent, - fmt.Sprintf("local branch %q still exists; reclaim leaves unfinished work in place", branch), id)) - } else if f, ok := gitcli.AsFailure(err); !ok || f.Kind != gitcli.KindRefUnavailable { - return reclaimResultPtr(reclaimSkip(ResultBlocked, ReasonReclaimBranchProbe, - fmt.Sprintf("could not probe local branch %q; refusing to reclaim on an unknown probe", branch), id)) - } - - // Remote: three-outcome probe — found blocks, absent is clean, error fails - // closed. ProbeRemoteBranch never reports absence for an errored probe. - rref, err := deps.Client.ProbeRemoteBranch(ctx, repo, originRemote, ref) - if err != nil { - return reclaimResultPtr(reclaimSkip(ResultBlocked, ReasonReclaimBranchProbe, - fmt.Sprintf("could not probe remote branch %q; refusing to reclaim on an unknown probe", branch), id)) - } - if rref.State == gitcli.RemoteRefFound { - return reclaimResultPtr(reclaimSkip(ResultBlocked, ReasonReclaimBranchPresent, - fmt.Sprintf("remote branch %q still exists; reclaim leaves unfinished work in place", branch), id)) - } - } - return nil -} - -// reclaimProveWorkspaceClear inspects the change's owned feature workspace and -// returns a retained skip when the inspection cannot be answered (probe failure) -// or reports a live-holder state (allocating/ready/dirty/ambiguous). The -// inspection is this reclaim's ownership and live-gate/process-liveness probe. -func reclaimProveWorkspaceClear(ctx context.Context, deps PlanningDeps, wdeps WorkspaceDeps, repoDir string, id int) *ChangeReclaimResult { - insp := WorkspaceInspect(ctx, deps, wdeps, repoDir, WorkspaceIDRequest{ID: id}) - if insp.Result != ResultApplied { - return reclaimResultPtr(reclaimSkip(ResultBlocked, ReasonReclaimWorkspaceProbe, insp.Message, id)) - } - if reclaimActiveWorkspaceStates[insp.State] { - return reclaimResultPtr(reclaimSkip(ResultBlocked, ReasonReclaimWorkspaceActive, - fmt.Sprintf("an owned workspace is %q for change %04d; the work still exists", insp.State, id), id)) - } - return nil -} - -// reclaimProofSummary renders the fixed proof-summary clause the reclaim-log -// entry records: what the pre-transaction gate proved before the reclaim. -func reclaimProofSummary(ttlHours int) string { - return fmt.Sprintf("lease strictly expired (TTL %dh); recorded and conventional feature branch cleanly absent locally and remotely; no owned live workspace or gate run.", ttlHours) -} - -// reclaimResultFromOutcome folds a transaction outcome into the result document. -// A plan refusal carrying the illegal-source-status reason is remapped onto -// `contended` — the record's fresh status moved out from under the exact revision. -// Every other in-transaction refusal (a lease re-evaluation that no longer -// strictly expires, a branch fact that reappeared) is a retained skip. -func reclaimResultFromOutcome(res transaction.Result, execErr error) ChangeReclaimResult { - if res.Disposition == transaction.DispositionRefused && firstFindingCode(res.Findings) == reclaimReasonIllegalSource { - return newChangeReclaimResult(ResultContended, ChangeReclaimResult{ - Disposition: ReclaimDispContended, - Findings: findingsToStatus(res.Findings), - }) - } - result, _ := mapOutcome(res, execErr, ResultBlocked) - out := ChangeReclaimResult{Findings: findingsToStatus(res.Findings)} - if rec, ok := decodeChangeReclaimReceipt(res.Receipt); ok { - out.ID = rec.ID - } - switch { - case res.Disposition == transaction.DispositionFailed: - out.Disposition = ReclaimDispFailed - case result == ResultApplied: - out.Disposition = ReclaimDispReclaimed - out.Revision = string(res.AppliedCommit) - case result == ResultNoOp: - out.Disposition = ReclaimDispReclaimed - case result == ResultContended: - out.Disposition = ReclaimDispContended - default: - out.Disposition = ReclaimDispSkipped - out.Reason = firstFindingCode(res.Findings) - } - r := newChangeReclaimResult(result, out) - r.Failure = failureStatus(res, execErr) - return r -} - -// decodeChangeReclaimReceipt decodes a persisted reclaim receipt. -func decodeChangeReclaimReceipt(b []byte) (changeReclaimReceipt, bool) { - if len(b) == 0 { - return changeReclaimReceipt{}, false - } - var rec changeReclaimReceipt - if err := json.Unmarshal(b, &rec); err != nil { - return changeReclaimReceipt{}, false - } - return rec, true -} - -// validateReclaimShape runs the configuration-independent request checks that -// never reach the engine: the pinned-entity fields (id and revision). -func validateReclaimShape(req ChangeReclaimRequest) []StatusFinding { - return dropFindingCode(validateLifecycleShape("id", req.ID, "", req.Revision), FCEmptyPath) -} - -// reclaimOp is the SemanticOperation the engine drives per attempt. Every field -// is fixed before the transaction; the state-dependent work (the domain -// lease/branch gate, the reclaim-log append, field patching, rendering) re-runs -// from the attempt's own fresh state. -type reclaimOp struct { - id int - ttlHours int - facts domain.BranchFacts - proofSummary string - eff config.Effective - clock transaction.Clock - inline bool - link render.LinkContext - changesDir string -} - -func (o reclaimOp) Key() transaction.OperationKey { - return transaction.OperationKey(OperationChangeReclaim) -} - -// Plan re-decides the reclaim on the attempt's fresh snapshot via domain.Reclaim -// (the authoritative strict-expiry lease + branch-fact gate), appends the dated -// reclaim-log entry recording the previous claim and the proof summary, applies -// the domain's owned FieldChanges (status→proposed, cleared branch/claim, -// reconciled:false) plus the refreshed updated date, rerenders the artifact -// block, and assembles the closed plan with the inline board when enabled. -func (o reclaimOp) Plan(ctx context.Context, st transaction.AttemptState) (transaction.MutationPlan, transaction.OperationResult, error) { - snap := st.State.Snapshot - c, out := snap.Change(domain.ChangeID(o.id)) - if out != domain.LookupFound { - return refuseReclaim("not-found", fmt.Sprintf("change %04d is not present in the current corpus", o.id)) - } - - // Capture the previous claim from the SAME fresh copy the mutation clears, so - // the reclaim log records exactly what was taken back. - prevClaim := c.ClaimedAt() - prevBranch := c.Branch() - - // Authoritative gate: strict-expiry lease + proven branch absence. A - // non-in-progress source is an illegal-source-status refusal the result mapper - // folds onto `contended`; a non-strictly-expired lease is a retained skip. - result, fail := domain.Reclaim(c, o.clock.Now(), o.ttlHours, o.facts) - if fail != nil { - return refuseLifecyclePolicy(fail) - } - - src, ok := st.State.Sources[c.Path()] - if !ok { - return refuseReclaim("path-mismatch", fmt.Sprintf("no record source loaded at %q for change %04d", c.Path(), o.id)) - } - - // 1. Append the dated reclaim-log entry over the exact source bytes. - edited, err := appendReclaimLog(src, o.clock.Now().UTC().Format("2006-01-02"), o.reclaimLogEntry(prevClaim, prevBranch)) - if err != nil { - return refuseReclaim("reclaim-log-append-failed", err.Error()) - } - - // 2. Patch the domain's owned FieldChanges plus the refreshed updated date. A - // bool field (reconciled) is patched as a typed bool so its parsed type is - // preserved; cleared fields (branch, claimed_at) become the bare null form. - doc1, err := document.Parse(edited) - if err != nil { - return transaction.MutationPlan{}, transaction.OperationResult{}, fmt.Errorf("change reclaim: reparsing edited record: %w", err) - } - var ps document.PatchSet - for _, fc := range result.Changed { - if fc.Field == "reconciled" { - ps.SetField(fc.Field, document.Bool(fc.To == "true")) - continue - } - ps.SetField(fc.Field, lifecycleFieldValue(fc.To)) - } - upsertField(&ps, doc1, "updated", document.String(o.clock.Now().UTC().Format("2006-01-02"))) - intermediate, err := doc1.Apply(ps) - if err != nil { - return transaction.MutationPlan{}, transaction.OperationResult{}, fmt.Errorf("change reclaim: patching record fields: %w", err) - } - - // 3. Re-render the artifact block against the reclaimed candidate snapshot. - candidate, err := buildGroomCandidate(o.eff, st.State.Documents, c.Path(), intermediate) - if err != nil { - return transaction.MutationPlan{}, transaction.OperationResult{}, err - } - gc, gout := candidate.Change(domain.ChangeID(o.id)) - if gout != domain.LookupFound { - return transaction.MutationPlan{}, transaction.OperationResult{}, fmt.Errorf("change reclaim: reclaimed record %04d absent from candidate snapshot", o.id) - } - body, err := render.ArtifactBlockContent(gc, candidate, o.link) - if err != nil { - return refuseReclaim("artifact-render-failed", err.Error()) - } - doc2, err := document.Parse(intermediate) - if err != nil { - return transaction.MutationPlan{}, transaction.OperationResult{}, fmt.Errorf("change reclaim: reparsing patched record: %w", err) - } - var ps2 document.PatchSet - ps2.ReplaceBlock("artifacts", body) - finalBytes, err := doc2.Apply(ps2) - if err != nil { - return transaction.MutationPlan{}, transaction.OperationResult{}, fmt.Errorf("change reclaim: writing artifact block: %w", err) - } - - files := []transaction.FileMutation{ - {Path: gitcli.RepoPath(c.Path()), Kind: transaction.MutationReplace, Bytes: finalBytes}, - } - - // Reclaim moves the record's status (board-visible), so the board renders from - // the reclaimed CANDIDATE snapshot, not the before-state — a stale before-state - // render would recommit the pre-reclaim board. - if o.inline { - boardPath := path.Join(o.changesDir, "BOARD.md") - if err := includeBoard(ctx, st.Tree, boardPath, candidate, boardUnrenderable(st.State, o.changesDir), boardPresentation(o.eff), &files); err != nil { - return transaction.MutationPlan{}, transaction.OperationResult{}, fmt.Errorf("change reclaim: %w", err) - } - } - - receipt, err := json.Marshal(changeReclaimReceipt{ID: o.id, Op: OperationChangeReclaim}) - if err != nil { - return transaction.MutationPlan{}, transaction.OperationResult{}, fmt.Errorf("change reclaim: encoding receipt: %w", err) - } - return transaction.MutationPlan{ - Files: files, - CommitSubject: fmt.Sprintf("change %04d reclaimed", o.id), - Receipt: receipt, - }, transaction.OperationResult{}, nil -} - -// reclaimLogEntry renders the single reclaim-log entry body: the previous claim -// stamp and branch that were cleared, plus the pre-transaction proof summary. -func (o reclaimOp) reclaimLogEntry(prevClaim domain.OptionalTime, prevBranch domain.OptionalString) string { - claim := "(none)" - if prevClaim.State != domain.FieldAbsent && prevClaim.Raw != "" { - claim = prevClaim.Raw - } - branch := "(none)" - if prevBranch.State == domain.FieldPresent && prevBranch.Value != "" { - branch = prevBranch.Value - } - var b strings.Builder - b.WriteString("Reclaimed an expired claim to proposed.\n\n") - b.WriteString("- Previous claim: " + claim + " (branch " + branch + ").\n") - b.WriteString("- Proof: " + o.proofSummary + "\n") - return b.String() -} - -// appendReclaimLog appends one dated entry to the record's ## Reclaim log -// section, creating the section at EOF when absent. It preserves prior entries by -// replacing the section body with (old body + the new entry) through the -// loss-preserving render.ApplySectionEdits — which also enforces the section's -// uniqueness (a duplicate heading refuses the whole edit). The old body is sliced -// between the heading and its NAMED terminator (the next top-level heading, or -// EOF), reusing the same fence-aware heading scan the splice uses. -func appendReclaimLog(src []byte, date, entryBody string) ([]byte, error) { - entry := "### " + date + "\n\n" + strings.TrimRight(entryBody, "\r\n") - - oldBody, present, err := reclaimLogBody(src) - if err != nil { - return nil, err - } - markdown := entry - if present { - if trimmed := strings.Trim(oldBody, "\r\n"); trimmed != "" { - markdown = trimmed + "\n\n" + entry - } - } - return render.ApplySectionEdits(src, []string{reclaimLogHeading}, - []render.SectionEdit{{Heading: reclaimLogHeading, Intent: render.SectionReplace, Markdown: markdown}}) -} - -// reclaimLogBody returns the body of the single ## Reclaim log section and -// whether it is present, scanning headings fence-aware (a heading-shaped line in -// a fenced block is authored content). A duplicate heading yields no single body -// and is an error (the whole-record splice refuses it too, but slicing must not -// pick one silently). It reuses scanTopHeadings from the reconcile operation. -func reclaimLogBody(src []byte) (body string, present bool, err error) { - heads := scanTopHeadings(src) - idx := -1 - for i, h := range heads { - if h.heading == reclaimLogHeading { - if idx >= 0 { - return "", false, fmt.Errorf("owned heading %q appears more than once; the reclaim-log slice has no single terminator", reclaimLogHeading) - } - idx = i - } - } - if idx < 0 { - return "", false, nil - } - bodyStart := heads[idx].lineEnd - bodyEnd := len(src) - if idx+1 < len(heads) { - bodyEnd = heads[idx+1].start - } - return string(src[bodyStart:bodyEnd]), true, nil -} - -// refuseReclaim builds a refusing (plan, OperationResult) pair carrying one -// state-shaped finding for the reclaim Plan closure. -func refuseReclaim(code, msg string) (transaction.MutationPlan, transaction.OperationResult, error) { - return transaction.MutationPlan{}, transaction.OperationResult{ - Refused: true, - Findings: []domain.Finding{{ - Code: code, - Severity: domain.SeverityError, - Entity: domain.EntityRef{Kind: domain.EntityChange}, - Detail: map[string]string{"message": msg}, - }}, - }, nil -} - -// reclaimResultPtr returns a pointer to a ChangeReclaimResult — the retained-refusal return -// shape the destructive-gate helpers hand back. -func reclaimResultPtr(r ChangeReclaimResult) *ChangeReclaimResult { return &r } diff --git a/internal/app/change_reclaim_test.go b/internal/app/change_reclaim_test.go deleted file mode 100644 index 95a7c99c6..000000000 --- a/internal/app/change_reclaim_test.go +++ /dev/null @@ -1,178 +0,0 @@ -package app - -import ( - "context" - "github.com/danielhanold/docket/internal/domain" - "github.com/danielhanold/docket/internal/render" - "github.com/danielhanold/docket/internal/repository/transaction" - "github.com/danielhanold/docket/internal/workspace" - "strings" - "testing" -) - -// This file drives `change reclaim`: the proof-gated return of a strictly-expired -// in-progress claim to proposed. The lease gate and the applied mutation run over -// the in-memory fakeTree Plan harness (blockPlanFor); the destructive branch and -// workspace gates, the atomic transaction, and the exact-revision contention run -// end-to-end over real bare-remote repositories in both metadata modes with a -// fake WorkspaceService scripting the inspected state. - -// --- fake WorkspaceService for the reclaim ownership/gate probe ------------ - -// fakeReclaimWorkspace scripts the inspected workspace state (or a probe error) -// the reclaim reads to decide whether the change's work still exists. Prepare and -// PublishHead panic — reclaim only inspects. -type fakeReclaimWorkspace struct { - kind workspace.StateKind - err error -} - -func (f fakeReclaimWorkspace) Prepare(context.Context, workspace.PrepareRequest) (workspace.Workspace, error) { - panic("Prepare: reclaim must not allocate") -} -func (f fakeReclaimWorkspace) Inspect(context.Context, workspace.InspectRequest) (workspace.Inspection, error) { - if f.err != nil { - return workspace.Inspection{}, f.err - } - return workspace.Inspection{Kind: f.kind}, nil -} -func (f fakeReclaimWorkspace) PublishHead(context.Context, workspace.PublishRequest) (workspace.PublishResult, error) { - panic("PublishHead: reclaim must not publish") -} - -// reclaimClearWorkspace is the quiescent inspection (no owned live workspace) the -// clear-path fixtures inject so the workspace condition passes. -var reclaimClearWorkspace = WorkspaceDeps{Service: fakeReclaimWorkspace{kind: workspace.StateForeign}} - -// reclaimOpFixture builds the reclaim Plan operation with proven-absent branch -// facts, matching what ChangeReclaim assembles once its destructive gate holds. -func reclaimOpFixture(id int, surfaces []string) reclaimOp { - return reclaimOp{ - id: id, - ttlHours: 72, - facts: domain.NewBranchFacts(nil), - proofSummary: reclaimProofSummary(72), - eff: planningTestConfig(surfaces), - clock: testClock(), - inline: len(surfaces) > 0 && surfaces[0] == "inline", - link: render.LinkContext{MetadataBranch: "main"}, - changesDir: "docs/changes", - } -} - -// reclaimRecordWithClaim renders an in-progress record whose claim stamp is set -// to claim, so a lease-state row can be exercised deterministically. -func reclaimRecordWithClaim(id int, slug, claim string) string { - return strings.Replace(lifecycleChange(id, slug, "in-progress"), - "claimed_at: 2026-08-02T00:00:00Z", "claimed_at: "+claim, 1) -} - -// --- lease gate (plan closure) --------------------------------------------- - -// TestReclaimRequiresStrictExpiry proves the lease gate: only a strictly-expired -// in-progress lease applies; a future or exactly-at-boundary stamp is a retained -// refusal, and a non-in-progress source is an illegal-source-status refusal (the -// result mapper folds it onto contended). The missing/empty/malformed rows are -// corpus-invalid states the engine's load-before validation refuses end-to-end -// (TestReclaimMalformedLeaseSkips) and the domain's own EvaluateLease coverage -// pins; they cannot be represented as a clean corpus here. -func TestReclaimRequiresStrictExpiry(t *testing.T) { - recPath := groomPath(3, "widget") - - // Strictly expired (claimed 2026-08-02, evaluated 2026-08-16, TTL 72h): applies. - t.Run("expired-applies", func(t *testing.T) { - files := map[string]string{ - recPath: lifecycleChange(3, "widget", "in-progress"), - "docs/changes/BOARD.md": "# Backlog\n\nold\n", - } - plan, opRes := blockPlanFor(t, files, planningTestConfig([]string{"inline"}), reclaimOpFixture(3, []string{"inline"})) - if opRes.Refused { - t.Fatalf("strict expiry refused: %v", opRes.Findings) - } - rec := lifecycleRecordBytes(t, plan, recPath) - for _, want := range []string{"status: 'proposed'", "reconciled: false", "## Reclaim log", "2026-08-02T00:00:00Z", "lease strictly expired"} { - if !strings.Contains(rec, want) { - t.Errorf("reclaimed record missing %q:\n%s", want, rec) - } - } - if strings.Contains(rec, "branch: feat/widget") { - t.Errorf("branch not cleared:\n%s", rec) - } - if strings.Contains(rec, "claimed_at: 2026-08-02") { - t.Errorf("claim stamp not cleared:\n%s", rec) - } - }) - - // Future and exactly-at-boundary stamps are not expiry: retained refusal. - for _, tc := range []struct{ name, claim string }{ - {"future", "2026-08-20T00:00:00Z"}, - {"exactly-at-boundary", "2026-08-13T12:00:00Z"}, // 72h before the clock - } { - t.Run(tc.name, func(t *testing.T) { - files := map[string]string{recPath: reclaimRecordWithClaim(3, "widget", tc.claim)} - _, opRes := blockPlanFor(t, files, planningTestConfig(nil), reclaimOpFixture(3, nil)) - if !opRes.Refused || firstFindingCode(opRes.Findings) != "lease-not-expired" { - t.Fatalf("%s: refused=%v code=%q, want lease-not-expired", tc.name, opRes.Refused, firstFindingCode(opRes.Findings)) - } - }) - } - - // A non-in-progress source has no lease to expire: illegal-source-status. - t.Run("non-in-progress", func(t *testing.T) { - files := map[string]string{recPath: lifecycleChange(3, "widget", "proposed")} - _, opRes := blockPlanFor(t, files, planningTestConfig(nil), reclaimOpFixture(3, nil)) - if !opRes.Refused || firstFindingCode(opRes.Findings) != reclaimReasonIllegalSource { - t.Fatalf("non-in-progress: refused=%v code=%q, want %q", opRes.Refused, firstFindingCode(opRes.Findings), reclaimReasonIllegalSource) - } - }) -} - -// --- destructive gate: proven absence (real git) --------------------------- - -// --- transaction (real git, both modes) ------------------------------------ - -// --- helpers --------------------------------------------------------------- - -func assertReclaimSkipped(t *testing.T, res ChangeReclaimResult, wantReason string) { - t.Helper() - if res.Result == ResultApplied { - t.Fatalf("expected a skip, got applied") - } - if res.Disposition != ReclaimDispSkipped { - t.Errorf("disposition = %q, want skipped", res.Disposition) - } - if res.Reason != wantReason { - t.Errorf("reason = %q, want %q", res.Reason, wantReason) - } -} - -func assertOriginRecordUnchanged(t *testing.T, origin, branch, path, before string) { - t.Helper() - after, ok := originFile(t, origin, branch, path) - if !ok { - t.Fatalf("record %q vanished on a refusal", path) - } - if after != before { - t.Errorf("a refused reclaim mutated the origin record:\n--before--\n%s\n--after--\n%s", before, after) - } -} - -// TestReclaimResultFromOutcomeFailedCarriesCause proves a reclaim transaction -// that fails mid-flight is dispositioned `failed` (not mislabeled as a reasonless -// `skipped`) and carries its typed cause in the envelope's failure diagnosis. -func TestReclaimResultFromOutcomeFailedCarriesCause(t *testing.T) { - execErr := &transaction.Failure{ - Stage: transaction.StageVerifyDelta, - Kind: transaction.KindInvalidState, - Detail: "an undeclared path changed in the worktree", - } - out := reclaimResultFromOutcome( - transaction.Result{Disposition: transaction.DispositionFailed}, execErr) - - if out.Disposition != ReclaimDispFailed { - t.Errorf("disposition = %q, want %q — a failed reclaim is not a reasonless skip", out.Disposition, ReclaimDispFailed) - } - if out.Failure == nil || out.Failure.Detail == "" { - t.Fatalf("failure diagnosis missing or empty: %+v", out.Failure) - } -} diff --git a/internal/app/change_relink.go b/internal/app/change_relink.go index 451e79ad0..53930039b 100644 --- a/internal/app/change_relink.go +++ b/internal/app/change_relink.go @@ -389,7 +389,7 @@ type githubPR struct { } // relinkProveCandidateBranch proves the branch the record will carry is present -// on the remote (the same remote branch-facts probe reclaim gathers). An absent +// on the remote through the remote branch-facts probe. An absent // branch, or a probe that cannot be answered, is candidate-branch-absent — // never adopted on an unknown (probe-error-is-not-clean-absence). func relinkProveCandidateBranch(ctx context.Context, deps PlanningDeps, repo gitcli.Repository, branch string, id int) *RelinkResult { diff --git a/internal/app/derived_views.go b/internal/app/derived_views.go index 1081666a9..e3096d922 100644 --- a/internal/app/derived_views.go +++ b/internal/app/derived_views.go @@ -147,7 +147,7 @@ func renderCanonicalADRIndex(snap domain.Snapshot, unrenderable []render.BoardUn // // This single declare-only-when-changed shape covers every board-authoritative // mutation. Operations whose edits are always board-visible (create, groom, -// kill, lifecycle, mark-implemented, reclaim, relink, closeout) always render a +// kill, lifecycle, mark-implemented, relink, closeout) always render a // board that differs from the committed one, so the board is always declared — // as a create when BOARD.md is absent, a replace otherwise. Operations whose // edits are NOT board-visible (attach, reconcile, clear-block via diff --git a/internal/app/derived_views_guard_test.go b/internal/app/derived_views_guard_test.go index cf98b83b4..cf6fee499 100644 --- a/internal/app/derived_views_guard_test.go +++ b/internal/app/derived_views_guard_test.go @@ -32,7 +32,7 @@ import ( // - CHANGE-PATH shape: the write's Path is gitcli.RepoPath(X.Path()) — a CALL // of a no-arg method named Path. In today's corpus this call form appears // ONLY on a domain.Change value (`c.Path()`), so it uniquely marks an -// in-place change-record rewrite (claim, attach, implemented, reclaim, +// in-place change-record rewrite (claim, attach, implemented, // reconcile, relink, halt, resume-halted, block, clear-block, stacked // closeout). Every non-change write instead uses a plain identifier // (recPath, adrRelPath, activePath, archivePath, specPath, p) or a field diff --git a/internal/app/finalize_e2e_test.go b/internal/app/finalize_e2e_test.go index 511731af5..a7692b17d 100644 --- a/internal/app/finalize_e2e_test.go +++ b/internal/app/finalize_e2e_test.go @@ -32,7 +32,7 @@ import ( // isolated configuration. They prove the spec's "End-to-end and mutation tests" // section bullet-for-bullet: ordinary finalize to archive+cleanup in both // repository modes, conflict/repair, response-loss convergence, the -// stack outcomes, out-of-band merge recovery, halt/resume plus reclaim, the +// stack outcomes, out-of-band merge recovery, halt/resume, the // deferred-capability refusal, and no dependence on a PATH `docket`. // // Isolation contract (per the Global Constraints and the spec): @@ -1620,22 +1620,18 @@ func TestE2EMergeMethodUnavailable(t *testing.T) { } } -// --- TestE2EHaltResumeAndReclaim ------------------------------------------ +// --- TestE2EHaltResume ---------------------------------------------------- -// TestE2EHaltResumeAndReclaim proves the two implementation-side recovery paths -// through CLI argv: a persistent `change halt` records a durable run-halted -// marker on an in-progress change and `change resume-halted --acknowledge- -// quiescent` clears it and refreshes the claim; and an expired, no-work in- -// progress change (claim past its lease TTL, no branch or workspace) is reclaimed -// back to proposed. -func TestE2EHaltResumeAndReclaim(t *testing.T) { +// TestE2EHaltResume proves the implementation-side recovery path through CLI +// argv: a persistent `change halt` records a durable run-halted marker on an +// in-progress change and `change resume-halted --acknowledge-quiescent` clears +// it and refreshes the claim. +func TestE2EHaltResume(t *testing.T) { t.Parallel() requireRealGit(t) docketBin, ghBin := sharedBinaries(t) - // Two claimed, in-progress changes: id 3 exercises halt/resume; id 4 is left - // to expire and be reclaimed. lease_ttl is 1h so the testClock claim stamp is - // unambiguously expired against the binary's real system clock. + // One claimed, in-progress change (id 3) exercises halt/resume. s := reachInProgress(t, docketBin, ghBin) // --- halt then resume (id 3) --- @@ -1658,43 +1654,27 @@ func TestE2EHaltResumeAndReclaim(t *testing.T) { if res2.result() == "applied" { t.Fatalf("resume-halted replayed as a success though the marker was cleared\n%s", res2.stdout) } - - // --- expired no-work reclaim (id 4) --- - rc := s.dk(t, "", "change", "reclaim", "--id", "4", "--revision", verOf(t, s, 4)) - if rc.result() != "applied" { - t.Fatalf("change reclaim of an expired no-work change = %q\n%s", rc.result(), rc.stdout) - } - // The reclaimed change is back to proposed (its claim released). The status - // scalar may be quoted, so match either spelling. - body, ok := originFile(t, s.repo.origin, s.mode.branch, groomPath(4, "gadget")) - if !ok || (!strings.Contains(body, "status: proposed") && !strings.Contains(body, "status: 'proposed'")) { - t.Errorf("reclaimed change 4 is not back to proposed:\n%s", body) - } } // verOf reads the current record revision for one id from the origin oracle. func verOf(t *testing.T, s *e2eState, id int) string { t.Helper() - slug := map[int]string{3: "widget", 4: "gadget"}[id] + slug := map[int]string{3: "widget"}[id] return blobRevisionAt(t, s.repo.origin, s.mode.branch, groomPath(id, slug)) } -// reachInProgress builds a main-mode repo with two claimed (in-progress) changes -// and a short reclaim lease TTL, returning the argv harness state. No workspace -// is prepared and no feature branch is pushed, so the changes present as no-work -// for the reclaim path. +// reachInProgress builds a main-mode repo with one claimed (in-progress) change +// that owns a prepared workspace, returning the argv harness state. func reachInProgress(t *testing.T, docketBin, ghBin string) *e2eState { t.Helper() requireRealGit(t) m := planRepoModes()[0] records := map[string]string{ groomPath(3, "widget"): buildReadyChange(3, "widget"), - groomPath(4, "gadget"): buildReadyChange(4, "gadget"), fixtureSpecPath("widget"): fixtureSpecFile(3, "widget"), - fixtureSpecPath("gadget"): fixtureSpecFile(4, "gadget"), } repo := newWorkingRepo(t, mergeMaps(map[string]string{ - ".docket.yml": "reclaim:\n lease_ttl: 1\n auto: false\nbuild:\n test_command: 'exit 0'\nfinalize:\n test_command: 'exit 0'\n", + ".docket.yml": "build:\n test_command: 'exit 0'\nfinalize:\n test_command: 'exit 0'\n", }, records)) node := e2eNode(t, repo.invocation) @@ -1705,7 +1685,7 @@ func reachInProgress(t *testing.T, docketBin, ghBin string) *e2eState { wdeps := WorkspaceDeps{Service: svc} ctx := context.Background() ver := func(id int, slug string) string { return blobRevisionAt(t, repo.origin, m.branch, groomPath(id, slug)) } - for _, id := range []int{3, 4} { + for _, id := range []int{3} { cx := ContextImplementation(ctx, node.deps, node.dir, ImplementationContextRequest{ID: id}) if cx.Result != ResultApplied || cx.Context == nil { t.Fatalf("context implementation id %d = %q", id, cx.Result) @@ -1716,7 +1696,7 @@ func reachInProgress(t *testing.T, docketBin, ghBin string) *e2eState { } } // id 3 gets an owned workspace so resume-halted has a matching-ownership, - // quiescent workspace to reprobe; id 4 is left no-work for the reclaim path. + // quiescent workspace to reprobe. prep := WorkspacePrepare(ctx, node.deps, wdeps, node.dir, WorkspaceIDRequest{ID: 3, Revision: ver(3, "widget")}) if prep.Result != ResultApplied { t.Fatalf("workspace prepare id 3 = %q (reason %q)", prep.Result, prep.Reason) @@ -1803,7 +1783,6 @@ func TestE2EUnsupportedConfigRefused(t *testing.T) { {"closeout", []string{"finalize", "closeout", "--id", strconv.Itoa(s.id)}}, {"halt", []string{"change", "halt", "--id", strconv.Itoa(s.id), "--revision", revision, "--input", reportPath}}, {"resume-halted", []string{"change", "resume-halted", "--id", strconv.Itoa(s.id), "--revision", revision, "--acknowledge-quiescent"}}, - {"reclaim", []string{"change", "reclaim", "--id", strconv.Itoa(s.id), "--revision", revision}}, {"maintenance-sweep", []string{"maintenance", "sweep"}}, } for _, op := range refused { diff --git a/internal/app/finding_codes.go b/internal/app/finding_codes.go index 22387962a..cba32b101 100644 --- a/internal/app/finding_codes.go +++ b/internal/app/finding_codes.go @@ -14,26 +14,25 @@ type FindingCode string const ( // Request-shape findings on the change/lifecycle/finalize operations // (minted through lifecycleFinding and the StatusFinding literal form). - FCAuthoredInputTooLarge FindingCode = "authored-input-too-large" - FCEmptyAttempt FindingCode = "empty-attempt" - FCEmptyChildPRRevision FindingCode = "empty-child_pr_revision" - FCEmptyEvidence FindingCode = "empty-evidence" - FCEmptyNoteEntry FindingCode = "empty-note-entry" - FCEmptyPath FindingCode = "empty-path" - FCEmptyPR FindingCode = "empty-pr" - FCEmptyReason FindingCode = "empty-reason" - FCEmptyReport FindingCode = "empty-report" - FCEmptyRevision FindingCode = "empty-revision" - FCEmptyWhyDeferred FindingCode = "empty-why_deferred" - FCEmptyWhyKilled FindingCode = "empty-why_killed" - FCDuplicateChildID FindingCode = "duplicate-child_id" - FCInvalidChangeID FindingCode = "invalid-change_id" - FCInvalidChildID FindingCode = "invalid-child_id" - FCInvalidChildPRNumber FindingCode = "invalid-child_pr_number" - FCInvalidHead FindingCode = "invalid-head" - FCInvalidID FindingCode = "invalid-id" - FCInvalidNoteEntry FindingCode = "invalid-note-entry" - FCWorkspaceServiceUnavailable FindingCode = "workspace-service-unavailable" + FCAuthoredInputTooLarge FindingCode = "authored-input-too-large" + FCEmptyAttempt FindingCode = "empty-attempt" + FCEmptyChildPRRevision FindingCode = "empty-child_pr_revision" + FCEmptyEvidence FindingCode = "empty-evidence" + FCEmptyNoteEntry FindingCode = "empty-note-entry" + FCEmptyPath FindingCode = "empty-path" + FCEmptyPR FindingCode = "empty-pr" + FCEmptyReason FindingCode = "empty-reason" + FCEmptyReport FindingCode = "empty-report" + FCEmptyRevision FindingCode = "empty-revision" + FCEmptyWhyDeferred FindingCode = "empty-why_deferred" + FCEmptyWhyKilled FindingCode = "empty-why_killed" + FCDuplicateChildID FindingCode = "duplicate-child_id" + FCInvalidChangeID FindingCode = "invalid-change_id" + FCInvalidChildID FindingCode = "invalid-child_id" + FCInvalidChildPRNumber FindingCode = "invalid-child_pr_number" + FCInvalidHead FindingCode = "invalid-head" + FCInvalidID FindingCode = "invalid-id" + FCInvalidNoteEntry FindingCode = "invalid-note-entry" // State-shape refusals built by refuseLifecycle inside a Plan closure. FCArtifactRenderFailed FindingCode = "artifact-render-failed" @@ -248,7 +247,6 @@ var AllFindingCodes = []FindingCode{ FCBinaryAliasMissing, FCBranchLeftBehind, FCBranchMalformed, - FindingCode("branch-still-exists"), FCBuiltStackDescendants, FCCollectionPending, FCDanglingReference, @@ -337,15 +335,12 @@ var AllFindingCodes = []FindingCode{ FCInvalidTitle, FCInvalidTopics, FCInvalidType, - FindingCode("lease-not-expired"), FCLocalMetadataAhead, FCLocalMetadataDiverged, - FindingCode("malformed-claim-stamp"), FCMetadataRootForeign, FCMetadataRootUnresolved, FCMetadataWorktreeDirty, FCMigrationIncomplete, - FindingCode("missing-claim-stamp"), FCNotDeferrable, FCNotFound, FindingCode(ReasonImplementedNotPRDeliverable), @@ -373,7 +368,6 @@ var AllFindingCodes = []FindingCode{ FCUnknownOperation, FCUnknownPriority, FCUnknownType, - FCWorkspaceServiceUnavailable, } // invalidIDCodeByKey selects the id-shape finding code for a lifecycle request diff --git a/internal/app/finding_codes_test.go b/internal/app/finding_codes_test.go index 4d1a942e6..1b5fab76c 100644 --- a/internal/app/finding_codes_test.go +++ b/internal/app/finding_codes_test.go @@ -32,8 +32,7 @@ import ( // empty-path, empty-pr, empty-reason, empty-report, empty-revision, // empty-why_deferred, empty-why_killed, invalid-change_id, invalid-child_id, // invalid-child_pr_number, invalid-head, invalid-id, invalid-note-entry, -// workspace-service-unavailable, artifact-render-failed, not-found, -// path-mismatch, section-edit-failed. +// artifact-render-failed, not-found, path-mismatch, section-edit-failed. // // Non-literal mints that already reference a constant and so are not scanned: // parse-failed (migrated to string(FCParseFailed)), the ReasonStatus* tokens, @@ -91,7 +90,7 @@ func appPackageDir(t *testing.T) string { func TestNoInlineFindingCodeLiterals(t *testing.T) { codeLit := regexp.MustCompile(`Code:\s*"[^"]*"`) convLit := regexp.MustCompile(`FindingCode\(\s*"`) - ctorLit := regexp.MustCompile(`(?:lifecycleFinding|refuseLifecycle|attachRefusal|haltRefusal|implementedRefusal|reclaimSkip|relinkRefusal|closeoutRefusal|mergeRefusal|maintenanceRefusal|prRefusal|backlinkRefusal|addShape|adrFinding|learningFinding)\(\s*"`) + ctorLit := regexp.MustCompile(`(?:lifecycleFinding|refuseLifecycle|attachRefusal|haltRefusal|implementedRefusal|relinkRefusal|closeoutRefusal|mergeRefusal|maintenanceRefusal|prRefusal|backlinkRefusal|addShape|adrFinding|learningFinding)\(\s*"`) root := appPackageDir(t) var violations []string err := filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error { diff --git a/internal/app/maintenance.go b/internal/app/maintenance.go index 3389aacb3..50756b0db 100644 --- a/internal/app/maintenance.go +++ b/internal/app/maintenance.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "sort" - "time" "github.com/danielhanold/docket/internal/config" "github.com/danielhanold/docket/internal/domain" @@ -14,10 +13,10 @@ import ( "github.com/danielhanold/docket/internal/workspace" ) -// This file is the `maintenance sweep` operation: the batch driver that reclaims -// docket's closing half over one pinned inventory. `docket status` stays +// This file is the `maintenance sweep` operation: the batch driver for docket's +// closing half over one pinned inventory. `docket status` stays // read-only; every mutation this file dispatches goes through the same verified -// closeout, cleanup, and reclaim operations a human invokes one at a time +// closeout and cleanup operations a human invokes one at a time // (Tasks 12-14). The sweep composes them — it invents no new lifecycle policy, // merges no open PR, overrides no approval, retargets no child, repairs no code, // and edits no authored artifact. It pins one inventory to decide the worklist, @@ -43,15 +42,14 @@ const sweepBandMergedRecovery = "merged-recovery" const ( sweepKindCloseout = "closeout" sweepKindCleanup = "cleanup" - sweepKindReclaim = "reclaim" ) // SweepScope is the allowed maintenance-sweep scope values (change 0389). // full is the whole worklist — today's behavior, the default when the flag is // omitted. implementation is the implementation-startup preflight: current -// merged-work closeouts (with their safe cleanup suffixes) and reclaim gating, -// with independent cleanup retries for records that were ALREADY final at the -// pinned inventory deferred to explicit full maintenance. The CLI resolves the +// merged-work closeouts (with their safe cleanup suffixes), with independent +// cleanup retries for records that were ALREADY final at the pinned inventory +// deferred to explicit full maintenance. The CLI resolves the // scope once; the app layer never re-derives it from anything else. type SweepScope string @@ -78,9 +76,6 @@ const ( // The stable reasons the sweep reports for a skipped item or a whole-sweep // refusal. Message text is explanatory and must not be parsed. const ( - // ReasonSweepReclaimAutoDisabled: a reclaim-eligible record was left alone - // because reclaim.auto is false; explicit `change reclaim` still applies. - ReasonSweepReclaimAutoDisabled = "reclaim-auto-disabled" // ReasonSweepPrerequisiteUnresolved: a destructive suffix was withheld // because its prerequisite operation did not succeed (an unknown, contended, // blocked, or failed closeout). The resource is untouched. @@ -91,19 +86,16 @@ const ( // ReasonSweepReloadFailed: the fresh pre-mutation reload could not be read; // the sweep dispatched no mutation for this item and moved on. ReasonSweepReloadFailed = "reload-failed" - // ReasonSweepReclaimRevisionMissing: the reloaded record carried no usable - // blob revision to pin the exact-revision reclaim; nothing was dispatched. - ReasonSweepReclaimRevisionMissing = "reclaim-revision-missing" // ReasonSweepScopeInvalid: the typed scope was outside the allowed // values; the sweep read nothing and dispatched nothing. ReasonSweepScopeInvalid = "sweep-scope-invalid" ) -// sweepOps is the injection seam for the three verified operations the sweep +// sweepOps is the injection seam for the two verified operations the sweep // composes and the per-attempt metadata preparer they share. Production wires // each operation to the real Task 12-14 entry point over the live seams; unit // tests inject recording fakes so the orchestration — order, per-item isolation, -// the unknown-prerequisite rule, reclaim gating, and the ONE shared observation +// the unknown-prerequisite rule, and the ONE shared observation // per operation attempt — is proved without a real repository. type sweepOps struct { // prepare produces the ONE fresh metadata observation an operation attempt @@ -123,13 +115,12 @@ type sweepOps struct { // batch (silent omission is not success). Production wires it to // sweepSelectPRFacts over deps.PRBatch; tests inject the seam directly. probeFacts func(ctx context.Context, snap domain.Snapshot) (map[domain.ChangeID]domain.PRFacts, []StatusFinding) - // closeout/cleanup/reclaim each receive the attempt's shared observation so the + // closeout and cleanup each receive the attempt's shared observation so the // dispatched operation reads the same fresh metadata the presence check saw, // with zero additional metadata fetches (the bound reader serves the pin and // corpus; operation-specific proofs stay live). closeout func(ctx context.Context, id int, obs *sweepObservation) CloseoutResult cleanup func(ctx context.Context, id int, obs *sweepObservation) CleanupOpResult - reclaim func(ctx context.Context, id int, revision string, obs *sweepObservation) ChangeReclaimResult // assessHistorical, when set, resolves FULL-scope historical (done/stacked- // merged) cleanup candidates from the pinned inventory and shared read-only // inventories BEFORE they are dispatched, returning the non-actionable @@ -153,7 +144,7 @@ type sweepOps struct { // MaintenanceEntry is one item's structured outcome. Disposition is a closed // sweep token. Operation distinguishes the two kinds of entry: a DISPATCHED- // operation result names the op key that produced it (finalize.closeout, -// finalize.cleanup, change.reclaim) and carries that operation's own protocol +// finalize.cleanup) and carries that operation's own protocol // verdict; a PRE-DISPATCH observation — a policy skip, a vanished/reload skip, or // a full-scope snapshot assessment that resolved a historical record locally // without dispatching anything — carries an EMPTY Operation and is never a @@ -272,34 +263,28 @@ type sweepWorkItem struct { depth int // stack-ancestor count; only meaningful for closeout items } -// MaintenanceSweep composes the verified closeout, cleanup, and reclaim +// MaintenanceSweep composes the verified closeout and cleanup // operations over one pinned inventory. It is the production entry point; the // CLI wires it, and it delegates to maintenanceSweep with real operation // closures over the live seams. func MaintenanceSweep(ctx context.Context, deps FinalizeDeps, repoDir string, scope SweepScope) MaintenanceResult { - // The reclaim leg needs a full workspace service (Prepare/Inspect/Publish); - // FinalizeDeps carries only the narrower finalize workspace seam, so build the - // reclaim workspace over the same git client the deps already hold. A build - // failure is not fatal to the whole sweep: only reclaim items need it, and - // each such item then fails closed with a failed entry rather than mutating. + // Historical-cleanup assessment reads through a full workspace service; + // FinalizeDeps carries only the narrower finalize workspace seam, so build one + // over the same git client the deps already hold. When it cannot be built (no + // git client, or a NewService error) wdeps stays at its zero value, which the + // assessment already tolerates. var wdeps WorkspaceDeps - var wsErr error if deps.Planning.Client != nil { - svc, err := workspace.NewService(deps.Planning.Client) - if err != nil { - wsErr = err - } else { + if svc, err := workspace.NewService(deps.Planning.Client); err == nil { wdeps = WorkspaceDeps{Service: svc} } - } else { - wsErr = fmt.Errorf("no git client wired for the reclaim workspace") } // depsFor binds each operation attempt's deps to the attempt's shared metadata // observation: the planning reader becomes a boundStatusReader that serves the // observation's pin and corpus WITHOUT a re-pin or a re-read, so the dispatched - // operation and its nested readers (reclaim's WorkspaceInspect reads through - // deps.Planning.Reader) perform zero additional metadata fetches. deps.Planning + // operation and its nested readers (which read through deps.Planning.Reader) + // perform zero additional metadata fetches. deps.Planning // .Reader is the initial-pinned production *gitStatusReader, so the bound // reader's same-repository guard is active; operation-specific proofs // (BranchFacts/ArtifactExists/ReadArtifact) still delegate to it and stay live. @@ -332,14 +317,6 @@ func MaintenanceSweep(ctx context.Context, deps FinalizeDeps, repoDir string, sc cleanup: func(ctx context.Context, id int, obs *sweepObservation) CleanupOpResult { return FinalizeCleanup(ctx, depsFor(obs), repoDir, id) }, - reclaim: func(ctx context.Context, id int, revision string, obs *sweepObservation) ChangeReclaimResult { - if wsErr != nil { - return newChangeReclaimResult(ResultInternalError, ChangeReclaimResult{ - ID: id, Findings: []StatusFinding{lifecycleFinding(FCWorkspaceServiceUnavailable, wsErr.Error())}, - }) - } - return ChangeReclaim(ctx, depsFor(obs).Planning, wdeps, repoDir, ChangeReclaimRequest{ID: id, Revision: revision}) - }, probeFacts: func(ctx context.Context, snap domain.Snapshot) (map[domain.ChangeID]domain.PRFacts, []StatusFinding) { // One shared GitHub identity, batched exact-number reads over the whole // finalize population — never a probe per change. @@ -435,7 +412,7 @@ func maintenanceSweep(ctx context.Context, deps FinalizeDeps, repoDir string, op } queue := domain.SelectFinalizeQueue(inv.snap, facts, nil) - items, deferredHistorical := sweepWorklist(inv.snap, queue, eff, deps.Planning.Clock.Now(), scope) + items, deferredHistorical := sweepWorklist(inv.snap, queue, scope) // Full-scope snapshot assessment: resolve the historical (done/stacked-merged) // cleanup candidates locally from the pinned inventory and the shared read-only @@ -485,8 +462,6 @@ func maintenanceSweep(ctx context.Context, deps FinalizeDeps, repoDir string, op continue } entries = append(entries, sweepRunCleanup(ctx, ops, it.id)) - case sweepKindReclaim: - entries = append(entries, sweepRunReclaim(ctx, eff, ops, it.id)) } } @@ -641,9 +616,10 @@ func gatherSweepSharedFacts(ctx context.Context, deps FinalizeDeps, repoDir stri // snapshot: closeout items (active implemented changes with a merged PR), // ordered children-before-ancestors so a root can carry its descendants; then // cleanup items (done or stacked-merged records — archived changes and completed -// stacks) by id; then reclaim items (in-progress records whose lease is strictly -// expired) by id. The three status sets are disjoint, so no id is double-listed. -func sweepWorklist(snap domain.Snapshot, queue []domain.FinalizeCandidate, eff config.Effective, now time.Time, scope SweepScope) (items []sweepWorkItem, deferredHistorical int) { +// stacks) by id. The two status sets are disjoint, so no id is double-listed. +// An in-progress record is never a sweep item: stranded-run recovery belongs to +// the run tracker and resume, not to maintenance. +func sweepWorklist(snap domain.Snapshot, queue []domain.FinalizeCandidate, scope SweepScope) (items []sweepWorkItem, deferredHistorical int) { var closeouts []sweepWorkItem for _, cand := range queue { if cand.Band != sweepBandMergedRecovery { @@ -669,14 +645,12 @@ func sweepWorklist(snap domain.Snapshot, queue []domain.FinalizeCandidate, eff c return closeouts[i].id < closeouts[j].id }) - var cleanups, reclaims []sweepWorkItem - ttl := eff.Reclaim.LeaseTTL.Value + var cleanups []sweepWorkItem for _, c := range snap.Changes() { if _, out := snap.Change(c.ID()); out != domain.LookupFound { continue } - switch { - case c.Status() == domain.StatusDone || c.Status() == domain.StatusStackedMerged: + if c.Status() == domain.StatusDone || c.Status() == domain.StatusStackedMerged { // Implementation scope defers records that were already final at // the pinned inventory: they are counted, never enqueued, so the // worklist stays independent of the historical population. A record @@ -687,17 +661,13 @@ func sweepWorklist(snap domain.Snapshot, queue []domain.FinalizeCandidate, eff c continue } cleanups = append(cleanups, sweepWorkItem{id: int(c.ID()), kind: sweepKindCleanup}) - case domain.EvaluateLease(c, now, ttl) == domain.LeaseExpired: - reclaims = append(reclaims, sweepWorkItem{id: int(c.ID()), kind: sweepKindReclaim}) } } sort.SliceStable(cleanups, func(i, j int) bool { return cleanups[i].id < cleanups[j].id }) - sort.SliceStable(reclaims, func(i, j int) bool { return reclaims[i].id < reclaims[j].id }) - out := make([]sweepWorkItem, 0, len(closeouts)+len(cleanups)+len(reclaims)) + out := make([]sweepWorkItem, 0, len(closeouts)+len(cleanups)) out = append(out, closeouts...) out = append(out, cleanups...) - out = append(out, reclaims...) return out, deferredHistorical } @@ -810,34 +780,6 @@ func sweepRunCleanup(ctx context.Context, ops sweepOps, id int) MaintenanceEntry return entry } -// sweepRunReclaim gates the reclaim on reclaim.auto: when it is off the eligible -// record is surfaced as skipped and nothing is prepared or dispatched; when it -// is on the sweep prepares ONE fresh metadata observation to pin the exact blob -// revision and dispatches the verified reclaim against it. -func sweepRunReclaim(ctx context.Context, eff config.Effective, ops sweepOps, id int) MaintenanceEntry { - if !eff.Reclaim.Auto.Value { - return sweepEntry(id, sweepKindReclaim, SweepDispSkipped, "", ReasonSweepReclaimAutoDisabled, - "reclaim.auto is false; run `docket change reclaim` explicitly") - } - obs, err := ops.prepare(ctx) - if err != nil { - return sweepEntry(id, sweepKindReclaim, SweepDispSkipped, "", ReasonSweepReloadFailed, err.Error()) - } - revision, present := sweepObservedRevision(obs, id) - if !present { - // A successful fetch with a missing record is vanished, never a fetch failure. - return sweepEntry(id, sweepKindReclaim, SweepDispSkipped, "", ReasonSweepItemVanished, "record absent or ambiguous on reload") - } - if revision == "" { - return sweepEntry(id, sweepKindReclaim, SweepDispSkipped, "", ReasonSweepReclaimRevisionMissing, "reloaded record carried no record revision") - } - res := ops.reclaim(ctx, id, revision, obs) - return MaintenanceEntry{ - ID: id, Kind: sweepKindReclaim, Disposition: sweepDispositionForResult(res.Env().Result), - Operation: res.Env().Operation, Reason: res.Reason, Message: res.Message, - } -} - // sweepObservedRevision reads the record's presence and exact blob revision from // one prepared observation — the shared authority the attempt already fetched, // never a fresh re-pin. present is false when the record is absent or ambiguous diff --git a/internal/app/maintenance_assess_test.go b/internal/app/maintenance_assess_test.go index e559e6f7c..9140c6784 100644 --- a/internal/app/maintenance_assess_test.go +++ b/internal/app/maintenance_assess_test.go @@ -592,17 +592,14 @@ func TestLegacyArchivedPRBacklinkIsFullSweepWorkOnly(t *testing.T) { f := newAssessFixture(t, []StatusBlob{blob}, nil) n := prNumberOf(t, f, 41) c, _ := f.inv.snap.Change(domain.ChangeID(41)) - eff := f.pin.Config.Effective - now := testClock().Now() - // Implementation scope: deferred, never enqueued, never assessed. - implItems, implDeferred := sweepWorklist(f.inv.snap, nil, eff, now, SweepScopeImplementation) + implItems, implDeferred := sweepWorklist(f.inv.snap, nil, SweepScopeImplementation) if len(implItems) != 0 || implDeferred != 1 { t.Fatalf("implementation scope must defer the legacy record untouched: items=%v deferred=%d", implItems, implDeferred) } // Full scope: enqueued as a cleanup and assessed as PR-backlink work. - fullItems, fullDeferred := sweepWorklist(f.inv.snap, nil, eff, now, SweepScopeFull) + fullItems, fullDeferred := sweepWorklist(f.inv.snap, nil, SweepScopeFull) if fullDeferred != 0 || len(fullItems) != 1 || fullItems[0].id != 41 || fullItems[0].kind != sweepKindCleanup { t.Fatalf("full scope must enqueue the legacy record as a cleanup: items=%v deferred=%d", fullItems, fullDeferred) } @@ -614,7 +611,7 @@ func TestLegacyArchivedPRBacklinkIsFullSweepWorkOnly(t *testing.T) { // The dispatched cleanup's PR-backlink leg repoints it — no prior attempt needed. pr := newFakePRBody(map[int]string{n: stale}) - cc := &closeoutContext{eff: eff, change: c, body: blob.Data, link: linkContextOf(f.pin)} + cc := &closeoutContext{eff: f.pin.Config.Effective, change: c, body: blob.Data, link: linkContextOf(f.pin)} if fnd := finalizeCleanupPRBacklinkRepair(context.Background(), FinalizeDeps{PRBody: pr}, cc, githubcli.Repository{}, n); fnd != nil { t.Fatalf("cleanup's PR-backlink leg returned a finding: %+v", *fnd) } diff --git a/internal/app/maintenance_preflight_test.go b/internal/app/maintenance_preflight_test.go index f7eefe35b..43d985a63 100644 --- a/internal/app/maintenance_preflight_test.go +++ b/internal/app/maintenance_preflight_test.go @@ -16,7 +16,6 @@ func cleanSweep() MaintenanceResult { Scope: string(SweepScopeImplementation), Entries: []MaintenanceEntry{ {ID: 12, Kind: "closeout", Disposition: SweepDispApplied}, - {ID: 13, Kind: "reclaim", Disposition: SweepDispSkipped, Reason: ReasonSweepReclaimAutoDisabled}, {ID: 14, Kind: "closeout", Disposition: SweepDispNoOp}, }, DeferredHistoricalCleanups: 241, @@ -40,7 +39,7 @@ func TestPreflightCleanComposesBothHalves(t *testing.T) { if res.Preflight != PreflightClean { t.Fatalf("verdict: %q", res.Preflight) } - if len(res.Sweep.Entries) != 3 || len(res.Sweep.ProblemEntries) != 0 || res.Sweep.DeferredHistoricalCleanups != 241 { + if len(res.Sweep.Entries) != 2 || len(res.Sweep.ProblemEntries) != 0 || res.Sweep.DeferredHistoricalCleanups != 241 { t.Fatalf("sweep half: %+v", res.Sweep) } if res.Sweep.Scope != string(SweepScopeImplementation) { @@ -99,7 +98,6 @@ func TestPreflightCleanDispositionsStayClean(t *testing.T) { Entries: []MaintenanceEntry{ {ID: 30, Kind: "closeout", Disposition: SweepDispApplied}, {ID: 31, Kind: "closeout", Disposition: SweepDispNoOp}, - {ID: 32, Kind: "reclaim", Disposition: SweepDispSkipped, Reason: ReasonSweepReclaimAutoDisabled}, {ID: 33, Kind: "cleanup", Disposition: SweepDispSkipped, Reason: ReasonSweepItemVanished}, }, }) @@ -159,7 +157,7 @@ func TestPreflightStatusFailureKeepsSweepHalf(t *testing.T) { if res.Result != ResultExternalFailed { t.Fatalf("result = %q, want external-failed (mirrored)", res.Result) } - if len(res.Sweep.Entries) != 3 { + if len(res.Sweep.Entries) != 2 { t.Fatalf("sweep half not preserved: %+v", res.Sweep) } if res.Status != nil { diff --git a/internal/app/maintenance_test.go b/internal/app/maintenance_test.go index 09f835897..a1b00c1bb 100644 --- a/internal/app/maintenance_test.go +++ b/internal/app/maintenance_test.go @@ -12,24 +12,22 @@ import ( "github.com/danielhanold/docket/internal/repository" ) -// This file drives `maintenance sweep` — the batch driver that reclaims -// docket's closing half — over a fake corpus reader, a scriptable PR prober, -// and RECORDING operation seams. The three verified operations (closeout, -// cleanup, reclaim) are heavy real-git effects proved in their own tasks; here -// they are injected fakes so the sweep's orchestration is proved in isolation: -// the deterministic worklist, children-before-ancestors closeout order, the -// per-item destructive-suffix rule, reclaim gating on reclaim.auto, item -// isolation, the structured sorted report, and — the premium-risk property — ONE +// This file drives `maintenance sweep` — the batch driver for docket's closing +// half — over a fake corpus reader, a scriptable PR prober, and RECORDING +// operation seams. The two verified operations (closeout and cleanup) are heavy +// real-git effects proved in their own tasks; here they are injected fakes so +// the sweep's orchestration is proved in isolation: the deterministic worklist, +// children-before-ancestors closeout order, the per-item destructive-suffix +// rule, item isolation, the structured sorted report, and — the premium-risk property — ONE // fresh metadata observation prepared per dispatched operation attempt, shared // between that attempt's presence check and its dispatched op. // --- recording ops seam --------------------------------------------------- type sweepCall struct { - kind string - id int - revision string - obs *sweepObservation // the shared observation this dispatch received + kind string + id int + obs *sweepObservation // the shared observation this dispatch received } // recordingSweepOps records every dispatch and answers from scripted results, @@ -42,7 +40,6 @@ type recordingSweepOps struct { calls []sweepCall closeout map[int]CloseoutResult cleanup map[int]CleanupOpResult - reclaim map[int]ChangeReclaimResult // reader is the reload source Prepare pins/builds from (defaults to the // inventory reader; a test may point it at a divergent corpus to script a @@ -116,13 +113,6 @@ func (r *recordingSweepOps) seam(reader StatusReader, prober FinalizePRProber) s } return newCleanupResult(OperationFinalizeCleanup, ResultApplied, CleanupOpResult{ID: id, Disposition: CleanupDispCleaned}) }, - reclaim: func(_ context.Context, id int, revision string, obs *sweepObservation) ChangeReclaimResult { - r.calls = append(r.calls, sweepCall{kind: sweepKindReclaim, id: id, revision: revision, obs: obs}) - if res, ok := r.reclaim[id]; ok { - return res - } - return newChangeReclaimResult(ResultApplied, ChangeReclaimResult{ID: id, Disposition: ReclaimDispReclaimed}) - }, } } @@ -158,18 +148,15 @@ func (r *recordingSweepOps) called(kind string, id int) bool { // --- corpus + deps helpers ------------------------------------------------ -// sweepPin clones the docket-mode pin and sets reclaim policy for the run. -func sweepPin(t *testing.T, auto bool, ttlHours int) StatusPin { +// sweepPin clones the docket-mode pin for the run. +func sweepPin(t *testing.T) StatusPin { t.Helper() - p := docketPin(t) - p.Config.Effective.Reclaim.Auto.Value = auto - p.Config.Effective.Reclaim.LeaseTTL.Value = ttlHours - return p + return docketPin(t) } // sweepInProgressBlob builds an in-progress record with an old claim stamp -// (2026-08-02, well before the fixed test clock's 2026-08-16), so its lease is -// strictly expired under any small TTL. +// (2026-08-02, well before the fixed test clock's 2026-08-16): the kind of +// long-stranded claim the sweep must leave alone. func sweepInProgressBlob(id int, slug string) StatusBlob { return StatusBlob{ Kind: repository.KindChange, @@ -216,7 +203,7 @@ func TestSweepFindsMergedImplemented(t *testing.T) { finalizeBlob(31, "childa", "implemented", "high", prRefFor(31), "stacked_on: 30\n"), finalizeBlob(32, "childb", "implemented", "high", prRefFor(32), "stacked_on: 30\n"), } - reader := &fakeReader{pin: sweepPin(t, false, 24), corpus: corpus} + reader := &fakeReader{pin: sweepPin(t), corpus: corpus} prober := &fakeFinalizeProber{facts: map[string]domain.PRFacts{ prRefFor(30): withHead(mergedFacts(30, "main"), "feat/root"), prRefFor(31): withHead(mergedFacts(31, "feat/root"), "feat/childa"), @@ -269,7 +256,7 @@ func TestSweepRetriesSuffixes(t *testing.T) { finalizeBlob(40, "completed", "stacked-merged", "high", prRefFor(40), ""), finalizeBlob(41, "archived", "done", "high", prRefFor(41), ""), } - reader := &fakeReader{pin: sweepPin(t, false, 24), corpus: corpus} + reader := &fakeReader{pin: sweepPin(t), corpus: corpus} prober := &fakeFinalizeProber{facts: map[string]domain.PRFacts{}} ops := &recordingSweepOps{} @@ -289,41 +276,6 @@ func TestSweepRetriesSuffixes(t *testing.T) { } } -// TestSweepReclaimGatedOnAuto: an eligible (in-progress, strictly-expired) record -// is reclaimed only when reclaim.auto is true; with auto false it is surfaced as -// skipped with the reclaim-auto-disabled reason and no reclaim is dispatched. -func TestSweepReclaimGatedOnAuto(t *testing.T) { - corpus := []StatusBlob{sweepInProgressBlob(50, "stale")} - prober := &fakeFinalizeProber{facts: map[string]domain.PRFacts{}} - - t.Run("auto true reclaims", func(t *testing.T) { - reader := &fakeReader{pin: sweepPin(t, true, 24), corpus: corpus} - ops := &recordingSweepOps{} - maintenanceSweep(context.Background(), sweepDeps(reader, prober), "repo", ops.seam(reader, prober), SweepScopeFull) - if !ops.called(sweepKindReclaim, 50) { - t.Fatalf("auto reclaim must dispatch reclaim for 50; calls=%v", ops.calls) - } - }) - - t.Run("auto false skips with reason", func(t *testing.T) { - reader := &fakeReader{pin: sweepPin(t, false, 24), corpus: corpus} - ops := &recordingSweepOps{} - res := maintenanceSweep(context.Background(), sweepDeps(reader, prober), "repo", ops.seam(reader, prober), SweepScopeFull) - if ops.called(sweepKindReclaim, 50) { - t.Fatalf("reclaim.auto:false must NOT dispatch reclaim; calls=%v", ops.calls) - } - var entry *MaintenanceEntry - for i := range res.Entries { - if res.Entries[i].ID == 50 && res.Entries[i].Kind == sweepKindReclaim { - entry = &res.Entries[i] - } - } - if entry == nil || entry.Disposition != SweepDispSkipped || entry.Reason != ReasonSweepReclaimAutoDisabled { - t.Fatalf("want skipped/reclaim-auto-disabled entry, got %+v", entry) - } - }) -} - // TestSweepNeverEscalates: the sweep acts only on merged-recovery closeout work; // an implemented change whose PR is still OPEN is left entirely alone (merging it // is the attended finalize flow's job, never the sweep's). A merged implemented @@ -334,7 +286,7 @@ func TestSweepNeverEscalates(t *testing.T) { finalizeBlob(60, "merged", "implemented", "high", prRefFor(60), ""), finalizeBlob(61, "open", "implemented", "high", prRefFor(61), ""), } - reader := &fakeReader{pin: sweepPin(t, false, 24), corpus: corpus} + reader := &fakeReader{pin: sweepPin(t), corpus: corpus} prober := &fakeFinalizeProber{facts: map[string]domain.PRFacts{ prRefFor(60): withHead(mergedFacts(60, "main"), "feat/merged"), prRefFor(61): openFacts(61, "MERGEABLE", 2, 20), @@ -366,7 +318,7 @@ func TestSweepItemIsolation(t *testing.T) { finalizeBlob(70, "unknownitem", "implemented", "high", prRefFor(70), ""), finalizeBlob(71, "gooditem", "implemented", "high", prRefFor(71), ""), } - reader := &fakeReader{pin: sweepPin(t, false, 24), corpus: corpus} + reader := &fakeReader{pin: sweepPin(t), corpus: corpus} prober := &fakeFinalizeProber{facts: map[string]domain.PRFacts{ prRefFor(70): withHead(mergedFacts(70, "main"), "feat/unknownitem"), prRefFor(71): withHead(mergedFacts(71, "main"), "feat/gooditem"), @@ -408,9 +360,8 @@ func TestSweepStructuredReport(t *testing.T) { corpus := []StatusBlob{ finalizeBlob(80, "merged", "implemented", "high", prRefFor(80), ""), finalizeBlob(81, "stack", "stacked-merged", "high", prRefFor(81), ""), - sweepInProgressBlob(82, "stale"), } - reader := &fakeReader{pin: sweepPin(t, true, 24), corpus: corpus} + reader := &fakeReader{pin: sweepPin(t), corpus: corpus} prober := &fakeFinalizeProber{facts: map[string]domain.PRFacts{ prRefFor(80): withHead(mergedFacts(80, "main"), "feat/merged"), }} @@ -446,9 +397,8 @@ func TestSweepStructuredReport(t *testing.T) { func TestSweepReloadsBeforeMutation(t *testing.T) { corpus := []StatusBlob{ finalizeBlob(90, "merged", "implemented", "high", prRefFor(90), ""), - sweepInProgressBlob(91, "stale"), // reclaim.auto false ⇒ skipped, no preparation } - reader := &fakeReader{pin: sweepPin(t, false, 24), corpus: corpus} + reader := &fakeReader{pin: sweepPin(t), corpus: corpus} prober := &fakeFinalizeProber{facts: map[string]domain.PRFacts{ prRefFor(90): withHead(mergedFacts(90, "main"), "feat/merged"), }} @@ -456,12 +406,12 @@ func TestSweepReloadsBeforeMutation(t *testing.T) { maintenanceSweep(context.Background(), sweepDeps(reader, prober), "repo", ops.seam(reader, prober), SweepScopeFull) - // 90: closeout (applied) + cleanup suffix = 2 dispatches. 91: skipped, none. + // 90: closeout (applied) + cleanup suffix = 2 dispatches. dispatches := len(ops.calls) if dispatches != 2 { t.Fatalf("dispatches = %d, want 2 (closeout+suffix for 90); calls=%v", dispatches, ops.calls) } - // One preparation per dispatch, and none for the skipped reclaim. + // One preparation per dispatch. if len(ops.prepared) != dispatches { t.Fatalf("prepared %d observations, want %d (one per dispatch)", len(ops.prepared), dispatches) } @@ -479,7 +429,7 @@ func TestSweepReloadsBeforeMutation(t *testing.T) { // exactly one attempt to inspect. func TestEachAttemptPreparesOnceAndSharesObservation(t *testing.T) { corpus := []StatusBlob{finalizeBlob(30, "merged", "implemented", "high", prRefFor(30), "")} - reader := &fakeReader{pin: sweepPin(t, false, 24), corpus: corpus} + reader := &fakeReader{pin: sweepPin(t), corpus: corpus} prober := &fakeFinalizeProber{facts: map[string]domain.PRFacts{ prRefFor(30): withHead(mergedFacts(30, "main"), "feat/merged"), }} @@ -508,7 +458,7 @@ func TestEachAttemptPreparesOnceAndSharesObservation(t *testing.T) { // must observe freshly. func TestCleanupSuffixPreparesAgain(t *testing.T) { corpus := []StatusBlob{finalizeBlob(30, "merged", "implemented", "high", prRefFor(30), "")} - reader := &fakeReader{pin: sweepPin(t, false, 24), corpus: corpus} + reader := &fakeReader{pin: sweepPin(t), corpus: corpus} prober := &fakeFinalizeProber{facts: map[string]domain.PRFacts{ prRefFor(30): withHead(mergedFacts(30, "main"), "feat/merged"), }} @@ -530,40 +480,12 @@ func TestCleanupSuffixPreparesAgain(t *testing.T) { } } -// TestDisabledReclaimPreparesNothing: with reclaim.auto false the eligible record -// is surfaced as skipped and NOTHING is prepared — the auto gate precedes any -// metadata preparation. -func TestDisabledReclaimPreparesNothing(t *testing.T) { - corpus := []StatusBlob{sweepInProgressBlob(50, "stale")} - reader := &fakeReader{pin: sweepPin(t, false, 24), corpus: corpus} - prober := &fakeFinalizeProber{facts: map[string]domain.PRFacts{}} - ops := &recordingSweepOps{} - - res := maintenanceSweep(context.Background(), sweepDeps(reader, prober), "repo", ops.seam(reader, prober), SweepScopeFull) - - if len(ops.prepared) != 0 { - t.Fatalf("reclaim.auto:false must prepare nothing; prepared=%d", len(ops.prepared)) - } - if ops.called(sweepKindReclaim, 50) { - t.Fatalf("reclaim.auto:false must not dispatch reclaim") - } - var e *MaintenanceEntry - for i := range res.Entries { - if res.Entries[i].ID == 50 && res.Entries[i].Kind == sweepKindReclaim { - e = &res.Entries[i] - } - } - if e == nil || e.Disposition != SweepDispSkipped || e.Reason != ReasonSweepReclaimAutoDisabled { - t.Fatalf("want skipped/reclaim-auto-disabled entry, got %+v", e) - } -} - // TestPrepareFailureIsReloadFailedSkipNoDispatch: a failed metadata preparation // (the fetch could not be read) yields a skipped/reload-failed entry and // dispatches no operation for that item. func TestPrepareFailureIsReloadFailedSkipNoDispatch(t *testing.T) { corpus := []StatusBlob{finalizeBlob(30, "merged", "implemented", "high", prRefFor(30), "")} - reader := &fakeReader{pin: sweepPin(t, false, 24), corpus: corpus} + reader := &fakeReader{pin: sweepPin(t), corpus: corpus} prober := &fakeFinalizeProber{facts: map[string]domain.PRFacts{ prRefFor(30): withHead(mergedFacts(30, "main"), "feat/merged"), }} @@ -593,11 +515,11 @@ func TestPrepareFailureIsReloadFailedSkipNoDispatch(t *testing.T) { // built from a divergent reader whose corpus dropped it. func TestVanishedOnObservationSkipsAfterThatPrepare(t *testing.T) { corpus := []StatusBlob{finalizeBlob(30, "merged", "implemented", "high", prRefFor(30), "")} - invReader := &fakeReader{pin: sweepPin(t, false, 24), corpus: corpus} + invReader := &fakeReader{pin: sweepPin(t), corpus: corpus} prober := &fakeFinalizeProber{facts: map[string]domain.PRFacts{ prRefFor(30): withHead(mergedFacts(30, "main"), "feat/merged"), }} - reloadReader := &fakeReader{pin: sweepPin(t, false, 24), corpus: []StatusBlob{}} + reloadReader := &fakeReader{pin: sweepPin(t), corpus: []StatusBlob{}} ops := &recordingSweepOps{} res := maintenanceSweep(context.Background(), sweepDeps(invReader, prober), "repo", ops.seam(reloadReader, prober), SweepScopeFull) @@ -622,47 +544,9 @@ func TestVanishedOnObservationSkipsAfterThatPrepare(t *testing.T) { } } -// TestReclaimRevisionFromObservation: the exact blob revision the reclaim is pinned -// to comes from the SHARED observation the attempt prepared — obs.inv -// .revisionByPath[path] — not a separate re-pin. -func TestReclaimRevisionFromObservation(t *testing.T) { - corpus := []StatusBlob{sweepInProgressBlob(50, "stale")} - reader := &fakeReader{pin: sweepPin(t, true, 24), corpus: corpus} - prober := &fakeFinalizeProber{facts: map[string]domain.PRFacts{}} - ops := &recordingSweepOps{} - - maintenanceSweep(context.Background(), sweepDeps(reader, prober), "repo", ops.seam(reader, prober), SweepScopeFull) - - if len(ops.prepared) != 1 { - t.Fatalf("expected exactly one reclaim preparation, got %d", len(ops.prepared)) - } - obs := ops.prepared[0] - c, out := obs.inv.snap.Change(domain.ChangeID(50)) - if out != domain.LookupFound { - t.Fatalf("record 50 must be present in the observation") - } - want := obs.inv.revisionByPath[c.Path()] - if want == "" { - t.Fatalf("observation carried no blob revision for 50") - } - var got string - found := false - for _, cl := range ops.calls { - if cl.kind == sweepKindReclaim && cl.id == 50 { - got, found = cl.revision, true - } - } - if !found { - t.Fatalf("reclaim was not dispatched for 50; calls=%v", ops.calls) - } - if got != want { - t.Fatalf("reclaim revision = %q, want %q (from obs.inv.revisionByPath)", got, want) - } -} - // TestSweepImplementationScopeDefersHistorical: implementation scope schedules -// current merged-implemented closeouts (whose cleanup SUFFIX still runs) and -// gated reclaims, but enqueues NO independent cleanup item for a record that was +// current merged-implemented closeouts (whose cleanup SUFFIX still runs), but +// enqueues NO independent cleanup item for a record that was // already done/stacked-merged at the pinned inventory. Those are counted as a // scope summary, never rendered as per-item outcomes. Full scope on the same // corpus retains the historical retries. @@ -671,14 +555,13 @@ func TestSweepImplementationScopeDefersHistorical(t *testing.T) { finalizeBlob(30, "current", "implemented", "high", prRefFor(30), ""), finalizeBlob(40, "completed", "stacked-merged", "high", prRefFor(40), ""), finalizeBlob(41, "archived", "done", "high", prRefFor(41), ""), - sweepInProgressBlob(50, "stale"), } prober := &fakeFinalizeProber{facts: map[string]domain.PRFacts{ prRefFor(30): withHead(mergedFacts(30, "main"), "feat/current"), }} - t.Run("implementation defers historical, keeps closeout+suffix+reclaim", func(t *testing.T) { - reader := &fakeReader{pin: sweepPin(t, true, 24), corpus: corpus} + t.Run("implementation defers historical, keeps closeout+suffix", func(t *testing.T) { + reader := &fakeReader{pin: sweepPin(t), corpus: corpus} ops := &recordingSweepOps{} res := maintenanceSweep(context.Background(), sweepDeps(reader, prober), "repo", ops.seam(reader, prober), SweepScopeImplementation) @@ -688,9 +571,6 @@ func TestSweepImplementationScopeDefersHistorical(t *testing.T) { if !ops.called(sweepKindCleanup, 30) { t.Errorf("the closeout's cleanup SUFFIX must still run in implementation scope; calls=%v", ops.calls) } - if !ops.called(sweepKindReclaim, 50) { - t.Errorf("reclaim gating must be preserved (auto=true dispatches); calls=%v", ops.calls) - } for _, id := range []int{40, 41} { if ops.called(sweepKindCleanup, id) { t.Errorf("historical %d must NOT get an independent cleanup dispatch; calls=%v", id, ops.calls) @@ -710,7 +590,7 @@ func TestSweepImplementationScopeDefersHistorical(t *testing.T) { }) t.Run("full retains historical retries and reports zero deferred", func(t *testing.T) { - reader := &fakeReader{pin: sweepPin(t, true, 24), corpus: corpus} + reader := &fakeReader{pin: sweepPin(t), corpus: corpus} ops := &recordingSweepOps{} res := maintenanceSweep(context.Background(), sweepDeps(reader, prober), "repo", ops.seam(reader, prober), SweepScopeFull) if !ops.called(sweepKindCleanup, 40) || !ops.called(sweepKindCleanup, 41) { @@ -726,7 +606,7 @@ func TestSweepImplementationScopeDefersHistorical(t *testing.T) { // values is a fail-closed input refusal that dispatches nothing and reads // nothing (defense in depth behind the CLI's own validation). func TestSweepInvalidScopeRefusesBeforeAnyRead(t *testing.T) { - reader := &fakeReader{pin: sweepPin(t, true, 24), corpus: nil} + reader := &fakeReader{pin: sweepPin(t), corpus: nil} ops := &recordingSweepOps{} res := maintenanceSweep(context.Background(), sweepDeps(reader, &fakeFinalizeProber{}), "repo", ops.seam(reader, &fakeFinalizeProber{}), SweepScope("bogus")) if res.Result != ResultInvalidInput || res.Reason != ReasonSweepScopeInvalid { @@ -782,7 +662,7 @@ func (s *recordingSyncSeam) fn() func(context.Context) *SyncOutcome { // after the (empty) item loop; the outcome rides IntegrationSync, and a skipped // sync never inflates the envelope past no-op. func TestSweepRunsIntegrationSyncOnceOnEmptyFullScope(t *testing.T) { - reader := &fakeReader{pin: sweepPin(t, false, 24), corpus: []StatusBlob{}} + reader := &fakeReader{pin: sweepPin(t), corpus: []StatusBlob{}} prober := &fakeFinalizeProber{facts: map[string]domain.PRFacts{}} ops := &recordingSweepOps{} seam := ops.seam(reader, prober) @@ -811,7 +691,7 @@ func TestSweepRunsIntegrationSyncOncePerImplementationScope(t *testing.T) { finalizeBlob(70, "unknownitem", "implemented", "high", prRefFor(70), ""), finalizeBlob(71, "gooditem", "implemented", "high", prRefFor(71), ""), } - reader := &fakeReader{pin: sweepPin(t, false, 24), corpus: corpus} + reader := &fakeReader{pin: sweepPin(t), corpus: corpus} prober := &fakeFinalizeProber{facts: map[string]domain.PRFacts{ prRefFor(70): withHead(mergedFacts(70, "main"), "feat/unknownitem"), prRefFor(71): withHead(mergedFacts(71, "main"), "feat/gooditem"), @@ -843,10 +723,14 @@ func TestSweepRunsIntegrationSyncOncePerImplementationScope(t *testing.T) { // an otherwise no-op sweep to applied, but the sync advance is NOT an entry and // must never inflate the entry-derived applied count. func TestSweepIntegrationSyncAdvanceUpgradesNoOpToApplied(t *testing.T) { - corpus := []StatusBlob{sweepInProgressBlob(50, "stale")} // reclaim.auto false ⇒ skipped, no applied entry - reader := &fakeReader{pin: sweepPin(t, false, 24), corpus: corpus} + // One historical cleanup whose fake result is a verified no-op: the sweep + // dispatches it, but its entry is noop, so no entry is applied. + corpus := []StatusBlob{finalizeBlob(41, "archived", "done", "high", prRefFor(41), "")} + reader := &fakeReader{pin: sweepPin(t), corpus: corpus} prober := &fakeFinalizeProber{facts: map[string]domain.PRFacts{}} - ops := &recordingSweepOps{} + ops := &recordingSweepOps{cleanup: map[int]CleanupOpResult{ + 41: newCleanupResult(OperationFinalizeCleanup, ResultNoOp, CleanupOpResult{ID: 41, Disposition: CleanupDispAlready}), + }} seam := ops.seam(reader, prober) sync := &recordingSyncSeam{out: &SyncOutcome{Disposition: SyncDispAdvanced, IntegrationBranch: "main"}} seam.syncIntegration = sync.fn() @@ -865,6 +749,35 @@ func TestSweepIntegrationSyncAdvanceUpgradesNoOpToApplied(t *testing.T) { if applied != 0 { t.Fatalf("applied ENTRY count = %d, want 0 (the sync advance rides IntegrationSync, not entries)", applied) } + if len(res.Entries) != 1 || res.Entries[0].ID != 41 || res.Entries[0].Disposition != SweepDispNoOp { + t.Fatalf("want exactly one noop entry for 41, got %+v", res.Entries) + } +} + +// TestSweepIgnoresInProgressRecords: an in-progress record, however long ago it +// was claimed, is never a sweep item in either scope — no entry, no +// preparation, no dispatch. Stranded-run recovery is resume's job. +func TestSweepIgnoresInProgressRecords(t *testing.T) { + for _, scope := range []SweepScope{SweepScopeFull, SweepScopeImplementation} { + t.Run(string(scope), func(t *testing.T) { + corpus := []StatusBlob{sweepInProgressBlob(50, "stale")} + reader := &fakeReader{pin: sweepPin(t), corpus: corpus} + prober := &fakeFinalizeProber{facts: map[string]domain.PRFacts{}} + ops := &recordingSweepOps{} + + res := maintenanceSweep(context.Background(), sweepDeps(reader, prober), "repo", ops.seam(reader, prober), scope) + + if res.Reason != "" { + t.Fatalf("sweep refused: %s %s", res.Reason, res.Message) + } + if len(res.Entries) != 0 { + t.Fatalf("an in-progress record must yield no sweep entry, got %+v", res.Entries) + } + if len(ops.prepared) != 0 || len(ops.calls) != 0 { + t.Fatalf("nothing may be prepared or dispatched; prepared=%d calls=%v", len(ops.prepared), ops.calls) + } + }) + } } // TestSweepIntegrationSyncFailureNeverDowngradesAppliedSweep: a sync failure is @@ -872,7 +785,7 @@ func TestSweepIntegrationSyncAdvanceUpgradesNoOpToApplied(t *testing.T) { // entry-derived envelope result. func TestSweepIntegrationSyncFailureNeverDowngradesAppliedSweep(t *testing.T) { corpus := []StatusBlob{finalizeBlob(30, "merged", "implemented", "high", prRefFor(30), "")} - reader := &fakeReader{pin: sweepPin(t, false, 24), corpus: corpus} + reader := &fakeReader{pin: sweepPin(t), corpus: corpus} prober := &fakeFinalizeProber{facts: map[string]domain.PRFacts{ prRefFor(30): withHead(mergedFacts(30, "main"), "feat/merged"), }} @@ -896,7 +809,7 @@ func TestSweepIntegrationSyncFailureNeverDowngradesAppliedSweep(t *testing.T) { // IntegrationSync. func TestSweepRefusalSkipsIntegrationSync(t *testing.T) { t.Run("invalid scope", func(t *testing.T) { - reader := &fakeReader{pin: sweepPin(t, true, 24), corpus: nil} + reader := &fakeReader{pin: sweepPin(t), corpus: nil} prober := &fakeFinalizeProber{} ops := &recordingSweepOps{} seam := ops.seam(reader, prober) @@ -911,7 +824,7 @@ func TestSweepRefusalSkipsIntegrationSync(t *testing.T) { } }) t.Run("pin error", func(t *testing.T) { - reader := &fakeReader{pin: sweepPin(t, true, 24), pinErr: errors.New("boom")} + reader := &fakeReader{pin: sweepPin(t), pinErr: errors.New("boom")} prober := &fakeFinalizeProber{} ops := &recordingSweepOps{} seam := ops.seam(reader, prober) @@ -930,7 +843,7 @@ func TestSweepRefusalSkipsIntegrationSync(t *testing.T) { // TestSweepCancelledContextSkipsIntegrationSync: a cancelled context before the // suffix skips the sync (no detached work) and leaves IntegrationSync nil. func TestSweepCancelledContextSkipsIntegrationSync(t *testing.T) { - reader := &fakeReader{pin: sweepPin(t, false, 24), corpus: []StatusBlob{}} + reader := &fakeReader{pin: sweepPin(t), corpus: []StatusBlob{}} prober := &fakeFinalizeProber{facts: map[string]domain.PRFacts{}} ops := &recordingSweepOps{} seam := ops.seam(reader, prober) @@ -953,7 +866,7 @@ func TestSweepCancelledContextSkipsIntegrationSync(t *testing.T) { // syncIntegration nil (the pre-0388 shape) runs without panic and leaves // IntegrationSync nil — existing orchestration tests stay green. func TestSweepNilIntegrationSyncSeamIsNoPanic(t *testing.T) { - reader := &fakeReader{pin: sweepPin(t, false, 24), corpus: []StatusBlob{}} + reader := &fakeReader{pin: sweepPin(t), corpus: []StatusBlob{}} prober := &fakeFinalizeProber{facts: map[string]domain.PRFacts{}} ops := &recordingSweepOps{} seam := ops.seam(reader, prober) // syncIntegration left nil @@ -1019,7 +932,7 @@ func TestSweepSelectionUsesBatchedFactsNotPerChangeProbe(t *testing.T) { corpus := []StatusBlob{ finalizeBlob(30, "merged", "implemented", "high", prRefFor(30), ""), } - reader := &fakeReader{pin: sweepPin(t, false, 24), corpus: corpus} + reader := &fakeReader{pin: sweepPin(t), corpus: corpus} // The per-change prober must NEVER be consulted by the sweep. cp := &countingProber{inner: &fakeFinalizeProber{}} batch := &fakeSweepBatchReader{result: SweepPRSetResult{ @@ -1058,13 +971,12 @@ func TestSweepImplementationScopeDoesNotGrowWithHistory(t *testing.T) { t.Helper() corpus := []StatusBlob{ finalizeBlob(30, "current", "implemented", "high", prRefFor(30), ""), - sweepInProgressBlob(50, "stale"), } for i := 0; i < historical; i++ { id := 1000 + i corpus = append(corpus, finalizeBlob(id, fmt.Sprintf("hist%04d", i), "done", "high", prRefFor(id), "")) } - cr := &countingReader{inner: &fakeReader{pin: sweepPin(t, true, 24), corpus: corpus}} + cr := &countingReader{inner: &fakeReader{pin: sweepPin(t), corpus: corpus}} cp := &countingProber{inner: &fakeFinalizeProber{facts: map[string]domain.PRFacts{ prRefFor(30): withHead(mergedFacts(30, "main"), "feat/current"), }}} @@ -1108,7 +1020,7 @@ func TestSweepImplementationScopeDoesNotGrowWithHistory(t *testing.T) { // the safety-net path. func TestSweepCleanupSurfacesWorkspaceRemnant(t *testing.T) { corpus := []StatusBlob{finalizeBlob(30, "merged", "implemented", "high", prRefFor(30), "")} - reader := &fakeReader{pin: sweepPin(t, false, 24), corpus: corpus} + reader := &fakeReader{pin: sweepPin(t), corpus: corpus} prober := &fakeFinalizeProber{facts: map[string]domain.PRFacts{ prRefFor(30): withHead(mergedFacts(30, "main"), "feat/merged"), }} @@ -1149,7 +1061,7 @@ func TestSweepCleanupSurfacesWorkspaceRemnant(t *testing.T) { func sweepKeptBranchRun(t *testing.T, findings []StatusFinding) (MaintenanceResult, MaintenanceEntry) { t.Helper() corpus := []StatusBlob{finalizeBlob(30, "merged", "implemented", "high", prRefFor(30), "")} - reader := &fakeReader{pin: sweepPin(t, false, 24), corpus: corpus} + reader := &fakeReader{pin: sweepPin(t), corpus: corpus} prober := &fakeFinalizeProber{facts: map[string]domain.PRFacts{ prRefFor(30): withHead(mergedFacts(30, "main"), "feat/merged"), }} @@ -1205,7 +1117,7 @@ func TestSweepCleanupKeptBranchSetsEmptyReason(t *testing.T) { // A kept-branch warning that is not the result's first finding still // supplies the entry reason when the result carried none. corpus := []StatusBlob{finalizeBlob(30, "merged", "implemented", "high", prRefFor(30), "")} - reader := &fakeReader{pin: sweepPin(t, false, 24), corpus: corpus} + reader := &fakeReader{pin: sweepPin(t), corpus: corpus} prober := &fakeFinalizeProber{facts: map[string]domain.PRFacts{ prRefFor(30): withHead(mergedFacts(30, "main"), "feat/merged"), }} @@ -1257,7 +1169,7 @@ func carriedRootCorpus(t *testing.T) (*fakeReader, *fakeFinalizeProber) { finalizeBlob(31, "childa", "implemented", "high", prRefFor(31), "stacked_on: 30\n"), finalizeBlob(32, "childb", "implemented", "high", prRefFor(32), "stacked_on: 30\n"), } - reader := &fakeReader{pin: sweepPin(t, false, 24), corpus: corpus} + reader := &fakeReader{pin: sweepPin(t), corpus: corpus} prober := &fakeFinalizeProber{facts: map[string]domain.PRFacts{ prRefFor(30): withHead(mergedFacts(30, "main"), "feat/root"), prRefFor(31): withHead(mergedFacts(31, "feat/root"), "feat/childa"), @@ -1401,7 +1313,7 @@ func TestSweepAlreadyClosedOutCarriesNoChildCleanup(t *testing.T) { corpus := []StatusBlob{ finalizeBlob(30, "root", "implemented", "high", prRefFor(30), ""), } - reader := &fakeReader{pin: sweepPin(t, false, 24), corpus: corpus} + reader := &fakeReader{pin: sweepPin(t), corpus: corpus} prober := &fakeFinalizeProber{facts: map[string]domain.PRFacts{ prRefFor(30): withHead(mergedFacts(30, "main"), "feat/root"), }} @@ -1426,7 +1338,7 @@ func TestSweepCarriedChildNotCleanedTwice(t *testing.T) { finalizeBlob(30, "root", "implemented", "high", prRefFor(30), ""), finalizeBlob(31, "child", "stacked-merged", "high", prRefFor(31), "stacked_on: 30\n"), } - reader := &fakeReader{pin: sweepPin(t, false, 24), corpus: corpus} + reader := &fakeReader{pin: sweepPin(t), corpus: corpus} prober := &fakeFinalizeProber{facts: map[string]domain.PRFacts{ prRefFor(30): withHead(mergedFacts(30, "main"), "feat/root"), }} diff --git a/internal/app/maintenance_traffic_integration_test.go b/internal/app/maintenance_traffic_integration_test.go index 505a5804b..4d24eb673 100644 --- a/internal/app/maintenance_traffic_integration_test.go +++ b/internal/app/maintenance_traffic_integration_test.go @@ -46,18 +46,18 @@ import ( // proved cleanly at the session seam by sweep_session_integration_test.go // (TestIntegrationContextProbePrepareIsOneMetadataFetchZeroSetupProbes, TestIntegrationContextProbeBoundReaderNeverFetches) with // the same real-process counting. It is NOT re-asserted as a bare fetch count -// around a live mutation here, because a dispatched reclaim's transaction engine +// around a live mutation here, because a dispatched closeout's transaction engine // legitimately re-fetches the metadata branch for its own fresh-origin CAS commit // (learning cas-re-read-fresh-origin) — that fetch is required proof, not a // duplicate reader read, so a naive "one fetch per op" count around a real // mutation would be counting two different, both-correct things. // // Gaps deliberately left to their existing owners / noted precisely: -// - A successful closeout+cleanup SUFFIX over a fake `gh` executable would need a -// scripted gh speaking the full merged-facts reprobe/merge surface; that live -// end-to-end suffix is exercised by the CLI e2e matrix (finalize_e2e_test.go), -// not re-built here. The dispatched-operation traffic proof here uses reclaim, -// which needs no gh. +// - The dispatched-operation traffic proof here is one applied closeout over a +// scripted gh that answers only the selection batch and the merged reprobe; +// its cleanup suffix stops at the workspace leg. A fully successful +// closeout+cleanup suffix is exercised by the CLI e2e matrix +// (finalize_e2e_test.go), not re-built here. // - Mid-sweep source movement between prepare points (Step 4's two-phase hook) is // proved at the session seam by sweep_session_integration_test.go's // TestIntegrationContextProbePrepareObservesFreshMetadataTip; the movement @@ -581,61 +581,114 @@ func TestIntegrationSweepImplementationScopeInspectsNoDeferredResources(t *testi } } -// --- Step 1 (dispatched op): reclaim keeps setup once --------------------- - -// TestIntegrationSweepDispatchedReclaimKeepsSetupOnce drives a REAL dispatched -// mutation (an expired-lease reclaim, reclaim.auto on) end-to-end and proves the -// invocation still runs full setup exactly ONCE: one default-branch probe and no -// shared inventory (a reclaim is not a done candidate). The reclaim dispatch runs -// the workspace inspection and the transaction's own fresh-origin CAS re-read — so -// this also witnesses that a dispatched operation adds no setup re-probe. The -// bytes-level "one preparation fetch shared by nested readers" property is proved -// at the session seam (sweep_session_integration_test.go); see this file's header note. -func TestIntegrationSweepDispatchedReclaimKeepsSetupOnce(t *testing.T) { +// --- Step 1 (dispatched op): closeout keeps setup once -------------------- + +// trafficGHMerged is trafficGH for a corpus whose one PR is merged: `repo view` +// answers the fixed acme/widgets identity, `api graphql` (the batched selection +// read) answers alias pr0 with prDoc, and `pr view` (the closeout's authoritative +// reprobe) answers prDoc. Every other verb — the best-effort PR-backlink edit — +// answers `{}`. Every invocation is logged to logPath. +func trafficGHMerged(t *testing.T, logPath, prDoc string) *githubcli.Client { + t.Helper() + dir := testsupport.TempDir(t) + if err := os.WriteFile(filepath.Join(dir, "pr.json"), []byte(prDoc), 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "batch.json"), []byte(`{"data":{"repository":{"pr0":`+prDoc+`}}}`), 0o600); err != nil { + t.Fatal(err) + } + wrapper := filepath.Join(dir, "gh") + script := "#!/bin/sh\nprintf '%s\\n' \"$*\" >> '" + logPath + "'\n" + + "case \"$1 $2\" in\n" + + "'repo view') printf '%s' '{\"nameWithOwner\":\"acme/widgets\",\"owner\":{\"login\":\"acme\"},\"name\":\"widgets\",\"url\":\"https://github.com/acme/widgets\"}';;\n" + + "'api graphql') cat '" + filepath.Join(dir, "batch.json") + "';;\n" + + "'pr view') cat '" + filepath.Join(dir, "pr.json") + "';;\n" + + "*) printf '%s' '{}';;\n" + + "esac\n" + if err := os.WriteFile(wrapper, []byte(script), 0o755); err != nil { + t.Fatal(err) + } + client, err := githubcli.NewClient(githubcli.WithExecutable(wrapper)) + if err != nil { + t.Fatalf("githubcli.NewClient: %v", err) + } + return client +} + +// TestIntegrationSweepDispatchedCloseoutKeepsSetupOnce drives a REAL dispatched +// mutation (the closeout of an implemented record whose PR the fake gh reports +// merged into main, at a merge commit that is main's real tip) end-to-end and +// proves the invocation still runs full setup exactly ONCE: one default-branch +// probe for the sweep plus the integration-sync suffix's one. The closeout runs +// its own authoritative reprobe, the integration-tip fetch and ancestry proof, +// and the transaction's fresh-origin CAS re-read — so this also witnesses that a +// dispatched operation adds no setup re-probe. The bytes-level "one preparation +// fetch shared by nested readers" property is proved at the session seam +// (sweep_session_integration_test.go); see this file's header note. +func TestIntegrationSweepDispatchedCloseoutKeepsSetupOnce(t *testing.T) { requireRealGit(t) records := map[string]string{ - // An in-progress record whose claim (2026-08-02) is well before the fixed - // test clock (2026-08-16); a 12-hour lease is strictly expired. - "docs/changes/active/0050-stale.md": lifecycleChange(50, "stale", "in-progress"), + "docs/changes/active/0030-current.md": closeoutRecord(30, "current", "implemented", "acme/widgets#30", + "docs/superpowers/specs/2026-08-16-current.md", + "docs/superpowers/plans/2026-08-16-current.md", + "docs/changes/results/0030-current-results.md"), } - r := trafficRepo(t, "integration_branch: main\nreclaim:\n lease_ttl: 12\n auto: true\n", records) + r := trafficRepo(t, "", records) + mergeCommit := strings.TrimSpace(runGit(t, r.origin, "rev-parse", "refs/heads/main")) + prDoc := `{"number":30,"url":"https://github.com/acme/widgets/pull/30","state":"MERGED","isDraft":false,` + + `"headRefName":"feat/current","headRefOid":"` + strings.Repeat("a", 40) + `","baseRefName":"main",` + + `"title":"A change","body":"","reviewDecision":null,"mergedAt":"2026-08-10T00:00:00Z",` + + `"mergeCommit":{"oid":"` + mergeCommit + `"},"mergeable":"UNKNOWN"}` gitLog := filepath.Join(testsupport.TempDir(t), "git.log") - deps := trafficDeps(t, trafficGit(t, gitLog, ""), trafficGH(t, filepath.Join(testsupport.TempDir(t), "gh.log"))) + deps := trafficDeps(t, trafficGit(t, gitLog, ""), trafficGHMerged(t, filepath.Join(testsupport.TempDir(t), "gh.log"), prDoc)) res := MaintenanceSweep(context.Background(), deps, r.invocation, SweepScopeFull) - // The reclaim was actually dispatched and applied (WorkspaceInspect ran). - var reclaim *MaintenanceEntry + // The closeout was actually dispatched and applied. + var closeout *MaintenanceEntry for i := range res.Entries { - if res.Entries[i].ID == 50 && res.Entries[i].Kind == sweepKindReclaim { - reclaim = &res.Entries[i] + if res.Entries[i].ID == 30 && res.Entries[i].Kind == sweepKindCloseout { + closeout = &res.Entries[i] } } - if reclaim == nil { - t.Fatalf("reclaim was not dispatched for the expired record; entries=%+v", res.Entries) + if closeout == nil { + t.Fatalf("closeout was not dispatched for the merged record; entries=%+v", res.Entries) } - if reclaim.Disposition != SweepDispApplied || reclaim.Operation != OperationChangeReclaim { - t.Fatalf("reclaim entry = %+v, want an applied change.reclaim dispatch", *reclaim) + if closeout.Disposition != SweepDispApplied || closeout.Operation != OperationFinalizeCloseout { + t.Fatalf("closeout entry = %+v, want an applied finalize.closeout dispatch", *closeout) + } + // The cleanup suffix ran after the applied closeout (a dispatched op of its + // own). It stops at the workspace leg — this fixture publishes no feature + // workspace — which is fine: the proof here is setup traffic, not cleanup. + var suffix *MaintenanceEntry + for i := range res.Entries { + if res.Entries[i].ID == 30 && res.Entries[i].Kind == sweepKindCleanup { + suffix = &res.Entries[i] + } + } + if suffix == nil || suffix.Operation != OperationFinalizeCleanup { + t.Fatalf("the applied closeout's cleanup suffix was not dispatched; entries=%+v", res.Entries) } gl := gitLogLines(t, gitLog) // Full setup ran once even across the dispatched mutation, plus the once-per-sweep // integration-sync suffix's one bounded operational-context load (change 0388) — - // a fixed 1 + 1. The dispatched reclaim itself adds NO setup re-probe; the extra + // a fixed 1 + 1. The dispatched closeout itself adds NO setup re-probe; the extra // probe is the sync suffix's, not a per-history or per-op re-pin. wantProbes := 1 + syncSuffixDefaultBranchProbes if got := countMatching(gl, "ls-remote", "--symref"); got != wantProbes { t.Errorf("default-branch probes ran %d times, want exactly %d across a dispatched op (sweep setup + one bounded integration-sync load)", got, wantProbes) } - // A reclaim is not a done candidate: no snapshot assessment, no shared inventory. + // The shared `ls-remote --heads` inventory is gathered only for FULL-scope + // historical assessment, and only when the PINNED inventory holds a done + // candidate. Here the one record was implemented at the pin: the closeout + // reads its merge facts from gh and its destination from one integration-tip + // fetch, and the suffix stops at the workspace leg before any remote-branch + // read. So the count is zero by what these two operations need, not by a + // per-history rule — a fan-out would show up on the discovery and scaling + // tests above, which assert on a growing done population. if got := countMatching(gl, "ls-remote", "--heads"); got != 0 { - t.Errorf("a reclaim-only sweep must gather no shared inventory, got %d ls-remote --heads", got) - } - // NOTE: a dispatched reclaim's own feature-branch check (`ls-remote … - // refs/heads/feat/stale`) is REQUIRED operation-specific proof, not a forbidden - // per-HISTORY assessment probe — so featureRefProbes is deliberately NOT asserted - // zero here. The forbidden-per-item-probe invariant is asserted on the - // non-dispatched assessment path (discovery/scaling/unknown-advertisement tests), - // where any feature-ref ls-remote would be a per-history fan-out. + t.Errorf("a closeout-only sweep must gather no shared inventory, got %d ls-remote --heads", got) + } } // --- Step 2: blocked-probe / required-access regressions ------------------ diff --git a/internal/app/schema_registry.go b/internal/app/schema_registry.go index 6af66b8f6..52531e554 100644 --- a/internal/app/schema_registry.go +++ b/internal/app/schema_registry.go @@ -59,7 +59,6 @@ var operationBindings = []OperationBinding{ {ID: "change.halt", Request: ChangeHaltInput{}, Result: HaltResult{}}, // ChangeHalt {ID: "change.kill", Request: ChangeKillRequest{}, Result: ChangeKillResult{}}, // ChangeKill {ID: "change.mark-implemented", Request: nil, Result: ChangeLifecycleResult{}}, // ChangeMarkImplemented - {ID: "change.reclaim", Request: nil, Result: ChangeReclaimResult{}}, // ChangeReclaim {ID: "change.reconcile", Request: ChangeReconcileRequest{}, Result: ChangeReconcileResult{}}, // ChangeReconcile {ID: "change.relink", Request: nil, Result: RelinkResult{}}, // Relink {ID: "change.resume-halted", Request: nil, Result: HaltResult{}}, // ChangeResumeHalted diff --git a/internal/app/schema_vocab.go b/internal/app/schema_vocab.go index f8968dd29..19622b581 100644 --- a/internal/app/schema_vocab.go +++ b/internal/app/schema_vocab.go @@ -87,10 +87,6 @@ func SchemaVocabularies(effects []string) map[string]Vocabulary { HaltDispHalted, HaltDispResumed, HaltDispContended, HaltDispRefused, HaltDispFailed, }} - v["reclaim_dispositions"] = Vocabulary{Members: []string{ - ReclaimDispReclaimed, ReclaimDispSkipped, - ReclaimDispContended, ReclaimDispFailed, - }} v["complete_dispositions"] = Vocabulary{Members: []string{ CompleteDispCompleted, CompleteDispAlreadyCompleted, CompleteDispContended, CompleteDispFailed, diff --git a/internal/app/schema_vocab_test.go b/internal/app/schema_vocab_test.go index 6eff3db4b..cb7ffe50a 100644 --- a/internal/app/schema_vocab_test.go +++ b/internal/app/schema_vocab_test.go @@ -166,7 +166,6 @@ func TestVocabularyConstCompleteness(t *testing.T) { {vocab: "groom_outcomes", byType: "GroomOutcome"}, {vocab: "claim_dispositions", byPrefix: "ClaimDisposition"}, {vocab: "halt_dispositions", byPrefix: "HaltDisp"}, - {vocab: "reclaim_dispositions", byPrefix: "ReclaimDisp"}, {vocab: "reconcile_dispositions", byPrefix: "ReconcileDisposition"}, {vocab: "complete_dispositions", byPrefix: "CompleteDisp"}, {vocab: "block_dispositions", byPrefix: "BlockDisp"}, diff --git a/internal/cli/change.go b/internal/cli/change.go index bbf14ce4d..a84cffd4a 100644 --- a/internal/cli/change.go +++ b/internal/cli/change.go @@ -140,13 +140,11 @@ func newChangeCommand(setResult func(app.OperationResult)) *cobra.Command { resumeHalted := newResumeHaltedSubcommand(setResult) - reclaim := newReclaimSubcommand(setResult) - markImplemented := newMarkImplementedSubcommand(setResult) relink := newRelinkSubcommand(setResult) - changeCmd.AddCommand(create, groom, block, deferCmd, unblock, revive, kill, complete, claim, reconcile, attachPlan, attachResults, halt, resumeHalted, reclaim, markImplemented, relink) + changeCmd.AddCommand(create, groom, block, deferCmd, unblock, revive, kill, complete, claim, reconcile, attachPlan, attachResults, halt, resumeHalted, markImplemented, relink) return changeCmd } @@ -250,44 +248,6 @@ func newResumeHaltedSubcommand(setResult func(app.OperationResult)) *cobra.Comma return cmd } -// newReclaimSubcommand builds `change reclaim`: the proof-gated return of a -// strictly-expired in-progress claim to proposed. Its scalar identities (id, -// revision) ride on flags; the reclaim generates its own dated log entry, so it -// takes no request file. It composes the read-only planning seams and the -// workspace service — the workspace inspection is the reclaim's ownership and -// live-gate probe. -func newReclaimSubcommand(setResult func(app.OperationResult)) *cobra.Command { - cmd := &cobra.Command{ - Use: "reclaim", - Short: "Return a strictly-expired, branchless, workspaceless in-progress claim to proposed", - Args: cobra.NoArgs, - Annotations: capability("change.reclaim", EffectMetadataWrite), - RunE: func(c *cobra.Command, _ []string) error { - repoDir, err := resolveRepoDir(c) - if err != nil { - return err - } - id, _ := c.Flags().GetInt("id") - revision, _ := c.Flags().GetString("revision") - deps, wdeps, err := newWorkspaceDeps(repoDir) - if err != nil { - return err - } - setResult(app.ChangeReclaim(c.Context(), deps, wdeps, repoDir, app.ChangeReclaimRequest{ - ID: id, - Revision: revision, - })) - return nil - }, - } - cmd.Flags().Int("id", 0, "expired in-progress change `id` to reclaim (required)") - cmd.Flags().String("revision", "", "exact record `revision` (the blob object id) from the authoritative context read (required)") - cmd.Flags().String("repo-dir", "", "repository `dir` to operate on (default: current directory)") - _ = cmd.MarkFlagRequired("id") - _ = cmd.MarkFlagRequired("revision") - return cmd -} - // newMarkImplementedSubcommand builds `change mark-implemented`: the final // verified transition. Its scalar identities (id, revision, head, pr) ride on // flags; the canonical build-evidence record rides in a file (or stdin) via diff --git a/internal/cli/change_test.go b/internal/cli/change_test.go index 7e0e1443e..47e9f36aa 100644 --- a/internal/cli/change_test.go +++ b/internal/cli/change_test.go @@ -208,6 +208,35 @@ func TestChangeRefreshClaimRetired(t *testing.T) { } } +// TestChangeReclaimRetired pins the deletion of change.reclaim: no command, no +// catalog entry, no schema binding — while change.claim stays, so the catalog +// probe is not vacuous. Stranded-run recovery is resume by id. +func TestChangeReclaimRetired(t *testing.T) { + root := productionRootForTest(t) + if c, _, err := root.Find([]string{"change", "reclaim"}); err == nil && c != nil && c.Name() == "reclaim" { + t.Fatal("change reclaim is still registered") + } + entries, err := collectCapabilities(root) + if err != nil { + t.Fatalf("collectCapabilities: %v", err) + } + if _, ok := entryByID(entries, "change.reclaim"); ok { + t.Fatal("catalog still lists change.reclaim") + } + if _, ok := entryByID(entries, "change.claim"); !ok { + t.Fatal("non-vacuity: change.claim missing from catalog") + } + if _, ok, _ := app.SchemaFor("change.reclaim", []string{"write"}); ok { + t.Fatal("schema registry still binds change.reclaim") + } + if _, ok, _ := app.SchemaFor("change.claim", []string{"write"}); !ok { + t.Fatal("non-vacuity: schema registry lost change.claim") + } + if _, _, code := runCLI(t, "change", "reclaim", "--id", "1", "--revision", "x", "--json"); code != 2 { + t.Fatalf("change reclaim exit = %d, want 2 (unknown command)", code) + } +} + // TestChangeReconcileRegistered proves reconcile is wired as a change subcommand // carrying the scalar --input request-file flag (authored Markdown rides in the // JSON body, never shell-escaped flags). @@ -594,53 +623,6 @@ func TestChangeResumeHaltedReachesOperation(t *testing.T) { } } -// --- change reclaim -------------------------------------------------------- - -// TestChangeReclaimRegistered proves `change reclaim` is wired with the scalar -// identity flags and is asset-independent. -func TestChangeReclaimRegistered(t *testing.T) { - root := captureTree(t) - cmd, _, err := root.Find([]string{"change", "reclaim"}) - if err != nil || cmd == nil || cmd.Name() != "reclaim" { - t.Fatalf("change reclaim not registered: cmd=%v err=%v", cmd, err) - } - for _, flag := range []string{"id", "revision", "repo-dir"} { - if cmd.Flags().Lookup(flag) == nil { - t.Errorf("change reclaim: missing --%s flag", flag) - } - } - if !assetIndependent["change reclaim"] { - t.Errorf("%q is not registered asset-independent", "change reclaim") - } -} - -// TestChangeReclaimFlagsRequired proves --id and --revision are required: omitting -// them is an argument error (exit 2) before any operation runs. -func TestChangeReclaimFlagsRequired(t *testing.T) { - _, errS, code := runCLI(t, "change", "reclaim") - if code != 2 || errS == "" { - t.Fatalf("err=%q code=%d, want a required-flag argument error", errS, code) - } -} - -// TestChangeReclaimReachesOperation proves reclaim decodes its scalar flags and -// reaches the operation, which returns exactly one protocol-v1 document naming -// it. A non-repository repo-dir refuses while pinning context, so no live -// metadata is mutated. -func TestChangeReclaimReachesOperation(t *testing.T) { - out, errS, _ := runCLI(t, "change", "reclaim", - "--id", "3", "--revision", "1234123412341234123412341234123412341234", "--repo-dir", testsupport.TempDir(t), "--json") - if errS != "" { - t.Fatalf("unexpected stderr %q", errS) - } - if !strings.Contains(out, `"operation":"change.reclaim"`) { - t.Fatalf("document did not name the operation: %q", out) - } - if strings.Count(out, "\n") != 1 || !strings.HasSuffix(out, "\n") { - t.Fatalf("must be exactly one newline-terminated document, got %q", out) - } -} - // TestChangeRelinkRetiresRepairIdentity is the ADR-0129 row 70 hard cut: the // catalog lists change.relink and no longer lists change.repair-identity, and the // old verb is not a registered subcommand. diff --git a/internal/cli/finalize.go b/internal/cli/finalize.go index a18e1d1dd..7c26c6775 100644 --- a/internal/cli/finalize.go +++ b/internal/cli/finalize.go @@ -17,7 +17,7 @@ import ( // the outcome. The closing-half mutation subcommands land here in later change // 0316 tasks; today the group is registered so its tree and shared dependency // wiring exist for those subcommands to attach to. Every lifecycle, Git, -// GitHub, stack, reclaim, and cleanup policy belongs to internal/app, so no body +// GitHub, stack, and cleanup policy belongs to internal/app, so no body // here branches on repository content. // newFinalizeCommand builds the `finalize` command group. setResult is the diff --git a/internal/cli/install.go b/internal/cli/install.go index 07609c91c..e66ff3b1a 100644 --- a/internal/cli/install.go +++ b/internal/cli/install.go @@ -50,7 +50,6 @@ var assetIndependent = map[string]bool{ "change attach-results": true, "change halt": true, "change resume-halted": true, - "change reclaim": true, "change mark-implemented": true, "change relink": true, "context": true, // the group itself; it reports a missing command diff --git a/internal/cli/maintenance.go b/internal/cli/maintenance.go index 6b2316d12..f62be7b08 100644 --- a/internal/cli/maintenance.go +++ b/internal/cli/maintenance.go @@ -57,7 +57,7 @@ func newSweepFinalizeDeps() (app.FinalizeDeps, error) { // operation over the real Git/GitHub/workspace seams, and let the presenter own // the outcome. `docket status` stays read-only; batch mutation of docket's // closing half is reached only through `docket maintenance sweep`. Every -// lifecycle, Git, GitHub, stack, reclaim, and cleanup policy belongs to +// lifecycle, Git, GitHub, stack, and cleanup policy belongs to // internal/app, so no body here branches on repository content. // newMaintenanceCommand builds the `maintenance` command group. setResult is the @@ -66,7 +66,7 @@ func newSweepFinalizeDeps() (app.FinalizeDeps, error) { func newMaintenanceCommand(setResult func(app.OperationResult)) *cobra.Command { maintenanceCmd := &cobra.Command{ Use: "maintenance", - Short: "Reclaim docket's closing half in batch (docket status stays read-only)", + Short: "Run docket's closing half in batch (docket status stays read-only)", // A command group resolves its subcommand before Args runs, so anything // reaching here named no subcommand; NoArgs names an offending token and // the bare `docket maintenance` falls through to RunE's missing-command @@ -126,18 +126,18 @@ func newMaintenancePreflightSubcommand(setResult func(app.OperationResult)) *cob // newMaintenanceSweepSubcommand builds `maintenance sweep`: one pinned inventory, // processed in a deterministic order, that closes out merged changes (stacked // children before ancestors), retries PR backlink repair and ownership-safe -// cleanup for archived/done records and completed stacks, and reclaims expired -// claims when reclaim.auto is on. It reloads fresh authority before every +// cleanup for archived/done records and completed stacks. It reloads fresh +// authority before every // mutation and reports every item as a structured entry. Two flags ride on it — // --repo-dir names the target directory and --scope selects the closed sweep // scope (full or implementation) — and there is no authored request body. func newMaintenanceSweepSubcommand(setResult func(app.OperationResult)) *cobra.Command { cmd := &cobra.Command{ Use: "sweep", - Short: "Close out merged changes, retry close-out cleanup, and reclaim expired claims in one pass", + Short: "Close out merged changes and retry close-out cleanup in one pass", Args: cobra.NoArgs, - // metadata-write + local-write + external-write: composes closeout, - // cleanup, and reclaim and inherits the full union of their effects. + // metadata-write + local-write + external-write: composes closeout and + // cleanup and inherits the full union of their effects. Annotations: capability("maintenance.sweep", EffectMetadataWrite, EffectLocalWrite, EffectExternalWrite), RunE: func(c *cobra.Command, _ []string) error { // Scope resolves once, here, to a typed value — the app layer never diff --git a/internal/cli/revision_rename_test.go b/internal/cli/revision_rename_test.go index 363f60e9f..000de1ba0 100644 --- a/internal/cli/revision_rename_test.go +++ b/internal/cli/revision_rename_test.go @@ -60,7 +60,7 @@ func TestRetiredRevisionRequestKeysRefused(t *testing.T) { // the record revision on a flag. var revisionFlagOps = [][]string{ {"change", "attach-plan"}, {"change", "attach-results"}, {"change", "claim"}, {"change", "halt"}, - {"change", "mark-implemented"}, {"change", "reclaim"}, {"change", "resume-halted"}, + {"change", "mark-implemented"}, {"change", "resume-halted"}, {"finalize", "block"}, {"finalize", "clear-block"}, {"finalize", "merge"}, {"finalize", "rebase"}, {"finalize", "retarget-children"}, {"workspace", "prepare"}, } @@ -181,7 +181,6 @@ func TestRevisionFlagReachesRequest(t *testing.T) { args []string }{ {"", []string{"change", "claim", "--id", "1"}}, - {"", []string{"change", "reclaim", "--id", "1"}}, {"", []string{"change", "resume-halted", "--id", "1"}}, {"# Plan\n\nSteps.\n", []string{"change", "attach-plan", "--id", "1", "--path", "p.md", "--markdown", "-"}}, {"# R\n\n## Outcome\n\nDone.\n", []string{"change", "attach-results", "--id", "1", "--path", "r.md", "--markdown", "-"}}, diff --git a/internal/domain/actions.go b/internal/domain/actions.go index a09aa3202..d0ad765c2 100644 --- a/internal/domain/actions.go +++ b/internal/domain/actions.go @@ -422,10 +422,6 @@ func Complete(c Change) (ActionResult, *PolicyFailure) { return b.result(), nil } -// Reclaim is declared in lease.go, alongside the EvaluateReclaim predicate it -// evaluates: the transition is trivial, and the policy that gates it is the -// lease vocabulary. - // requireStatus refuses c unless its status is one of the legal source states, // naming the attempted action in the failure detail. func requireStatus(c Change, action string, legal ...Status) *PolicyFailure { diff --git a/internal/domain/lease.go b/internal/domain/lease.go index 90ec55c68..1f4b348e5 100644 --- a/internal/domain/lease.go +++ b/internal/domain/lease.go @@ -18,14 +18,6 @@ const ( LeaseNotInProgress LeaseState = "not-in-progress" // the record holds no lease ) -// The stable reasons a reclaim is refused. -const ( - reasonLeaseNotExpired = "lease-not-expired" - reasonMissingStamp = "missing-claim-stamp" - reasonMalformedStamp = "malformed-claim-stamp" - reasonBranchExists = "branch-still-exists" -) - // EvaluateLease reports the condition of c's claim lease against the injected // now and a TTL in hours. // @@ -54,85 +46,3 @@ func EvaluateLease(c Change, now time.Time, ttlHours int) LeaseState { return LeaseMissing } } - -// ReclaimVerdict is the evaluated reclaim predicate: whether the claim may be -// taken back, the lease condition that decided it, and the branch that blocked -// it when one did. BlockingBranch is the empty string when no branch blocked. -type ReclaimVerdict struct { - Eligible bool - Lease LeaseState - BlockingBranch string -} - -// EvaluateReclaim reports whether c's claim may be reclaimed. Three conditions -// must all hold: the record is in-progress, its lease is strictly expired, and -// neither the branch it recorded nor the branch a fresh claim would mint from -// type/branch_prefix/slug exists among the supplied facts. A live branch is -// unfinished work whoever left it, so it blocks the reclaim independently of the -// lease age — BlockingBranch is populated even for a fresh lease, naming the -// recorded branch in preference to the mint candidate. -func EvaluateReclaim(c Change, now time.Time, ttlHours int, facts BranchFacts) ReclaimVerdict { - lease := EvaluateLease(c, now, ttlHours) - blocking := blockingBranch(c, facts) - return ReclaimVerdict{ - Eligible: lease == LeaseExpired && blocking == "", - Lease: lease, - BlockingBranch: blocking, - } -} - -// blockingBranch returns the name of the live branch that stands in the way of -// reclaiming c, or the empty string when neither candidate exists. -func blockingBranch(c Change, facts BranchFacts) string { - if recorded := c.Branch(); recorded.State == FieldPresent && recorded.Value != "" { - if facts.HasBranch(recorded.Value) { - return recorded.Value - } - } - if minted := MintBranch(c.Type(), c.BranchPrefix(), c.Slug()); facts.HasBranch(minted) { - return minted - } - return "" -} - -// Reclaim returns an in-progress change whose claim aged out to proposed, -// clearing the branch it recorded and its claim stamp and marking it -// unreconciled: the next claimant inherits no facts from the abandoned run. -// -// A record that is not in-progress is an illegal source state; every other -// refusal is a blocked failure carrying the verdict's stable reason. A live -// branch is reported ahead of the lease condition because it is the actionable -// one — a fresh lease resolves itself, an unmerged branch does not. -func Reclaim(c Change, now time.Time, ttlHours int, facts BranchFacts) (ActionResult, *PolicyFailure) { - if fail := requireStatus(c, "reclaim", StatusInProgress); fail != nil { - return ActionResult{}, fail - } - verdict := EvaluateReclaim(c, now, ttlHours, facts) - if !verdict.Eligible { - if verdict.BlockingBranch != "" { - return ActionResult{}, newFailure(c, FailBlocked, reasonBranchExists, map[string]string{ - "branch": verdict.BlockingBranch, - }) - } - return ActionResult{}, newFailure(c, FailBlocked, leaseRefusalReason(verdict.Lease), nil) - } - - b := newChangeBuilder(c) - b.setStatus(StatusProposed) - b.setBranch("") - b.clearClaimedAt() - b.setReconciled(false) - return b.result(), nil -} - -// leaseRefusalReason maps a non-expired lease onto its stable refusal reason. -func leaseRefusalReason(lease LeaseState) string { - switch lease { - case LeaseMissing: - return reasonMissingStamp - case LeaseMalformed: - return reasonMalformedStamp - default: - return reasonLeaseNotExpired - } -} diff --git a/internal/domain/lease_test.go b/internal/domain/lease_test.go index 342623c87..7c06e629b 100644 --- a/internal/domain/lease_test.go +++ b/internal/domain/lease_test.go @@ -36,15 +36,6 @@ func leaseStamp(offset time.Duration) OptionalTime { return OptionalTime{State: FieldPresent, Value: at, Raw: at.Format(time.RFC3339)} } -// leaseBranches is the branch-existence fact set for the reclaim tests. -func leaseBranches(names ...string) BranchFacts { - set := make(map[string]bool, len(names)) - for _, n := range names { - set[n] = true - } - return NewBranchFacts(set) -} - func TestEvaluateLeaseStates(t *testing.T) { cases := []struct { name string @@ -83,301 +74,3 @@ func TestEvaluateLeaseStatusOutranksStamp(t *testing.T) { t.Fatalf("EvaluateLease = %q, want %q", got, LeaseNotInProgress) } } - -func TestEvaluateReclaimConditions(t *testing.T) { - expired := leaseStamp(-10 * time.Hour) - fresh := leaseStamp(-time.Hour) - - cases := []struct { - name string - status Status - stamp OptionalTime - branch string - branches []string - wantEligible bool - wantLease LeaseState - wantBlocking string - }{ - { - name: "all three conditions met", status: StatusInProgress, stamp: expired, - branch: "feat/lease-slug", branches: nil, - wantEligible: true, wantLease: LeaseExpired, - }, - { - name: "no recorded branch and no conventional branch", status: StatusInProgress, stamp: expired, - branches: []string{"feat/someone-else"}, - wantEligible: true, wantLease: LeaseExpired, - }, - { - name: "recorded branch still exists", status: StatusInProgress, stamp: expired, - branch: "feat/renamed-branch", branches: []string{"feat/renamed-branch"}, - wantEligible: false, wantLease: LeaseExpired, wantBlocking: "feat/renamed-branch", - }, - { - name: "recorded branch blocks regardless of lease age", status: StatusInProgress, stamp: fresh, - branch: "feat/renamed-branch", branches: []string{"feat/renamed-branch"}, - wantEligible: false, wantLease: LeaseFresh, wantBlocking: "feat/renamed-branch", - }, - { - name: "recorded branch absent but conventional branch exists", status: StatusInProgress, stamp: expired, - branch: "feat/renamed-branch", branches: []string{"feat/lease-slug"}, - wantEligible: false, wantLease: LeaseExpired, wantBlocking: "feat/lease-slug", - }, - { - name: "conventional branch exists with no recorded branch", status: StatusInProgress, stamp: expired, - branches: []string{"feat/lease-slug"}, - wantEligible: false, wantLease: LeaseExpired, wantBlocking: "feat/lease-slug", - }, - { - name: "fresh lease is never eligible", status: StatusInProgress, stamp: fresh, - wantEligible: false, wantLease: LeaseFresh, - }, - { - name: "exact ttl boundary is never eligible", status: StatusInProgress, stamp: leaseStamp(-leaseTTL * time.Hour), - wantEligible: false, wantLease: LeaseFresh, - }, - { - name: "missing stamp is not evidence of expiry", status: StatusInProgress, stamp: OptionalTime{}, - wantEligible: false, wantLease: LeaseMissing, - }, - { - name: "malformed stamp is not evidence of expiry", status: StatusInProgress, - stamp: OptionalTime{State: FieldMalformed, Raw: "yesterday"}, - wantEligible: false, wantLease: LeaseMalformed, - }, - { - name: "a change holding no lease is not reclaimable", status: StatusProposed, stamp: expired, - wantEligible: false, wantLease: LeaseNotInProgress, - }, - } - - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - c := leaseChange(tc.status, tc.stamp, tc.branch) - got := EvaluateReclaim(c, leaseNow, leaseTTL, leaseBranches(tc.branches...)) - if got.Eligible != tc.wantEligible { - t.Errorf("Eligible = %v, want %v", got.Eligible, tc.wantEligible) - } - if got.Lease != tc.wantLease { - t.Errorf("Lease = %q, want %q", got.Lease, tc.wantLease) - } - if got.BlockingBranch != tc.wantBlocking { - t.Errorf("BlockingBranch = %q, want %q", got.BlockingBranch, tc.wantBlocking) - } - }) - } -} - -func TestReclaimEligibleReturnsProposed(t *testing.T) { - c := leaseChange(StatusInProgress, leaseStamp(-10*time.Hour), "feat/lease-slug") - before := fingerprint(c) - - got, fail := Reclaim(c, leaseNow, leaseTTL, leaseBranches()) - if fail != nil { - t.Fatalf("Reclaim failed: %v", fail) - } - if got.Change.Status() != StatusProposed { - t.Errorf("status = %q, want %q", got.Change.Status(), StatusProposed) - } - if b := got.Change.Branch(); b.State != FieldAbsent || b.Value != "" { - t.Errorf("branch = %+v, want cleared", b) - } - if s := got.Change.ClaimedAt(); s.State != FieldAbsent || s.Raw != "" { - t.Errorf("claimed_at = %+v, want cleared", s) - } - if got.Change.Reconciled() { - t.Error("reconciled = true, want false") - } - for _, field := range []string{"status", "branch", "claimed_at"} { - if !hasField(got, field) { - t.Errorf("Changed set missing %q: %v", field, changedFields(got)) - } - } - if to, ok := fieldTo(got, "branch"); !ok || to != "" { - t.Errorf("branch change To = %q (present %v), want cleared", to, ok) - } - if after := fingerprint(c); after != before { - t.Errorf("Reclaim mutated its input: %q -> %q", before, after) - } -} - -func TestReclaimRefusals(t *testing.T) { - cases := []struct { - name string - status Status - stamp OptionalTime - branch string - branches []string - wantKind PolicyFailureKind - wantReason string - }{ - { - name: "fresh lease", status: StatusInProgress, stamp: leaseStamp(-time.Hour), - wantKind: FailBlocked, wantReason: "lease-not-expired", - }, - { - name: "exact ttl boundary", status: StatusInProgress, stamp: leaseStamp(-leaseTTL * time.Hour), - wantKind: FailBlocked, wantReason: "lease-not-expired", - }, - { - name: "missing stamp", status: StatusInProgress, stamp: OptionalTime{}, - wantKind: FailBlocked, wantReason: "missing-claim-stamp", - }, - { - name: "malformed stamp", status: StatusInProgress, stamp: OptionalTime{State: FieldMalformed, Raw: "??"}, - wantKind: FailBlocked, wantReason: "malformed-claim-stamp", - }, - { - name: "recorded branch still exists", status: StatusInProgress, stamp: leaseStamp(-10 * time.Hour), - branch: "feat/renamed-branch", branches: []string{"feat/renamed-branch"}, - wantKind: FailBlocked, wantReason: "branch-still-exists", - }, - { - name: "conventional branch still exists", status: StatusInProgress, stamp: leaseStamp(-10 * time.Hour), - branches: []string{"feat/lease-slug"}, - wantKind: FailBlocked, wantReason: "branch-still-exists", - }, - { - name: "not in progress", status: StatusProposed, stamp: leaseStamp(-10 * time.Hour), - wantKind: FailInvalidState, wantReason: "illegal-source-status", - }, - } - - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - c := leaseChange(tc.status, tc.stamp, tc.branch) - got, fail := Reclaim(c, leaseNow, leaseTTL, leaseBranches(tc.branches...)) - if fail == nil { - t.Fatalf("Reclaim succeeded, want %s/%s", tc.wantKind, tc.wantReason) - } - if fail.Kind != tc.wantKind || fail.Reason != tc.wantReason { - t.Fatalf("failure = %s/%s, want %s/%s", fail.Kind, fail.Reason, tc.wantKind, tc.wantReason) - } - if fail.Change != c.ID() || fail.State != c.Status() { - t.Errorf("failure identity = %d/%q, want %d/%q", fail.Change, fail.State, c.ID(), c.Status()) - } - if len(got.Changed) != 0 || len(got.OwnedRemovals) != 0 { - t.Errorf("refused Reclaim returned an outcome: %+v", got) - } - }) - } -} - -func TestReclaimBranchFailureNamesTheBranch(t *testing.T) { - c := leaseChange(StatusInProgress, leaseStamp(-10*time.Hour), "feat/renamed-branch") - _, fail := Reclaim(c, leaseNow, leaseTTL, leaseBranches("feat/renamed-branch")) - if fail == nil { - t.Fatal("Reclaim succeeded, want a blocked failure") - } - if fail.Detail["branch"] != "feat/renamed-branch" { - t.Fatalf("detail branch = %q, want %q", fail.Detail["branch"], "feat/renamed-branch") - } -} - -// mintCandidateChange builds an in-progress, branchless, strictly-expired change -// whose fresh-mint candidate is minted from its type and optional branch_prefix -// — the branch a fresh claim would take, which blockingBranch must probe. -func mintCandidateChange(changeType string, prefix OptionalString) Change { - return NewChange(ChangeSpec{ - ID: 7, - Slug: "lease-slug", - Type: changeType, - Status: StatusInProgress, - RawStatus: string(StatusInProgress), - ClaimedAt: leaseStamp(-10 * time.Hour), - BranchPrefix: prefix, - }) -} - -func TestBlockingBranchProbesMintCandidate(t *testing.T) { - // blockingBranch probes the branch a fresh claim would MINT from - // type/branch_prefix/slug, not the fixed feat/: a type-fix change is - // blocked by a live fix/; a branch_prefix override moves the candidate; - // and a live feat/ alone does not block a fix change. - cases := []struct { - name string - changeType string - prefix OptionalString - branches []string - wantBlocking string - }{ - { - name: "type mints the candidate", changeType: "fix", - branches: []string{"fix/lease-slug"}, wantBlocking: "fix/lease-slug", - }, - { - name: "branch_prefix overrides the type", changeType: "fix", - prefix: OptionalString{State: FieldPresent, Value: "hotfix"}, - branches: []string{"hotfix/lease-slug"}, wantBlocking: "hotfix/lease-slug", - }, - { - name: "feat/ does not block a fix change", changeType: "fix", - branches: []string{"feat/lease-slug"}, wantBlocking: "", - }, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - c := mintCandidateChange(tc.changeType, tc.prefix) - got := EvaluateReclaim(c, leaseNow, leaseTTL, leaseBranches(tc.branches...)) - if got.BlockingBranch != tc.wantBlocking { - t.Fatalf("BlockingBranch = %q, want %q", got.BlockingBranch, tc.wantBlocking) - } - }) - } -} - -func TestBlockingBranchPrefersRecorded(t *testing.T) { - // A live recorded branch is named ahead of the mint candidate even when the - // mint candidate (feature/lease-slug) is also live. - c := NewChange(ChangeSpec{ - ID: 7, - Slug: "lease-slug", - Type: "feature", - Status: StatusInProgress, - RawStatus: string(StatusInProgress), - ClaimedAt: leaseStamp(-10 * time.Hour), - Branch: OptionalString{State: FieldPresent, Value: "feature/other-name"}, - }) - got := EvaluateReclaim(c, leaseNow, leaseTTL, leaseBranches("feature/other-name", "feature/lease-slug")) - if got.BlockingBranch != "feature/other-name" { - t.Fatalf("BlockingBranch = %q, want recorded %q", got.BlockingBranch, "feature/other-name") - } -} - -func TestReclaimPreservesBranchPrefix(t *testing.T) { - // Reclaiming a branchless expired claim clears the branch but leaves - // branch_prefix exactly as recorded — the next claimant re-mints from it. - c := mintCandidateChange("fix", OptionalString{State: FieldPresent, Value: "hotfix"}) - got, fail := Reclaim(c, leaseNow, leaseTTL, leaseBranches()) - if fail != nil { - t.Fatalf("Reclaim failed: %v", fail) - } - if b := got.Change.Branch(); b.State != FieldAbsent || b.Value != "" { - t.Errorf("branch = %+v, want cleared", b) - } - if bp := got.Change.BranchPrefix(); bp.State != FieldPresent || bp.Value != "hotfix" { - t.Errorf("branch_prefix = %+v, want preserved {Present hotfix}", bp) - } -} - -func TestReclaimPreservesAutoGroomable(t *testing.T) { - // The change builder seeds every durable input, auto_groomable included: a - // domain transition must never drop the human's override. - want := OptionalBool{State: FieldPresent, Value: true, Raw: "true"} - c := NewChange(ChangeSpec{ - ID: 7, - Slug: "lease-slug", - Type: "fix", - Status: StatusInProgress, - RawStatus: string(StatusInProgress), - ClaimedAt: leaseStamp(-10 * time.Hour), - AutoGroomable: want, - }) - got, fail := Reclaim(c, leaseNow, leaseTTL, leaseBranches()) - if fail != nil { - t.Fatalf("Reclaim failed: %v", fail) - } - if ag := got.Change.AutoGroomable(); ag != want { - t.Errorf("auto_groomable = %+v, want preserved %+v", ag, want) - } -} diff --git a/tests/test_go_integration_app_changeruntime.sh b/tests/test_go_integration_app_changeruntime.sh index 95aecc43f..5a7266e90 100755 --- a/tests/test_go_integration_app_changeruntime.sh +++ b/tests/test_go_integration_app_changeruntime.sh @@ -2,7 +2,7 @@ # docket-suite: go # tests/test_go_integration_app_changeruntime.sh — Go integration shard (change 0434): # the change run-lifecycle real-repository tests (run-tracker start/verdict, run-verify, -# repair, reclaim, halt/resume, mark-implemented, pr-publish), behind the +# repair, halt/resume, mark-implemented, pr-publish), behind the # `integration` build tag, prefix ^TestIntegrationChangeRuntime. Split out of # tests/test_go_integration_app_change.sh. Declarations only — execution and inspection live in # tests/lib/go-integration-shard.sh; the completeness contract is From 110147fb46b9865d2284d56ee42c1361c0f5b510 Mon Sep 17 00:00:00 2001 From: Daniel Hanold Date: Thu, 22 Oct 2026 07:04:25 -0400 Subject: [PATCH 3/7] refactor: stop requiring or repairing claimed_at in validation and repository repair --- internal/app/change_create_test.go | 2 +- internal/app/config_diagnostics_test.go | 4 +- internal/app/finding_catalog_test.go | 35 ++-- internal/app/repair_remedy_family_test.go | 6 +- internal/app/repository_check.go | 2 +- internal/app/repository_migrate.go | 2 +- .../app/repository_repair_integration_test.go | 45 ++-- internal/app/repository_repair_test.go | 56 ++--- internal/app/testdata/finding-catalog.txt | 25 --- internal/app/validation_text.go | 7 - internal/app/validation_text_test.go | 4 - internal/document/document.go | 5 +- internal/document/empty_value_test.go | 9 +- internal/reposetup/findingtext_test.go | 10 +- internal/reposetup/repair.go | 144 +------------ internal/reposetup/repair_test.go | 194 +++--------------- internal/reposetup/repair_text_test.go | 38 +--- internal/repository/decode.go | 4 +- internal/repository/validate.go | 23 +-- internal/repository/validate_test.go | 49 +++-- 20 files changed, 171 insertions(+), 493 deletions(-) diff --git a/internal/app/change_create_test.go b/internal/app/change_create_test.go index 54bbf89ba..66cddecac 100644 --- a/internal/app/change_create_test.go +++ b/internal/app/change_create_test.go @@ -462,7 +462,7 @@ func TestChangeCreateRecordHasNoRepairFindings(t *testing.T) { t.Fatalf("title = %q (err %v), want %q", fm.Title, err, title) } - fs, err := reposetup.PlanRepairs(recPath, rec, false, reposetup.RecordLocator{}) + fs, err := reposetup.PlanRepairs(recPath, rec, reposetup.RecordLocator{}) if err != nil { t.Fatalf("PlanRepairs: %v", err) } diff --git a/internal/app/config_diagnostics_test.go b/internal/app/config_diagnostics_test.go index 82b725a21..b23cc8aeb 100644 --- a/internal/app/config_diagnostics_test.go +++ b/internal/app/config_diagnostics_test.go @@ -340,9 +340,9 @@ func TestConfigDiagnosticLine(t *testing.T) { // the remedy, and absent entirely when the finding carries no impact. func TestAppendFindingBlockPrintsImpactBetweenMessageAndRemedy(t *testing.T) { var b strings.Builder - appendFindingBlock(&b, reposetup.Finding{Code: "drop-final-claimed-at", Severity: reposetup.SeverityWarning, + appendFindingBlock(&b, reposetup.Finding{Code: "quote-unsafe-scalar", Severity: reposetup.SeverityWarning, Ref: "docs/x.md", Message: "what is wrong", Impact: "whether it matters", Remedy: "what to do"}) - if want := "\n- [warning] drop-final-claimed-at (docs/x.md)\n what is wrong\n whether it matters\n remedy: what to do"; b.String() != want { + if want := "\n- [warning] quote-unsafe-scalar (docs/x.md)\n what is wrong\n whether it matters\n remedy: what to do"; b.String() != want { t.Fatalf("with impact:\n got %q\nwant %q", b.String(), want) } b.Reset() diff --git a/internal/app/finding_catalog_test.go b/internal/app/finding_catalog_test.go index 38a4ac018..b4024e2d2 100644 --- a/internal/app/finding_catalog_test.go +++ b/internal/app/finding_catalog_test.go @@ -24,29 +24,24 @@ var updateCatalog = flag.Bool("update", false, "rewrite testdata/finding-catalog const findingCatalogPath = "testdata/finding-catalog.txt" // catalogFrontmatterShapes is one source per frontmatter-repair shape -// PlanRepairs words (the same seven shapes TestRepairFindingsCarryThreeParts +// PlanRepairs words (the same five shapes TestRepairFindingsCarryThreeParts // pins in package reposetup), each rendered as the check would print it. func catalogFrontmatterShapes() []struct { - name string - src string - archived bool + name string + src string } { fm := func(extra string) string { return "---\nid: 1\nslug: wisdom-ai-bastion\nstatus: done\ntitle: T\ntype: feature\n" + extra + "---\n\nBody.\n" } - claimed := fm("claimed_at: 2026-05-20T10:00:00Z\n") return []struct { - name string - src string - archived bool + name string + src string }{ - {"drop-final-claimed-at", claimed, true}, - {"quote-unsafe-scalar", strings.Replace(fm(""), "title: T", "title: yes", 1), false}, - {"scalar-to-list", fm("depends_on: 3, 4\n"), false}, - {"ambiguous value", strings.Replace(fm(""), "title: T", "title: true", 1), false}, - {"non-id list", fm("related: foo\n"), false}, - {"claimed_at, not done", strings.Replace(claimed, "status: done", "status: proposed", 1), true}, - {"undecodable", "---\nid: 1\nid: 2\n---\nbody\n", false}, + {"quote-unsafe-scalar", strings.Replace(fm(""), "title: T", "title: yes", 1)}, + {"scalar-to-list", fm("depends_on: 3, 4\n")}, + {"ambiguous value", strings.Replace(fm(""), "title: T", "title: true", 1)}, + {"non-id list", fm("related: foo\n")}, + {"undecodable", "---\nid: 1\nid: 2\n---\nbody\n"}, } } @@ -109,7 +104,7 @@ func renderFindingCatalog(t *testing.T) string { b.WriteString("\n## Frontmatter-repair findings\n") rel := "docs/changes/archive/2026-05-28-0001-wisdom-ai-bastion.md" for _, shape := range catalogFrontmatterShapes() { - rfs, err := reposetup.PlanRepairs(rel, []byte(shape.src), shape.archived, dotDocket) + rfs, err := reposetup.PlanRepairs(rel, []byte(shape.src), dotDocket) if err != nil { t.Fatalf("PlanRepairs(%s): %v", shape.name, err) } @@ -136,7 +131,7 @@ func renderFindingCatalog(t *testing.T) string { blocked := checkRecordLocator(layout.Layout{}, reposetup.StateNeedsReview) fmt.Fprintf(&b, "\n### validator (%s)\nremedy: %s\n", danglingDep().Code, explainValidation(danglingDep(), blocked).Remedy) for _, shape := range catalogFrontmatterShapes() { - rfs, err := reposetup.PlanRepairs(rel, []byte(shape.src), shape.archived, blocked) + rfs, err := reposetup.PlanRepairs(rel, []byte(shape.src), blocked) if err != nil { t.Fatalf("PlanRepairs(%s): %v", shape.name, err) } @@ -190,7 +185,7 @@ func TestFindingCatalogGolden(t *testing.T) { got := renderFindingCatalog(t) floor := []string{ - string(reposetup.RepairQuoteScalar), string(reposetup.RepairScalarToList), string(reposetup.RepairDropClaimedAt), + string(reposetup.RepairQuoteScalar), string(reposetup.RepairScalarToList), reposetup.CodeFrontmatterManualReview, reposetup.CodeBoardStale, reposetup.CodeADRIndexStale, reposetup.CodeArtifactLinksStale, reposetup.CodeArtifactLinksMissing, reposetup.CodeArtifactLinksMalformed, @@ -202,8 +197,8 @@ func TestFindingCatalogGolden(t *testing.T) { t.Errorf("catalog has no %q finding block", code) } } - if n := strings.Count(got, "] "+reposetup.CodeFrontmatterManualReview+" "); n < 4 { - t.Errorf("catalog has %d %s blocks, want at least 4 (one per non-repairable frontmatter shape)", n, reposetup.CodeFrontmatterManualReview) + if n := strings.Count(got, "] "+reposetup.CodeFrontmatterManualReview+" "); n < 3 { + t.Errorf("catalog has %d %s blocks, want at least 3 (one per non-repairable frontmatter shape)", n, reposetup.CodeFrontmatterManualReview) } path := filepath.FromSlash(findingCatalogPath) diff --git a/internal/app/repair_remedy_family_test.go b/internal/app/repair_remedy_family_test.go index 8dd126e33..66df2842f 100644 --- a/internal/app/repair_remedy_family_test.go +++ b/internal/app/repair_remedy_family_test.go @@ -29,8 +29,8 @@ func TestRepairableFamilyRemediesNameRepairNotMigrate(t *testing.T) { malformedFM := strings.Replace(derivedChangeFM, "id: 1\nslug: example", "id: 4\nslug: malformed", 1) corpus := checkCorpus{ records: []corpusRecord{ - // repairable frontmatter: a real claim stamp on a final archived record - {path: "docs/changes/archive/2026-01-02-0003-archived-change.md", bytes: []byte("---\nid: 3\nslug: archived-change\nstatus: done\ntitle: Change archived-change\ntype: feature\nclaimed_at: 2026-08-01T10:00:00Z\n---\n\nBody.\n"), kind: repository.KindChange, location: repository.LocationArchive}, + // repairable frontmatter: an unquoted boolean-keyword title + {path: "docs/changes/archive/2026-01-02-0003-archived-change.md", bytes: []byte("---\nid: 3\nslug: archived-change\nstatus: done\ntitle: yes\ntype: feature\n---\n\nBody.\n"), kind: repository.KindChange, location: repository.LocationArchive}, // manual-review frontmatter: an unsafe scalar with an ambiguous decode {path: "docs/changes/active/0002-other.md", bytes: []byte("---\nid: 2\nslug: other\nstatus: proposed\ntitle: true\ntype: feature\n---\n\nBody.\n"), kind: repository.KindChange, location: repository.LocationActive}, // repairable derived: a stale artifact-links block @@ -69,7 +69,7 @@ func TestRepairableFamilyRemediesNameRepairNotMigrate(t *testing.T) { // Population floor (marker-scoped-guard-needs-a-population-floor): both // producers, both polarities. for _, code := range []string{ - string(reposetup.RepairDropClaimedAt), reposetup.CodeFrontmatterManualReview, repository.CodeChangeReferenceDangling, + string(reposetup.RepairQuoteScalar), reposetup.CodeFrontmatterManualReview, repository.CodeChangeReferenceDangling, reposetup.CodeBoardStale, reposetup.CodeArtifactLinksStale, reposetup.CodeArtifactLinksMalformed, } { if !seen[code] { diff --git a/internal/app/repository_check.go b/internal/app/repository_check.go index c32bcfb2b..d0d596ce1 100644 --- a/internal/app/repository_check.go +++ b/internal/app/repository_check.go @@ -1115,7 +1115,7 @@ func corpusFindings(cfg config.Effective, recs []corpusRecord, loc reposetup.Rec if r.kind != repository.KindChange { continue } - fnds, err := reposetup.PlanRepairs(r.path, r.bytes, r.location == repository.LocationArchive, loc) + fnds, err := reposetup.PlanRepairs(r.path, r.bytes, loc) if err != nil { continue } diff --git a/internal/app/repository_migrate.go b/internal/app/repository_migrate.go index 047b3910a..b930fbab1 100644 --- a/internal/app/repository_migrate.go +++ b/internal/app/repository_migrate.go @@ -428,7 +428,7 @@ func gatherMigrationRepairs(ctx context.Context, git *gitcli.Client, sc setupCon mr.archived[rec.path] = archived // A migration has no attached metadata checkout yet, so the remedy // names the record on the metadata branch. - findings, perr := reposetup.PlanRepairs(rec.path, rec.bytes, archived, reposetup.RecordLocator{}) + findings, perr := reposetup.PlanRepairs(rec.path, rec.bytes, reposetup.RecordLocator{}) if perr != nil { continue } diff --git a/internal/app/repository_repair_integration_test.go b/internal/app/repository_repair_integration_test.go index 38b7cccdb..a0ba3e1bd 100644 --- a/internal/app/repository_repair_integration_test.go +++ b/internal/app/repository_repair_integration_test.go @@ -89,27 +89,32 @@ func (r *initRepo) runRepair(t *testing.T, o RepairOptions) RepositoryRepairResu } const ( - repairStampPath = "docs/changes/archive/2026-01-02-0003-archived-change.md" + repairQuotePath = "docs/changes/archive/2026-01-02-0003-archived-change.md" repairEmptyPath = "docs/changes/archive/2026-01-03-0004-archived-empty.md" ) -// repairArchivedRecord renders a minimal valid archived done record carrying the -// given claimed_at line. -func repairArchivedRecord(id int, slug, claimedLine string) string { - return "---\nid: " + strconv.Itoa(id) + "\nslug: " + slug + "\nstatus: done\ntitle: Change " + slug + - "\ntype: feature\n" + claimedLine + "\n---\n\nBody for " + slug + ".\n" +// repairArchivedRecord renders a minimal valid archived done record with the +// given title token and extra frontmatter lines. +func repairArchivedRecord(id int, slug, title string, extraLines ...string) string { + var extra string + for _, l := range extraLines { + extra += l + "\n" + } + return "---\nid: " + strconv.Itoa(id) + "\nslug: " + slug + "\nstatus: done\ntitle: " + title + + "\ntype: feature\n" + extra + "---\n\nBody for " + slug + ".\n" } -// publishFrontmatterDrift publishes one archived done record with a REAL claim -// stamp (a repairable drop-final-claimed-at) and one with the EMPTY cleared form -// (not a finding; it must survive every repair byte-identical). +// publishFrontmatterDrift publishes one archived done record with an unquoted +// boolean-keyword title (a repairable quote-unsafe-scalar) and one with an +// EMPTY claimed_at (not a finding; it must survive every repair +// byte-identical). func (r *initRepo) publishFrontmatterDrift(t *testing.T) { t.Helper() dotDocket := filepath.Join(r.invocation, ".docket") - writeRepoFile(t, dotDocket, repairStampPath, repairArchivedRecord(3, "archived-change", "claimed_at: 2026-08-01T10:00:00Z")) - writeRepoFile(t, dotDocket, repairEmptyPath, repairArchivedRecord(4, "archived-empty", "claimed_at:")) - runGit(t, dotDocket, "add", "--", repairStampPath, repairEmptyPath) - runGit(t, dotDocket, "commit", "-q", "-m", "publish archived claim stamps") + writeRepoFile(t, dotDocket, repairQuotePath, repairArchivedRecord(3, "archived-change", "yes")) + writeRepoFile(t, dotDocket, repairEmptyPath, repairArchivedRecord(4, "archived-empty", "Change archived-empty", "claimed_at:")) + runGit(t, dotDocket, "add", "--", repairQuotePath, repairEmptyPath) + runGit(t, dotDocket, "commit", "-q", "-m", "publish archived frontmatter drift") runGit(t, dotDocket, "push", "-q", "origin", string(layout.SharedName)) } @@ -130,7 +135,7 @@ func TestIntegrationRepoRepairPreviewListsBothKindsAndWritesNothing(t *testing.T if res.SourceRevision != before { t.Errorf("SourceRevision = %q, want the pinned docket tip %q", res.SourceRevision, before) } - for _, p := range []string{"docs/changes/BOARD.md", "docs/changes/active/0001-example.md", repairStampPath} { + for _, p := range []string{"docs/changes/BOARD.md", "docs/changes/active/0001-example.md", repairQuotePath} { if !containsPath(res.RepairedFiles, p) { t.Errorf("RepairedFiles = %v, want %s", res.RepairedFiles, p) } @@ -138,10 +143,10 @@ func TestIntegrationRepoRepairPreviewListsBothKindsAndWritesNothing(t *testing.T if containsPath(res.RepairedFiles, repairEmptyPath) { t.Errorf("the empty claimed_at record must not be a repair: %v", res.RepairedFiles) } - if len(res.Repairs) != 1 || res.Repairs[0].Code != reposetup.RepairDropClaimedAt || res.Repairs[0].Path != repairStampPath { - t.Errorf("Repairs = %+v, want exactly the stamped record's drop", res.Repairs) + if len(res.Repairs) != 1 || res.Repairs[0].Code != reposetup.RepairQuoteScalar || res.Repairs[0].Path != repairQuotePath { + t.Errorf("Repairs = %+v, want exactly the unquoted title's quote", res.Repairs) } - for _, want := range []string{"--yes", "[drop-final-claimed-at] " + repairStampPath, "[board-stale] docs/changes/BOARD.md"} { + for _, want := range []string{"--yes", "[quote-unsafe-scalar] " + repairQuotePath, "[board-stale] docs/changes/BOARD.md"} { if !strings.Contains(res.HumanText(), want) { t.Errorf("preview human lacks %q:\n%s", want, res.HumanText()) } @@ -192,8 +197,8 @@ func TestIntegrationRepoRepairAppliesOneDescendantCommit(t *testing.T) { if !strings.Contains(record, "| Spec |") || !strings.Contains(record, repairAuthoredSentinel) { t.Errorf("repaired record must carry the Spec row and the untouched prose:\n%s", record) } - if stamped := showDocketFile(t, r, repairStampPath); strings.Contains(stamped, "claimed_at") { - t.Errorf("stamped archived record still carries claimed_at:\n%s", stamped) + if quoted := showDocketFile(t, r, repairQuotePath); !strings.Contains(quoted, "\ntitle: 'yes'\n") { + t.Errorf("archived record's title was not quoted:\n%s", quoted) } if got := showDocketFile(t, r, repairEmptyPath); got != emptyBefore { t.Errorf("empty claimed_at record changed:\n%s", got) @@ -534,7 +539,7 @@ func TestIntegrationRepoRepairRefusesFreshRepository(t *testing.T) { // repository. func TestIntegrationRepoRepairEmptyClaimedAtIsCleanNoOp(t *testing.T) { r := newHealthyRepo(t) - r.writeDocketFileAndPush(t, repairEmptyPath, repairArchivedRecord(4, "archived-empty", "claimed_at:"), "publish an archived record with the cleared claimed_at") + r.writeDocketFileAndPush(t, repairEmptyPath, repairArchivedRecord(4, "archived-empty", "Change archived-empty", "claimed_at:"), "publish an archived record with the cleared claimed_at") before := currentDocketTip(t, r) res := r.runRepair(t, RepairOptions{Authorized: true}) diff --git a/internal/app/repository_repair_test.go b/internal/app/repository_repair_test.go index d98d09533..f0cda3656 100644 --- a/internal/app/repository_repair_test.go +++ b/internal/app/repository_repair_test.go @@ -13,12 +13,19 @@ import ( ) // repairArchivedDone is a minimal valid ARCHIVED done record (the same shape the -// migration fixtures use) carrying the given claimed_at line. -func repairArchivedDone(claimedLine string) []byte { - return []byte("---\nid: 3\nslug: archived-change\nstatus: done\ntitle: Change archived-change\ntype: feature\n" + - claimedLine + "\n---\n\nBody for archived-change.\n") +// migration fixtures use) with the given title token and extra frontmatter lines. +func repairArchivedDone(title string, extraLines ...string) []byte { + extra := "" + for _, l := range extraLines { + extra += l + "\n" + } + return []byte("---\nid: 3\nslug: archived-change\nstatus: done\ntitle: " + title + "\ntype: feature\n" + + extra + "---\n\nBody for archived-change.\n") } +// repairArchivedTitle is the archived record's ordinary, already-safe title. +const repairArchivedTitle = "Change archived-change" + const repairArchivedPath = "docs/changes/archive/2026-01-02-0003-archived-change.md" func repairLink() render.LinkContext { @@ -68,10 +75,10 @@ func TestPlanRepositoryRepairComposesFrontmatterAndArtifactLinks(t *testing.T) { func TestPlanRepositoryRepairBoardRecomputedOverRepairedCorpus(t *testing.T) { cfg := derivedTestConfig() path, canonical := canonicalChangeRecord(t, cfg) - stamped := corpusRecord{path: repairArchivedPath, bytes: repairArchivedDone("claimed_at: 2026-08-01T10:00:00Z"), kind: repository.KindChange, location: repository.LocationArchive} + unquoted := corpusRecord{path: repairArchivedPath, bytes: repairArchivedDone("yes"), kind: repository.KindChange, location: repository.LocationArchive} active := corpusRecord{path: path, bytes: canonical, kind: repository.KindChange, location: repository.LocationActive} corpus := checkCorpus{ - records: []corpusRecord{active, stamped}, + records: []corpusRecord{active, unquoted}, link: repairLink(), board: corpusFile{present: true, bytes: []byte("# Backlog\n\nstale bytes\n")}, } @@ -81,7 +88,7 @@ func TestPlanRepositoryRepairBoardRecomputedOverRepairedCorpus(t *testing.T) { } board := boardCorpusPath(cfg) if !planHasFile(plan.files, board) || !planHasFile(plan.files, repairArchivedPath) { - t.Fatalf("files = %v, want the board and the stamped archived record", plan.files) + t.Fatalf("files = %v, want the board and the unquoted archived record", plan.files) } repairedRecs := []corpusRecord{active, {path: repairArchivedPath, bytes: plan.contents[repairArchivedPath], kind: repository.KindChange, location: repository.LocationArchive}} snap, ok := buildCorpusSnapshot(cfg, repairedRecs) @@ -95,25 +102,28 @@ func TestPlanRepositoryRepairBoardRecomputedOverRepairedCorpus(t *testing.T) { if !bytes.Equal(plan.contents[board], want) { t.Errorf("board bytes are not the canonical render over the repaired corpus") } - if bytes.Contains(plan.contents[repairArchivedPath], []byte("claimed_at")) { - t.Errorf("stamped archived record still carries claimed_at:\n%s", plan.contents[repairArchivedPath]) + if !bytes.Contains(plan.contents[repairArchivedPath], []byte("\ntitle: 'yes'\n")) { + t.Errorf("archived record's title was not quoted:\n%s", plan.contents[repairArchivedPath]) } } -// TestPlanRepositoryRepairEmptyClaimedAtIsClean proves the 269-record shape — a -// final archived record with the empty cleared claimed_at — plans nothing, while -// the same record with a real stamp (the control) plans the drop. -func TestPlanRepositoryRepairEmptyClaimedAtIsClean(t *testing.T) { +// TestPlanRepositoryRepairClaimedAtIsClean proves a final archived record +// carrying a leftover claimed_at — empty or stamped — plans nothing, while the +// same record with an unquoted boolean-keyword title (the control) plans the +// quote. +func TestPlanRepositoryRepairClaimedAtIsClean(t *testing.T) { cfg := derivedTestConfig() for _, tc := range []struct { - name, line string - wantFiles int + name string + src []byte + wantFiles int }{ - {"empty cleared form", "claimed_at:", 0}, - {"control: real stamp", "claimed_at: 2026-08-01T10:00:00Z", 1}, + {"empty cleared form", repairArchivedDone(repairArchivedTitle, "claimed_at:"), 0}, + {"leftover stamp", repairArchivedDone(repairArchivedTitle, "claimed_at: 2026-08-01T10:00:00Z"), 0}, + {"control: unquoted title", repairArchivedDone("yes"), 1}, } { t.Run(tc.name, func(t *testing.T) { - rec := corpusRecord{path: repairArchivedPath, bytes: repairArchivedDone(tc.line), kind: repository.KindChange, location: repository.LocationArchive} + rec := corpusRecord{path: repairArchivedPath, bytes: tc.src, kind: repository.KindChange, location: repository.LocationArchive} plan, err := planRepositoryRepair(setupContext{cfg: cfg}, checkCorpus{records: []corpusRecord{rec}, link: repairLink()}) if err != nil { t.Fatalf("planRepositoryRepair: %v", err) @@ -167,7 +177,7 @@ func TestPlanRepositoryRepairMalformedMarkerIsManualOnly(t *testing.T) { // repair kinds, and names --yes. func TestRepairConfirmationRequiredNamesYes(t *testing.T) { plan := repositoryRepairPlan{ - frontmatter: []reposetup.RepairFinding{{Path: repairArchivedPath, Field: "claimed_at", Code: reposetup.RepairDropClaimedAt, Repairable: true, Patch: []byte("-claimed_at: x\n")}}, + frontmatter: []reposetup.RepairFinding{{Path: repairArchivedPath, Field: "title", Code: reposetup.RepairQuoteScalar, Repairable: true, Patch: []byte("-title: x\n")}}, derived: []reposetup.DerivedFinding{{Code: reposetup.CodeBoardStale, Path: "docs/changes/BOARD.md", Repairable: true}}, files: []string{"docs/changes/BOARD.md", repairArchivedPath}, contents: map[string][]byte{}, @@ -183,7 +193,7 @@ func TestRepairConfirmationRequiredNamesYes(t *testing.T) { t.Errorf("preview sets = files %v repairs %v views %v", out.RepairedFiles, out.Repairs, out.RepairedViews) } h := out.HumanText() - for _, want := range []string{"--yes", "[drop-final-claimed-at] " + repairArchivedPath, "[board-stale] docs/changes/BOARD.md", "-claimed_at: x"} { + for _, want := range []string{"--yes", "[quote-unsafe-scalar] " + repairArchivedPath, "[board-stale] docs/changes/BOARD.md", "-title: x"} { if !strings.Contains(h, want) { t.Errorf("preview human lacks %q:\n%s", want, h) } @@ -269,7 +279,7 @@ func TestRepairFromMigrateResultRestampsOperation(t *testing.T) { // TestRepairResultJSONFieldNames pins the protocol-v1 keys. func TestRepairResultJSONFieldNames(t *testing.T) { out := repairApplied("newtip", "priortip", repositoryRepairPlan{ - frontmatter: []reposetup.RepairFinding{{Path: repairArchivedPath, Code: reposetup.RepairDropClaimedAt, Repairable: true}}, + frontmatter: []reposetup.RepairFinding{{Path: repairArchivedPath, Code: reposetup.RepairQuoteScalar, Repairable: true}}, derived: []reposetup.DerivedFinding{{Code: reposetup.CodeBoardStale, Path: "docs/changes/BOARD.md", Repairable: true}}, manual: []string{"[x] y: z"}, files: []string{"docs/changes/BOARD.md", repairArchivedPath}, @@ -304,7 +314,7 @@ func planHasFile(files []string, p string) bool { } // TestPlanRepositoryRepairBoardRendersFrontmatterRepairedRecord is the -// discriminating companion to the test above, whose claimed_at drop never changes +// discriminating companion to the test above, whose title quoting never changes // what the board renders: a scalar id-list field (`depends_on: 3`) decodes as a // malformed list with no dependency, while the repaired `[3]` decodes as a // dependency on #3, so the board rendered over the unrepaired corpus differs from @@ -315,7 +325,7 @@ func TestPlanRepositoryRepairBoardRendersFrontmatterRepairedRecord(t *testing.T) cfg := derivedTestConfig() path := "docs/changes/active/0001-example.md" listed := corpusRecord{path: path, bytes: changeRecordBytes(derivedChangeFM+"depends_on: 3\n", ""), kind: repository.KindChange, location: repository.LocationActive} - archived := corpusRecord{path: repairArchivedPath, bytes: repairArchivedDone("claimed_at:"), kind: repository.KindChange, location: repository.LocationArchive} + archived := corpusRecord{path: repairArchivedPath, bytes: repairArchivedDone(repairArchivedTitle, "claimed_at:"), kind: repository.KindChange, location: repository.LocationArchive} corpus := checkCorpus{ records: []corpusRecord{listed, archived}, link: repairLink(), diff --git a/internal/app/testdata/finding-catalog.txt b/internal/app/testdata/finding-catalog.txt index 85dfdbbc6..b982aabc5 100644 --- a/internal/app/testdata/finding-catalog.txt +++ b/internal/app/testdata/finding-catalog.txt @@ -129,11 +129,6 @@ Change 0263's file is named `0263-y.md`, but its frontmatter says `id: 0263` and Links and lookups that build the file name from the id and slug miss this record. remedy: In `.docket/docs/changes/active/0263-y.md`, make the file name and the `id:` and `slug:` fields agree; then commit and push it from `.docket`, and run `docket repository repair` so the board and link blocks catch up. -### change-final-claim-stamp — stamp (error) -Change 0001 is done but still has `claimed_at: 2026-05-01T10:00:00Z` from when it was being built. -It's harmless: nothing reads it once a change is closed. Older docket versions left it behind. -remedy: Run `docket repository repair` to remove it (it shows the edit first). Or edit it by hand: in `.docket/docs/changes/archive/2026-05-28-0001-wisdom-ai-bastion.md`, delete the `claimed_at:` line; then commit and push it from `.docket`. - ### change-id-duplicate — two (error) Change 0263's number is also used by 1 other record. docket can't tell these changes apart, so every command that names this number refuses. @@ -355,13 +350,6 @@ remedy: In `docs/changes/active/0263-x.md` on the metadata branch, remove `172` ## Frontmatter-repair findings -### drop-final-claimed-at - -- [warning] drop-final-claimed-at (docs/changes/archive/2026-05-28-0001-wisdom-ai-bastion.md) - This finished change still has a `claimed_at` timestamp from when it was being built. - It's harmless: nothing reads it once a change is closed. Older docket versions left it behind. - remedy: Run `docket repository repair` to remove it (it shows the edit first). Or edit it by hand: in `.docket/docs/changes/archive/2026-05-28-0001-wisdom-ai-bastion.md`, delete the `claimed_at:` line; then commit and push it from `.docket`. - ### quote-unsafe-scalar - [warning] quote-unsafe-scalar (docs/changes/archive/2026-05-28-0001-wisdom-ai-bastion.md) @@ -390,13 +378,6 @@ remedy: In `docs/changes/active/0263-x.md` on the metadata branch, remove `172` docket can't read it as a list, so it ignores this field. remedy: In `.docket/docs/changes/archive/2026-05-28-0001-wisdom-ai-bastion.md`, rewrite it as a list of numbers, such as `related: [12, 40]`, or delete the line; then commit and push it from `.docket`, and run `docket repository repair` so the board and link blocks catch up. -### claimed_at, not done - -- [error] frontmatter-manual-review (docs/changes/archive/2026-05-28-0001-wisdom-ai-bastion.md) - This archived change still has a `claimed_at` timestamp, but its status is `proposed`, not done or killed. - An archived change should be done or killed; docket won't remove the timestamp until the status is settled. - remedy: In `.docket/docs/changes/archive/2026-05-28-0001-wisdom-ai-bastion.md`, set `status:` to `done` or `killed` (or move the file back into `active/` if the change is still open); then commit and push it from `.docket`, and run `docket repository repair` so the board and link blocks catch up. - ### undecodable - [error] frontmatter-manual-review (docs/changes/archive/2026-05-28-0001-wisdom-ai-bastion.md) @@ -448,9 +429,6 @@ remedy: In `docs/changes/active/0263-x.md` on the metadata branch, remove `172` ### validator (change-reference-dangling) remedy: In `docs/changes/active/0263-x.md` on the metadata branch, remove `172` from `depends_on:` or correct it to the right number; then commit and push it. Once the setup finding above is resolved, run `docket repository repair` so the board and link blocks catch up. -### drop-final-claimed-at — drop-final-claimed-at -remedy: Edit it by hand: in `docs/changes/archive/2026-05-28-0001-wisdom-ai-bastion.md` on the metadata branch, delete the `claimed_at:` line; then commit and push it. Or, once the setup finding above is resolved, run `docket repository repair` to remove it (it shows the edit first). - ### quote-unsafe-scalar — quote-unsafe-scalar remedy: Edit it by hand: in `docs/changes/archive/2026-05-28-0001-wisdom-ai-bastion.md` on the metadata branch, quote the `title:` value; then commit and push it. Or, once the setup finding above is resolved, run `docket repository repair` to add the quotes (it shows the edit first). @@ -463,9 +441,6 @@ remedy: In `docs/changes/archive/2026-05-28-0001-wisdom-ai-bastion.md` on the me ### frontmatter-manual-review — non-id list remedy: In `docs/changes/archive/2026-05-28-0001-wisdom-ai-bastion.md` on the metadata branch, rewrite it as a list of numbers, such as `related: [12, 40]`, or delete the line; then commit and push it. Once the setup finding above is resolved, run `docket repository repair` so the board and link blocks catch up. -### frontmatter-manual-review — claimed_at, not done -remedy: In `docs/changes/archive/2026-05-28-0001-wisdom-ai-bastion.md` on the metadata branch, set `status:` to `done` or `killed` (or move the file back into `active/` if the change is still open); then commit and push it. Once the setup finding above is resolved, run `docket repository repair` so the board and link blocks catch up. - ### frontmatter-manual-review — undecodable remedy: In `docs/changes/archive/2026-05-28-0001-wisdom-ai-bastion.md` on the metadata branch, fix the frontmatter between the two `---` lines; then commit and push it. Once the setup finding above is resolved, run `docket repository repair` so the board and link blocks catch up. diff --git a/internal/app/validation_text.go b/internal/app/validation_text.go index b663cb077..55399795f 100644 --- a/internal/app/validation_text.go +++ b/internal/app/validation_text.go @@ -448,13 +448,6 @@ var validationTexts = map[string]validationExplainer{ Remedy: handEdit(f, loc, "rename the file to start with the date it was archived, such as `2026-05-28-`"), } }, - repository.CodeChangeFinalClaimStamp: func(f domain.Finding, loc reposetup.RecordLocator) findingText { - return findingText{ - Message: fmt.Sprintf("%s is %s but still has `claimed_at: %s` from when it was being built.", subjectOf(f.Entity), f.Detail["status"], f.Detail["raw"]), - Impact: "It's harmless: nothing reads it once a change is closed. Older docket versions left it behind.", - Remedy: loc.RepairOrHandEdit("remove it", "delete the `claimed_at:` line", validationRecordPath(f)), - } - }, repository.CodeChangeStateIncoherent: func(f domain.Finding, loc reposetup.RecordLocator) findingText { status := f.Detail["status"] return findingText{ diff --git a/internal/app/validation_text_test.go b/internal/app/validation_text_test.go index c27ca0d42..65b294bcd 100644 --- a/internal/app/validation_text_test.go +++ b/internal/app/validation_text_test.go @@ -245,10 +245,6 @@ func validationFixtures() map[string][]validationFixture { {"date", f(repository.CodeChangeArchiveDateInvalid, E, domain.EntityRef{Kind: domain.EntityChange, ID: 263, Slug: "x", Path: "docs/changes/archive/0263-x.md"}, "path", map[string]string{"base": "0263-x.md"})}, }, - repository.CodeChangeFinalClaimStamp: { - {"stamp", f(repository.CodeChangeFinalClaimStamp, E, fxArchived(1, "wisdom-ai-bastion"), "claimed_at", - map[string]string{"raw": "2026-05-01T10:00:00Z", "status": "done"})}, - }, repository.CodeChangeStateIncoherent: { {"missing", f(repository.CodeChangeStateIncoherent, E, fxChange(263, "x"), "branch", map[string]string{"status": "in-progress"})}, }, diff --git a/internal/document/document.go b/internal/document/document.go index 30f4e3428..c3e4e6b6a 100644 --- a/internal/document/document.go +++ b/internal/document/document.go @@ -295,9 +295,8 @@ func (d Document) Field(name string) (Field, bool) { // empty here. node is the caller's own parsed node for the entry, nil when the // YAML tree has none; located/locatedOK are Field's results for the same key. // -// The repository decoder's FieldEmpty classification and reposetup's -// claimed_at planner both decide through this one function, so the planner and -// the snapshot validator cannot drift apart on what "no stamp" means (0496). +// The repository decoder's FieldEmpty classification decides through this +// function. func EmptyValue(located Field, locatedOK bool, node *yaml.Node) bool { if locatedOK && located.Shape == ShapeEmpty { return true diff --git a/internal/document/empty_value_test.go b/internal/document/empty_value_test.go index ce7f3fdce..d0339c4c6 100644 --- a/internal/document/empty_value_test.go +++ b/internal/document/empty_value_test.go @@ -6,11 +6,10 @@ import ( "go.yaml.in/yaml/v3" ) -// TestEmptyValueSpellings pins the one empty-value rule shared by the -// repository decoder's FieldEmpty classification and reposetup's claimed_at -// planner (change 0496): every empty spelling is empty, every non-empty value — -// including a collection — is not, and an undecoded entry (nil node) falls back -// to the located shape alone. Mutation probe: drop any clause of EmptyValue +// TestEmptyValueSpellings pins the one empty-value rule the repository +// decoder's FieldEmpty classification uses: every empty spelling is empty, +// every non-empty value — including a collection — is not, and an undecoded +// entry (nil node) falls back to the located shape alone. Mutation probe: drop any clause of EmptyValue // (the ShapeEmpty check, the !!null tag check, or the empty-string check) and // the matching subtests redden. func TestEmptyValueSpellings(t *testing.T) { diff --git a/internal/reposetup/findingtext_test.go b/internal/reposetup/findingtext_test.go index 51b4c06ea..e49565e96 100644 --- a/internal/reposetup/findingtext_test.go +++ b/internal/reposetup/findingtext_test.go @@ -50,15 +50,15 @@ func TestRecordLocatorEmptyRelNamesNoFile(t *testing.T) { if got != want { t.Errorf("HandEditThenRepair(empty rel):\n got %q\nwant %q", got, want) } - got = RecordLocator{Checkout: ".docket"}.RepairOrHandEdit("remove it", "delete the `claimed_at:` line", "") + got = RecordLocator{Checkout: ".docket"}.RepairOrHandEdit("add the quotes", "quote the `title:` value", "") if strings.Contains(got, "push it") || !strings.Contains(got, "commit and push the edited records") { t.Errorf("RepairOrHandEdit(empty rel) = %q", got) } } func TestRecordLocatorRepairOrHandEdit(t *testing.T) { - got := RecordLocator{Checkout: ".docket"}.RepairOrHandEdit("remove it", "delete the `claimed_at:` line", locatorRel) - want := "Run `docket repository repair` to remove it (it shows the edit first). Or edit it by hand: in `.docket/" + locatorRel + "`, delete the `claimed_at:` line; then commit and push it from `.docket`." + got := RecordLocator{Checkout: ".docket"}.RepairOrHandEdit("add the quotes", "quote the `title:` value", locatorRel) + want := "Run `docket repository repair` to add the quotes (it shows the edit first). Or edit it by hand: in `.docket/" + locatorRel + "`, quote the `title:` value; then commit and push it from `.docket`." if got != want { t.Errorf("RepairOrHandEdit:\n got %q\nwant %q", got, want) } @@ -74,8 +74,8 @@ func TestRecordLocatorSetupBlocked(t *testing.T) { "In `" + locatorRel + "` on the metadata branch, remove `172` from `depends_on`; then commit and push it. Once the setup finding above is resolved, run `docket repository repair` so the board and link blocks catch up."}, {"hand edit, several records", loc.HandEditThenRepair(locatorInstr, ""), "Remove `172` from `depends_on`; then commit and push the edited records. Once the setup finding above is resolved, run `docket repository repair` so the board and link blocks catch up."}, - {"repair or hand edit", loc.RepairOrHandEdit("remove it", "delete the `claimed_at:` line", locatorRel), - "Edit it by hand: in `" + locatorRel + "` on the metadata branch, delete the `claimed_at:` line; then commit and push it. Or, once the setup finding above is resolved, run `docket repository repair` to remove it (it shows the edit first)."}, + {"repair or hand edit", loc.RepairOrHandEdit("add the quotes", "quote the `title:` value", locatorRel), + "Edit it by hand: in `" + locatorRel + "` on the metadata branch, quote the `title:` value; then commit and push it. Or, once the setup finding above is resolved, run `docket repository repair` to add the quotes (it shows the edit first)."}, {"run repair", loc.RunRepair(" to regenerate it"), "Once the setup finding above is resolved, run `docket repository repair` to regenerate it."}, {"run repair, healthy", RecordLocator{Checkout: ".docket"}.RunRepair(""), diff --git a/internal/reposetup/repair.go b/internal/reposetup/repair.go index 93af3fce3..a524b17cc 100644 --- a/internal/reposetup/repair.go +++ b/internal/reposetup/repair.go @@ -11,7 +11,7 @@ package reposetup // fails one of those gates is reported as a NON-repairable finding, never // silently repaired. // -// The three roster entries are: +// The two roster entries are: // // quote-unsafe-scalar a plain string scalar whose decoded text is an // unambiguous string but whose token SHAPE violates the @@ -22,9 +22,6 @@ package reposetup // parses as an exact valid sequence of the item type — // re-emitted as an UNQUOTED flow sequence, same items, // same order. -// drop-final-claimed-at a NON-EMPTY claimed_at removed from an -// already-final (done/killed) archived change; an empty -// claimed_at is the cleared form and is never a finding. // // Byte edits are produced by internal/document's own PatchSet/serializer, so // YAML validity and the reparse gate are construction properties, not hopes. @@ -39,7 +36,6 @@ import ( "strings" "github.com/danielhanold/docket/internal/document" - "github.com/danielhanold/docket/internal/domain" "go.yaml.in/yaml/v3" ) @@ -48,9 +44,8 @@ import ( type RepairCode string const ( - RepairQuoteScalar RepairCode = "quote-unsafe-scalar" - RepairScalarToList RepairCode = "scalar-to-list" - RepairDropClaimedAt RepairCode = "drop-final-claimed-at" + RepairQuoteScalar RepairCode = "quote-unsafe-scalar" + RepairScalarToList RepairCode = "scalar-to-list" ) // RepairFinding is one diagnosis about a single change record. A repairable @@ -125,11 +120,10 @@ var changeStringFields = map[string]bool{ // non-repairable findings for the shapes it can name but must not touch. An // undecodable frontmatter block (including a duplicate key, which document.Parse // rejects) yields a single non-repairable finding naming the whole record. -// archived enables RepairDropClaimedAt, and only for a final-status record. // Every finding carries the three plain-language parts — Message, Impact, and // Remedy — and loc names where the record is really edited in the remedy; the // text never feeds RepairDigest or ApplyRepairs. -func PlanRepairs(path string, src []byte, archived bool, loc RecordLocator) ([]RepairFinding, error) { +func PlanRepairs(path string, src []byte, loc RecordLocator) ([]RepairFinding, error) { doc, err := document.Parse(src) if err != nil { return []RepairFinding{{ @@ -157,9 +151,6 @@ func PlanRepairs(path string, src []byte, archived bool, loc RecordLocator) ([]R } } } - if fnd, ok := planClaimedAt(path, src, doc, archived, loc); ok { - findings = append(findings, fnd) - } return findings, nil } @@ -243,102 +234,6 @@ func planList(path string, src []byte, doc document.Document, f document.Field, }, true } -// planClaimedAt decides the drop-final-claimed-at roster entry. An EMPTY -// claimed_at (the bare null closeout's clearClaimedAt writes, or any other -// spelling the decode layer reads as FieldEmpty) is not a claim stamp and is -// never a finding — the snapshot validator raises CodeChangeFinalClaimStamp only -// for FieldPresent, and this planner agrees (change 0496). -func planClaimedAt(path string, src []byte, doc document.Document, archived bool, loc RecordLocator) (RepairFinding, bool) { - f, ok := doc.Field("claimed_at") - if !ok { - return RepairFinding{}, false - } - if !claimedAtHoldsValue(doc, f) { - return RepairFinding{}, false - } - if !archived { - // An active record legitimately holds a claim lease; leave it alone. - return RepairFinding{}, false - } - if !finalStatus(doc) { - statusText := "it has no `status:`, so it is not done or killed" - if st := rawStatus(doc); st != "" { - statusText = "its status is `" + st + "`, not done or killed" - } - return RepairFinding{ - Path: path, - Field: "claimed_at", - Repairable: false, - Message: "This archived change still has a `claimed_at` timestamp, but " + statusText + ".", - Impact: "An archived change should be done or killed; docket won't remove the timestamp until the status is settled.", - Remedy: loc.HandEditThenRepair("set `status:` to `done` or `killed` (or move the file back into `active/` if the change is still open)", path), - }, true - } - _, preview, err := buildRepair(doc, src, RepairDropClaimedAt, "claimed_at") - if err != nil { - return RepairFinding{}, false - } - return RepairFinding{ - Path: path, - Field: "claimed_at", - Code: RepairDropClaimedAt, - Repairable: true, - Message: "This finished change still has a `claimed_at` timestamp from when it was being built.", - Impact: "It's harmless: nothing reads it once a change is closed. Older docket versions left it behind.", - Remedy: loc.RepairOrHandEdit("remove it", "delete the `claimed_at:` line", path), - Patch: preview, - }, true -} - -// claimedAtHoldsValue reports whether the located claimed_at entry carries a -// value. It decides through document.EmptyValue, the same empty-value rule the -// decode layer's (*decoder).state uses to classify FieldEmpty, so the planner -// and the snapshot validator cannot drift: a valueless key, a YAML null (`null`, -// `~`), and an empty string are no stamp; anything else — a timestamp, a -// malformed non-empty value, a collection — holds a value. An undecodable -// frontmatter block is judged on the located shape alone, failing toward -// "holds a value", which keeps the pre-0496 finding rather than hiding one. -func claimedAtHoldsValue(doc document.Document, f document.Field) bool { - var node *yaml.Node - var m map[string]yaml.Node - if err := doc.DecodeFrontmatter(&m); err == nil { - n, ok := m["claimed_at"] - if !ok { - return false - } - node = &n - } - return !document.EmptyValue(f, true, node) -} - -// finalStatus reports whether the record's decoded status is a final end -// state (done or killed). -func finalStatus(doc document.Document) bool { - var head struct { - Status string `yaml:"status"` - } - if err := doc.DecodeFrontmatter(&head); err != nil { - return false - } - st, ok := domain.ParseStatus(head.Status) - return ok && st.Final() -} - -// rawStatus returns the record's status as written, for wording a finding -// only — never for a decision (finalStatus decides). It decodes status exactly -// as finalStatus does and returns "" when the status is empty or the -// frontmatter cannot be decoded, so the caller words that case as absent -// rather than quoting a placeholder as if it were stored. -func rawStatus(doc document.Document) string { - var head struct { - Status string `yaml:"status"` - } - if err := doc.DecodeFrontmatter(&head); err != nil { - return "" - } - return head.Status -} - // booleanKeywords are the scalar spellings the house rule requires quoting // because a YAML 1.1 reader would coerce them to booleans. var booleanKeywords = map[string]bool{ @@ -491,19 +386,6 @@ func buildRepair(doc document.Document, src []byte, code RepairCode, field strin } return cand, diffPreview(field, oldToken, tokenOf(cand, field)), nil - case RepairDropClaimedAt: - if field != "claimed_at" { - return nil, nil, fmt.Errorf("reposetup: drop applies only to claimed_at") - } - cand := spliceOut(src, f.Entry) - if _, perr := document.Parse(cand); perr != nil { - return nil, nil, fmt.Errorf("reposetup: claimed_at removal did not reparse: %w", perr) - } - if fieldStillPresent(cand, "claimed_at") { - return nil, nil, fmt.Errorf("reposetup: claimed_at still present after removal") - } - return cand, []byte("-" + field + ": " + oldToken + "\n"), nil - default: return nil, nil, fmt.Errorf("reposetup: unknown repair code %q", code) } @@ -592,24 +474,6 @@ func decodedString(candidate []byte, field string) (string, bool) { return s, true } -// fieldStillPresent reports whether field survives in candidate's frontmatter. -func fieldStillPresent(candidate []byte, field string) bool { - cdoc, err := document.Parse(candidate) - if err != nil { - return true // fail closed: an unreadable candidate is not proof of removal - } - _, ok := cdoc.Field(field) - return ok -} - -// spliceOut returns src with the half-open byte range span removed. -func spliceOut(src []byte, span document.Span) []byte { - out := make([]byte, 0, len(src)-(span.End-span.Start)) - out = append(out, src[:span.Start]...) - out = append(out, src[span.End:]...) - return out -} - // ApplyRepairs applies the given repairable findings to src and returns the // repaired bytes. Each finding is re-derived from the current bytes and its // preview is compared against the stored patch, so a tampered finding is diff --git a/internal/reposetup/repair_test.go b/internal/reposetup/repair_test.go index 5e23ae398..2df15c119 100644 --- a/internal/reposetup/repair_test.go +++ b/internal/reposetup/repair_test.go @@ -11,9 +11,9 @@ import ( // planOne runs PlanRepairs and returns the findings; it fails the test on a // non-nil error, which the roster never produces for a well-formed call. -func planOne(t *testing.T, path string, src string, archived bool) []RepairFinding { +func planOne(t *testing.T, path string, src string) []RepairFinding { t.Helper() - fs, err := PlanRepairs(path, []byte(src), archived, RecordLocator{}) + fs, err := PlanRepairs(path, []byte(src), RecordLocator{}) if err != nil { t.Fatalf("PlanRepairs(%q) unexpected error: %v", path, err) } @@ -65,7 +65,7 @@ func TestRepairQuoteScalarEligible(t *testing.T) { } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - fs := planOne(t, "docs/changes/active/0001-x.md", tc.src, false) + fs := planOne(t, "docs/changes/active/0001-x.md", tc.src) f := repairableWithCode(t, fs, RepairQuoteScalar) if f.Field != "title" { t.Fatalf("Field = %q, want title", f.Field) @@ -93,7 +93,7 @@ func TestRepairQuoteScalarRefused(t *testing.T) { } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - fs := planOne(t, "docs/changes/active/0001-x.md", tc.src, false) + fs := planOne(t, "docs/changes/active/0001-x.md", tc.src) if hasRepairableCode(fs, RepairQuoteScalar) { t.Fatalf("expected no repairable quote finding, got %+v", fs) } @@ -120,7 +120,7 @@ func TestRepairScalarToListEligible(t *testing.T) { } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - fs := planOne(t, "docs/changes/active/0001-x.md", tc.src, false) + fs := planOne(t, "docs/changes/active/0001-x.md", tc.src) f := repairableWithCode(t, fs, RepairScalarToList) if f.Field != "depends_on" { t.Fatalf("Field = %q, want depends_on", f.Field) @@ -147,7 +147,7 @@ func TestRepairScalarToListRefused(t *testing.T) { } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - fs := planOne(t, "docs/changes/active/0001-x.md", tc.src, false) + fs := planOne(t, "docs/changes/active/0001-x.md", tc.src) if hasRepairableCode(fs, RepairScalarToList) { t.Fatalf("expected no repairable list finding, got %+v", fs) } @@ -155,92 +155,11 @@ func TestRepairScalarToListRefused(t *testing.T) { } } -func TestRepairDropClaimedAtEligible(t *testing.T) { - cases := []struct { - name string - src string - want string - }{ - { - name: "done record", - src: "---\nid: 7\nstatus: done\nclaimed_at: 2026-08-01T10:00:00Z\n---\nbody\n", - want: "---\nid: 7\nstatus: done\n---\nbody\n", - }, - { - name: "killed record", - src: "---\nid: 7\nclaimed_at: 2026-08-01T10:00:00Z\nstatus: killed\n---\nbody\n", - want: "---\nid: 7\nstatus: killed\n---\nbody\n", - }, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - fs := planOne(t, "docs/changes/archive/2026-08-01-0007-x.md", tc.src, true) - f := repairableWithCode(t, fs, RepairDropClaimedAt) - if f.Field != "claimed_at" { - t.Fatalf("Field = %q, want claimed_at", f.Field) - } - out, err := ApplyRepairs([]byte(tc.src), fs) - if err != nil { - t.Fatalf("ApplyRepairs: %v", err) - } - if string(out) != tc.want { - t.Fatalf("ApplyRepairs =\n%q\nwant\n%q", out, tc.want) - } - }) - } -} - -func TestRepairDropClaimedAtRefused(t *testing.T) { - cases := []struct { - name string - src string - archived bool - }{ - // Mutation-probe target: the final-status check refuses this. - {"non-final archived record", "---\nid: 7\nstatus: in-progress\nclaimed_at: 2026-08-01T10:00:00Z\n---\nbody\n", true}, - // An active (unarchived) record legitimately holds a claim lease. - {"active unarchived record", "---\nid: 7\nstatus: done\nclaimed_at: 2026-08-01T10:00:00Z\n---\nbody\n", false}, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - fs := planOne(t, "docs/changes/x.md", tc.src, tc.archived) - if hasRepairableCode(fs, RepairDropClaimedAt) { - t.Fatalf("expected no repairable drop finding, got %+v", fs) - } - }) - } -} - -// TestRepairClaimedAtUnsettledStatusWording pins that an absent status is -// worded as absent, never quoted as if `missing` were the stored value. -func TestRepairClaimedAtUnsettledStatusWording(t *testing.T) { - cases := []struct{ name, src, want, never string }{ - {"stored status", "---\nid: 7\nstatus: in-progress\nclaimed_at: 2026-08-01T10:00:00Z\n---\nbody\n", - "its status is `in-progress`, not done or killed", ""}, - {"no status", "---\nid: 7\nclaimed_at: 2026-08-01T10:00:00Z\n---\nbody\n", - "it has no `status:`", "`missing`"}, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - fs := planOne(t, "docs/changes/archive/2026-05-28-0007-x.md", tc.src, true) - var msg string - for _, f := range fs { - if f.Field == "claimed_at" { - msg = f.Message - } - } - if !strings.Contains(msg, tc.want) || (tc.never != "" && strings.Contains(msg, tc.never)) { - t.Errorf("Message = %q, want it to contain %q", msg, tc.want) - } - }) - } -} - func TestRepairUndecodableSingleFinding(t *testing.T) { // Duplicate key: document.Parse rejects it, so the whole record is named // once as non-repairable rather than partially repaired. src := "---\nid: 7\nid: 8\n---\nbody\n" - fs := planOne(t, "docs/changes/active/0001-x.md", src, false) + fs := planOne(t, "docs/changes/active/0001-x.md", src) if len(fs) != 1 { t.Fatalf("want exactly one finding, got %d: %+v", len(fs), fs) } @@ -254,7 +173,7 @@ func TestRepairUndecodableSingleFinding(t *testing.T) { func TestApplyRepairsTamperedPatchErrors(t *testing.T) { src := "---\nid: 7\ntitle: yes\n---\nbody\n" - fs := planOne(t, "docs/changes/active/0001-x.md", src, false) + fs := planOne(t, "docs/changes/active/0001-x.md", src) f := repairableWithCode(t, fs, RepairQuoteScalar) // Tamper the preview so it no longer matches the canonical repair. tampered := f @@ -270,8 +189,8 @@ func TestApplyRepairsTamperedPatchErrors(t *testing.T) { func TestRepairDigestStableAndSensitive(t *testing.T) { srcA := "---\nid: 7\ntitle: yes\n---\nbody\n" srcB := "---\nid: 7\ndepends_on: 3\n---\nbody\n" - a := planOne(t, "a.md", srcA, false) - b := planOne(t, "b.md", srcB, false) + a := planOne(t, "a.md", srcA) + b := planOne(t, "b.md", srcB) // Stable across runs. if RepairDigest(a) != RepairDigest(a) { @@ -304,7 +223,7 @@ func TestRepairDigestStableAndSensitive(t *testing.T) { // scalar blocked_by must never be converted to a flow sequence. func TestRepairListFieldRosterExcludesBlockedBy(t *testing.T) { src := "---\nid: 7\nblocked_by: 3\n---\nbody\n" - fs := planOne(t, "docs/changes/active/0001-x.md", src, false) + fs := planOne(t, "docs/changes/active/0001-x.md", src) if hasRepairableCode(fs, RepairScalarToList) { t.Fatalf("blocked_by must not be list-converted: %+v", fs) } @@ -390,7 +309,7 @@ func TestRepairWellFormedQuotedScalarNoFinding(t *testing.T) { } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - if fs := planOne(t, "docs/changes/active/0001-x.md", tc.src, false); len(fs) != 0 { + if fs := planOne(t, "docs/changes/active/0001-x.md", tc.src); len(fs) != 0 { t.Fatalf("want no findings for a well-formed quoted scalar, got %+v", fs) } }) @@ -402,7 +321,7 @@ func TestRepairWellFormedQuotedScalarNoFinding(t *testing.T) { // malformed quoting still yields a non-empty (undecodable-record) finding. func TestRepairBareScalarsKeepTheirVerdict(t *testing.T) { t.Run("bare true stays manual review", func(t *testing.T) { - fs := planOne(t, "docs/changes/active/0001-x.md", "---\nid: 7\ntitle: true\n---\nbody\n", false) + fs := planOne(t, "docs/changes/active/0001-x.md", "---\nid: 7\ntitle: true\n---\nbody\n") if len(fs) != 1 { t.Fatalf("want exactly one finding, got %d: %+v", len(fs), fs) } @@ -416,7 +335,7 @@ func TestRepairBareScalarsKeepTheirVerdict(t *testing.T) { "---\nid: 7\ntitle: 'a' b\n---\nbody\n", // trailing content } { t.Run(fmt.Sprintf("malformed %q", src), func(t *testing.T) { - fs := planOne(t, "docs/changes/active/0001-x.md", src, false) + fs := planOne(t, "docs/changes/active/0001-x.md", src) if len(fs) == 0 { t.Fatalf("malformed quoting must not be silently accepted; got no findings") } @@ -494,79 +413,32 @@ func assertParity(t *testing.T, path string, rec []byte, s string) { if !bytes.Contains(rec, []byte("\ntitle: '")) { t.Fatalf("writer did not single-quote the title; parity row is vacuous:\n%s", rec) } - if fs := planOne(t, path, string(rec), false); len(fs) != 0 { + if fs := planOne(t, path, string(rec)); len(fs) != 0 { t.Fatalf("checker disagrees with writer for %q: %+v\n%s", s, fs, rec) } } -// TestRepairDropClaimedAtSpelling pins ADR-0129 row 58 (change 0474). -func TestRepairDropClaimedAtSpelling(t *testing.T) { - if got := string(RepairDropClaimedAt); got != "drop-final-claimed-at" { - t.Errorf("RepairDropClaimedAt = %q, want drop-final-claimed-at", got) - } -} - -// TestRepairDropClaimedAtEmptyValueIsNoStamp pins change 0496: an EMPTY claimed_at -// is docket's deliberate cleared form (closeout's clearClaimedAt writes the bare -// null), and the decode layer reads every empty spelling as FieldEmpty — "no -// stamp". planClaimedAt must agree: no finding at all (neither repairable nor -// manual review), for every empty spelling, on final AND non-final archived -// records. Mutation probe: delete the claimedAtHoldsValue gate in planClaimedAt — -// every subtest here must redden. -func TestRepairDropClaimedAtEmptyValueIsNoStamp(t *testing.T) { - spellings := []struct{ name, line string }{ - {"bare key", "claimed_at:"}, - {"bare key trailing space", "claimed_at: "}, - {"single-quoted empty", "claimed_at: ''"}, - {"double-quoted empty", `claimed_at: ""`}, - {"null keyword", "claimed_at: null"}, - {"tilde", "claimed_at: ~"}, - } - for _, sp := range spellings { - for _, status := range []string{"done", "killed", "in-progress"} { - t.Run(sp.name+"/"+status, func(t *testing.T) { - src := "---\nid: 7\nstatus: " + status + "\n" + sp.line + "\n---\nbody\n" - fs := planOne(t, "docs/changes/archive/2026-08-01-0007-x.md", src, true) - for _, f := range fs { - if f.Field == "claimed_at" { - t.Fatalf("empty claimed_at (%q) on a %s archived record must yield no finding, got %+v", sp.line, status, f) - } - } - }) - } - } -} - -// TestRepairDropClaimedAtNonEmptyUnchanged proves the empty-value gate leaves every -// NON-empty value on the existing path: a timestamp and a malformed non-empty -// value on a final archived record still yield the repairable drop with the -// unchanged patch preview; a timestamp on a non-final archived record is still a -// manual-review finding. -func TestRepairDropClaimedAtNonEmptyUnchanged(t *testing.T) { - for _, tc := range []struct{ name, value string }{ - {"timestamp", "2026-08-01T10:00:00Z"}, - {"malformed non-empty", "not-a-timestamp"}, +// TestPlanRepairsIgnoresClaimedAt pins that the repair planner never reports a +// leftover claim stamp, whatever the record's status or placement. +func TestPlanRepairsIgnoresClaimedAt(t *testing.T) { + for _, tc := range []struct{ name, path, src string }{ + {"archived done", "docs/changes/archive/2026-08-01-0007-x.md", + "---\nid: 7\nstatus: done\nclaimed_at: 2026-08-01T10:00:00Z\n---\nbody\n"}, + {"archived proposed", "docs/changes/archive/2026-08-01-0007-x.md", + "---\nid: 7\nstatus: proposed\nclaimed_at: 2026-08-01T10:00:00Z\n---\nbody\n"}, + {"active in-progress", "docs/changes/active/0007-x.md", + "---\nid: 7\nstatus: in-progress\nclaimed_at: 2026-08-01T10:00:00Z\n---\nbody\n"}, } { t.Run(tc.name, func(t *testing.T) { - src := "---\nid: 7\nstatus: done\nclaimed_at: " + tc.value + "\n---\nbody\n" - fs := planOne(t, "docs/changes/archive/2026-08-01-0007-x.md", src, true) - f := repairableWithCode(t, fs, RepairDropClaimedAt) - if want := "-claimed_at: " + tc.value + "\n"; string(f.Patch) != want { - t.Errorf("Patch = %q, want %q (preview must be unchanged)", f.Patch, want) + fs, err := PlanRepairs(tc.path, []byte(tc.src), RecordLocator{}) + if err != nil { + t.Fatalf("PlanRepairs: %v", err) + } + for _, f := range fs { + if f.Field == "claimed_at" { + t.Fatalf("unexpected claimed_at finding: %+v", f) + } } }) } - t.Run("non-final timestamp is manual review", func(t *testing.T) { - src := "---\nid: 7\nstatus: in-progress\nclaimed_at: 2026-08-01T10:00:00Z\n---\nbody\n" - fs := planOne(t, "docs/changes/archive/2026-08-01-0007-x.md", src, true) - var got *RepairFinding - for i := range fs { - if fs[i].Field == "claimed_at" { - got = &fs[i] - } - } - if got == nil || got.Repairable { - t.Fatalf("non-final archived timestamp must stay a manual-review finding, got %+v", fs) - } - }) } diff --git a/internal/reposetup/repair_text_test.go b/internal/reposetup/repair_text_test.go index e83f63fd5..566dc4fa5 100644 --- a/internal/reposetup/repair_text_test.go +++ b/internal/reposetup/repair_text_test.go @@ -23,22 +23,19 @@ func TestRepairFindingsCarryThreeParts(t *testing.T) { cases := []struct { name string src string - archived bool field string // "" selects the whole-record finding repairable bool msg string }{ - {"drop-final-claimed-at", fm("claimed_at: 2026-05-20T10:00:00Z\n"), true, "claimed_at", true, "`claimed_at`"}, - {"quote-unsafe-scalar", strings.Replace(fm(""), "title: T", "title: yes", 1), false, "title", true, "`title: yes`"}, - {"scalar-to-list", fm("depends_on: 3, 4\n"), false, "depends_on", true, "`depends_on: 3, 4`"}, - {"ambiguous value", strings.Replace(fm(""), "title: T", "title: true", 1), false, "title", false, "`title: true`"}, - {"non-id list", fm("related: foo\n"), false, "related", false, "`related: foo`"}, - {"claimed_at not done", strings.Replace(fm("claimed_at: 2026-05-20T10:00:00Z\n"), "status: done", "status: proposed", 1), true, "claimed_at", false, "`proposed`"}, - {"undecodable", "---\nid: 1\nid: 2\n---\nbody\n", false, "", false, "frontmatter"}, + {"quote-unsafe-scalar", strings.Replace(fm(""), "title: T", "title: yes", 1), "title", true, "`title: yes`"}, + {"scalar-to-list", fm("depends_on: 3, 4\n"), "depends_on", true, "`depends_on: 3, 4`"}, + {"ambiguous value", strings.Replace(fm(""), "title: T", "title: true", 1), "title", false, "`title: true`"}, + {"non-id list", fm("related: foo\n"), "related", false, "`related: foo`"}, + {"undecodable", "---\nid: 1\nid: 2\n---\nbody\n", "", false, "frontmatter"}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - fs, err := PlanRepairs(rel, []byte(tc.src), tc.archived, loc) + fs, err := PlanRepairs(rel, []byte(tc.src), loc) if err != nil { t.Fatalf("PlanRepairs: %v", err) } @@ -75,26 +72,3 @@ func TestRepairFindingsCarryThreeParts(t *testing.T) { }) } } - -// TestDropFinalClaimedAtText pins the spec's worked example byte for byte. -func TestDropFinalClaimedAtText(t *testing.T) { - rel := "docs/changes/archive/2026-05-28-0001-wisdom-ai-bastion.md" - src := "---\nid: 1\nslug: wisdom-ai-bastion\nstatus: done\ntitle: T\ntype: feature\nclaimed_at: 2026-05-20T10:00:00Z\n---\n\nBody.\n" - fs, err := PlanRepairs(rel, []byte(src), true, RecordLocator{Checkout: ".docket"}) - if err != nil || len(fs) != 1 { - t.Fatalf("PlanRepairs = %+v, %v; want one finding", fs, err) - } - f := fs[0] - wantMsg := "This finished change still has a `claimed_at` timestamp from when it was being built." - wantImpact := "It's harmless: nothing reads it once a change is closed. Older docket versions left it behind." - wantRemedy := "Run `docket repository repair` to remove it (it shows the edit first). Or edit it by hand: in `.docket/" + rel + "`, delete the `claimed_at:` line; then commit and push it from `.docket`." - if f.Message != wantMsg { - t.Errorf("message:\n got %q\nwant %q", f.Message, wantMsg) - } - if f.Impact != wantImpact { - t.Errorf("impact:\n got %q\nwant %q", f.Impact, wantImpact) - } - if f.Remedy != wantRemedy { - t.Errorf("remedy:\n got %q\nwant %q", f.Remedy, wantRemedy) - } -} diff --git a/internal/repository/decode.go b/internal/repository/decode.go index fc927ba8d..bce3d1aee 100644 --- a/internal/repository/decode.go +++ b/internal/repository/decode.go @@ -189,8 +189,8 @@ func (d *decoder) malformedWarning(field, raw string) { } // state classifies how a captured scalar appeared. FieldEmpty is decided by -// document.EmptyValue — the one empty-value rule reposetup's claimed_at planner -// shares — over the located frontmatter entry and the parsed node, so a key the +// document.EmptyValue, docket's one empty-value rule, over the located +// frontmatter entry and the parsed node, so a key the // YAML tree resolves to null and a key the byte locator sees as valueless agree. // // FieldMalformed here means only "written as something other than a scalar"; diff --git a/internal/repository/validate.go b/internal/repository/validate.go index a32d8fbe0..1e4482fff 100644 --- a/internal/repository/validate.go +++ b/internal/repository/validate.go @@ -45,9 +45,6 @@ const ( // CodeChangeArchiveDateInvalid marks an archived record whose filename // carries no usable YYYY-MM-DD prefix. CodeChangeArchiveDateInvalid = "change-archive-date-invalid" - // CodeChangeFinalClaimStamp marks an archived record that still - // carries a claim stamp — a lease nothing can ever release. - CodeChangeFinalClaimStamp = "change-final-claim-stamp" // CodeChangeStateIncoherent marks a lifecycle state missing a fact the // state itself guarantees. Field names the missing fact. CodeChangeStateIncoherent = "change-state-incoherent" @@ -251,10 +248,6 @@ func changePlacement(c domain.Change) []domain.Finding { findings = append(findings, finding(CodeChangeArchiveDateInvalid, domain.SeverityError, ref, "path", map[string]string{"base": path.Base(c.Path())})) } - if final && c.ClaimedAt().State == domain.FieldPresent { - findings = append(findings, finding(CodeChangeFinalClaimStamp, domain.SeverityError, ref, "claimed_at", - map[string]string{"raw": c.ClaimedAt().Raw, "status": string(c.Status())})) - } } return findings } @@ -268,7 +261,7 @@ func changeCoherence(c domain.Change) []domain.Finding { var missing []string switch c.Status() { case domain.StatusInProgress: - missing = append(missing, claimFacts(c)...) + missing = append(missing, branchFacts(c)...) case domain.StatusBlocked: if !present(c.BlockedBy()) { missing = append(missing, "blocked_by") @@ -289,22 +282,20 @@ func changeCoherence(c domain.Change) []domain.Finding { return findings } -// claimFacts names the claim facts a held lease requires. -func claimFacts(c domain.Change) []string { +// branchFacts names the facts a claimed change carries: the branch its work +// lives on. +func branchFacts(c domain.Change) []string { var missing []string if !present(c.Branch()) { missing = append(missing, "branch") } - if c.ClaimedAt().State != domain.FieldPresent { - missing = append(missing, "claimed_at") - } return missing } -// implementedFacts names the facts an implemented record carries: the claim -// facts plus the delivery evidence. +// implementedFacts names the facts an implemented record carries: the branch +// plus the delivery evidence. func implementedFacts(c domain.Change) []string { - missing := claimFacts(c) + missing := branchFacts(c) if !present(c.Plan()) { missing = append(missing, "plan") } diff --git a/internal/repository/validate_test.go b/internal/repository/validate_test.go index 38f9c3330..bfdfc373b 100644 --- a/internal/repository/validate_test.go +++ b/internal/repository/validate_test.go @@ -179,15 +179,6 @@ func TestValidateSingleSnapshot(t *testing.T) { field: "path", entity: changeEntity(42, "widget", "docs/changes/archive/0042-widget.md"), }, - { - name: "archived final record still holding a claim stamp", - docs: []InputDocument{record(t, KindChange, LocationArchive, archivePath, - minimalChange(42, "widget", "done", "claimed_at: 2026-08-01T10:00:00Z"))}, - code: CodeChangeFinalClaimStamp, - severity: domain.SeverityError, - field: "claimed_at", - entity: changeEntity(42, "widget", archivePath), - }, { name: "in-progress without a branch", docs: []InputDocument{record(t, KindChange, LocationActive, activePath, @@ -197,15 +188,6 @@ func TestValidateSingleSnapshot(t *testing.T) { field: "branch", entity: changeEntity(42, "widget", activePath), }, - { - name: "in-progress with an unreadable claim stamp", - docs: []InputDocument{record(t, KindChange, LocationActive, activePath, - minimalChange(42, "widget", "in-progress", "branch: feat/widget", "claimed_at: yesterday"))}, - code: CodeChangeStateIncoherent, - severity: domain.SeverityError, - field: "claimed_at", - entity: changeEntity(42, "widget", activePath), - }, { name: "blocked without a reason", docs: []InputDocument{record(t, KindChange, LocationActive, activePath, minimalChange(42, "widget", "blocked"))}, @@ -561,11 +543,8 @@ func TestValidateReportIsDeterministic(t *testing.T) { } } -// TestFinalLifecycleFindingSpellings pins ADR-0129 rows 58 and 59 (change 0474). +// TestFinalLifecycleFindingSpellings pins ADR-0129 row 59 (change 0474). func TestFinalLifecycleFindingSpellings(t *testing.T) { - if got := string(CodeChangeFinalClaimStamp); got != "change-final-claim-stamp" { - t.Errorf("CodeChangeFinalClaimStamp = %q", got) - } if got := string(CodeADRUpdateAfterFinal); got != "adr-update-after-final" { t.Errorf("CodeADRUpdateAfterFinal = %q", got) } @@ -601,3 +580,29 @@ func TestChangeIdentityDeliverableUnknown(t *testing.T) { t.Errorf("finding = %+v, want warning on deliverable with raw research, status proposed", f) } } + +// TestInProgressWithoutClaimStampIsCoherent pins that an in-progress record +// needs only its branch: no claim stamp is a fact the state guarantees. +func TestInProgressWithoutClaimStampIsCoherent(t *testing.T) { + const path = "docs/changes/active/0042-widget.md" + findings := buildRecords(t, record(t, KindChange, LocationActive, path, + minimalChange(42, "widget", "in-progress", "branch: 'feat/x'"))).Report.Findings() + for _, f := range findings { + if f.Code == CodeChangeStateIncoherent { + t.Fatalf("unexpected %s/%s on %+v", f.Code, f.Field, f.Entity) + } + } +} + +// TestArchivedFinalRecordWithClaimStampHasNoFinding pins that a leftover claim +// stamp on a closed record is not a finding: nothing reads it. +func TestArchivedFinalRecordWithClaimStampHasNoFinding(t *testing.T) { + const path = "docs/changes/archive/2026-08-01-0042-widget.md" + findings := buildRecords(t, record(t, KindChange, LocationArchive, path, + minimalChange(42, "widget", "done", "claimed_at: '2026-05-20T10:00:00Z'"))).Report.Findings() + for _, f := range findings { + if f.Field == "claimed_at" { + t.Fatalf("unexpected %s/%s on %+v", f.Code, f.Field, f.Entity) + } + } +} From 2752598460d1173fa146556e26dc53cb64bf534e Mon Sep 17 00:00:00 2001 From: Daniel Hanold Date: Thu, 22 Oct 2026 07:27:16 -0400 Subject: [PATCH 4/7] refactor: stop stamping claimed_at and drop the claim lease from the claim result --- internal/app/change_claim.go | 33 ++--- internal/app/change_claim_test.go | 68 ++++++++++- internal/app/change_complete_test.go | 8 +- internal/app/change_groom_test.go | 2 +- internal/app/change_halt.go | 57 +++------ internal/app/change_halt_test.go | 38 +++++- internal/app/change_implemented.go | 6 +- internal/app/change_integration_test.go | 38 +++--- internal/app/change_kill_test.go | 7 +- internal/app/change_reconcile.go | 21 +--- internal/app/change_reconcile_test.go | 8 +- .../app/claim_proof_git_integration_test.go | 24 ++-- internal/app/claim_workflow_git_test.go | 5 +- .../app/finalize_closeout_integration_test.go | 8 +- internal/app/finalize_e2e_test.go | 2 +- .../runtracker_ownership_integration_test.go | 24 ++-- internal/app/runtracker_verdict.go | 13 +- .../runtracker_verdict_integration_test.go | 26 +--- internal/app/workflow_e2e_test.go | 2 +- internal/app/workflow_integration_test.go | 30 +++-- internal/cli/change.go | 4 +- internal/domain/actions.go | 53 ++------ internal/domain/actions_test.go | 114 +++++------------- internal/domain/entities.go | 4 - internal/domain/entities_test.go | 22 ++-- internal/domain/lease.go | 48 -------- internal/domain/lease_test.go | 76 ------------ internal/domain/types_test.go | 2 +- internal/repository/decode.go | 10 +- internal/repository/decode_test.go | 46 ++++--- 30 files changed, 322 insertions(+), 477 deletions(-) delete mode 100644 internal/domain/lease.go delete mode 100644 internal/domain/lease_test.go diff --git a/internal/app/change_claim.go b/internal/app/change_claim.go index a9f546d65..51f73e54b 100644 --- a/internal/app/change_claim.go +++ b/internal/app/change_claim.go @@ -23,8 +23,7 @@ import ( // refreshed updated date, its re-rendered artifact block, and the inline board) // as one validated atomic transaction. The domain owns legality: domain.Claim // decides whether the current status may take the transition and yields the -// exact FieldChanges to apply. The lease is re-stamped only by claim, -// change.reconcile, and change.resume-halted. +// exact FieldChanges to apply. // // Claim additionally re-proves eligibility INSIDE the transaction against the // attempt's own fresh snapshot — proposed, uniquely identified, build-ready, @@ -132,8 +131,6 @@ type ChangeClaimResult struct { ID int `json:"id,omitempty"` Status string `json:"status,omitempty" docket:"success-only,enum=statuses"` Branch string `json:"branch,omitempty"` - ClaimedAt string `json:"claimed_at,omitempty"` - Lease string `json:"lease,omitempty"` Revision string `json:"committed_revision,omitempty"` Disposition string `json:"disposition,omitempty" docket:"enum=claim_dispositions"` Findings []StatusFinding `json:"findings"` @@ -144,7 +141,7 @@ type ChangeClaimResult struct { func (r ChangeClaimResult) HumanText() string { switch r.Result { case ResultApplied: - return fmt.Sprintf("change %04d %s (%s) lease %s — %s", r.ID, r.Disposition, r.Branch, r.Lease, r.Revision) + return fmt.Sprintf("change %04d %s (%s) — %s", r.ID, r.Disposition, r.Branch, r.Revision) default: disp := r.Disposition if disp == "" { @@ -167,19 +164,19 @@ func newChangeClaimResult(opKey string, result Result, r ChangeClaimResult) Chan // changeClaimReceipt is the canonical receipt persisted with a claim commit and // replayed verbatim on an idempotent re-run. Field order is alphabetical so // json.Marshal emits the canonical, sorted-key compact form the engine's receipt -// validator requires. +// validator requires. A receipt committed by an older docket may also carry +// claimed_at and lease keys; json.Unmarshal ignores them, so such a receipt +// still replays. type changeClaimReceipt struct { - Branch string `json:"branch"` - ClaimedAt string `json:"claimed_at"` + Branch string `json:"branch"` // RunContextHash is the hashed run context this claim was bound to ("" // for an ungated claim). It is the durable, authoritative proof the keyed // verdict path resolves ownership from (change 0407). Placed between - // claimed_at and id so the struct's field order stays alphabetical by json key + // branch and id so the struct's field order stays alphabetical by json key // — json.Marshal then emits the canonical sorted-key form the receipt // validator requires. RunContextHash string `json:"gate_context_hash"` ID int `json:"id"` - Lease string `json:"lease"` Op string `json:"op"` // Selection is how the run chose this change (claimSelection's normalized // value), omitted when unknown so an unknown claim's receipt is byte-identical @@ -273,7 +270,6 @@ func ChangeClaim(ctx context.Context, deps PlanningDeps, repoDir string, req Cha facts: facts, eff: eff, clock: deps.Clock, - ttlHours: eff.Reclaim.LeaseTTL.Value, inline: inline, link: linkContextOf(pin), changesDir: eff.ChangesDir.Value, @@ -454,8 +450,6 @@ func claimResultFromOutcome(opKey string, res transaction.Result, execErr error) out.ID = rec.ID out.Status = rec.Status out.Branch = rec.Branch - out.ClaimedAt = rec.ClaimedAt - out.Lease = rec.Lease } out.Revision = string(res.AppliedCommit) } @@ -531,7 +525,6 @@ type changeClaimOp struct { facts domain.BranchFacts eff config.Effective clock transaction.Clock - ttlHours int inline bool link render.LinkContext changesDir string @@ -570,7 +563,7 @@ func (o changeClaimOp) Plan(ctx context.Context, st transaction.AttemptState) (t if fail := domain.ClaimEligibility(snap, c, o.facts); fail != nil { return refuseLifecyclePolicy(fail) } - result, fail := domain.Claim(c, o.clock.Now()) + result, fail := domain.Claim(c) if fail != nil { return refuseLifecyclePolicy(fail) } @@ -590,9 +583,10 @@ func (o changeClaimOp) Plan(ctx context.Context, st transaction.AttemptState) (t // First patch pass: the domain's owned claim FieldChanges plus the refreshed // updated date. Each field is upserted in its own parse/apply cycle rather - // than batched, because a claim inserts SEVERAL absent fields (branch, - // claimed_at) into a proposed record and two InsertFields batched into one - // PatchSet resolve to the same pre-fence position — an overlapping edit. + // than batched, because a claim can insert SEVERAL absent fields (branch, + // and updated on a record without one) into a proposed record and two + // InsertFields batched into one PatchSet resolve to the same pre-fence + // position — an overlapping edit. intermediate := edited for _, fc := range result.Changed { intermediate, err = upsertFieldBytes(intermediate, fc.Field, lifecycleFieldValue(fc.To)) @@ -644,13 +638,10 @@ func (o changeClaimOp) Plan(ctx context.Context, st transaction.AttemptState) (t } } - lease := string(domain.EvaluateLease(result.Change, o.clock.Now(), o.ttlHours)) receipt, err := json.Marshal(changeClaimReceipt{ Branch: result.Change.Branch().Value, - ClaimedAt: result.Change.ClaimedAt().Raw, RunContextHash: o.runContextHash, ID: o.changeID, - Lease: lease, Op: o.opKey, Selection: o.selection, Status: string(result.Change.Status()), diff --git a/internal/app/change_claim_test.go b/internal/app/change_claim_test.go index d25f1f9bf..00ad7a3c4 100644 --- a/internal/app/change_claim_test.go +++ b/internal/app/change_claim_test.go @@ -2,6 +2,7 @@ package app import ( "context" + "encoding/json" "errors" "github.com/danielhanold/docket/internal/domain" "github.com/danielhanold/docket/internal/gitcli" @@ -15,7 +16,7 @@ import ( // claimableChange renders a proposed, build-ready change: the canonical proposed // record linking a spec (so it carries a design) and no claim fields yet. -// Claiming it must INSERT branch/claimed_at/reconciled. +// Claiming it must INSERT branch and set reconciled. func claimableChange(id int, slug string) string { return withLinkedSpec(lifecycleChange(id, slug, "proposed"), fixtureSpecPath(slug)) } @@ -143,8 +144,8 @@ func appliedGateResult(t *testing.T, id int) transaction.Result { Disposition: transaction.DispositionApplied, AppliedCommit: gateClaimCommit, Receipt: mustMarshal(t, changeClaimReceipt{ - Branch: "feat/widget", ClaimedAt: "2026-08-16T12:00:00Z", - ID: id, Lease: "fresh", Op: OperationChangeClaim, Status: "in-progress", + Branch: "feat/widget", + ID: id, Op: OperationChangeClaim, Status: "in-progress", }), } } @@ -454,6 +455,67 @@ func assertUnrelatedShapeIntact(t *testing.T, repo *gitRepo, branch string, shap t.Errorf("%s: status no longer reports a finding on the unrelated records; findings %+v", shape.name, st.Findings) } +// TestClaimWritesNoClaimStamp: a claim records the branch and nothing that +// dates the claim — the committed record gains no claimed_at: line, the +// receipt carries no claimed_at or lease key, and the human line names +// identity, disposition, branch, and revision only. +func TestClaimWritesNoClaimStamp(t *testing.T) { + recPath := groomPath(1, "widget") + src := claimableChange(1, "widget") + if strings.Contains(src, "claimed_at") { + t.Fatalf("fixture already carries claimed_at:\n%s", src) + } + plan, opRes := claimPlanFor(t, map[string]string{recPath: src}, baseClaimOp([]string{"inline"}, 1, domain.NewBranchFacts(nil))) + if opRes.Refused { + t.Fatalf("claim refused: %v", opRes.Findings) + } + rec := killRecordBytes(t, plan, recPath) + if strings.Contains(rec, "claimed_at") { + t.Errorf("claimed record carries a claimed_at line:\n%s", rec) + } + if !strings.Contains(rec, "branch: 'feat/widget'") && !strings.Contains(rec, "branch: feat/widget") { + t.Errorf("claimed record lacks its branch:\n%s", rec) + } + + var keys map[string]json.RawMessage + if err := json.Unmarshal(plan.Receipt, &keys); err != nil { + t.Fatalf("receipt %s: %v", plan.Receipt, err) + } + for _, retired := range []string{"claimed_at", "lease"} { + if _, ok := keys[retired]; ok { + t.Errorf("claim receipt carries retired key %q: %s", retired, plan.Receipt) + } + } + + out := claimResultFromOutcome(OperationChangeClaim, transaction.Result{ + Disposition: transaction.DispositionApplied, AppliedCommit: gateClaimCommit, Receipt: plan.Receipt, + }, nil) + if want := "change 0001 applied (feat/widget) — " + gateClaimCommit; out.HumanText() != want { + t.Errorf("HumanText = %q, want %q", out.HumanText(), want) + } +} + +// TestDecodeChangeClaimReceiptToleratesRetiredKeys: a receipt committed before +// the claim lease was retired still carries claimed_at and lease; it must still +// decode, so an idempotent replay of that claim reports id, status, and branch. +func TestDecodeChangeClaimReceiptToleratesRetiredKeys(t *testing.T) { + old := []byte(`{"branch":"feat/x","claimed_at":"2026-08-02T00:00:00Z","gate_context_hash":"","id":7,"lease":"fresh","op":"change.claim","status":"in-progress"}`) + rec, ok := decodeChangeClaimReceipt(old) + if !ok { + t.Fatalf("pre-change receipt did not decode: %s", old) + } + if rec.ID != 7 || rec.Branch != "feat/x" || rec.Status != "in-progress" { + t.Errorf("decoded receipt = %+v, want id 7, branch feat/x, status in-progress", rec) + } + out := claimResultFromOutcome(OperationChangeClaim, transaction.Result{ + Disposition: transaction.DispositionAlreadyApplied, AppliedCommit: gateClaimCommit, Receipt: old, + }, nil) + if out.Result != ResultApplied || out.Disposition != ClaimDispositionAlreadyClaimed || + out.ID != 7 || out.Branch != "feat/x" || out.Status != "in-progress" { + t.Errorf("replay of a pre-change receipt = %+v, want already-claimed with id, branch, and status", out) + } +} + // TestChangeClaimRefusesLegacyTrivialRecord: a legacy record carrying // trivial: true and no spec is a stub, not build-ready, so a claim refuses it // as needs-grooming and writes nothing. diff --git a/internal/app/change_complete_test.go b/internal/app/change_complete_test.go index f75e1ab25..3fa814322 100644 --- a/internal/app/change_complete_test.go +++ b/internal/app/change_complete_test.go @@ -135,8 +135,8 @@ func TestChangeCompletePlanFromProposed(t *testing.T) { t.Errorf("archived record lacks %q:\n%s", want, rec) } } - if strings.Contains(rec, "claimed_at: 2026") { - t.Errorf("archived record carries a claim stamp:\n%s", rec) + if strings.Contains(rec, "claimed_at") { + t.Errorf("completing a proposed record wrote a claimed_at line:\n%s", rec) } results := killRecordBytes(t, plan, miResultsPath) if !strings.Contains(results, "../changes/archive/2026-08-16-0003-widget.md") { @@ -163,8 +163,8 @@ func TestChangeCompletePlanFromInProgressWithAndWithoutRunHalted(t *testing.T) { if !strings.Contains(rec, "status: 'done'") { t.Errorf("status not done:\n%s", rec) } - if strings.Contains(rec, "claimed_at: 2026") { - t.Errorf("claim stamp not cleared:\n%s", rec) + if !strings.Contains(rec, "\nclaimed_at: 2026-08-02T00:00:00Z\n") { + t.Errorf("completion rewrote the claimed_at line:\n%s", rec) } if !strings.Contains(rec, "branch: feat/widget") { t.Errorf("branch not kept:\n%s", rec) diff --git a/internal/app/change_groom_test.go b/internal/app/change_groom_test.go index 91e15d2a3..15ecd08ce 100644 --- a/internal/app/change_groom_test.go +++ b/internal/app/change_groom_test.go @@ -2503,7 +2503,7 @@ func TestChangeGroomTypeEditChangesNextClaimBranch(t *testing.T) { if out != domain.LookupFound { t.Fatalf("change 2 not found after groom") } - res, fail := domain.Claim(ch, testClock().Now()) + res, fail := domain.Claim(ch) if fail != nil { t.Fatalf("claim failed: %v", fail) } diff --git a/internal/app/change_halt.go b/internal/app/change_halt.go index aef258d70..5fa2e5768 100644 --- a/internal/app/change_halt.go +++ b/internal/app/change_halt.go @@ -8,7 +8,6 @@ import ( "strings" "github.com/danielhanold/docket/internal/config" - "github.com/danielhanold/docket/internal/document" "github.com/danielhanold/docket/internal/domain" "github.com/danielhanold/docket/internal/gitcli" "github.com/danielhanold/docket/internal/render" @@ -23,8 +22,8 @@ import ( // A run halt and a finalize block are DIFFERENT states with different source // and recovery, so they use different sections. `change halt` upserts one // bounded authored report into a single "## Run halted" section on an -// in-progress change WITHOUT touching its branch, claim lease, workspace, or -// build evidence — the work is paused, not abandoned. `run verify` reports the +// in-progress change WITHOUT touching its branch, workspace, or build +// evidence — the work is paused, not abandoned. `run verify` reports the // closed `run-halted` verdict for such a change (run_verify.go), and `context // implementation --id` surfaces the durable halt checkpoints // (implementation_context.go). @@ -32,10 +31,10 @@ import ( // `change resume-halted` is human-authorized recovery of the SAME work, not a // second claim. It requires the exact marked record and an explicit // acknowledgement that the prior worker is quiescent, reprobes the owned -// branch/workspace (refusing when a live writer may still hold it), refreshes -// the claim, removes exactly the marker section, and preserves every valid -// checkpoint. It never discards, resets, adopts, or reassigns a workspace whose -// writer may still be live. +// branch/workspace (refusing when a live writer may still hold it), removes +// exactly the marker section, and preserves every valid checkpoint and every +// frontmatter field. It never discards, resets, adopts, or reassigns a +// workspace whose writer may still be live. // // The reprobe is classified against a CLOSED admission set (classifyResumeAdmission): // a state outside the set never authorizes resume. A workspace proven cleanly @@ -190,7 +189,7 @@ type haltReceipt struct { // ChangeHalt records one bounded authored halt report into the single "## Run // halted" section on an in-progress change, in one exact-revision transaction. -// The change's branch, claim lease, workspace, and build evidence are untouched. +// The change's branch, workspace, and build evidence are untouched. func ChangeHalt(ctx context.Context, deps PlanningDeps, repoDir string, req HaltRequest) HaltResult { if findings := validateHaltShape(req); len(findings) > 0 { return newHaltResult(OperationChangeHalt, ResultInvalidInput, HaltResult{ID: req.ID, Findings: findings}) @@ -229,8 +228,8 @@ func ChangeHalt(ctx context.Context, deps PlanningDeps, repoDir string, req Halt // ChangeResumeHalted is human-authorized recovery of a halted run. It requires // the explicit acknowledgement, reprobes the owned workspace (refusing when a -// live writer may hold it), then refreshes the claim and removes the marker in -// one exact-revision transaction, preserving every other byte. +// live writer may hold it), then removes the marker in one exact-revision +// transaction, preserving every other byte. func ChangeResumeHalted(ctx context.Context, deps PlanningDeps, wdeps WorkspaceDeps, repoDir string, req ResumeRequest) HaltResult { if findings := validateResumeShape(req); len(findings) > 0 { return newHaltResult(OperationChangeResumeHalted, ResultInvalidInput, HaltResult{ID: req.ID, Findings: findings}) @@ -321,7 +320,6 @@ func ChangeResumeHalted(ctx context.Context, deps PlanningDeps, wdeps WorkspaceD op := resumeHaltedOp{ id: req.ID, eff: eff, - clock: deps.Clock, inline: inline, changesDir: eff.ChangesDir.Value, } @@ -608,14 +606,13 @@ func (o changeHaltOp) haltReportBody() string { } // resumeHaltedOp is the SemanticOperation the engine drives for `change -// resume-halted`. It gates the in-progress status on fresh state, refreshes the -// claim lease (re-stamps claimed_at), removes exactly the "## Run halted" -// section, and rerenders the inline board. Every other byte — branch, plan, -// results, checkpoints — is preserved. +// resume-halted`. It gates the in-progress status on fresh state, removes +// exactly the "## Run halted" section, and rerenders the inline board. Every +// other byte — every frontmatter field, plan, results, checkpoints — is +// preserved. type resumeHaltedOp struct { id int eff config.Effective - clock transaction.Clock inline bool changesDir string } @@ -630,8 +627,8 @@ func (o resumeHaltedOp) Plan(ctx context.Context, st transaction.AttemptState) ( if out != domain.LookupFound { return refuseHalt("not-found", fmt.Sprintf("change %04d is not present in the current corpus", o.id)) } - // A resume refreshes an in-progress claim; RefreshClaim itself requires - // in-progress, so the gate is remapped to `contended` on a moved fresh status. + // A resume continues an in-progress run, so the gate is remapped to + // `contended` on a moved fresh status. if c.Status() != domain.StatusInProgress { return refuseHalt(ReasonResumeNotHalted, fmt.Sprintf("change %04d is %q, not in-progress; there is no halted run to resume", o.id, c.Status())) @@ -645,34 +642,16 @@ func (o resumeHaltedOp) Plan(ctx context.Context, st transaction.AttemptState) ( fmt.Sprintf("change %04d carries no run-halted marker in the fresh state; there is nothing to resume", o.id)) } - // Remove exactly the marker section over the exact source bytes. + // Remove exactly the marker section over the exact source bytes; no + // frontmatter field is written. edited, err := render.ApplySectionEdits(src, []string{runHaltedSectionHeading}, []render.SectionEdit{{Heading: runHaltedSectionHeading, Intent: render.SectionRemove}}) if err != nil { return refuseHalt("marker-remove-failed", err.Error()) } - // Refresh the claim lease (re-stamp claimed_at). The in-progress gate above - // guarantees RefreshClaim succeeds. - refreshed, fail := domain.RefreshClaim(c, o.clock.Now()) - if fail != nil { - return refuseLifecyclePolicy(fail) - } - doc, err := document.Parse(edited) - if err != nil { - return transaction.MutationPlan{}, transaction.OperationResult{}, fmt.Errorf("change resume-halted: reparsing edited record: %w", err) - } - var ps document.PatchSet - for _, fc := range refreshed.Changed { - upsertField(&ps, doc, fc.Field, lifecycleFieldValue(fc.To)) - } - finalBytes, err := doc.Apply(ps) - if err != nil { - return transaction.MutationPlan{}, transaction.OperationResult{}, fmt.Errorf("change resume-halted: patching claim field: %w", err) - } - files := []transaction.FileMutation{ - {Path: gitcli.RepoPath(c.Path()), Kind: transaction.MutationReplace, Bytes: finalBytes}, + {Path: gitcli.RepoPath(c.Path()), Kind: transaction.MutationReplace, Bytes: edited}, } files, err = planInlineBoard(ctx, st, snap, o.inline, o.changesDir, boardPresentation(o.eff), files) if err != nil { diff --git a/internal/app/change_halt_test.go b/internal/app/change_halt_test.go index 03b6dbe79..2a442d1d1 100644 --- a/internal/app/change_halt_test.go +++ b/internal/app/change_halt_test.go @@ -59,7 +59,7 @@ func TestChangeHaltPreservesCheckpoints(t *testing.T) { if !strings.Contains(rec, "## Run halted") || !strings.Contains(rec, "Blocked on infra; see run 7.") { t.Errorf("halt report not recorded:\n%s", rec) } - // Branch and claim lease byte-identical — halt touches no frontmatter. + // Branch and claim fields byte-identical — halt touches no frontmatter. for _, want := range []string{"branch: feat/widget", "claimed_at: 2026-08-02T00:00:00Z", "reconciled: true"} { if !strings.Contains(rec, want) { t.Errorf("halt altered a preserved field; missing %q:\n%s", want, rec) @@ -75,6 +75,42 @@ func TestChangeHaltPreservesCheckpoints(t *testing.T) { } } +// TestResumeHaltedLeavesFrontmatterByteIdentical proves resume-halted removes +// exactly the "## Run halted" section and writes no frontmatter field: an older +// record's claimed_at: line, like every other field, is byte-identical after. +func TestResumeHaltedLeavesFrontmatterByteIdentical(t *testing.T) { + recPath := groomPath(3, "widget") + inProgress := lifecycleChange(3, "widget", "in-progress") + const stamped = "\nclaimed_at: 2026-08-02T00:00:00Z\n" + if !strings.Contains(inProgress, stamped) { + t.Fatalf("fixture lacks a stamped claimed_at line:\n%s", inProgress) + } + halted := inProgress + "\n## Run halted\n\n### 2026-08-10\n\nStopped at the gate.\n" + files := map[string]string{ + recPath: halted, + "docs/changes/BOARD.md": "# Backlog\n\nold\n", + } + op := resumeHaltedOp{id: 3, eff: planningTestConfig([]string{"inline"}), inline: true, changesDir: "docs/changes"} + plan, opRes := blockPlanFor(t, files, planningTestConfig([]string{"inline"}), op) + if opRes.Refused { + t.Fatalf("unexpected refusal: %v", opRes.Findings) + } + rec := lifecycleRecordBytes(t, plan, recPath) + if strings.Contains(rec, "## Run halted") { + t.Errorf("run-halted section survived the resume:\n%s", rec) + } + frontmatter := func(s string) string { + end := strings.Index(s[len("---\n"):], "\n---\n") + if !strings.HasPrefix(s, "---\n") || end < 0 { + t.Fatalf("record has no frontmatter block:\n%s", s) + } + return s[:len("---\n")+end+len("\n---\n")] + } + if got, want := frontmatter(rec), frontmatter(halted); got != want { + t.Errorf("resume rewrote the frontmatter:\n got: %s\nwant: %s", got, want) + } +} + // --- resume: acknowledgement gate + quiescence mapping (pure) -------------- // TestChangeResumeHaltedRequiresAcknowledgement proves resume refuses before any diff --git a/internal/app/change_implemented.go b/internal/app/change_implemented.go index 2601702ca..a34835f1f 100644 --- a/internal/app/change_implemented.go +++ b/internal/app/change_implemented.go @@ -476,7 +476,7 @@ func resultsArtifactProblem(resultsPath string, data []byte, found bool, ch doma // transaction as well as at the pre-transaction reprobe), upserts the owned // fields (status, pr, plan, updated), re-renders the artifact block, writes the // verified evidence record as the record's "## Build evidence" section, and — -// when inline is enabled — the board. It never touches claimed_at or branch: the claim +// when inline is enabled — the board. It never touches branch: the claim // survives the transition (0316 owns claim release). type changeImplementedOp struct { changeID int @@ -527,8 +527,8 @@ func (o changeImplementedOp) Plan(ctx context.Context, st transaction.AttemptSta // First patch pass: the domain's owned FieldChanges (status, pr, plan) plus the // refreshed updated date. Each field is upserted in its own parse/apply cycle // so an inserted absent field (pr on a record that never carried one) never - // collides with another at the pre-fence insertion point. claimed_at and branch - // are absent from result.Changed, so they are left byte-identical. + // collides with another at the pre-fence insertion point. branch is absent + // from result.Changed, so it is left byte-identical. intermediate := src var err error for _, fc := range result.Changed { diff --git a/internal/app/change_integration_test.go b/internal/app/change_integration_test.go index 15342cb9c..f17a23ff3 100644 --- a/internal/app/change_integration_test.go +++ b/internal/app/change_integration_test.go @@ -343,16 +343,16 @@ func TestIntegrationChangeAuthoringBlockAppliedResult(t *testing.T) { // TestChangeClaimApplies proves both halves of a successful claim: the app layer // submits the exact expected revision, an idempotency key, and the metadata -// target ref (recordingEngine); and the plan closure patches status/branch/ -// claimed_at and names the record, board, and artifact surfaces. +// target ref (recordingEngine); and the plan closure patches status/branch +// and names the record, board, and artifact surfaces. func TestIntegrationChangeAuthoringClaimApplies(t *testing.T) { const revision = "1234123412341234123412341234123412341234" t.Run("submitted request", func(t *testing.T) { repoDir := newWorkingRepo(t, nil).invocation receipt := mustMarshal(t, changeClaimReceipt{ - Branch: "feat/widget", ClaimedAt: "2026-08-16T12:00:00Z", - ID: 3, Lease: "fresh", Op: OperationChangeClaim, Status: "in-progress", + Branch: "feat/widget", + ID: 3, Op: OperationChangeClaim, Status: "in-progress", }) engine := &recordingEngine{result: transaction.Result{ Disposition: transaction.DispositionApplied, @@ -370,11 +370,8 @@ func TestIntegrationChangeAuthoringClaimApplies(t *testing.T) { if res.Disposition != ClaimDispositionApplied { t.Errorf("disposition = %q, want applied", res.Disposition) } - if res.Branch != "feat/widget" || res.Lease != "fresh" || res.Status != "in-progress" { - t.Errorf("result echoes (branch=%q lease=%q status=%q); want the claim receipt", res.Branch, res.Lease, res.Status) - } - if res.ClaimedAt != "2026-08-16T12:00:00Z" { - t.Errorf("claimed_at = %q", res.ClaimedAt) + if res.Branch != "feat/widget" || res.Status != "in-progress" { + t.Errorf("result echoes (branch=%q status=%q); want the claim receipt", res.Branch, res.Status) } if res.Revision != "cafebabecafebabecafebabecafebabecafebabe" { t.Errorf("revision = %q", res.Revision) @@ -427,7 +424,6 @@ func TestIntegrationChangeAuthoringClaimApplies(t *testing.T) { for _, want := range []string{ "status: 'in-progress'", "branch: 'feat/widget'", - "claimed_at: '2026-08-16T12:00:00Z'", "updated: '2026-08-16'", "docket:artifacts:start", } { @@ -547,8 +543,8 @@ func TestIntegrationChangeAuthoringClaimRetryConvergence(t *testing.T) { t.Run("matching identity replays as already-claimed", func(t *testing.T) { receipt := mustMarshal(t, changeClaimReceipt{ - Branch: "feat/widget", ClaimedAt: "2026-08-16T12:00:00Z", - ID: 3, Lease: "fresh", Op: OperationChangeClaim, Status: "in-progress", + Branch: "feat/widget", + ID: 3, Op: OperationChangeClaim, Status: "in-progress", }) res := setup(t, transaction.Result{ Disposition: transaction.DispositionAlreadyApplied, @@ -2687,8 +2683,7 @@ func TestIntegrationChangeRuntimeRelinkWorkspaceConflictBlocks(t *testing.T) { // TestChangeResumeHalted proves the full recovery: a live-writer reprobe refuses // and leaves the marker; a revision drift is contended; a quiescent reprobe -// refreshes the claim, removes exactly the marker section, and preserves every -// other byte. +// removes exactly the marker section and preserves every other byte. func TestIntegrationChangeRuntimeResumeHalted(t *testing.T) { for _, m := range planRepoModes() { t.Run(m.name, func(t *testing.T) { @@ -2718,8 +2713,8 @@ func TestIntegrationChangeRuntimeResumeHalted(t *testing.T) { } }) - // A quiescent reprobe recovers: claim refreshed, marker removed, other - // bytes preserved. + // A quiescent reprobe recovers: marker removed, every other byte — + // the older claimed_at: line included — preserved. t.Run("quiescent-resumes", func(t *testing.T) { f := setupHaltedFixture(t, m) got := ChangeResumeHalted(context.Background(), f.deps, @@ -2732,8 +2727,8 @@ func TestIntegrationChangeRuntimeResumeHalted(t *testing.T) { if strings.Contains(rec, "## Run halted") { t.Errorf("marker not removed on resume:\n%s", rec) } - if !strings.Contains(rec, "claimed_at: '2026-08-16T12:00:00Z'") { - t.Errorf("claim lease not refreshed:\n%s", rec) + if !strings.Contains(rec, "\nclaimed_at: 2026-08-02T00:00:00Z\n") { + t.Errorf("resume rewrote the claimed_at line:\n%s", rec) } // Preserved: branch and the authored ## Why section byte-identical. for _, want := range []string{"branch: feat/widget", "## Why\n\nOriginal why."} { @@ -3092,13 +3087,14 @@ func TestIntegrationChangeRuntimeResumeHaltedPreallocation(t *testing.T) { t.Fatalf("resume through the real service: result=%q disp=%q reason=%q", got.Result, got.Disposition, got.Reason) } - // Marker removed; claim refreshed; status and recorded branch preserved. + // Marker removed; status, recorded branch, and the older claimed_at: + // line preserved. rec, _ := originFile(t, f.repo.origin, f.branch, groomPath(f.id, f.slug)) if strings.Contains(rec, "## Run halted") { t.Errorf("halt marker survived resume:\n%s", rec) } - if !strings.Contains(rec, "claimed_at: '2026-08-16T12:00:00Z'") { - t.Errorf("claim lease not refreshed:\n%s", rec) + if !strings.Contains(rec, "\nclaimed_at: 2026-08-02T00:00:00Z\n") { + t.Errorf("resume rewrote the claimed_at line:\n%s", rec) } for _, want := range []string{"status: in-progress", "branch: feat/widget"} { if !strings.Contains(rec, want) { diff --git a/internal/app/change_kill_test.go b/internal/app/change_kill_test.go index 5c13b251c..d4935dd37 100644 --- a/internal/app/change_kill_test.go +++ b/internal/app/change_kill_test.go @@ -155,12 +155,13 @@ func TestChangeKillPlanFileSet(t *testing.T) { if !strings.Contains(rec, "docket:artifacts:start") { t.Errorf("artifact block missing:\n%s", rec) } - // Kill clears the lease and the recorded branch. + // Kill clears the recorded branch; an older record's claimed_at: line is + // compatibility data and survives byte-identical. if strings.Contains(rec, "branch: feat/widget") { t.Errorf("branch not cleared:\n%s", rec) } - if strings.Contains(rec, "claimed_at: 2026-08-02") { - t.Errorf("claimed_at not cleared:\n%s", rec) + if !strings.Contains(rec, "\nclaimed_at: 2026-08-02T00:00:00Z\n") { + t.Errorf("kill rewrote the claimed_at line:\n%s", rec) } } diff --git a/internal/app/change_reconcile.go b/internal/app/change_reconcile.go index e271904b0..c298fe53e 100644 --- a/internal/app/change_reconcile.go +++ b/internal/app/change_reconcile.go @@ -22,9 +22,9 @@ import ( // a whole-record replacement — it patches the owned proposal sections, appends // one dated ## Reconcile log entry, updates the complete desired relationship // values, optionally patches the still-mutable linked spec's sections, flips -// reconciled: true, and refreshes the claim (re-stamps claimed_at). Everything -// it does not name — unknown frontmatter, authored sections outside the patch, -// line endings, unrelated files — stays byte-identical. +// reconciled: true, and stamps updated:. Everything it does not name — unknown +// frontmatter, authored sections outside the patch, line endings, unrelated +// files — stays byte-identical. // // It is a non-allocating edit of an existing record, so it pins the submitted // record revision with an exact-blob entity expectation rather than an @@ -355,7 +355,7 @@ func (o changeReconcileOp) Key() transaction.OperationKey { return transaction.O // Plan gates the reconcile against the attempt's fresh snapshot, splices the // owned proposal sections, appends the dated reconcile-log entry, patches the -// reconciled/claim/updated fields and the desired relationships, patches the +// reconciled/updated fields and the desired relationships, patches the // linked spec's named sections, re-renders the artifact block, and assembles // the closed plan: the reconciled record, the patched spec (when requested), // and the re-rendered board when inline is enabled. @@ -394,22 +394,13 @@ func (o changeReconcileOp) Plan(ctx context.Context, st transaction.AttemptState return refuseReconcile("reconcile-log-append-failed", err.Error()) } - // 3. Patch the typed fields: refresh the claim (claimed_at), flip reconciled, - // stamp updated, and write the complete desired relationships. domain. - // RefreshClaim yields the claimed_at FieldChange (the in-progress gate above - // guarantees it succeeds). - refreshed, fail := domain.RefreshClaim(c, o.clock.Now()) - if fail != nil { - return refuseLifecyclePolicy(fail) - } + // 3. Patch the typed fields: flip reconciled, stamp updated, and write the + // complete desired relationships. doc1, err := document.Parse(edited) if err != nil { return transaction.MutationPlan{}, transaction.OperationResult{}, fmt.Errorf("change reconcile: reparsing edited record: %w", err) } var ps document.PatchSet - for _, fc := range refreshed.Changed { - upsertField(&ps, doc1, fc.Field, lifecycleFieldValue(fc.To)) - } upsertField(&ps, doc1, "reconciled", document.Bool(true)) upsertField(&ps, doc1, "updated", document.String(o.clock.Now().UTC().Format("2006-01-02"))) if rel := o.req.Relations; rel != nil { diff --git a/internal/app/change_reconcile_test.go b/internal/app/change_reconcile_test.go index 47ff0db38..2f346770f 100644 --- a/internal/app/change_reconcile_test.go +++ b/internal/app/change_reconcile_test.go @@ -78,9 +78,9 @@ func baseReconcileOp(surfaces []string, req ChangeReconcileRequest) changeReconc // TestChangeReconcileAppliesPatch proves the structured edit: the owned proposal // section is replaced, one dated log entry is appended under ## Reconcile log, -// reconciled flips true, claimed_at is restamped, relations are written as -// unquoted flow collections, and everything outside the patch — an unknown -// frontmatter key and the trailing ## Custom notes section — stays +// reconciled flips true, relations are written as unquoted flow collections, +// and everything outside the patch — an unknown frontmatter key, an older +// record's claimed_at: line, and the trailing ## Custom notes section — stays // byte-identical. func TestChangeReconcileAppliesPatch(t *testing.T) { recPath := groomPath(3, "widget") @@ -100,7 +100,7 @@ func TestChangeReconcileAppliesPatch(t *testing.T) { rec := lifecycleRecordBytes(t, plan, recPath) for _, want := range []string{ "reconciled: true", - "claimed_at: '2026-08-16T12:00:00Z'", + "\nclaimed_at: 2026-08-02T00:00:00Z\n", "updated: '2026-08-16'", "depends_on: [1]", "Refined why.", diff --git a/internal/app/claim_proof_git_integration_test.go b/internal/app/claim_proof_git_integration_test.go index 75158a5d3..691e3a1e6 100644 --- a/internal/app/claim_proof_git_integration_test.go +++ b/internal/app/claim_proof_git_integration_test.go @@ -24,10 +24,8 @@ import ( // depending on changeClaimReceipt having grown that field yet. type wireClaimReceipt struct { Branch string `json:"branch"` - ClaimedAt string `json:"claimed_at"` RunContextHash string `json:"gate_context_hash"` ID int `json:"id"` - Lease string `json:"lease"` Op string `json:"op"` Selection string `json:"selection,omitempty"` Status string `json:"status"` @@ -62,16 +60,16 @@ func commitClaimTrailers(t *testing.T, dir, subject string, trailers ...string) func TestIntegrationRecordOpsScanClaimProofsReadsCommittedReceipt(t *testing.T) { repo := newRunTrackerRepo(t) - // Older claim commit: change id 3, ungated (gate_context_hash ""). + // Older claim commit: change id 3, ungated (gate_context_hash ""), committed + // by an older docket whose receipt still carried the retired claimed_at and + // lease keys. The scanner must still read it as a proof. older := commitClaimTrailers(t, repo, "claim 3", "Docket-Transaction-ID: t1", "Docket-Operation: "+OperationChangeClaim, "Docket-Request-ID: claim-3-v1", "Docket-Request-Digest: sha256:aaaa", - "Docket-Result: "+encodeClaimReceipt(t, wireClaimReceipt{ - Branch: "fix/x", ClaimedAt: "2026-09-07T00:00:00Z", RunContextHash: "", - ID: 3, Lease: "live", Op: OperationChangeClaim, Status: "in-progress", - })) + "Docket-Result: "+base64.RawURLEncoding.EncodeToString([]byte( + `{"branch":"fix/x","claimed_at":"2026-09-07T00:00:00Z","gate_context_hash":"","id":3,"lease":"fresh","op":"change.claim","status":"in-progress"}`))) // A non-claim commit that carries a request id but a different operation: it // is returned by the trailer scan yet must be filtered out by the op check. @@ -90,8 +88,8 @@ func TestIntegrationRecordOpsScanClaimProofsReadsCommittedReceipt(t *testing.T) "Docket-Request-ID: claim-4-v2", "Docket-Request-Digest: sha256:cccc", "Docket-Result: "+encodeClaimReceipt(t, wireClaimReceipt{ - Branch: "fix/y", ClaimedAt: "2026-09-07T01:00:00Z", RunContextHash: "abc123", - ID: 4, Lease: "live", Op: OperationChangeClaim, Status: "in-progress", + Branch: "fix/y", RunContextHash: "abc123", + ID: 4, Op: OperationChangeClaim, Status: "in-progress", })) deps := PlanningDeps{ @@ -138,8 +136,8 @@ func TestIntegrationRecordOpsScanClaimProofsReadsSelection(t *testing.T) { "Docket-Request-ID: claim-3-v1", "Docket-Request-Digest: sha256:aaaa", "Docket-Result: "+encodeClaimReceipt(t, wireClaimReceipt{ - Branch: "fix/x", ClaimedAt: "2026-09-07T00:00:00Z", RunContextHash: "h3", - ID: 3, Lease: "live", Op: OperationChangeClaim, Status: "in-progress", + Branch: "fix/x", RunContextHash: "h3", + ID: 3, Op: OperationChangeClaim, Status: "in-progress", })) tip := commitClaimTrailers(t, repo, "claim 4", "Docket-Transaction-ID: t2", @@ -147,8 +145,8 @@ func TestIntegrationRecordOpsScanClaimProofsReadsSelection(t *testing.T) { "Docket-Request-ID: claim-4-v2", "Docket-Request-Digest: sha256:bbbb", "Docket-Result: "+encodeClaimReceipt(t, wireClaimReceipt{ - Branch: "fix/y", ClaimedAt: "2026-09-07T01:00:00Z", RunContextHash: "h4", - ID: 4, Lease: "live", Op: OperationChangeClaim, Selection: ClaimSelectionQueue, Status: "in-progress", + Branch: "fix/y", RunContextHash: "h4", + ID: 4, Op: OperationChangeClaim, Selection: ClaimSelectionQueue, Status: "in-progress", })) deps := PlanningDeps{ diff --git a/internal/app/claim_workflow_git_test.go b/internal/app/claim_workflow_git_test.go index 646fbb495..23fb49cbc 100644 --- a/internal/app/claim_workflow_git_test.go +++ b/internal/app/claim_workflow_git_test.go @@ -42,8 +42,9 @@ func buildReadyChange(id int, slug string) string { // planningDepsForClock is planningDepsFor with an explicit clock, so a // reconcile can run at a later wall time than the claim that preceded it against -// the same origin — the record's claimed_at/updated then genuinely change while -// the inline board (which shows none of those fields) re-renders byte-identical. +// the same origin — the record's updated: field and its dated reconcile-log +// entry then genuinely change while the inline board (which shows neither) +// re-renders byte-identical. func planningDepsForClock(t *testing.T, dir string, clock transaction.Clock) realNode { t.Helper() client := newGitClient(t) diff --git a/internal/app/finalize_closeout_integration_test.go b/internal/app/finalize_closeout_integration_test.go index 43ffaaf1b..36b827afc 100644 --- a/internal/app/finalize_closeout_integration_test.go +++ b/internal/app/finalize_closeout_integration_test.go @@ -382,8 +382,8 @@ func TestIntegrationFinalizeArchiveOrdinary(t *testing.T) { t.Fatalf("archive path = %q, want %q", res.ArchivePath, archivePath) } - // The active record is gone; the archived record is done, claimless, and - // stamped with the merge date. + // The active record is gone; the archived record is done and stamped + // with the merge date, its older claimed_at: line left byte-identical. recPath := groomPath(f.id, f.slug) if _, ok := originFile(t, f.repo.origin, f.branch, recPath); ok { t.Errorf("active record still present after closeout (marker-section state)") @@ -398,8 +398,8 @@ func TestIntegrationFinalizeArchiveOrdinary(t *testing.T) { if !strings.Contains(archived, "updated: '2026-08-18'") { t.Errorf("archived record not stamped with the merge date:\n%s", archived) } - if strings.Contains(archived, "claimed_at: '2026-08-02") { - t.Errorf("archived record still carries a claim stamp:\n%s", archived) + if !strings.Contains(archived, "\nclaimed_at: 2026-08-02T00:00:00Z\n") { + t.Errorf("closeout rewrote the claimed_at line:\n%s", archived) } // Historical branch/PR fields survive. if !strings.Contains(archived, "pr: '"+closeoutRef+"'") { diff --git a/internal/app/finalize_e2e_test.go b/internal/app/finalize_e2e_test.go index a7692b17d..be7d043b5 100644 --- a/internal/app/finalize_e2e_test.go +++ b/internal/app/finalize_e2e_test.go @@ -1625,7 +1625,7 @@ func TestE2EMergeMethodUnavailable(t *testing.T) { // TestE2EHaltResume proves the implementation-side recovery path through CLI // argv: a persistent `change halt` records a durable run-halted marker on an // in-progress change and `change resume-halted --acknowledge-quiescent` clears -// it and refreshes the claim. +// it. func TestE2EHaltResume(t *testing.T) { t.Parallel() requireRealGit(t) diff --git a/internal/app/runtracker_ownership_integration_test.go b/internal/app/runtracker_ownership_integration_test.go index 6b06244d2..b0fc39c37 100644 --- a/internal/app/runtracker_ownership_integration_test.go +++ b/internal/app/runtracker_ownership_integration_test.go @@ -210,7 +210,7 @@ func TestIntegrationRunFenceTwoRunsEachVerifyOnlyTheirOwn(t *testing.T) { // TestIntegrationRunFenceUnrelatedChurnDoesNotMoveOwnership — spec acceptance item 2 / item 6 first // half: after binding A→3, mutating the corpus (sibling in-progress claims, a -// refreshed claimed_at on 3, a priority edit) and adding sibling proofs under other +// re-stamped updated: on 3, a priority edit) and adding sibling proofs under other // context hashes leaves the verdict unchanged — same id, same run-complete outcome. // Ownership rests on the confirmed binding + the exact committed proof, never on the // current claim set. @@ -239,12 +239,23 @@ func TestIntegrationRunFenceUnrelatedChurnDoesNotMoveOwnership(t *testing.T) { t.Fatalf("baseline verdict = %q, want %q", got, want) } - // Refresh id 3's claimed_at and priority (a real reconcile / groom edit + // Re-stamp id 3's updated: and priority (a real reconcile / groom edit // leaves the change complete), and add two sibling in-progress claims — exactly - // the churn the pre-0407 before-set/run inference keyed on. + // the churn the pre-0407 before-set/run inference keyed on. Each edit must + // land, or the churn is a no-op and the ownership assert below proves nothing. refreshed := string(evidenced) - refreshed = strings.Replace(refreshed, "claimed_at: 2026-08-02T00:00:00Z", "claimed_at: 2026-09-05T00:00:00Z", 1) - refreshed = strings.Replace(refreshed, "priority: medium", "priority: high", 1) + for _, edit := range [][2]string{ + {"\nupdated: 2026-08-02\n", "\nupdated: 2026-09-05\n"}, + {"\npriority: medium\n", "\npriority: high\n"}, + } { + if strings.Count(refreshed, edit[0]) != 1 { + t.Fatalf("churn edit %q does not match the record exactly once:\n%s", edit[0], refreshed) + } + refreshed = strings.Replace(refreshed, edit[0], edit[1], 1) + } + if refreshed == string(evidenced) { + t.Fatal("the churn left change 3's record byte-identical") + } churnedCorpus := []StatusBlob{ mxBlob(3, "widget", []byte(refreshed)), runTrackerInProgressBlob(9, "sibling", "2026-09-01T00:00:00Z"), @@ -266,8 +277,7 @@ func TestIntegrationRunFenceUnrelatedChurnDoesNotMoveOwnership(t *testing.T) { // TestIntegrationRunFenceReplacementClaimBlocksOldRun — spec acceptance item 6 second half: after A // is confirmed-bound to change 3 at claim-3-v1, a NEWER committed proof for change 3 -// under a different request id means the change was reclaimed and re-claimed by -// another run. A's verdict stops run-tracker-unavailable claim-replaced, never spends the +// under a different request id means another run claimed the change again. A's verdict stops run-tracker-unavailable claim-replaced, never spends the // retry, and a subsequent verdict still refuses — the old gate never takes over the // replacement run. func TestIntegrationRunFenceReplacementClaimBlocksOldRun(t *testing.T) { diff --git a/internal/app/runtracker_verdict.go b/internal/app/runtracker_verdict.go index ccaac7f36..d589b32dd 100644 --- a/internal/app/runtracker_verdict.go +++ b/internal/app/runtracker_verdict.go @@ -136,10 +136,11 @@ const ( // ReasonRunBindingConflict: more than one committed claim proof matches the // record's context hash with no binding to arbitrate — unsafe ownership. ReasonRunBindingConflict = "binding-conflict" - // ReasonRunClaimReplaced: the bound change was reclaimed and re-claimed by - // another run — the old gate must detect that replacement and cannot retry or - // take over the new claim (spec: "the old gate must detect that replacement and - // cannot retry or take over the new claim"). + // ReasonRunClaimReplaced: a newer claim proof exists for the bound change — + // another run claimed it again — so the old gate must detect that + // replacement and cannot retry or take over the new claim (spec: "the old + // gate must detect that replacement and cannot retry or take over the new + // claim"). ReasonRunClaimReplaced = "claim-replaced" // ReasonRunProofUnavailable: committed claim proofs could not be read (no // scanner wired, a scan fault, or the binding's own receipt unseeable) — without @@ -813,8 +814,8 @@ func resolveRunTrackerOwnership(ctx context.Context, deps PlanningDeps, wdeps Wo switch { case hasBinding && binding.Confirmed: // Continuity: the NEWEST proof naming the bound change must still be this - // binding's own claim. A newer proof under a different request id means the - // change was reclaimed and re-claimed by another run. + // binding's own claim. A newer proof under a different request id means + // another run claimed the change again after this binding's claim. newest, found := runTrackerNewestProofForChange(proofs, binding.ChangeID) if !found { // The binding's own confirmed receipt could not even be seen (truncated diff --git a/internal/app/runtracker_verdict_integration_test.go b/internal/app/runtracker_verdict_integration_test.go index 439daaf15..cdf2d37e1 100644 --- a/internal/app/runtracker_verdict_integration_test.go +++ b/internal/app/runtracker_verdict_integration_test.go @@ -14,7 +14,6 @@ import ( "path/filepath" "strings" "testing" - "time" "github.com/danielhanold/docket/internal/gatedrive" "github.com/danielhanold/docket/internal/repository" @@ -22,10 +21,10 @@ import ( ) // These are the `docket run verdict ` (attributed mode) tests (change -// 0334, Task 3). run verdict loads the durable gate record, attributes exactly -// one new in-progress claim through the three filters (id not in the before-set; -// claimed_at parses; claimed_at >= dispatch time), then delegates the run -// predicate to RunVerify and maps its verdict onto the attributed vocabulary — +// 0334, Task 3). run verdict loads the durable gate record, resolves the run's +// change from its confirmed claim binding and the exact committed claim proof +// (never from a record's claim timestamp), then delegates the run predicate to +// RunVerify and maps its verdict onto the attributed vocabulary — // consuming the single retry permit BEFORE emitting so a lost retry is the safe // failure, and failing closed to run-tracker-unavailable on any load error or // unrecognized verdict. Every outcome is a report line that exits 0. @@ -35,19 +34,6 @@ import ( // RunVerify delegation is driven by the run_verify_test.go fixtures (rvFixture, // rvRecord, rvInProgressRecord, rvPR, rvAgreeingReceipt). -// runTrackerClaimUnix is the Unix epoch of runTrackerDefaultClaimedAt — the claim instant -// lifecycleChange stamps on an in-progress record. Attribution filter (c) -// compares a candidate's claimed_at against the record's DispatchedAt, so tests -// straddle this value. -func runTrackerClaimUnix(t *testing.T) int64 { - t.Helper() - tm, err := time.Parse(time.RFC3339, runTrackerDefaultClaimedAt) - if err != nil { - t.Fatalf("parse %q: %v", runTrackerDefaultClaimedAt, err) - } - return tm.Unix() -} - // runTrackerLightDeps wires a planning-only deps set over the given corpus (no git // client, no workspace/github seams) for attribution paths that never reach // RunVerify. @@ -908,8 +894,8 @@ func TestIntegrationRunVerdictVerdictAbsentBindingAdoptsSoleProof(t *testing.T) } // TestIntegrationRunVerdictVerdictClaimReplacedStops: a confirmed binding whose bound change carries a -// NEWER proof under a different request id means the change was reclaimed and -// re-claimed by another run — the old gate must neither retry nor take over the +// NEWER proof under a different request id means another run claimed the +// change again — the old gate must neither retry nor take over the // replacement. The binding is left unchanged and the retry is never spent. func TestIntegrationRunVerdictVerdictClaimReplacedStops(t *testing.T) { repo := newRunTrackerRepo(t) diff --git a/internal/app/workflow_e2e_test.go b/internal/app/workflow_e2e_test.go index 164bd9b55..e30e1dc08 100644 --- a/internal/app/workflow_e2e_test.go +++ b/internal/app/workflow_e2e_test.go @@ -120,7 +120,7 @@ func driveClaimToImplemented(t *testing.T, repo *gitRepo, branch, ghBin string, t.Fatalf("claim = (%q, %q), want applied/applied (findings %v)", claim.Result, claim.Disposition, claim.Findings) } - // (3) Reconcile: sets reconciled:true and refreshes the claim. + // (3) Reconcile: sets reconciled:true and appends a reconcile-log entry. rec := ChangeReconcile(ctx, node.deps, node.dir, ChangeReconcileRequest{ ID: id, Revision: ver(), ReconcileLogEntry: "Reconciled against current reality.\n", diff --git a/internal/app/workflow_integration_test.go b/internal/app/workflow_integration_test.go index 0bf942d78..28ee5261a 100644 --- a/internal/app/workflow_integration_test.go +++ b/internal/app/workflow_integration_test.go @@ -1333,18 +1333,18 @@ func TestIntegrationWorkflowRepoContextServesClaimedChange(t *testing.T) { } // TestIntegrationWorkflowRepoReconcileAppliesWhenBoardReRenderIsUnchanged: a -// reconcile after a claim re-stamps the record's claimed_at and updated fields -// and flips reconciled (a real change to the record) and re-renders the inline -// board. The board's in-progress row shows only id/title/priority/type/spec/ +// reconcile after a claim re-stamps the record's updated field, appends a dated +// ## Reconcile log entry, and flips reconciled (a real change to the record) and +// re-renders the inline board. The board's in-progress row shows only id/title/priority/type/spec/ // branch — none of which a reconcile touches — so the re-render is // byte-identical to the board the claim already committed. Declaring that // unchanged board would trip the engine's two-way actual-delta guard ("a // declared path is not an actual change", a *Failure at stage verify-delta) — // the change 0335 bug, first seen on the since-deleted refresh-claim operation -// (change 0360 retargeted this test at reconcile, which now owns re-stamping the -// lease). The plan declares only the record, so the reconcile applies: one -// metadata commit touching exactly the record, the lease re-stamped, the -// committed board untouched and still matching a fresh render. +// (change 0360 retargeted this test at reconcile). The plan declares only the +// record, so the reconcile applies: one metadata commit touching exactly the +// record, updated: and the reconcile log advanced, the committed board untouched +// and still matching a fresh render. // // The reconcile runs a day after the claim (advanced clock) so the record // genuinely changes; that isolates the board as the sole would-be @@ -1381,8 +1381,8 @@ func TestIntegrationWorkflowRepoReconcileAppliesWhenBoardReRenderIsUnchanged(t * claimedRevision := blobRevisionAt(t, repo.origin, m.branch, recPath) - // Reconcile a day later: claimed_at/updated genuinely change on the - // record while the board re-renders byte-identical. + // Reconcile a day later: updated: and the reconcile log genuinely + // change on the record while the board re-renders byte-identical. reconcileNode := planningDepsForClock(t, cloneOrigin(t, repo.origin), advanced) res := ChangeReconcile(ctx, reconcileNode.deps, reconcileNode.dir, ChangeReconcileRequest{ ID: id, Revision: claimedRevision, ReconcileLogEntry: "Reconciled against current reality.\n", @@ -1403,17 +1403,21 @@ func TestIntegrationWorkflowRepoReconcileAppliesWhenBoardReRenderIsUnchanged(t * t.Errorf("reconcile commit changed %v, want exactly [%s] (unchanged board must not be declared)", got, recPath) } - // The lease actually moved to the advanced clock. + // The record actually moved with the advanced clock: updated: and a + // new dated reconcile-log entry. No claim stamp is written. final, ok := originFile(t, repo.origin, m.branch, recPath) if !ok { t.Fatalf("record %s missing from origin after reconcile", recPath) } - if !strings.Contains(final, "claimed_at: '2026-08-17T12:00:00Z'") { - t.Errorf("reconcile did not re-stamp claimed_at:\n%s", final) - } if !strings.Contains(final, "updated: '2026-08-17'") { t.Errorf("reconcile did not re-stamp updated:\n%s", final) } + if !strings.Contains(final, "## Reconcile log") || !strings.Contains(final, "### 2026-08-17\n\nReconciled against current reality.\n") { + t.Errorf("reconcile did not append its dated log entry:\n%s", final) + } + if strings.Contains(final, "claimed_at") { + t.Errorf("claim or reconcile wrote a claimed_at line:\n%s", final) + } // The committed board still matches a fresh render of the corpus. assertBoardMatchesCommitted(t, repo.origin, m.branch, reconcileNode.dir) diff --git a/internal/cli/change.go b/internal/cli/change.go index a84cffd4a..4233d705e 100644 --- a/internal/cli/change.go +++ b/internal/cli/change.go @@ -210,13 +210,13 @@ func newRelinkSubcommand(setResult func(app.OperationResult)) *cobra.Command { // newResumeHaltedSubcommand builds `change resume-halted`: human-authorized // recovery of a halted run. It requires the exact marked record, the explicit // --acknowledge-quiescent acknowledgement, reprobes the owned workspace, then -// refreshes the claim and removes the marker. The scalar identity rides on flags; +// removes the marker. The scalar identity rides on flags; // there is no authored request body. It composes the read-only planning seams and // the workspace service (to reprobe the owned checkout). func newResumeHaltedSubcommand(setResult func(app.OperationResult)) *cobra.Command { cmd := &cobra.Command{ Use: "resume-halted", - Short: "Recover a halted run: reprobe the workspace, refresh the claim, and remove the marker", + Short: "Recover a halted run: reprobe the workspace and remove the marker", Args: cobra.NoArgs, Annotations: capability("change.resume-halted", EffectMetadataWrite), RunE: func(c *cobra.Command, _ []string) error { diff --git a/internal/domain/actions.go b/internal/domain/actions.go index d0ad765c2..7b9cf0ee5 100644 --- a/internal/domain/actions.go +++ b/internal/domain/actions.go @@ -68,9 +68,6 @@ const ReasonBuiltStackDescendants = "built-stack-descendants" // ReasonNotDeferrable is the policy reason Defer gives for a change being built. const ReasonNotDeferrable = "not-deferrable" -// stampLayout is the second-precision UTC layout for claimed_at. -const stampLayout = time.RFC3339 - // dateLayout is the date-only layout for created:/updated:. const dateLayout = "2006-01-02" @@ -130,9 +127,9 @@ func ClaimEligibility(s Snapshot, c Change, facts BranchFacts) *PolicyFailure { // Claim moves a proposed change to in-progress, recording the minted // / branch, or / when the optional per-change -// override is present, the injected timestamp as claimed_at, and reconciled: -// false. A historical "## Run halted" section is reported as an owned removal -// — the domain identifies the marker; the document layer removes it. +// override is present, and reconciled: false. A historical "## Run halted" +// section is reported as an owned removal — the domain identifies the marker; +// the document layer removes it. // // Claim guards only what it can see from the record itself: a legal source // status, a slug that is a usable branch component, and a mint component (the @@ -141,7 +138,7 @@ func ClaimEligibility(s Snapshot, c Change, facts BranchFacts) *PolicyFailure { // an unambiguous id — is NOT checked here, because it needs the Snapshot this // signature deliberately does not take; ClaimEligibility is that condition and // the workflow layer calls it first. -func Claim(c Change, now time.Time) (ActionResult, *PolicyFailure) { +func Claim(c Change) (ActionResult, *PolicyFailure) { if fail := requireStatus(c, "claim", StatusProposed); fail != nil { return ActionResult{}, fail } @@ -162,7 +159,6 @@ func Claim(c Change, now time.Time) (ActionResult, *PolicyFailure) { b := newChangeBuilder(c) b.setStatus(StatusInProgress) b.setBranch(MintBranch(c.Type(), c.BranchPrefix(), c.Slug())) - b.setClaimedAt(now) b.setReconciled(false) if c.HasRunHalted() { b.own(RunHaltedSection) @@ -170,17 +166,6 @@ func Claim(c Change, now time.Time) (ActionResult, *PolicyFailure) { return b.result(), nil } -// RefreshClaim re-stamps an in-progress change's lease without changing any -// other field. Its callers are change.reconcile and change.resume-halted. -func RefreshClaim(c Change, now time.Time) (ActionResult, *PolicyFailure) { - if fail := requireStatus(c, "refresh-claim", StatusInProgress); fail != nil { - return ActionResult{}, fail - } - b := newChangeBuilder(c) - b.setClaimedAt(now) - return b.result(), nil -} - // Block moves an in-progress change to blocked, recording a non-empty reason. // An empty reason is a malformed supplied fact, not an illegal transition. func Block(c Change, reason string) (ActionResult, *PolicyFailure) { @@ -241,8 +226,8 @@ func Revive(c Change) (ActionResult, *PolicyFailure) { return b.result(), nil } -// Kill terminates a proposed or in-progress change, clearing its claim stamp -// and recorded branch: a killed record holds no lease and owns no branch. +// Kill terminates a proposed or in-progress change, clearing its recorded +// branch: a killed record owns no branch. func Kill(c Change) (ActionResult, *PolicyFailure) { if fail := requireStatus(c, "kill", StatusProposed, StatusInProgress); fail != nil { return ActionResult{}, fail @@ -254,7 +239,6 @@ func Kill(c Change) (ActionResult, *PolicyFailure) { func killedResult(c Change) ActionResult { b := newChangeBuilder(c) b.setStatus(StatusKilled) - b.clearClaimedAt() b.setBranch("") return b.result() } @@ -373,8 +357,7 @@ func MarkStackedMerged(c Change, parentBranch string, f MergeFacts) (ActionResul } // MarkDone terminates an implemented or stacked-merged change once -// reachability from the integration branch is supplied as a verified fact. The -// claim stamp is cleared: an archived record holds no lease. +// reachability from the integration branch is supplied as a verified fact. func MarkDone(c Change, f DoneFacts) (ActionResult, *PolicyFailure) { if fail := requireStatus(c, "mark-done", StatusImplemented, StatusStackedMerged); fail != nil { return ActionResult{}, fail @@ -384,16 +367,14 @@ func MarkDone(c Change, f DoneFacts) (ActionResult, *PolicyFailure) { } b := newChangeBuilder(c) b.setStatus(StatusDone) - b.clearClaimedAt() return b.result(), nil } // Complete is the results-artifact ending: it terminates a proposed or // in-progress change whose deliverable is results-artifact, carries attached // results, and records no PR, moving it straight to done without a PR. The -// claim stamp is cleared (an archived record holds no lease); the recorded -// branch is kept, so finalize cleanup can find and delete it. A historical -// "## Run halted" section is an owned removal. The deliverable check keys on +// recorded branch is kept, so finalize cleanup can find and delete it. A +// historical "## Run halted" section is an owned removal. The deliverable check keys on // the effective value, so an absent field (pr) and an unknown stored value are // both refused rather than guessed. updated: is left to the persisting layer. func Complete(c Change) (ActionResult, *PolicyFailure) { @@ -415,7 +396,6 @@ func Complete(c Change) (ActionResult, *PolicyFailure) { } b := newChangeBuilder(c) b.setStatus(StatusDone) - b.clearClaimedAt() if c.HasRunHalted() { b.own(RunHaltedSection) } @@ -483,7 +463,6 @@ func newChangeBuilder(c Change) *changeBuilder { Hold: c.Hold(), BranchPrefix: c.BranchPrefix(), Branch: c.Branch(), - ClaimedAt: c.ClaimedAt(), PR: c.PR(), Issue: c.Issue(), BlockedBy: c.BlockedBy(), @@ -548,20 +527,6 @@ func (b *changeBuilder) setOptionalString(field string, target *OptionalString, *target = next } -// setClaimedAt stamps the lease at second-precision UTC. -func (b *changeBuilder) setClaimedAt(now time.Time) { - stamp := now.UTC().Truncate(time.Second) - next := OptionalTime{State: FieldPresent, Value: stamp, Raw: stamp.Format(stampLayout)} - b.record("claimed_at", b.spec.ClaimedAt.Raw, next.Raw) - b.spec.ClaimedAt = next -} - -// clearClaimedAt drops the lease stamp entirely. -func (b *changeBuilder) clearClaimedAt() { - b.record("claimed_at", b.spec.ClaimedAt.Raw, "") - b.spec.ClaimedAt = OptionalTime{} -} - // setUpdated stamps the date-only updated: field from the injected time. func (b *changeBuilder) setUpdated(now time.Time) { u := now.UTC() diff --git a/internal/domain/actions_test.go b/internal/domain/actions_test.go index 93d047214..4ea69c5d3 100644 --- a/internal/domain/actions_test.go +++ b/internal/domain/actions_test.go @@ -19,7 +19,6 @@ type actSpec struct { typ string // change type token; build defaults an empty value to "feat" branchPrefix string // per-change branch_prefix override, present when non-empty branch string - claimedAt string blockedBy string pr string plan string @@ -56,13 +55,6 @@ func (as actSpec) build() Change { if as.branch != "" { cs.Branch = OptionalString{State: FieldPresent, Value: as.branch} } - if as.claimedAt != "" { - stamp, err := time.Parse(time.RFC3339, as.claimedAt) - if err != nil { - panic(err) - } - cs.ClaimedAt = OptionalTime{State: FieldPresent, Value: stamp, Raw: as.claimedAt} - } if as.blockedBy != "" { cs.BlockedBy = OptionalString{State: FieldPresent, Value: as.blockedBy} } @@ -105,7 +97,6 @@ var allStatuses = []Status{ func fingerprint(c Change) string { return string(c.Status()) + "|" + c.RawStatus() + "|" + c.Branch().Value + "|" + string(rune('0'+int(c.Branch().State))) + "|" + - c.ClaimedAt().Raw + "|" + string(rune('0'+int(c.ClaimedAt().State))) + "|" + c.BlockedBy().Value + "|" + string(rune('0'+int(c.BlockedBy().State))) + "|" + c.PR().Value + "|" + c.Plan().Value + "|" + c.Updated().Raw + "|" + map[bool]string{true: "T", false: "F"}[c.Reconciled()] @@ -153,14 +144,9 @@ type actionCase struct { var matrixActions = []actionCase{ { name: "Claim", - apply: func(c Change) (ActionResult, *PolicyFailure) { return Claim(c, actNow) }, + apply: Claim, legal: map[Status]Status{StatusProposed: StatusInProgress}, }, - { - name: "RefreshClaim", - apply: func(c Change) (ActionResult, *PolicyFailure) { return RefreshClaim(c, actNow) }, - legal: map[Status]Status{StatusInProgress: StatusInProgress}, - }, { name: "Block", apply: func(c Change) (ActionResult, *PolicyFailure) { return Block(c, "waiting on review") }, @@ -221,7 +207,6 @@ func TestActionSourceStateMatrix(t *testing.T) { slug: "a-slug", status: from, branch: "feat/a-slug", - claimedAt: "2026-08-10T00:00:00Z", pr: "#7", plan: "docs/plan.md", reconciled: true, @@ -268,10 +253,10 @@ func TestActionSourceStateMatrix(t *testing.T) { } } -func TestClaimSetsBranchStampAndReconciled(t *testing.T) { +func TestClaimSetsBranchAndReconciled(t *testing.T) { input := actSpec{id: 12, slug: "widget-work", status: StatusProposed, reconciled: true}.build() - got, fail := Claim(input, actNow) + got, fail := Claim(input) if fail != nil { t.Fatalf("Claim failed: %v", fail) } @@ -282,21 +267,17 @@ func TestClaimSetsBranchStampAndReconciled(t *testing.T) { if b := got.Change.Branch(); b.State != FieldPresent || b.Value != wantBranch { t.Fatalf("branch = %+v, want %q", b, wantBranch) } - stamp := got.Change.ClaimedAt() - if stamp.State != FieldPresent || stamp.Raw != "2026-08-14T09:30:15Z" { - t.Fatalf("claimed_at = %+v, want the injected now", stamp) - } - if !stamp.Value.Equal(actNow) { - t.Fatalf("claimed_at value = %v, want %v", stamp.Value, actNow) - } if got.Change.Reconciled() { t.Fatal("reconciled should be cleared by a claim") } - for _, field := range []string{"status", "branch", "claimed_at", "reconciled"} { + for _, field := range []string{"status", "branch", "reconciled"} { if !hasField(got, field) { t.Fatalf("Changed set omits %q: %v", field, changedFields(got)) } } + if hasField(got, "claimed_at") { + t.Fatalf("a claim writes no claimed_at: %v", changedFields(got)) + } if len(got.OwnedRemovals) != 0 { t.Fatalf("OwnedRemovals = %v, want none without a run-halted section", got.OwnedRemovals) } @@ -304,7 +285,7 @@ func TestClaimSetsBranchStampAndReconciled(t *testing.T) { func TestClaimOwnsRunHaltedRemovalOnlyWhenPresent(t *testing.T) { halted := actSpec{id: 3, slug: "s", status: StatusProposed, runHalted: true}.build() - got, fail := Claim(halted, actNow) + got, fail := Claim(halted) if fail != nil { t.Fatalf("Claim failed: %v", fail) } @@ -318,30 +299,6 @@ func TestClaimOwnsRunHaltedRemovalOnlyWhenPresent(t *testing.T) { } } -func TestRefreshClaimRestampsOnly(t *testing.T) { - input := actSpec{ - id: 5, slug: "s", status: StatusInProgress, - branch: "feat/s", claimedAt: "2026-08-01T00:00:00Z", - }.build() - - got, fail := RefreshClaim(input, actNow) - if fail != nil { - t.Fatalf("RefreshClaim failed: %v", fail) - } - if got.Change.Status() != StatusInProgress { - t.Fatalf("status = %q", got.Change.Status()) - } - if fields := changedFields(got); len(fields) != 1 || fields[0] != "claimed_at" { - t.Fatalf("Changed = %v, want only claimed_at", fields) - } - if to, _ := fieldTo(got, "claimed_at"); to != "2026-08-14T09:30:15Z" { - t.Fatalf("claimed_at To = %q", to) - } - if got.Change.Branch().Value != "feat/s" { - t.Fatal("refresh must not touch the branch") - } -} - func TestBlockRequiresNonEmptyReason(t *testing.T) { input := actSpec{id: 9, slug: "s", status: StatusInProgress}.build() @@ -387,10 +344,10 @@ func TestUnblockClearsReason(t *testing.T) { } } -func TestKillClearsClaimAndBranch(t *testing.T) { +func TestKillClearsBranch(t *testing.T) { input := actSpec{ id: 4, slug: "s", status: StatusInProgress, - branch: "feat/s", claimedAt: "2026-08-01T00:00:00Z", + branch: "feat/s", }.build() got, fail := Kill(input) @@ -400,15 +357,14 @@ func TestKillClearsClaimAndBranch(t *testing.T) { if got.Change.Status() != StatusKilled { t.Fatalf("status = %q", got.Change.Status()) } - if got.Change.ClaimedAt().State != FieldAbsent || got.Change.Branch().State != FieldAbsent { - t.Fatalf("kill must clear claimed_at and branch: %+v %+v", - got.Change.ClaimedAt(), got.Change.Branch()) + if got.Change.Branch().State != FieldAbsent { + t.Fatalf("kill must clear branch: %+v", got.Change.Branch()) } - for _, field := range []string{"claimed_at", "branch"} { - to, ok := fieldTo(got, field) - if !ok || to != "" { - t.Fatalf("Changed %q To = %q, ok=%v", field, to, ok) - } + if to, ok := fieldTo(got, "branch"); !ok || to != "" { + t.Fatalf("Changed branch To = %q, ok=%v", to, ok) + } + if hasField(got, "claimed_at") { + t.Fatalf("a kill writes no claimed_at: %v", changedFields(got)) } } @@ -534,7 +490,7 @@ func TestMarkDoneRequiresReachability(t *testing.T) { for _, from := range []Status{StatusImplemented, StatusStackedMerged} { input := actSpec{ id: 2, slug: "s", status: from, - branch: "feat/s", claimedAt: "2026-08-01T00:00:00Z", + branch: "feat/s", }.build() if _, fail := MarkDone(input, DoneFacts{}); fail == nil { @@ -550,8 +506,8 @@ func TestMarkDoneRequiresReachability(t *testing.T) { if got.Change.Status() != StatusDone { t.Fatalf("%s: status = %q", from, got.Change.Status()) } - if got.Change.ClaimedAt().State != FieldAbsent { - t.Fatal("a done record must carry no claim stamp") + if hasField(got, "claimed_at") { + t.Fatalf("%s: MarkDone writes no claimed_at: %v", from, changedFields(got)) } } } @@ -669,8 +625,7 @@ func TestKillInSnapshotTerminatesOnCycle(t *testing.T) { } func TestKillInSnapshotLeavesDescendantsUntouched(t *testing.T) { - parent := actSpec{id: 1, slug: "root", status: StatusInProgress, branch: "feat/root", - claimedAt: "2026-08-01T00:00:00Z"} + parent := actSpec{id: 1, slug: "root", status: StatusInProgress, branch: "feat/root"} snap := actSnapshot(parent, actSpec{id: 2, slug: "kid", status: StatusProposed, parent: edge(1)}) before := map[ChangeID]string{} for _, c := range snap.Changes() { @@ -690,7 +645,7 @@ func TestKillInSnapshotLeavesDescendantsUntouched(t *testing.T) { } for _, f := range changedFields(result) { switch f { - case "status", "claimed_at", "branch": + case "status", "branch": default: t.Fatalf("Changed names %q; a kill rewrites only the parent's own fields", f) } @@ -734,7 +689,7 @@ func TestActionsPreserveUnrelatedFields(t *testing.T) { dependsOn: []ChangeID{1, 2}, }.build() - got, fail := Claim(input, actNow) + got, fail := Claim(input) if fail != nil { t.Fatalf("Claim failed: %v", fail) } @@ -937,7 +892,7 @@ func TestClaimEligibilityDoesNotTransition(t *testing.T) { } // Claim itself stays a pure status transition: the eligibility condition is // the workflow layer's to call, so Claim still succeeds here. - if _, fail := Claim(c, actNow); fail != nil { + if _, fail := Claim(c); fail != nil { t.Fatalf("Claim failed: %v", fail) } } @@ -947,7 +902,7 @@ func TestClaimRefusesUnusableSlug(t *testing.T) { for _, slug := range bad { t.Run("slug="+slug, func(t *testing.T) { c := NewChange(ChangeSpec{ID: 4, Slug: slug, Status: StatusProposed}) - _, fail := Claim(c, actNow) + _, fail := Claim(c) if fail == nil { t.Fatalf("Claim accepted slug %q", slug) } @@ -960,7 +915,7 @@ func TestClaimRefusesUnusableSlug(t *testing.T) { for _, slug := range []string{"a-slug", "2fa-support", "x"} { t.Run("ok="+slug, func(t *testing.T) { c := NewChange(ChangeSpec{ID: 4, Slug: slug, Status: StatusProposed, Type: "feat"}) - got, fail := Claim(c, actNow) + got, fail := Claim(c) if fail != nil { t.Fatalf("Claim(%q) failed: %v", slug, fail) } @@ -981,7 +936,7 @@ func TestClaimMintsTypePrefixedBranch(t *testing.T) { } { t.Run(tc.typ, func(t *testing.T) { c := actSpec{id: 20, slug: "widget", status: StatusProposed, typ: tc.typ}.build() - got, fail := Claim(c, actNow) + got, fail := Claim(c) if fail != nil { t.Fatalf("Claim failed: %v", fail) } @@ -996,7 +951,7 @@ func TestClaimHonorsBranchPrefixOverride(t *testing.T) { c := actSpec{ id: 21, slug: "widget", status: StatusProposed, typ: "fix", branchPrefix: "hotfix", }.build() - got, fail := Claim(c, actNow) + got, fail := Claim(c) if fail != nil { t.Fatalf("Claim failed: %v", fail) } @@ -1017,7 +972,7 @@ func TestClaimRejectsInvalidBranchComponent(t *testing.T) { t.Run(tc.name, func(t *testing.T) { input := tc.spec.build() before := fingerprint(input) - _, fail := Claim(input, actNow) + _, fail := Claim(input) if fail == nil { t.Fatal("Claim accepted an invalid branch component") } @@ -1059,7 +1014,7 @@ func TestCompleteMatrix(t *testing.T) { t.Run(fmt.Sprintf("in-progress completes (run halted %v)", halted), func(t *testing.T) { got, fail := Complete(actSpec{ id: 9, slug: "s", status: StatusInProgress, branch: "feat/s", - claimedAt: "2026-08-01T00:00:00Z", deliverable: ra, results: res, runHalted: halted, + deliverable: ra, results: res, runHalted: halted, }.build()) if fail != nil { t.Fatalf("Complete failed: %v", fail) @@ -1067,11 +1022,8 @@ func TestCompleteMatrix(t *testing.T) { if got.Change.Status() != StatusDone { t.Fatalf("status = %q, want done", got.Change.Status()) } - if got.Change.ClaimedAt().State != FieldAbsent { - t.Fatalf("claimed_at not cleared: %+v", got.Change.ClaimedAt()) - } - if to, ok := fieldTo(got, "claimed_at"); !ok || to != "" { - t.Fatalf("Changed claimed_at To = %q, ok=%v", to, ok) + if hasField(got, "claimed_at") { + t.Fatalf("Complete writes no claimed_at: %v", changedFields(got)) } if got.Change.Branch().Value != "feat/s" { t.Fatalf("branch = %+v, want kept", got.Change.Branch()) @@ -1124,7 +1076,7 @@ func TestCompleteMatrix(t *testing.T) { // deferred; every other non-proposed source keeps illegal-source-status. func TestDeferRefusesInProgressAsNotDeferrable(t *testing.T) { in := actSpec{id: 7, slug: "a-slug", status: StatusInProgress, branch: "feat/a-slug", - claimedAt: "2026-08-10T00:00:00Z", plan: "docs/plan.md", reconciled: true}.build() + plan: "docs/plan.md", reconciled: true}.build() before := fingerprint(in) _, fail := Defer(in) if fingerprint(in) != before { diff --git a/internal/domain/entities.go b/internal/domain/entities.go index 02d3899f2..9836053f3 100644 --- a/internal/domain/entities.go +++ b/internal/domain/entities.go @@ -95,7 +95,6 @@ type ChangeSpec struct { Hold OptionalBool // per-change hold; keeps the change out of autonomous build selection BranchPrefix OptionalString // per-change mint-prefix override; durable input Branch OptionalString - ClaimedAt OptionalTime // second-precision UTC; Raw kept PR OptionalString Issue OptionalString BlockedBy OptionalString @@ -222,9 +221,6 @@ func (c Change) BranchPrefix() OptionalString { return c.spec.BranchPrefix } // Branch returns the optional feature branch name. func (c Change) Branch() OptionalString { return c.spec.Branch } -// ClaimedAt returns the optional claim timestamp. -func (c Change) ClaimedAt() OptionalTime { return c.spec.ClaimedAt } - // PR returns the optional pull request reference. func (c Change) PR() OptionalString { return c.spec.PR } diff --git a/internal/domain/entities_test.go b/internal/domain/entities_test.go index e95f317a6..f2fe23820 100644 --- a/internal/domain/entities_test.go +++ b/internal/domain/entities_test.go @@ -45,7 +45,6 @@ func fullChangeSpec(t *testing.T) ChangeSpec { Plan: OptionalString{State: FieldEmpty}, Results: OptionalString{State: FieldAbsent}, Branch: OptionalString{State: FieldPresent, Value: "feat/domain-snapshot"}, - ClaimedAt: OptionalTime{State: FieldPresent, Value: time.Date(2026, 8, 13, 4, 5, 6, 0, time.UTC), Raw: "2026-08-13T04:05:06Z"}, PR: OptionalString{State: FieldPresent, Value: "https://example.test/pr/1"}, Issue: OptionalString{State: FieldMalformed, Value: "#"}, BlockedBy: OptionalString{State: FieldEmpty}, @@ -113,9 +112,6 @@ func TestChangeAccessorsRoundTrip(t *testing.T) { if got := c.Branch(); got != spec.Branch { t.Errorf("Branch() = %+v; want %+v", got, spec.Branch) } - if got := c.ClaimedAt(); got != spec.ClaimedAt { - t.Errorf("ClaimedAt() = %+v; want %+v", got, spec.ClaimedAt) - } if got := c.PR(); got != spec.PR { t.Errorf("PR() = %+v; want %+v", got, spec.PR) } @@ -154,26 +150,26 @@ func TestChangeAccessorsRoundTrip(t *testing.T) { // TestChangeOptionalFieldStates walks all four FieldStates through the // optional accessors the decoder relies on most. func TestChangeOptionalFieldStates(t *testing.T) { - claimRaw := "2026-08-13T04:05:06Z" - claimVal := time.Date(2026, 8, 13, 4, 5, 6, 0, time.UTC) + updatedRaw := "2026-08-13" + updatedVal := time.Date(2026, 8, 13, 0, 0, 0, 0, time.UTC) tests := []struct { - name string - spec OptionalString - claim OptionalTime + name string + spec OptionalString + updated OptionalTime }{ {"absent", OptionalString{State: FieldAbsent}, OptionalTime{State: FieldAbsent}}, {"empty", OptionalString{State: FieldEmpty}, OptionalTime{State: FieldEmpty, Raw: ""}}, {"malformed", OptionalString{State: FieldMalformed, Value: " "}, OptionalTime{State: FieldMalformed, Raw: "yesterday"}}, - {"present", OptionalString{State: FieldPresent, Value: "docs/spec.md"}, OptionalTime{State: FieldPresent, Value: claimVal, Raw: claimRaw}}, + {"present", OptionalString{State: FieldPresent, Value: "docs/spec.md"}, OptionalTime{State: FieldPresent, Value: updatedVal, Raw: updatedRaw}}, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - c := NewChange(ChangeSpec{Spec: tc.spec, ClaimedAt: tc.claim}) + c := NewChange(ChangeSpec{Spec: tc.spec, Updated: tc.updated}) if got := c.Spec(); got != tc.spec { t.Errorf("Spec() = %+v; want %+v", got, tc.spec) } - if got := c.ClaimedAt(); got != tc.claim { - t.Errorf("ClaimedAt() = %+v; want %+v", got, tc.claim) + if got := c.Updated(); got != tc.updated { + t.Errorf("Updated() = %+v; want %+v", got, tc.updated) } }) } diff --git a/internal/domain/lease.go b/internal/domain/lease.go deleted file mode 100644 index 1f4b348e5..000000000 --- a/internal/domain/lease.go +++ /dev/null @@ -1,48 +0,0 @@ -package domain - -import "time" - -// LeaseState is a claim lease's evaluated condition. It takes a fixed set of allowed values -// rather than a Boolean "stale" because the three non-fresh conditions are not -// interchangeable: an expired lease is positive evidence that a claim aged out, -// while a missing or malformed stamp is evidence of nothing at all — a record -// whose stamp cannot be read must never be treated as having aged out. -type LeaseState string - -// The closed set of lease states. -const ( - LeaseFresh LeaseState = "fresh" // claimed within the TTL - LeaseExpired LeaseState = "expired" // claimed strictly longer ago than the TTL - LeaseMissing LeaseState = "missing" // no claim stamp recorded - LeaseMalformed LeaseState = "malformed" // stamp present but unparseable - LeaseNotInProgress LeaseState = "not-in-progress" // the record holds no lease -) - -// EvaluateLease reports the condition of c's claim lease against the injected -// now and a TTL in hours. -// -// Status outranks the stamp: only an in-progress record holds a lease, so any -// other status reports not-in-progress whatever its stamp says. A stamp that is -// absent or present-but-empty is missing; one that is present but unparseable -// is malformed. Neither is expiry. -// -// The TTL boundary is strict: elapsed time must exceed the TTL to expire, so a -// lease evaluated at exactly its deadline is still fresh. A stamp in the future -// is fresh for the same reason — its elapsed time does not exceed the TTL. -func EvaluateLease(c Change, now time.Time, ttlHours int) LeaseState { - if c.Status() != StatusInProgress { - return LeaseNotInProgress - } - stamp := c.ClaimedAt() - switch stamp.State { - case FieldMalformed: - return LeaseMalformed - case FieldPresent: - if now.Sub(stamp.Value) > time.Duration(ttlHours)*time.Hour { - return LeaseExpired - } - return LeaseFresh - default: // FieldAbsent, FieldEmpty — no stamp to read - return LeaseMissing - } -} diff --git a/internal/domain/lease_test.go b/internal/domain/lease_test.go deleted file mode 100644 index 7c06e629b..000000000 --- a/internal/domain/lease_test.go +++ /dev/null @@ -1,76 +0,0 @@ -package domain - -import ( - "testing" - "time" -) - -// leaseNow is the injected clock reading every lease test evaluates against. -var leaseNow = time.Date(2026, 8, 14, 12, 0, 0, 0, time.UTC) - -// leaseTTL is the TTL every lease test uses unless it says otherwise. -const leaseTTL = 4 - -// leaseChange builds an in-progress change whose claim stamp is supplied as a -// ready-made OptionalTime, so a test can express absent, empty, malformed, and -// present stamps without going through a parser. -func leaseChange(status Status, stamp OptionalTime, branch string) Change { - cs := ChangeSpec{ - ID: 7, - Slug: "lease-slug", - Type: "feat", - Status: status, - RawStatus: string(status), - ClaimedAt: stamp, - } - if branch != "" { - cs.Branch = OptionalString{State: FieldPresent, Value: branch} - } - return NewChange(cs) -} - -// leaseStamp renders a present claim stamp offset from leaseNow: a negative -// offset is a claim taken in the past. -func leaseStamp(offset time.Duration) OptionalTime { - at := leaseNow.Add(offset) - return OptionalTime{State: FieldPresent, Value: at, Raw: at.Format(time.RFC3339)} -} - -func TestEvaluateLeaseStates(t *testing.T) { - cases := []struct { - name string - status Status - stamp OptionalTime - want LeaseState - }{ - {"well under ttl", StatusInProgress, leaseStamp(-time.Hour), LeaseFresh}, - {"one second under ttl", StatusInProgress, leaseStamp(-(leaseTTL*time.Hour - time.Second)), LeaseFresh}, - {"exactly at ttl is fresh", StatusInProgress, leaseStamp(-leaseTTL * time.Hour), LeaseFresh}, - {"one second past ttl", StatusInProgress, leaseStamp(-(leaseTTL*time.Hour + time.Second)), LeaseExpired}, - {"far past ttl", StatusInProgress, leaseStamp(-100 * time.Hour), LeaseExpired}, - {"stamp in the future", StatusInProgress, leaseStamp(2 * time.Hour), LeaseFresh}, - {"absent stamp", StatusInProgress, OptionalTime{}, LeaseMissing}, - {"empty stamp", StatusInProgress, OptionalTime{State: FieldEmpty}, LeaseMissing}, - {"malformed stamp", StatusInProgress, OptionalTime{State: FieldMalformed, Raw: "yesterday"}, LeaseMalformed}, - {"proposed change", StatusProposed, leaseStamp(-100 * time.Hour), LeaseNotInProgress}, - {"blocked change", StatusBlocked, leaseStamp(-100 * time.Hour), LeaseNotInProgress}, - {"done change", StatusDone, OptionalTime{}, LeaseNotInProgress}, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - got := EvaluateLease(leaseChange(tc.status, tc.stamp, ""), leaseNow, leaseTTL) - if got != tc.want { - t.Fatalf("EvaluateLease = %q, want %q", got, tc.want) - } - }) - } -} - -func TestEvaluateLeaseStatusOutranksStamp(t *testing.T) { - // An archived record with a malformed stamp is still reported by status: - // the stamp of a change holding no lease is not a lease diagnosis. - got := EvaluateLease(leaseChange(StatusKilled, OptionalTime{State: FieldMalformed, Raw: "??"}, ""), leaseNow, leaseTTL) - if got != LeaseNotInProgress { - t.Fatalf("EvaluateLease = %q, want %q", got, LeaseNotInProgress) - } -} diff --git a/internal/domain/types_test.go b/internal/domain/types_test.go index 719b3449e..32bb3f8f5 100644 --- a/internal/domain/types_test.go +++ b/internal/domain/types_test.go @@ -335,7 +335,7 @@ func TestLifecycleActionCarriesDeliverable(t *testing.T) { // claim keeps the stored hold rather than dropping it. func TestLifecycleActionCarriesHold(t *testing.T) { c := NewChange(ChangeSpec{ID: 1, Slug: "s", Status: StatusProposed, Type: "feat", Spec: specRef("docs/specs/a.md"), Hold: holdTrue}) - res, fail := Claim(c, actNow) + res, fail := Claim(c) if fail != nil { t.Fatalf("Claim: %v", fail) } diff --git a/internal/repository/decode.go b/internal/repository/decode.go index bce3d1aee..e3bb7debe 100644 --- a/internal/repository/decode.go +++ b/internal/repository/decode.go @@ -33,12 +33,8 @@ const ( CodeLearningPromotionUnknown = "learning-promotion-unknown" ) -// dateLayout is the stored date-only spelling; stampLayout the claim -// timestamp's second-precision UTC spelling. -const ( - dateLayout = "2006-01-02" - stampLayout = time.RFC3339 -) +// dateLayout is the stored date-only spelling. +const dateLayout = "2006-01-02" // archiveDatePrefixLen is the length of an archive filename's "YYYY-MM-DD" // prefix, which is followed by a hyphen. @@ -126,7 +122,6 @@ type changeWire struct { Hold scalar `yaml:"hold"` BranchPrefix scalar `yaml:"branch_prefix"` Branch scalar `yaml:"branch"` - ClaimedAt scalar `yaml:"claimed_at"` PR scalar `yaml:"pr"` Issue scalar `yaml:"issue"` BlockedBy scalar `yaml:"blocked_by"` @@ -579,7 +574,6 @@ func decodeChange(in InputDocument) (domain.Change, []domain.Finding) { spec.Hold = d.optionalBool("hold", wire.Hold) spec.BranchPrefix = d.optionalString("branch_prefix", wire.BranchPrefix) spec.Branch = d.optionalString("branch", wire.Branch) - spec.ClaimedAt = d.optionalTime("claimed_at", wire.ClaimedAt, stampLayout) spec.PR = d.optionalString("pr", wire.PR) spec.Issue = d.optionalString("issue", wire.Issue) spec.BlockedBy = d.optionalString("blocked_by", wire.BlockedBy) diff --git a/internal/repository/decode_test.go b/internal/repository/decode_test.go index c8fd3d308..b449d6c76 100644 --- a/internal/repository/decode_test.go +++ b/internal/repository/decode_test.go @@ -3,6 +3,7 @@ package repository import ( "crypto/sha256" "encoding/hex" + "strings" "testing" "time" @@ -140,12 +141,6 @@ func TestDecodeChangeHappyPath(t *testing.T) { got.Value != "feat/domain-snapshot-validation-graphs-and-selection" { t.Errorf("Branch = %+v", got) } - claimed := change.ClaimedAt() - if claimed.State != domain.FieldPresent || - !claimed.Value.Equal(time.Date(2026, 8, 14, 2, 39, 23, 0, time.UTC)) || - claimed.Raw != "2026-08-14T02:39:23Z" { - t.Errorf("ClaimedAt = %+v", claimed) - } if got := change.PR(); got.State != domain.FieldPresent || got.Value != "https://github.com/danielhanold/docket/pull/7" { t.Errorf("PR = %+v", got) @@ -217,18 +212,9 @@ func TestDecodeChangeOptionalStates(t *testing.T) { field: "created", }, { - name: "claimed_at malformed timestamp", - frontmatter: "id: 1\nslug: s\nclaimed_at: yesterday\n", - want: func(c domain.Change) (domain.FieldState, string) { return c.ClaimedAt().State, c.ClaimedAt().Raw }, - wantState: domain.FieldMalformed, - wantRaw: "yesterday", - wantFinding: true, - field: "claimed_at", - }, - { - name: "claimed_at empty is never malformed", - frontmatter: "id: 1\nslug: s\nclaimed_at:\n", - want: func(c domain.Change) (domain.FieldState, string) { return c.ClaimedAt().State, c.ClaimedAt().Raw }, + name: "updated empty is never malformed", + frontmatter: "id: 1\nslug: s\nupdated:\n", + want: func(c domain.Change) (domain.FieldState, string) { return c.Updated().State, c.Updated().Raw }, wantState: domain.FieldEmpty, }, { @@ -266,6 +252,30 @@ func TestDecodeChangeOptionalStates(t *testing.T) { } } +// TestDecodeIgnoresClaimedAt pins that a retired claimed_at: line is +// compatibility data: an older record carrying it stamped, empty, or malformed +// decodes with no finding, because nothing reads the line any more. +func TestDecodeIgnoresClaimedAt(t *testing.T) { + const stamped = "claimed_at: 2026-08-14T02:39:23Z\n" + if n := strings.Count(happyChange, stamped); n != 1 { + t.Fatalf("happyChange carries %d stamped claimed_at lines, want 1", n) + } + for name, line := range map[string]string{ + "stamped": stamped, + "empty": "claimed_at:\n", + "malformed": "claimed_at: not-a-time\n", + } { + t.Run(name, func(t *testing.T) { + src := strings.Replace(happyChange, stamped, line, 1) + _, findings := decodeChange(input(t, KindChange, LocationActive, + "docs/changes/active/0307-domain-snapshot-validation-graphs-and-selection.md", src)) + if len(findings) != 0 { + t.Errorf("claimed_at %q produced findings %v; the retired line must load silently", line, findingCodes(findings)) + } + }) + } +} + // TestDecodeChangeIgnoresBodyKeylikeLines pins the body-prose hazard: the // decoder reads frontmatter only, so a key-shaped line in a paragraph never // becomes a field value. From 51231224e7779aaec2087a167713373874096f6e Mon Sep 17 00:00:00 2001 From: Daniel Hanold Date: Thu, 22 Oct 2026 07:33:38 -0400 Subject: [PATCH 5/7] docs: describe resume-by-id as the only recovery for a stranded run --- docs/README.md | 2 +- docs/comparison/ai-native-sdlc-playbook.md | 6 +- docs/concepts/change-lifecycle.md | 2 +- docs/guide/README.md | 2 +- docs/guide/building-without-supervision.md | 7 +-- docs/guide/capturing-work.md | 12 +--- docs/guide/keeping-the-backlog-honest.md | 58 ++++--------------- docs/install/global-config.md | 2 +- docs/reference/cli.md | 4 +- docs/reference/config-keys.md | 2 - docs/reference/fields.md | 4 +- docs/reference/glossary.md | 39 +++---------- internal/assets/embedded/manifest.json | 18 +++--- .../tree/skills/docket-convention/SKILL.md | 14 +---- .../skills/docket-implement-next/SKILL.md | 14 ++--- .../references/edge-paths.md | 12 ++-- .../tree/skills/docket-status/SKILL.md | 19 +++--- internal/repoguard/budgets_test.go | 8 +-- internal/repoguard/prose_contracts_test.go | 23 ++++++-- skills/docket-convention/SKILL.md | 14 +---- skills/docket-implement-next/SKILL.md | 14 ++--- .../references/edge-paths.md | 12 ++-- skills/docket-status/SKILL.md | 19 +++--- 23 files changed, 118 insertions(+), 189 deletions(-) diff --git a/docs/README.md b/docs/README.md index 4971b0475..b926a9498 100644 --- a/docs/README.md +++ b/docs/README.md @@ -59,7 +59,7 @@ Index: [guide/README.md](guide/README.md) pull request into your mainline and out of your backlog, hands-off across a whole set of changes. - [Status: Keeping the backlog honest](guide/keeping-the-backlog-honest.md) — tell whether your backlog still reflects reality, and fix it when it does not: the read-only status report, the maintenance - sweep, reclaiming expired claims, and recovering a halted run. + sweep, and recovering a halted run. - [ADRs and learnings: Remembering why](guide/remembering-why.md) — where docket keeps the decisions it made and the lessons it learned, how you record a finding, and when a lesson belongs in your always-in-context instructions instead. diff --git a/docs/comparison/ai-native-sdlc-playbook.md b/docs/comparison/ai-native-sdlc-playbook.md index 9cbc8fb54..ef0b85fc2 100644 --- a/docs/comparison/ai-native-sdlc-playbook.md +++ b/docs/comparison/ai-native-sdlc-playbook.md @@ -118,7 +118,7 @@ fail-closed operations. In return docket has depth the playbook never mentions. | Scheduled security scans | Claude Security; validated findings; patches through the PR gate. | None. | Playbook only | | Incident channels and ticket triage | Claude in Slack/Teams as first responder. | None. | Playbook only | | Findings re-enter the pipeline | From production and scans. | From builds and close-outs, reported; a human files with `docket change create`. | Both (different source, manual capture) | -| Backlog hygiene and self-healing | Not described. | `docket status` (read-only), `maintenance sweep`, reclaim of expired branchless claims, `change resume-halted`. | docket only | +| Backlog hygiene and self-healing | Not described. | `docket status` (read-only), `maintenance sweep`, resume by id, `change resume-halted`. | docket only | | Health checks with typed findings | Not described. | Validation, artifact integrity, derived-view drift, topology, prepare-time refusals; two judgement checks warn-only. | docket only | | Decision ledger | Not described. | Immutable numbered ADRs; supersede and reverse as new records; 96 today. | docket only | | Build-loop memory with relevance-gated reads | `CLAUDE.md` always in context. | Findings read per relevance at groom, plan, review; only unprompted rules promoted. Harvest and index deferred. | docket · deferred | @@ -144,7 +144,7 @@ is current when build starts; docket assumes it is not. |---|---|---|---| | Governance as configuration | Skills, hooks, managed settings; `CLAUDE.md` and `REVIEW.md` reviewed like code. | Four config layers per key; shared-setting guard; every key documented in `.docket.example.yml` or the suite fails; the capability catalog is the only hard-coded CLI spelling. | Both (different content) | | Human judgement points | Intent, plan approval, design review, PR approval, findings triage, policy changes. | Change creation and grooming, the PR merge, finalize confirmations, learnings promotion, filing discovered work, abstained stubs. Plan approval deliberately not a human point. | Both | -| Audit trail | Git history; logged hook decisions; incident conversations. | Every transition a metadata commit; marker sections; receipts and leases; frozen plan/results records; ADR supersessions as new files. | Both | +| Audit trail | Git history; logged hook decisions; incident conversations. | Every transition a metadata commit; marker sections; receipts; frozen plan/results records; ADR supersessions as new files. | Both | | Legacy tracker integration | One system of record per artifact. | One-way GitHub Issues mirror; Projects v2 guarded but unwired. | Both (GitHub issues only) | | Autonomy without a human channel | Scoped subagents; gates ask a human. | Abort-and-report wrappers; autonomy precedence; forked children never yield; four dispositions drive any loop. | docket only | | Run-tracker bracketing for dispatched runs | Not described. | `run start` / `run verdict` / `run continue`; retry-once accounting in durable records. | docket only | @@ -168,7 +168,7 @@ no-test-edits guard during repair; an intake path from production or scanner fin | Proving the build | 4 | Build gate and evidence; gate driver and budgets; integration repair; configuring the suite | docket-build gate paragraphs, gate references, tests/README | | Reviewing before the human does | 5 | Reviewer contract and tiers; fix loop and disposition table; why the suite runs in the build gate | docket-review section, fix-loop reference | | Landing changes safely | 5 | Finalize end to end; blocked and relink; branch protection; /loop finalize | Closing out hands-free, hands-off finalize | -| Keeping the backlog honest | 6 | Status vs sweep; health codes; reclaim; halted recovery | Reclaiming stale claims, docket-status | +| Keeping the backlog honest | 6 | Status vs sweep; health codes; halted recovery | docket-status | | Remembering why | 6 | ADRs; learnings and promotion; what is human-curated today | Learnings, docket-adr | | Governing through configuration | cross | Layers and the shared-setting guard; every config block by purpose; skills map; capability catalog; dummy_mode | Configuration, convention config | | Running on your harness | cross | Install and update; model pins; invocation paths; Cursor/Codex/opencode; runner delegation | Install, Updating, Tuning, Runner delegation, docs/* | diff --git a/docs/concepts/change-lifecycle.md b/docs/concepts/change-lifecycle.md index b2a998f91..45e82f30d 100644 --- a/docs/concepts/change-lifecycle.md +++ b/docs/concepts/change-lifecycle.md @@ -89,7 +89,7 @@ and it moves to `done` once the root of its stack lands. truth, and the board is derived from it, never hand-edited into disagreement. - Grooming a change to build-ready records no claim — only a build does — so a groom and a build never fight over the same change. -- A claim records which branch will carry the work and when it was taken. +- A claim records which branch will carry the work. - A dependency is satisfied only when it is `done`; a change waits until every dependency is `done` before it is build-ready. - A stacked change's base is its parent's branch while the parent is live, and diff --git a/docs/guide/README.md b/docs/guide/README.md index 24d4c41ef..0b8056cf0 100644 --- a/docs/guide/README.md +++ b/docs/guide/README.md @@ -25,7 +25,7 @@ for whatever step you are on. Installing docket and configuring it is its own se pull request into your mainline and out of your backlog, hands-off across a whole set of changes. - [Status: Keeping the backlog honest](keeping-the-backlog-honest.md) — tell whether your backlog still reflects reality, and fix it when it does not: the read-only status report, the maintenance - sweep, reclaiming expired claims, and recovering a halted run. + sweep, and recovering a halted run. - [ADRs and learnings: Remembering why](remembering-why.md) — where docket keeps the decisions it made and the lessons it learned, how you record a finding, and when a lesson belongs in your always-in-context instructions instead. diff --git a/docs/guide/building-without-supervision.md b/docs/guide/building-without-supervision.md index 5c1a7ef0a..870910424 100644 --- a/docs/guide/building-without-supervision.md +++ b/docs/guide/building-without-supervision.md @@ -68,11 +68,8 @@ A single implement-next run walks a fixed path and then stops: 1. **Pick.** It selects the next **build-ready** change (a proposed change that has a spec and whose dependencies are all `done`). It never touches work that is not ready. 2. **Claim.** It takes a **claim** on that change (the moment a change is picked up for building; it - records which branch will carry the work and when it was taken) with a conflict-checked write on the - change's status, so two runs in parallel can never grab the same change. The claim carries a - **claim lease** (a timestamp on a claim; when it expires with no branch behind it, the change - goes back to the queue), which is what lets a crashed run's change self-heal instead of sitting - stuck — see [Keeping the backlog honest](./keeping-the-backlog-honest.md). + records which branch will carry the work) with a conflict-checked write on the change's status, + so two runs in parallel can never grab the same change. 3. **Reconcile.** The step above — freshen the change against reality, or kill or escalate it. 4. **Plan.** It cuts a feature branch, creates an isolated working copy of the repo on that branch (a *worktree*), commits a copy of the change's spec as the branch's first commit, and authors a diff --git a/docs/guide/capturing-work.md b/docs/guide/capturing-work.md index 456307897..4bd891243 100644 --- a/docs/guide/capturing-work.md +++ b/docs/guide/capturing-work.md @@ -68,15 +68,9 @@ parent rather than into your main line, so its code has not shipped yet — it p [Building without supervision](./building-without-supervision.md) page covers stacking from the build side. -There is also one edge running *backward*: `in-progress → proposed`. A **claim** (the moment a -change is picked up for building; it records which branch will carry the work and when it was -taken) carries a **claim lease** (a timestamp on a claim; when it expires with no branch behind -it, the change can go back to the queue). If a run crashes before it ever pushes a branch, the -change would otherwise sit stuck at `in-progress` forever; instead, once the lease has expired and -the change has no feature branch and no workspace, it can be reclaimed back to `proposed` — -by `docket maintenance sweep` when `reclaim.auto` is `true`, or by you with `docket change reclaim` -(the sweep reports such a change as skipped while `reclaim.auto` is `false`, the default). -Recovering these is covered in [Keeping the backlog honest](./keeping-the-backlog-honest.md). +A **claim** (the moment a change is picked up for building) records which branch will carry the +work. If a run crashes or is stopped, its change stays `in-progress` until you resume it by id — +see [Keeping the backlog honest](./keeping-the-backlog-honest.md). The **board** (the generated overview of every change and its state, never edited by hand) is your at-a-glance view. It groups every change into six sections — in progress, built, blocked, diff --git a/docs/guide/keeping-the-backlog-honest.md b/docs/guide/keeping-the-backlog-honest.md index 1bb96cb4c..6141053c9 100644 --- a/docs/guide/keeping-the-backlog-honest.md +++ b/docs/guide/keeping-the-backlog-honest.md @@ -3,8 +3,7 @@ By the end of this page you can tell whether your backlog still reflects reality — and fix it when it does not. You will know the difference between the read-only status report and the maintenance sweep that closes out merged work, what each health finding means and how to answer -it, how a change that a crashed run left stuck goes back to the queue, and how to recover a run -that stopped and asked for you. +it, and how to recover a run that stopped, crashed, or asked for you. ## Status versus the maintenance sweep @@ -12,17 +11,17 @@ Two different commands keep the backlog current, and it helps to keep them apart **`docket status` is read-only.** It reports the backlog — what is proposed, ready, in progress, implemented, or blocked, and the build-ready queue in selection order — plus any health findings. -It never merges, archives, reclaims, or rewrites anything, so you can run it as often as you like. +It never merges, archives, or rewrites anything, so you can run it as often as you like. **`docket maintenance sweep` does the tidying.** When a change (one unit of planned work, roughly one pull request, tracked as one markdown file) has its pull request merged, something has to move it to `done` and archive it. The deliberate way is to close the change out yourself right after the merge — see [Landing changes safely](./landing-changes.md). But you do not have to: the sweep is the safety net. In one pass it closes out every change whose pull request already merged, -retries any close-out cleanup that did not finish, and reclaims expired claims (below). That -cleanup retry also repoints the backlink in a merged pull request's description when it still -names the change's old `active/` path, even for a change archived long ago; to preview every such -pull request first and repoint them all at once, run `docket repository repair --pr-backlinks`. Every +and retries any close-out cleanup that did not finish. That cleanup retry also repoints the +backlink in a merged pull request's description when it still names the change's old `active/` +path, even for a change archived long ago; to preview every such pull request first and repoint +them all at once, run `docket repository repair --pr-backlinks`. Every change it touches re-renders the **board** (the generated overview of every change and its state, never edited by hand) in the same commit. @@ -52,39 +51,6 @@ A dependency only counts as satisfied once the change it names reaches `done`, s on unmerged work simply stays out of the build-ready queue; status shows which dependencies are still unmet. -## Reclaiming expired claims - -When a run crashes or is killed **before it ever pushes a branch**, its change is left stuck at -`in-progress`. Reclaim returns it to the queue, and only in the situation it can handle *safely*. - -Every **claim** (the moment a change is picked up for building; it records which branch will -carry the work and when it was taken) stamps the time it was taken. A change is eligible for -reclaim only when all three hold: - -- its claim lease has expired: the stamp is older than `reclaim.lease_ttl` hours (default `72`); -- no feature branch for it exists, locally or on the remote; -- no feature workspace for it exists. - -An eligible change goes back to `proposed` and re-enters the queue — the one edge in a change's -life that runs backward. Anything docket cannot confirm (a probe that fails, a branch it cannot -see clearly) leaves the change alone. - -- **Automatic reclaim is opt-in.** With `reclaim.auto: false` (the default) the maintenance sweep - leaves every eligible change alone and reports it as skipped with the reason - `reclaim-auto-disabled`. With `reclaim.auto: true` the sweep reclaims every eligible change - itself. -- **Run it by hand any time** with `docket change reclaim --id --revision ` — per - change, at its exact recorded revision — whatever `reclaim.auto` says. -- **A change that already has a branch is left to you.** A pushed branch might carry real, - un-merged work, so reclaim never touches it — the concrete risk is throwing away code nobody - backed up. - -```yaml -reclaim: - lease_ttl: 72 # hours before an unattended claim counts as expired - auto: false # true => the maintenance sweep reclaims eligible changes itself -``` - ## Recovering a halted run A build run ends by declaring one of four outcomes, and one of them — `halted` — means it stopped @@ -101,13 +67,13 @@ A halted change stays `in-progress`, and the board shows it as **run halted — Make the call it could not: re-design the change if reconcile found the design invalidated (a fresh design conversation, see [Designing before building](./designing-before-building.md)), or clear the blocker. Then recover the change with `docket change resume-halted`, which checks the - workspace, refreshes the claim, and removes the halt marker, and start the next run on it with + workspace and removes the halt marker, and start the next run on it with `docket run start implement-next --resume `. -- **It crashed before pushing a branch.** Nothing to recover — once the lease expires, reclaim - returns it to `proposed` as above, and the next run rebuilds from scratch. -- **It crashed after pushing a branch.** The branch holds real work, so reclaim leaves it alone. - Resume it deliberately with `docket run start implement-next --resume ` and name the id to - implement-next — a bare, unscoped run skips an in-progress change rather than resuming it. +- **It crashed or was stopped.** Resume it deliberately with + `docket run start implement-next --resume ` and name the id to implement-next — a bare, + unscoped run skips an in-progress change rather than resuming it. If the start refuses with + `resume-active-run`, nothing has confirmed the old run stopped: cancel it with + `docket run cancel --key --reason `, then resume. ## Before any of this: a set-up repository diff --git a/docs/install/global-config.md b/docs/install/global-config.md index 4d0972fc0..0411ab3c2 100644 --- a/docs/install/global-config.md +++ b/docs/install/global-config.md @@ -17,7 +17,7 @@ Two kinds of setting belong here: [`agents/harness-defaults.yml`](../../agents/harness-defaults.yml), a shipped file you read but never edit. To change one, see [Models](models-and-effort.md), then re-run the install. - **Any `scope: any layer` key you want as your personal default** across repositories — for - example `review.min_fix_severity` or `reclaim.lease_ttl`. A repository's own files still win. + example `review.min_fix_severity` or `review.max_fix_tasks`. A repository's own files still win. The canonical reference for every key is [`.docket.example.yml`](../../.docket.example.yml): every supported key at its built-in default, with a short note and a scope tag saying which layers may diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 825dc9d92..121b1f840 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -42,8 +42,8 @@ Each line is a pointer: the command, what its verbs govern, and where to read th installation is current and writes nothing, and `docket install collect`, which reclaims verified unreferenced installed version trees. Verbs: `docket install --help`. - **`docket learning`** — record and update learning findings. Verbs: `docket learning --help`. -- **`docket maintenance`** — close out merged changes, retry close-out cleanup, and reclaim - expired claims in one pass (`docket status` stays read-only). Verbs: `docket maintenance --help`. +- **`docket maintenance`** — close out merged changes and retry close-out cleanup in one pass + (`docket status` stays read-only). Verbs: `docket maintenance --help`. - **`docket open`** — open the board, or a change's record, spec, plan, results, or pull request, as a GitHub page or from the local metadata checkout. Without an id it opens the change whose branch is checked out. With `--export` it writes a clean Markdown copy of a change, spec, plan, diff --git a/docs/reference/config-keys.md b/docs/reference/config-keys.md index 6bb6d2669..adab380f0 100644 --- a/docs/reference/config-keys.md +++ b/docs/reference/config-keys.md @@ -50,8 +50,6 @@ Each key has one scope: | `run.max_consecutive_halts` | `2` | any layer | halts in a row, on changes a loop picked from the queue, before the loop stops | | `review.min_fix_severity` | `minor` | any layer | the lowest review-finding severity the fix pass repairs | | `review.max_fix_tasks` | `10` | any layer | the most non-blocker fix tasks one fix pass dispatches | -| `reclaim.lease_ttl` | `72` | any layer | hours a claim on an in-progress change lasts | -| `reclaim.auto` | `false` | any layer | whether `docket maintenance sweep` reclaims an eligible change or reports it skipped | | `learnings.enabled` | `true` | any layer | whether learnings are written and read | | `open.artifacts` | `github` | any layer | where `docket open` shows a shared repository's board and change artifacts: `github` pages, or the `local` metadata checkout's files | | `gate_observation_budget` | `30` | any layer | minutes docket waits for a test-suite run it started to finish | diff --git a/docs/reference/fields.md b/docs/reference/fields.md index 6061f9a00..f5f812b43 100644 --- a/docs/reference/fields.md +++ b/docs/reference/fields.md @@ -15,8 +15,8 @@ skill is reorganized). one unit of planned work, roughly one pull request, tracked as one markdown file) — owned by the convention section **"Change manifest (frontmatter at the top of each change file)"**. That section is the live list of every manifest key and its meaning: identity and title, lifecycle - status, priority and type, dependencies (`depends_on`), the claim fields that record which branch - will carry the work and when it was taken, and the spec/plan/results/pr links. + status, priority and type, dependencies (`depends_on`), the claim field that records which branch + will carry the work, and the spec/plan/results/pr links. - **Change body sections** (the headings the manifest's prose body may carry) — owned by the convention section **"Change body sections"**. - **ADR fields and body** — owned by the convention section **"ADR file (`/-.md`)"**, diff --git a/docs/reference/glossary.md b/docs/reference/glossary.md index fad4b9d08..78e0da3b7 100644 --- a/docs/reference/glossary.md +++ b/docs/reference/glossary.md @@ -384,7 +384,7 @@ docket learning update --request finding-update.json # {path, revision, hook, The frontmatter block at the top of a change file. Its fields (`status`, `priority`, `type`, `depends_on`, `stacked_on`, `related`, `discovered_from`, `adrs`, `spec`, `plan`, `results`, -`auto_groomable`, `deliverable`, `branch`, `claimed_at`, `pr`, `blocked_by`, `reconciled`, …) are owned +`auto_groomable`, `deliverable`, `branch`, `pr`, `blocked_by`, `reconciled`, …) are owned by the `docket-convention` skill (see [`fields.md`](fields.md)). **Used for:** the machine-readable state of a change. Edit it only through typed operations; a @@ -461,7 +461,7 @@ Statuses: `proposed` · `in-progress` · `blocked` · `deferred` · `implemented | Status | Meaning | Moved there by | |---|---|---| -| `proposed` | Drafted, awaiting work | `change create`, `change revive`, `change reclaim` | +| `proposed` | Drafted, awaiting work | `change create`, `change revive` | | `in-progress` | Claimed, being built | `change claim`, `change unblock` | | `blocked` | External blocker, recorded in `blocked_by:` | `change block` | | `deferred` | Consciously shelved, may revive | `change defer` | @@ -524,24 +524,17 @@ docket change complete --request complete.json # {change_id, path, revision} docket finalize cleanup --id 412 ``` -### Claim / claim lease / reclaim +### Claim A **claim** is the moment a change is picked up for building; it records which branch will carry -the work and when it was taken. The **claim lease** is a timestamp on a claim (`claimed_at:`), -stamped at claim and re-stamped at reconcile and resume-halted; when it expires with no branch -behind it, the change goes back to the queue. **Reclaim** is that -return trip (`in-progress → proposed`), logged in `## Reclaim log`. +the work. A change already in progress is resumed by id, never claimed again. -**Used for:** making sure an abandoned build never holds a change forever. A claim that already -has a feature branch or a workspace (real work) is never reclaimed. Grooming never takes a claim. +**Used for:** making sure two runs never build the same change. Grooming never takes a claim. ```sh -docket change claim --id 412 --revision -docket change reclaim --id 412 --revision # refuses with lease-not-expired if still live +docket change claim --id 412 --revision ``` -Config: `reclaim.lease_ttl` (hours) and `reclaim.auto`. - ### Dependency (`depends_on`) / implicitly blocked A change id that must reach `done` before this change is build-ready. An unsatisfied dependency @@ -1813,7 +1806,7 @@ tier agents and is never invoked by a human. See *Review tier* and *Fix pass*. The backlog read-and-janitor skill. A see-only request runs the read-only `docket status`. An explicit refresh first runs `docket maintenance sweep` (close out merged changes, retry close-out -cleanup, reclaim expired claims, sync the integration branch), then reads status. +cleanup, sync the integration branch), then reads status. **Used for:** knowing what is ready, stuck, or merged, and recovering a PR merged with the GitHub button. Health findings come from the status read and are warn-only: it never auto-fixes. Its dispatch fallback is `inline`: without dispatch it runs @@ -2067,20 +2060,6 @@ docket diagnostic config --repo-dir . --json # shows which layer each value ca Set by `change create` (default `medium`) and changed on a `proposed` change by `change groom`'s optional `priority` (any outcome but `abstain`). -### `reclaim.auto` / `reclaim.lease_ttl` - -`reclaim.lease_ttl` (default 72 hours) is how long a claim lease lasts. `reclaim.auto` (default -`false`) decides what the maintenance sweep does with an eligible claim: an expired lease, no -feature branch, and no workspace. With `false`, the sweep reports it as skipped -(`reclaim-auto-disabled`); with `true`, the sweep reclaims it back to `proposed`. - -**Used for:** letting crashed runs self-heal without a human. Detection is always on; only the -mutation is opt-in. A claim with a branch is never reclaimed automatically. - -```sh -docket change reclaim --id 412 --revision # the explicit, one-off reclaim -``` - ### Reserved type tokens `all` / `untyped`, and migrating to typed changes `all` and `untyped` match the change-type grammar but are reserved, so they may never be configured @@ -2132,7 +2111,6 @@ below. | `halt_dispositions` | `halted` `resumed` `contended` `refused` `failed` | `change halt`, `change resume-halted` | | `merge_dispositions` | `merged` `already-merged` `contended` `not-mergeable` `denied` `blocked` `unknown` | `finalize merge` | | `publish_dispositions` | `published` `noop` `contended` `unknown` `blocked` | `finalize publish` | -| `reclaim_dispositions` | `reclaimed` `skipped` `contended` `failed` | `change reclaim` | | `reconcile_dispositions` | `applied` `contended` `failed` | `change reconcile` | | `sync_dispositions` | `advanced` `already-current` `failed` `refused` `skipped` | `repository sync-integration`, `maintenance sweep` | | `section_intents` | `preserve` `replace` `remove` | `change groom` (request `sections[].intent`) | @@ -2353,7 +2331,7 @@ docket development install --source ~/dev/docket - [Capture modes: designed / rough stub / scan](#capture-modes-designed--rough-stub--scan) - [Change](#change) - [Change types](#change-types) -- [Claim / claim lease / reclaim](#claim--claim-lease--reclaim) +- [Claim](#claim) - [Close-out](#closeout--closeout-notes) — see Closeout / closeout notes - [Closeout / closeout notes](#closeout--closeout-notes) - [Complete (change complete)](#complete-change-complete) @@ -2458,7 +2436,6 @@ docket development install --source ~/dev/docket - [Rebase receipt / attempt token (--attempt)](#rebase-receipt--attempt-token---attempt) - [Rebase resolver / integration repair](#rebase-resolver--integration-repair) - [Re-certify (evidence recertify)](#re-certify-evidence-recertify) -- [reclaim.auto / reclaim.lease_ttl](#reclaimauto--reclaimlease_ttl) - [Reconcile / reconcile log](#reconcile--reconcile-log) - [Related / discovered_from](#related--discovered_from) - [Relink (change relink)](#relink-change-relink) diff --git a/internal/assets/embedded/manifest.json b/internal/assets/embedded/manifest.json index 620715422..4e575f17f 100644 --- a/internal/assets/embedded/manifest.json +++ b/internal/assets/embedded/manifest.json @@ -1,7 +1,7 @@ { "format_version": 1, "asset_protocol": 1, - "asset_set_id": "sha256:d89a536023d4ce4c601fe6fb1790ff898a747da0cad14ef4659bbd5fe54a8a40", + "asset_set_id": "sha256:1e65c5a2c1efe6eaa89608a5f6390ba12e92ff1474c44cadb16a9236220ee4f1", "entries": [ { "path": ".docket.example.yml", @@ -322,8 +322,8 @@ "path": "skills/docket-convention/SKILL.md", "role": "skill", "mode": 420, - "size": 53504, - "sha256": "58bac591609e709cebcf9afd598737607924fb3c140351a8eee2e55f69c22f4d" + "size": 52566, + "sha256": "5fd96420bb0abc33d780c58bdcc04e140e7c221ea1142e762f255811d810f234" }, { "path": "skills/docket-convention/references/agent-layer.md", @@ -378,15 +378,15 @@ "path": "skills/docket-implement-next/SKILL.md", "role": "skill", "mode": 420, - "size": 60752, - "sha256": "dc8cf283ada6cfd4d7b00740bd688afad006c9f1183481674b75673303f69221" + "size": 60475, + "sha256": "dbe62d791bde8851e9f5a1e0683a5a6f0acf4cf82eb50b751ce379e6a5c44f06" }, { "path": "skills/docket-implement-next/references/edge-paths.md", "role": "skill", "mode": 420, - "size": 7214, - "sha256": "9cae52fff741fff7e0bc0fa9443ccb79018b8d1669f85a8439ae368c0185a7f1" + "size": 7181, + "sha256": "b3f7b994d0bb7a2b58f55bd6bd1b74c5f9bc19461e92307c0efa9d206b3ad1a1" }, { "path": "skills/docket-implement-next/references/fix-pass.md", @@ -427,8 +427,8 @@ "path": "skills/docket-status/SKILL.md", "role": "skill", "mode": 420, - "size": 20121, - "sha256": "6a72745f574d8f2d5c2f868f9abc3d22ac9b4c77efe85586abfb164d487c4280" + "size": 19831, + "sha256": "a106ef5c91e04efb6157a73d6910a1287e95db4530494c8a55888ba35318ec03" } ] } diff --git a/internal/assets/embedded/tree/skills/docket-convention/SKILL.md b/internal/assets/embedded/tree/skills/docket-convention/SKILL.md index 1deed7316..2cfc8e310 100644 --- a/internal/assets/embedded/tree/skills/docket-convention/SKILL.md +++ b/internal/assets/embedded/tree/skills/docket-convention/SKILL.md @@ -38,9 +38,6 @@ run: review: min_fix_severity: minor max_fix_tasks: 10 -reclaim: - lease_ttl: 72 - auto: false learnings: enabled: true # false = read/write gate, never a purge gate_observation_budget: 30 # minutes; enforced by the gate driver @@ -95,7 +92,7 @@ When dispatch is genuinely unavailable the kinds are **not** equivalent, so the |---|---|---| | **`inline` — deterministic** | the `docket-status` and `docket-adr` composition dispatches | Run the same work **inline** — a **first-class equivalent path**, neither a degradation nor a warning, because the contract is git state on the metadata branch, not an in-context return. Every obligation holds unchanged: re-sync before reading, derive from fresh origin, never adopt or commit another agent's uncommitted files. | | **`abstain` — adversarial** | the `docket-auto-groom-critic` gate | **Abstain**, per *Autonomous grooming*. Self-critique by the agent that drafted the spec is not an adversarial gate, and the abstain is a path that skill already owns. | -| **`halt` — discipline** | the **plan-writer dispatch**, the `build` role skill's required nested dispatches, the controller's own review-tier dispatch (the `docket-review` skill itself never dispatches), and the in-branch fix workers (which run the `build` role's own contract) | **`halt`** — the run stops: the change stays `in-progress` with the halt reason recorded through `change.halt`. **No new status, no new field** — the reclaim lease self-heals an abandoned claim. | +| **`halt` — discipline** | the **plan-writer dispatch**, the `build` role skill's required nested dispatches, the controller's own review-tier dispatch (the `docket-review` skill itself never dispatches), and the in-branch fix workers (which run the `build` role's own contract) | **`halt`** — the run stops: the change stays `in-progress` with the halt reason recorded through `change.halt`. **No new status, no new field** — the caller resumes it by id, through `change.resume-halted`. | **Outside the table — `no-fallback`.** `docket-finalize-change`'s two finalize-gate dispatches — `docket-rebase-resolver` and `docket-integration-repair` — sit **outside** this table rather than in a row of it, because their contract is an **in-context report** gating the merge, not git state on the metadata branch. Neither fallback can be borrowed for them: `inline`'s first-class-equivalent path presupposes a git-state transition to reproduce, and `halt` belongs to the workflow roles, and these dispatches are not a role. When dispatch is genuinely unavailable for either — established per the resolution rule above, never from a tool name — the posture is finalize's own pre-existing **abort-and-report**: the gate stops, the PR stays open, the change stays `implemented`, and the reason is recorded through the three channels `docket-finalize-change`'s failure reference owns. **Inline substitution is forbidden** for both, and that is the point of `no-fallback` rather than a table row: reconciling the conflict, or authoring the repair, inside the very agent that would then merge that work is the same self-approval shape `abstain` exists to avoid for the critic. @@ -189,12 +186,11 @@ plan: # plan FILE on the metadata branch; FILE and FIELD wri results: # results FILE on the metadata branch; FILE and FIELD written together by change.attach-results at the first checkpoint, required before the implemented transition auto_groomable: # `true` makes a stub auto-groomable; unset or `false` means not hold: # `true` keeps a groomed change out of autonomous build selection; naming it still builds it -branch_prefix: # optional one unqualified branch-path component; overrides at mint, consumed only at claim, inert once branch: is populated, survives reclaim +branch_prefix: # optional one unqualified branch-path component; overrides at mint, consumed only at claim, inert once branch: is populated branch: # minted / (or /) name, set on claim; sole feature-head source of truth after, never reconstructed; branch itself created at build (step 4) pr: # set when the PR is opened blocked_by: # free text; set only when status: blocked reconciled: false # set true after the just-in-time reconcile pass -claimed_at: # UTC ISO-8601 claim lease (YYYY-MM-DDTHH:MM:SSZ); stamped by claim, reconcile, and resume-halted; cleared on leaving in-progress --- ``` @@ -222,7 +218,6 @@ change, never in the frozen artifact. - `## Open questions` — unknowns to resolve during reconcile/design. - `## Reconcile log` — dated entries appended by the implementer's reconcile pass. - `## Closeout notes` — final-only, **optional**, and the **final authored body section** of an archived record. Written solely by the `finalize.closeout` operation from its structured request (`verification_outcomes` / `late_findings`, rendered as `### Verification` / `### Late findings` bullet lists); never hand-edited, copied to a stacked descendant, or a link-bearing artifact. The closed-out `results:` file stays a frozen build record — the freeze rule above is unchanged. -- `## Reclaim log` — dated entries appended by the `change.reclaim` operation when an expired-lease, no-branch claim self-heals back to `proposed`. - `## Auto-groom blocked` — dated abstain record written by `change.groom` `outcome: abstain`; contents and lifecycle (including removal by `outcome: re-enable`) are defined by the *Autonomous grooming* shared definition below. - `## Finalize blocked` — dated record appended by `docket-finalize-change` when a gate failure leaves a change needing a human; presence drives the board's `finalize blocked — needs you` cell. It is a visible note that never stops finalize selection or merge, so the next finalize run retries the change. The clearing rule is owned by `docket-finalize-change` and not restated here. - `## Run halted` — written by the `change.halt` operation when an autonomous run stops needing a human (the `halted` disposition); the heading is **bare**, never dated — the reader is a whole-line match, so the date sits inside the body. **Marker-section state**, in the same family as `## Auto-groom blocked` and `## Finalize blocked`: while the section is present the `run.verify` operation reports `run-halted`, which is what makes a `halted` disposition verifiable in git rather than a claim in a completion report. It is removed by the `change.resume-halted` operation, and by the claim when a halted change is claimed again. @@ -262,8 +257,7 @@ An `Accepted` ADR is immutable except its `status:` line; a non-reversing contex │ │ │ (archive/) │ ├──results attached + change.complete (results-artifact; also from proposed)──▶ done │ │ └──into stack parent──▶ stacked-merged ──root lands──▶ done - │ ├──blocker──▶ blocked ──clears──▶ in-progress - │ └──lease expired, no branch (reclaim)──▶ proposed + │ └──blocker──▶ blocked ──clears──▶ in-progress ├──── deferred (shelved; revive → proposed) └──── killed (obsolete — from proposed, or from in-progress via reconcile; → archive/) ────▶ ``` @@ -281,8 +275,6 @@ An `Accepted` ADR is immutable except its `status:` line; a non-reversing contex **Rules.** `active/` holds every non-final status; `archive/` holds the two final outcomes. `stacked-merged` is non-final for that reason: merged into its stack parent, not the integration branch, so it stays in `active/` until the stack close-out promotes it when the stack root lands. The single physical move (`active/ → archive/`, date-prefixed) happens once on the final transition and is **idempotent**: re-pull, re-read `status` on the metadata branch, no-op if already final. `deferred` is entered only from `proposed` (add `## Why deferred`; a change being built is blocked or killed instead) and revived to `proposed`; clear a blocker with `change.unblock` (`blocked` → `in-progress`, clearing `blocked_by`) and revive with `change.revive` (`deferred` → `proposed`) — typed operations, no file move. A change whose `depends_on` is unsatisfied is *implicitly* blocked — the selector skips it and the board shows it **waiting on #N**. A dependency is **satisfied when it reaches `done`**; if `#N` is still `implemented` the board flags **waiting on #N — needs your merge**, distinct from **waiting on #N — not yet built**. Reserve explicit `blocked` for external blockers the system can't infer. -**Reclaim edge (`in-progress → proposed`).** An `in-progress` change whose claim lease (`claimed_at:` + `reclaim.lease_ttl`) has expired AND that has no feature branch is flipped back to `proposed` by the reclaim operation (opt-in via `reclaim.auto`, or an explicit `change.reclaim`), clearing `branch:`/`claimed_at:` and resetting `reconciled: false` so a fresh reconcile runs on re-claim. The has-branch case is never auto-reclaimed (it may carry real work) — it stays flagged for a human. - **Board refresh on status writes.** Every board-authoritative typed mutation re-renders `BOARD.md` **atomically inside its own metadata commit** — the same commit that writes the change record it reflects — so there is **no separate Board pass**, and no skill hand-renders, hand-commits, or three-way-merges the board. The shared app-layer inclusion path owns the whole decision: it resolves the enabled surfaces (fail-closed), renders the `inline` surface, and writes `BOARD.md` only when it actually changed. **No surfaces value is ever passed or spelled by a skill**: the caller never resolves or forwards one — so an unresolved config can never be mistaken for a disabled board. A read-only `status` read never writes a board; a repo with `board_surfaces: []` renders and commits nothing, and a pre-existing `BOARD.md` is left untouched rather than truncated. Exceptional out-of-band board drift (a hand-edit, an interrupted legacy write) is surfaced by `repository.check` and repaired by the authorized `repository.repair` operation (resolve argv from the capability catalog; a human authorizes its `--yes` apply) — never a hand-render. The board is a derived view and must never trail the change files. ### Build-readiness & selection (shared definition) diff --git a/internal/assets/embedded/tree/skills/docket-implement-next/SKILL.md b/internal/assets/embedded/tree/skills/docket-implement-next/SKILL.md index d295618d6..4b70dc207 100644 --- a/internal/assets/embedded/tree/skills/docket-implement-next/SKILL.md +++ b/internal/assets/embedded/tree/skills/docket-implement-next/SKILL.md @@ -26,7 +26,7 @@ Before anything else in this skill, invoke the `docket-convention` skill via the Run the convention's **startup check** (load the convention; run the capability bootstrap; run the `repository.prepare` operation with `--repo-dir --json` as its own Bash call; validate the protocol-v1 envelope and carry its typed context values forward as literals; act on the disposition). All bookkeeping in this skill (claim, reconcile, `status`, `pr:`, `plan:`, `adrs:`, the plan and results files, build evidence) lands in the metadata worktree (`metadata_worktree_path` in the `repository.prepare` context) on the metadata branch, pushed to the metadata remote (`metadata_remote`) immediately; only the spec copy and the code land on the feature branch. -**Named invocation — no maintenance preflight.** When this run was invoked with exactly **one explicit change id** — an initial named call, an attributed retry carrying the id, or a named resume of an in-progress change — skip the implementation preflight and Step 1's status-digest certification entirely: after the `repository.prepare` operation succeeds, go **directly** to the authoritative `context.implementation` operation with `--id ` and the existing claim/resume path. The named path never runs `maintenance.preflight` or any maintenance sweep first — another change's failing closeout, cleanup, or reclaim can never halt this change before its own claim/gate; anyone who wants those maintenance outcomes runs the explicit `maintenance.preflight` or `maintenance.sweep` operation deliberately, where every problem stays visible. Every local check for the named change is kept — readiness, record revision, dependencies, effective base, claim eligibility, run context, and resume/cancellation; an `in-progress` id is served only to its own resume (Step 1). A held change (`on-hold`) is built when named. So a malformed, absent, not-ready, or improperly resumed id returns its existing typed refusal, reported with its reason exactly as a scoped-id skip is (ending `drained` when nothing else is in scope); a named request **never falls back to selecting another change**, and shared repository/configuration/transport failures keep the `halted` posture. +**Named invocation — no maintenance preflight.** When this run was invoked with exactly **one explicit change id** — an initial named call, an attributed retry carrying the id, or a named resume of an in-progress change — skip the implementation preflight and Step 1's status-digest certification entirely: after the `repository.prepare` operation succeeds, go **directly** to the authoritative `context.implementation` operation with `--id ` and the existing claim/resume path. The named path never runs `maintenance.preflight` or any maintenance sweep first — another change's failing closeout or cleanup can never halt this change before its own claim/gate; anyone who wants those maintenance outcomes runs the explicit `maintenance.preflight` or `maintenance.sweep` operation deliberately, where every problem stays visible. Every local check for the named change is kept — readiness, record revision, dependencies, effective base, claim eligibility, run context, and resume/cancellation; an `in-progress` id is served only to its own resume (Step 1). A held change (`on-hold`) is built when named. So a malformed, absent, not-ready, or improperly resumed id returns its existing typed refusal, reported with its reason exactly as a scoped-id skip is (ending `drained` when nothing else is in scope); a named request **never falls back to selecting another change**, and shared repository/configuration/transport failures keep the `halted` posture. **The named change's own merged dependencies.** Skipping the sweep never declares a dependency satisfied. When the named path's `context.implementation` read refuses `not-ready-waiting-dependency`, **read `references/edge-paths.md` now (blocking)** for the bounded closeout of the named change's own `implemented` dependencies — never any other change's. @@ -46,24 +46,24 @@ The digest is an **accelerator, not the sole channel**: the authoritative read i ### Step 2 — Claim (conflict-checked write) -Claim by transaction: the `change.claim` operation with `--id --revision ` (the exact revision from the step-1 bundle). When the dispatch prompt carried a **run context** token, pass it to the claim as --run-context : the claim validates it against the started run, records durable proof binding this dispatch to its successful claim, and the parent's keyed verdict resolves ownership from that proof; an invalid or conflicting run context is a typed refusal that writes nothing — never retried as an ungated claim. A claim without the token stays supported for ungated invocations. Also pass `--selection queue` on the selection path and `--selection named` on the named path: the run tracker counts a halt toward a loop's halt limit only for a change picked from the queue. In the **metadata working tree** the operation reloads fresh origin, re-proves the change is still `proposed`, uniquely identified, build-ready, and has a resolved effective base, then applies the landed claim (`status: in-progress` + `branch: /` + `updated:` + `claimed_at:` — the lease the `change.reclaim` operation and the maintenance sweep's reclaim key on) and updates the change record, `## Artifacts` block, and inline board **together in one metadata commit** on the metadata branch, pushed to the metadata remote. It returns the feature branch, lease classification, and a closed disposition; a wrong revision or a not-`proposed`/not-build-ready/duplicate/unresolved-base change returns `contended`/a typed refusal that **writes nothing and creates no workspace**. A lost-response retry converges by re-reading authority — an already-held matching claim returns the applied receipt or a typed `already-claimed`, a foreign claim returns `contended`; never adopt a branch or workspace as proof the claim landed. A `contended` result is the **`contended`** disposition (see *Terminal disposition*): a lost conflict-checked claim race is a normal, continue-able outcome a driver re-selects past, **never `halted`** — re-sync (re-run the `repository.prepare` operation) and re-select. No worktree yet. +Claim by transaction: the `change.claim` operation with `--id --revision ` (the exact revision from the step-1 bundle). When the dispatch prompt carried a **run context** token, pass it to the claim as --run-context : the claim validates it against the started run, records durable proof binding this dispatch to its successful claim, and the parent's keyed verdict resolves ownership from that proof; an invalid or conflicting run context is a typed refusal that writes nothing — never retried as an ungated claim. A claim without the token stays supported for ungated invocations. Also pass `--selection queue` on the selection path and `--selection named` on the named path: the run tracker counts a halt toward a loop's halt limit only for a change picked from the queue. In the **metadata working tree** the operation reloads fresh origin, re-proves the change is still `proposed`, uniquely identified, build-ready, and has a resolved effective base, then applies the landed claim (`status: in-progress` + `branch: /` + `updated:`) and updates the change record, `## Artifacts` block, and inline board **together in one metadata commit** on the metadata branch, pushed to the metadata remote. It returns the feature branch and a closed disposition; a wrong revision or a not-`proposed`/not-build-ready/duplicate/unresolved-base change returns `contended`/a typed refusal that **writes nothing and creates no workspace**. A lost-response retry converges by re-reading authority — an already-held matching claim returns the applied receipt or a typed `already-claimed`, a foreign claim returns `contended`; never adopt a branch or workspace as proof the claim landed. A `contended` result is the **`contended`** disposition (see *Terminal disposition*): a lost conflict-checked claim race is a normal, continue-able outcome a driver re-selects past, **never `halted`** — re-sync (re-run the `repository.prepare` operation) and re-select. No worktree yet. **Revision lookups.** The claim pins the pre-claim bundle's revision and `change.resume-halted` the context bundle's. Before every later write to its own record — `change.reconcile`, `change.halt`, a reconcile-kill's `change.kill`, `workspace.prepare`, the revision handed to the plan-writer, the producing-change revision handed to `docket-adr`, each `change.attach-results`, and `change.mark-implemented` — the run reads the revision from the local metadata checkout in the same shell call as the write (or immediately before the dispatch carrying it): `R=$(git -C rev-parse HEAD:)`, `` being the bundle's `change.path`, which does not move while the change is active. A receipt's `committed_revision` is the commit id, never a `--revision` value. On `contended`, re-sync once (the `repository.prepare` operation), look the revision up again, and retry the write once — except `change.reconcile`, which keeps its re-read-and-re-author rule (Step 3); a second `contended` follows the step's existing stop rule. -A claim of a `proposed` record that still carries a `## Run halted` section removes that section in the same transaction. **Resuming a halted in-progress change** — one the caller re-dispatches by id after a `run.verify` verdict of **`run-halted`** — goes through the `change.resume-halted` operation with `--id --revision --acknowledge-quiescent`, never a fresh claim: it requires the exact marked record and the explicit `--acknowledge-quiescent` acknowledgement that the prior worker is quiescent, reprobes the branch/workspace/live gate, refreshes the claim, and removes exactly the `## Run halted` marker section while preserving every other byte and checkpoint — it never resets or adopts a workspace whose writer may be live. It refuses (writing nothing) without the acknowledgement, on revision drift (`contended`), or on a live gate lock. A change that instead reached `proposed` through the `change.reclaim` operation carries no live claim, so it re-enters through the ordinary claim above. The claim and resume both render the inline board in their own transaction, so no separate Board pass runs here. Starting the resume also passes through the run tracker, which refuses a second run over one that has not verifiably stopped — **read `references/edge-paths.md` now (blocking)** for those run-tracker resume refusals and their remedies. +A claim of a `proposed` record that still carries a `## Run halted` section removes that section in the same transaction. **Resuming a halted in-progress change** — one the caller re-dispatches by id after a `run.verify` verdict of **`run-halted`** — goes through the `change.resume-halted` operation with `--id --revision --acknowledge-quiescent`, never a fresh claim: it requires the exact marked record and the explicit `--acknowledge-quiescent` acknowledgement that the prior worker is quiescent, reprobes the branch/workspace/live gate and removes exactly the `## Run halted` marker section while preserving every other byte and checkpoint — it never resets or adopts a workspace whose writer may be live. It refuses (writing nothing) without the acknowledgement, on revision drift (`contended`), or on a live gate lock. A stranded run recovers only by the caller resuming its change by id (the `run.start` operation with `implement-next --resume `), with the run tracker deciding. The claim and resume both render the inline board in their own transaction, so no separate Board pass runs here. Starting the resume also passes through the run tracker, which refuses a second run over one that has not verifiably stopped — **read `references/edge-paths.md` now (blocking)** for those run-tracker resume refusals and their remedies. > Two agents must NOT share one local clone — each needs its own. ### Step 3 — Reconcile ⭐ -Re-read the step-1 bundle's change + spec bytes against `related` + recently-archived changes, cited + recent ADRs, and CURRENT code, and decide NON-INTERACTIVELY what is true NOW (drop work done elsewhere, adjust scope, fold in new constraints). That judgment is yours; the write is a transaction. **Author** a reconcile request — structured replacement text for the owned proposal sections and still-mutable linked-spec content, the complete desired relations (`depends_on`/`stacked_on`/`related`/`adrs`/`discovered_from`) when reality requires them, and one dated `## Reconcile log` entry — and apply it with the `change.reconcile` operation with `--input ` (the request file carries `id`, the pinned `revision`, and the authored Markdown — never a shell-escaped flag). The `reconcile_log_entry` is the **section body only** — the operation writes the `### YYYY-MM-DD` heading. When nothing changed (spec, stack base, related changes, and scope all hold), send just `{id, revision, reconcile_log_entry}` with a one-line body such as "Unchanged against ``"; sections and relations go in only when reality requires a change. The transaction checks the exact revision and legal `in-progress` status, sets `reconciled: true`, refreshes the claim, rerenders backlinks/`## Artifacts` block/inline board, validates the whole repository, and commits atomically on the metadata branch, pushed to the metadata remote; unknown frontmatter, unlisted authored sections, line endings, and unrelated files stay byte-identical, and a request naming a non-owned field/section is a typed refusal that writes nothing. If fresh origin state diverges incompatibly, the operation returns `contended` and writes nothing — never a text-merge; re-read fresh context and re-author. +Re-read the step-1 bundle's change + spec bytes against `related` + recently-archived changes, cited + recent ADRs, and CURRENT code, and decide NON-INTERACTIVELY what is true NOW (drop work done elsewhere, adjust scope, fold in new constraints). That judgment is yours; the write is a transaction. **Author** a reconcile request — structured replacement text for the owned proposal sections and still-mutable linked-spec content, the complete desired relations (`depends_on`/`stacked_on`/`related`/`adrs`/`discovered_from`) when reality requires them, and one dated `## Reconcile log` entry — and apply it with the `change.reconcile` operation with `--input ` (the request file carries `id`, the pinned `revision`, and the authored Markdown — never a shell-escaped flag). The `reconcile_log_entry` is the **section body only** — the operation writes the `### YYYY-MM-DD` heading. When nothing changed (spec, stack base, related changes, and scope all hold), send just `{id, revision, reconcile_log_entry}` with a one-line body such as "Unchanged against ``"; sections and relations go in only when reality requires a change. The transaction checks the exact revision and legal `in-progress` status, sets `reconciled: true`, rerenders backlinks/`## Artifacts` block/inline board, validates the whole repository, and commits atomically on the metadata branch, pushed to the metadata remote; unknown frontmatter, unlisted authored sections, line endings, and unrelated files stay byte-identical, and a request naming a non-owned field/section is a typed refusal that writes nothing. If fresh origin state diverges incompatibly, the operation returns `contended` and writes nothing — never a text-merge; re-read fresh context and re-author. Adjacent follow-up work this pass surfaces is **noted for the final report** — nothing is minted automatically; a human captures reported work deliberately with `docket change create`, guided by the backlog verdict final consolidation attaches (Step 6.5 *Backlog match*). Two escape hatches: - Change now **OBSOLETE** → kill it via the convention's close-out (**read `../docket-convention/references/close-out.md` now — blocking**) — one atomic `change.kill` operation transaction that archives the record on `docket`, retargets the linked spec's back-link, and renders the inline board in its own metadata commit. Caller posture and the cleanup notes: **read `references/edge-paths.md` now (blocking)**. Because the `change.kill` operation renders the board atomically inside its own commit, **no separate Board pass follows** — the board already drops the killed change. Then return to Step 1. -- Design **FUNDAMENTALLY invalidated** (not just scope-adjustable) → STOP and escalate to the human — end the run with the **`halted`** disposition (see *Terminal disposition*), the driver's stop-and-surface signal — and **write that halt into git before stopping**: the `change.halt` operation with `--id --revision --input ` records a bounded authored run-halted report into a `## Run halted` section on the in-progress change in one exact-revision transaction, leaving the branch, lease, workspace, and evidence untouched (the authored Markdown travels as a request file, never a shell-escaped flag; a non-in-progress record is refused, writing nothing). The `report` is the section **body only** — the operation alone writes the `## Run halted` heading and dated `###` sub-heading, so the body starts with prose, a list, or a `###`-or-deeper subsection. A body carrying its own column-zero `## ` heading (a repeated or dated halt heading included) or an unterminated code fence is refused `invalid-input` (`invalid-section-markdown`, field `report`), writing nothing; keep heading examples inside closed code fences. This is the producer half of the section the convention defines: a `halted` disposition that exists only as a sentence in a completion report is exactly the untrusted self-report the `run.verify` operation was built to stop trusting. The same write is required for **any** hard error that ends the run `halted`, wherever it occurs. Any hard error that prevents reaching a PR is likewise `halted`. This skill cannot re-brainstorm alone; re-brainstorming is a human act handled by `superpowers:brainstorming` + `docket-new-change`. +- Design **FUNDAMENTALLY invalidated** (not just scope-adjustable) → STOP and escalate to the human — end the run with the **`halted`** disposition (see *Terminal disposition*), the driver's stop-and-surface signal — and **write that halt into git before stopping**: the `change.halt` operation with `--id --revision --input ` records a bounded authored run-halted report into a `## Run halted` section on the in-progress change in one exact-revision transaction, leaving the branch, workspace, and evidence untouched (the authored Markdown travels as a request file, never a shell-escaped flag; a non-in-progress record is refused, writing nothing). The `report` is the section **body only** — the operation alone writes the `## Run halted` heading and dated `###` sub-heading, so the body starts with prose, a list, or a `###`-or-deeper subsection. A body carrying its own column-zero `## ` heading (a repeated or dated halt heading included) or an unterminated code fence is refused `invalid-input` (`invalid-section-markdown`, field `report`), writing nothing; keep heading examples inside closed code fences. This is the producer half of the section the convention defines: a `halted` disposition that exists only as a sentence in a completion report is exactly the untrusted self-report the `run.verify` operation was built to stop trusting. The same write is required for **any** hard error that ends the run `halted`, wherever it occurs. Any hard error that prevents reaching a PR is likewise `halted`. This skill cannot re-brainstorm alone; re-brainstorming is a human act handled by `superpowers:brainstorming` + `docket-new-change`. ### Step 4 — Worktree + plan @@ -166,7 +166,7 @@ Each step below is complete only when its row holds — read from **git**, never | Step | Complete only when | |---|---| -| 2 Claim | `status: in-progress` + `branch:` + `updated:` + `claimed_at:` committed on the metadata branch **and landed** (an `applied` claim receipt). | +| 2 Claim | `status: in-progress` + `branch:` + `updated:` committed on the metadata branch **and landed** (an `applied` claim receipt). | | 3 Reconcile | `reconciled: true` and a dated `## Reconcile log` entry landed on the metadata branch — or, on the kill path, the change archived. | | 4 Worktree + plan | the spec copy committed as the first commit on `/`, then `plan:` and the plan file with its backlink landed on the metadata branch, the feature HEAD unchanged by planning. | | 5 Build | the executed plan committed on `/`, with a build-evidence record at `result: green` (or `skipped` / `build-gate-off` under `build.gate: off`) whose `head_sha` **equals branch HEAD**. | @@ -215,7 +215,7 @@ A change is drafted against a *snapshot* of the codebase, ADRs, and other in-fli ### The field-write rule -Every change-file field write in this run (claim's `status:`/`branch:`, reconcile, `plan:`, `adrs:`, `results:`, `pr:` + `status: implemented`) lands through a **`change.*` / attach / mark-implemented transaction** in the metadata worktree on the metadata branch — never a hand-edit, never in the feature worktree — which reloads fresh origin, checks the exact record revision, and commits and pushes atomically. The skill **never invokes a facade renderer and never hand-writes a derived view**: for any **link-bearing field** (`spec:`/`plan:`/`adrs:`/`pr:`/`results:`), the transaction regenerates the `## Artifacts` block and inline board in the same commit; `claimed_at` is stamped only by the claim, reconcile, and resume-halted transactions. The halt-path authored sections also land through transactions, never a hand-edit: the `change.halt` operation writes the `## Run halted` section (Step 3) and the `change.resume-halted` operation removes it on resume (Step 2), each an exact-revision transaction that renders the inline board in its own commit. The skill authors the halt report as a request file and hands it across; it never edits the section bytes itself. **Stage by explicit path** — that tree is shared, so a bare `add -A` commits another agent's staged work under your message. +Every change-file field write in this run (claim's `status:`/`branch:`, reconcile, `plan:`, `adrs:`, `results:`, `pr:` + `status: implemented`) lands through a **`change.*` / attach / mark-implemented transaction** in the metadata worktree on the metadata branch — never a hand-edit, never in the feature worktree — which reloads fresh origin, checks the exact record revision, and commits and pushes atomically. The skill **never invokes a facade renderer and never hand-writes a derived view**: for any **link-bearing field** (`spec:`/`plan:`/`adrs:`/`pr:`/`results:`), the transaction regenerates the `## Artifacts` block and inline board in the same commit. The halt-path authored sections also land through transactions, never a hand-edit: the `change.halt` operation writes the `## Run halted` section (Step 3) and the `change.resume-halted` operation removes it on resume (Step 2), each an exact-revision transaction that renders the inline board in its own commit. The skill authors the halt report as a request file and hands it across; it never edits the section bytes itself. **Stage by explicit path** — that tree is shared, so a bare `add -A` commits another agent's staged work under your message. ### Feature branch invariants diff --git a/internal/assets/embedded/tree/skills/docket-implement-next/references/edge-paths.md b/internal/assets/embedded/tree/skills/docket-implement-next/references/edge-paths.md index 40b85d961..9bfbafdc5 100644 --- a/internal/assets/embedded/tree/skills/docket-implement-next/references/edge-paths.md +++ b/internal/assets/embedded/tree/skills/docket-implement-next/references/edge-paths.md @@ -12,7 +12,7 @@ with `--json` (a write-free read) and take the named change's `unmet_dependencie For **each** id in that set — and never any other change — run one `finalize.closeout` operation with `--id ` (resolve argv from the capability catalog). The operation itself re-proves the -merged PR and applies the one verified final shape, so run no cleanup suffix and no reclaim, and +merged PR and applies the one verified final shape, so run no cleanup suffix, and never widen or recurse beyond this set. Map each envelope locally and key success on the envelope `result` `applied` or `no-op` — never on its `disposition` token: - Every closeout succeeds → re-run the `repository.prepare` operation and re-run @@ -47,15 +47,15 @@ non-interactive). `run-halted` verdict — resumes only through the `change.resume-halted` operation with `--id --revision --acknowledge-quiescent`, never a fresh claim or a hand-deleted section. The operation requires the exact marked record and the explicit acknowledgement that the prior -worker is quiescent, reprobes the branch/workspace/live gate, refreshes the claim, and removes +worker is quiescent, reprobes the branch/workspace/live gate, and removes exactly the marker section while preserving every other byte and checkpoint. It refuses (writing nothing) without the acknowledgement, on revision drift (`contended`), or on a live gate lock — it never resets or adopts a workspace whose writer may still be live. Once resumed, the change re-enters this resume path with its marker gone. -**Starting a resume over a live run.** Resuming a change starts the run tracker again too, and one -worktree carries at most one live run. When the caller starts the resume (`run.start … --resume -`), `run.start` refuses to open a second run over one that has not verifiably stopped: +**Starting a resume over a live run.** A stranded run recovers only by resuming its change by id +(the `run.start` operation with `implement-next --resume `); one worktree carries at most one +live run, so `run.start` refuses to open a second run over one that has not verifiably stopped: - Prior run still **active** (an undispatched earlier resume start counts) → refused `resume-active-run`, naming the change and run key, with the remedy: cancel the prior run via the @@ -94,6 +94,6 @@ rather than force-writing its local view. or a checkpoint boundary is reached while the ownership or gate-drive contract forbids a safe write, the results artifact cannot be captured yet. That case keeps its **existing disposition** (the halt or the continuation it was already going to take) and **reports the capture limitation through the -existing halt/continuation channel** — no fabricated results path, no stolen lease, and no delayed +existing halt/continuation channel** — no fabricated results path, no stolen claim, and no delayed gate handoff to make room for a write. The missing capture is a reported limitation, never a reason to force a workspace, a commit, or a HEAD move. diff --git a/internal/assets/embedded/tree/skills/docket-status/SKILL.md b/internal/assets/embedded/tree/skills/docket-status/SKILL.md index 74593aa07..c70489448 100644 --- a/internal/assets/embedded/tree/skills/docket-status/SKILL.md +++ b/internal/assets/embedded/tree/skills/docket-status/SKILL.md @@ -22,28 +22,27 @@ Invoke the `docket-convention` skill via the Skill tool first — unless already ## Mode choice -- **The user only wants to *see* the backlog** (no explicit refresh requested, nothing merged recently that you know of) ⇒ run the write-free read alone: the `status` operation (resolve argv from the capability catalog) with `--json`. It never merges, archives, reclaims, or renders a board. -- Implementation scope (`--scope implementation`) is the startup-preflight scope: current merged-work recovery plus reclaim gating, with independent historical cleanup retries deferred and counted in `deferred_historical_cleanups`. It is owned by the `maintenance.preflight` operation, which `docket-implement-next` runs inline at its Step 0 on its selection path (no id or an id set) — not a mode of this skill. This skill's two modes are the see-only read and the explicit `--scope full` refresh/cleanup. -- **An explicit refresh/cleanup request** — or a post-merge cleanup after a PR merged via the GitHub button ⇒ run the `maintenance.sweep` operation with `--scope full --json` first (merge sweep + historical cleanup retries + eligible reclaims + integration sync), then read the refreshed state with the `status` operation and `--json`. +- **The user only wants to *see* the backlog** (no explicit refresh requested, nothing merged recently that you know of) ⇒ run the write-free read alone: the `status` operation (resolve argv from the capability catalog) with `--json`. It never merges, archives, or renders a board. +- Implementation scope (`--scope implementation`) is the startup-preflight scope: current merged-work recovery, with independent historical cleanup retries deferred and counted in `deferred_historical_cleanups`. It is owned by the `maintenance.preflight` operation, which `docket-implement-next` runs inline at its Step 0 on its selection path (no id or an id set) — not a mode of this skill. This skill's two modes are the see-only read and the explicit `--scope full` refresh/cleanup. +- **An explicit refresh/cleanup request** — or a post-merge cleanup after a PR merged via the GitHub button ⇒ run the `maintenance.sweep` operation with `--scope full --json` first (merge sweep + historical cleanup retries + integration sync), then read the refreshed state with the `status` operation and `--json`. ## Maintenance sweep — the merged-PR recovery mutation (only when asked) The **read is separate from the mutation.** The human `status` read stays read-only: it -reports the backlog and never merges, archives, reclaims, or cleans up. When the caller explicitly +reports the backlog and never merges, archives, or cleans up. When the caller explicitly asks to refresh or clean up — a post-merge cleanup, an out-of-band merge to recover — run the `maintenance.sweep` operation (resolve argv from the capability catalog, scope per *Mode choice*) **before** the read, then read the refreshed state. Both maintenance-sweep scopes (full and implementation) run the `repository.sync-integration` operation once as their end-of-run suffix; status itself stays read-only and relies on maintenance's embedded sync when it requests a sweep, and it must not invoke a duplicate `repository.sync-integration`. The `maintenance.sweep` operation pins an initial inventory, walks it in deterministic order, and reloads fresh authority before **every** mutation. It closes out each `implemented` change whose PR merged -(stacked children before ancestors, then the root carrying its descendants), retries pending -backlink-repair and cleanup suffixes, and attempts an eligible reclaim only when `reclaim.auto` is -true. It emits one structured entry per item with a closed disposition — `applied` | `noop` | +(stacked children before ancestors, then the root carrying its descendants), and retries pending +backlink-repair and cleanup suffixes. It emits one structured entry per item with a closed disposition — `applied` | `noop` | `contended` | `blocked` | `unknown` | `failed` | `skipped`, each with its stable reason — never a collapsed boolean. It never merges an open PR, never overrides approval, never retargets an unauthorized child, and never edits authored results; a destructive suffix never runs after an `unknown` prerequisite, and one item's failure never stops the independent items. Surface the per-item report; act only on the `blocked`/`failed`/`unknown` entries a human must see. -`--scope` takes a fixed set of allowed values. `full` — the default when omitted — is the whole worklist, including cleanup retries for every `done`/`stacked-merged` record — which also repoint, unpreviewed, every merged PR description whose backlink still names an `active/` path (the `repository.repair` operation with `--pr-backlinks` previews that repair). `implementation` is the implementation-startup preflight: it still schedules every current merged-implemented closeout, the cleanup suffix such a closeout carries in the same invocation, and the `reclaim.auto`-gated reclaims, but it does not enqueue an independent cleanup for a record that was already final at the pinned inventory. Those are reported as a deferred COUNT — a population deliberately not probed, never evidence anything is dirty or blocked; explicit full maintenance owns those retries, and a failed or interrupted suffix stays recoverable through `--scope full` or the targeted finalize cleanup. +`--scope` takes a fixed set of allowed values. `full` — the default when omitted — is the whole worklist, including cleanup retries for every `done`/`stacked-merged` record — which also repoint, unpreviewed, every merged PR description whose backlink still names an `active/` path (the `repository.repair` operation with `--pr-backlinks` previews that repair). `implementation` is the implementation-startup preflight: it still schedules every current merged-implemented closeout and the cleanup suffix such a closeout carries in the same invocation, but it does not enqueue an independent cleanup for a record that was already final at the pinned inventory. Those are reported as a deferred COUNT — a population deliberately not probed, never evidence anything is dirty or blocked; explicit full maintenance owns those retries, and a failed or interrupted suffix stays recoverable through `--scope full` or the targeted finalize cleanup. ## Run the pass @@ -68,7 +67,7 @@ Starting the sweep command is not finishing it. If the shell tool's foreground w Only the sweep's actual terminal protocol-v1 envelope completes the command. Validate it and every entry: `protocol_version` `1`, `operation` `maintenance.sweep`, a `scope` equal to the one you requested, and each entry's closed disposition. Retain the original structured output — a harness result handle or a task-local output artifact — and extract the compact summary plus any problem entries in one read/parse rather than reopening the full output repeatedly; stdout is the JSON document, and any progress diagnostics belong on a separate channel. Only after that terminal validation run the post-sweep read: the `status` operation (resolve argv from the capability catalog) with `--json`. A read taken after a failed or unvalidated sweep is diagnostic only — label it as diagnostic; it can never authorize selection. -The envelope's top-level `applied` means some work applied, never that every item succeeded. A `blocked`, `failed`, or `unknown` entry — or a `contended` entry on work this preflight required — is a failed preflight even under an `applied` envelope: surface it per *Read the report* below and stop, per the *Scope of this stop* rule above. Intentional policy skips (`reclaim-auto-disabled`) and genuine no-ops remain non-errors — never collapse arbitrary `skipped` reasons into success. On cancellation, request cancellation of the exact owned task where the harness supports it, then observe its termination; never broadly kill processes, abandon a watcher, or spawn a replacement sweep while the prior one may still run. If quiescence cannot be established, halt naming the exact live task identity and preserve its output — an explicit failure here beats claiming an orphan-free exit. +The envelope's top-level `applied` means some work applied, never that every item succeeded. A `blocked`, `failed`, or `unknown` entry — or a `contended` entry on work this preflight required — is a failed preflight even under an `applied` envelope: surface it per *Read the report* below and stop, per the *Scope of this stop* rule above. Intentional policy skips and genuine no-ops remain non-errors — never collapse arbitrary `skipped` reasons into success. On cancellation, request cancellation of the exact owned task where the harness supports it, then observe its termination; never broadly kill processes, abandon a watcher, or spawn a replacement sweep while the prior one may still run. If quiescence cannot be established, halt naming the exact live task identity and preserve its output — an explicit failure here beats claiming an orphan-free exit. When a caller dispatched this skill, the final report must name: the resolved scope, the sweep's terminal envelope result, every problem entry, where the original sweep and status outputs live, and the post-sweep metadata revision (`git -C rev-parse HEAD`). The prose re-summary is never a second authority — the caller verifies against the originals. @@ -121,6 +120,6 @@ The pass reads nothing and writes nothing under `learnings/`, and nothing refres ### Findings -Flag what the pass reports (do not auto-fix unless asked). This skill never runs a checker directly — it invokes the `maintenance.sweep` / `status` operations and reads their `findings`. The `status` read reports configuration diagnostics, `parse-failed`, record validation findings (such as `change-stack-cycle`), `artifact-missing` for a spec/plan/results link on neither the metadata branch nor, for a plan or results closed before the move, the integration branch, and `branch-malformed`. Derived-view drift — the board, the ADR index, a change's `## Artifacts` block, or the backlink at the top of a spec, plan, or results file being out of date or broken — is reported by the `repository.check` operation. Each finding carries its own remedy: most clear with `repository.repair`; a broken marker, or a file linked from more than one change, needs a hand edit first. Relay the finding's remedy rather than telling the human to just run repair. A stale claim surfaces as a `maintenance.sweep` reclaim entry, applied only when `reclaim.auto` is true. A stalled dependency surfaces in the backlog digest as a change with `waiting-dependency` readiness and its `unmet_dependencies`. Each finding's code and shape are owned by the `schema` operation. +Flag what the pass reports (do not auto-fix unless asked). This skill never runs a checker directly — it invokes the `maintenance.sweep` / `status` operations and reads their `findings`. The `status` read reports configuration diagnostics, `parse-failed`, record validation findings (such as `change-stack-cycle`), `artifact-missing` for a spec/plan/results link on neither the metadata branch nor, for a plan or results closed before the move, the integration branch, and `branch-malformed`. Derived-view drift — the board, the ADR index, a change's `## Artifacts` block, or the backlink at the top of a spec, plan, or results file being out of date or broken — is reported by the `repository.check` operation. Each finding carries its own remedy: most clear with `repository.repair`; a broken marker, or a file linked from more than one change, needs a hand edit first. Relay the finding's remedy rather than telling the human to just run repair. A stalled dependency surfaces in the backlog digest as a change with `waiting-dependency` readiness and its `unmet_dependencies`. Each finding's code and shape are owned by the `schema` operation. One judgment check stays in-model, on top of the operations: `blocked_by:` re-examination (see *Judgment follow-ups* above) — warn-only, never auto-fix. diff --git a/internal/repoguard/budgets_test.go b/internal/repoguard/budgets_test.go index adfdf6e3b..e3ec6835a 100644 --- a/internal/repoguard/budgets_test.go +++ b/internal/repoguard/budgets_test.go @@ -199,7 +199,7 @@ var skillBudgets = []skillBudget{ {"docket-build/references/gate-driver.md", 138, 1552}, // 0502 review: the raw-verb section names finalize's repaired-head re-gate (137/1546 -> 138/1552); 0502: "loop" means /loop only (137/1550 -> 137/1546); 0502: finalize's repaired-head re-gate is a direct caller (136/1523 -> 137/1550); 0502: the gate-execution intro reference is deleted (138/1555 -> 136/1523); 0502: renamed from gate-caller-loop.md; 0497: +halted-gate tree-survives finding relay (134/1510 -> 138/1555); 0491: the run id is retired (134/1513 -> 134/1510); 0490: the admission section describes the supervisor-held worktree lock; launch-unconfirmed is no longer a refusal (136/1511 -> 134/1513); 0488 review fix: finalize reaches the driver only through finalize.rebase; task-era handoff clauses dropped (word ceiling 1504 -> 1511); 0488 review: start row carries --change-id (word ceiling 1491 -> 1504); 0488: worker-scope/takeover/acknowledge rows and the parent-takeover section removed; callers are the full-suite gates (175/1872 -> 136/1491); 0467: +prepare-scope --run-id and scope-inherited start run id (word ceiling 1826 -> 1872); 0375: +worktree-admission section (word ceiling 1750 -> 1826) {"docket-build/references/task-routing.md", 50, 500}, {"docket-build-task/SKILL.md", 173, 1695}, // 0532: the private-repository writing rule and visibility hand-off (168/1640 -> 173/1695); 0531: the metadata worktree and remote come from the repository.prepare context (168/1637 -> 168/1640); 0488: scoped drive protocol replaced by direct foreground tests under timeout; three outcomes (211/2235 -> 168/1637); 0467 review fix: +the repair re-run run-id exception (206/2183 -> 211/2235); 0467: +the run id rides on the scope, never the bundle (204/2151 -> 206/2183); 0459: +post-handoff continuation never acknowledges or reuses the transferred scope (188/1964 -> 204/2151); 0405: sequential-drive receipt and acknowledgement; 0420: shell-safe capture; 0375: worktree-busy-not-a-retry rule (179/1842 -> 188/1964) - {"docket-convention/SKILL.md", 361, 7377}, // 0360: claimed_at is stamped by claim, reconcile, and resume-halted; a halt no longer claims a refreshed lease (361/7381 -> 361/7377); 0573: trivial retired (362/7411 -> 361/7381); 0560: the hold manifest field, its selection rule, the ## Why on hold section, and the auto-groomer's hold write (360/7331 -> 362/7411); 0565: a kill refuses on built stacked descendants; the killed-parent board text and exits table (360/7317 -> 360/7331); 0568: deferred is entered only from proposed (363/7317 -> 360/7317); 0559: the manifest lists deliverable; done means a merged PR or a completed results artifact; archive dates and change.complete (361/7276 -> 363/7317); 0533: editing visibility never moves a repository; repository.set-visibility does (361/7263 -> 361/7276); 0532: the private-repository writing rule and visibility hand-off (359/7160 -> 361/7263); 0531 review: skills say "the metadata branch", naming `docket` once for shared mode (359/7155 -> 359/7160); 0531: the metadata worktree and remote come from the repository.prepare context (357/7062 -> 359/7155); 0530: plan, results, and build evidence live on the docket branch — the plan-writer's one metadata operation, the attach operations as file-backlink writers, relative same-branch links, and the new ## Build evidence record section (357/7026 -> 357/7062); 0529 review: the backlink block names its PR-body writers beside artifact.backlink, one shared renderer (357/7004 -> 357/7026); 0515: the repair sign-off is retired; a green repair merges (357/7007 -> 357/7004); 0502 rebase onto 0510: kept the backlog-match follow-up clause in the results-artifact paragraph (357/7004 -> 357/7007); 0502 review: the review-tier dispatch is the controller's own (357/6995 -> 357/7004); 0502: configuration read paths corrected — operations read .docket.yml from origin's default-branch tip, the repository setup operations from the primary worktree (357/6959 -> 357/6995); 0502: "loop" means /loop only (357/7036 -> 357/7037); 0502: one metadata layout — the docket branch and the .docket/ worktree (357/7035 -> 357/7036); 0502: agent layer names user-level wrappers and global-only pins (357/7024 -> 357/7035); 0502: typed operations replace the Bash-era script names; ## Run halted facts corrected (359/7092 -> 357/7024); 0502: terminal publish, the learnings cap, and the repository auto_groom default are deleted (362/7256 -> 359/7092); 0502: the auto-capture export paragraph is deleted (370/7334 -> 362/7256); 0502: the configuration contract rewritten from the schema (371/7488 -> 370/7334); 0502: fixed role skills; halt posture (372/7660 -> 371/7488); 0502: record blocks mirror the renderers (367/7619 -> 372/7660); 0502: the dummy-mode shared definition is deleted (390/7848 -> 367/7619); 0410: +required-results lifecycle prose; 0399: +schema request/result contract prose; 0388: +sync-integration prose (see note above); 0502: drop change citations and Go v1 narration (357/7037 -> 357/6958); 0502: the harness adapter is named without a docket source path (357/6958 -> 357/6959) + {"docket-convention/SKILL.md", 353, 7257}, // 0575: reclaim and the claim lease are retired (361/7377 -> 353/7257); 0360: claimed_at is stamped by claim, reconcile, and resume-halted; a halt no longer claims a refreshed lease (361/7381 -> 361/7377); 0573: trivial retired (362/7411 -> 361/7381); 0560: the hold manifest field, its selection rule, the ## Why on hold section, and the auto-groomer's hold write (360/7331 -> 362/7411); 0565: a kill refuses on built stacked descendants; the killed-parent board text and exits table (360/7317 -> 360/7331); 0568: deferred is entered only from proposed (363/7317 -> 360/7317); 0559: the manifest lists deliverable; done means a merged PR or a completed results artifact; archive dates and change.complete (361/7276 -> 363/7317); 0533: editing visibility never moves a repository; repository.set-visibility does (361/7263 -> 361/7276); 0532: the private-repository writing rule and visibility hand-off (359/7160 -> 361/7263); 0531 review: skills say "the metadata branch", naming `docket` once for shared mode (359/7155 -> 359/7160); 0531: the metadata worktree and remote come from the repository.prepare context (357/7062 -> 359/7155); 0530: plan, results, and build evidence live on the docket branch — the plan-writer's one metadata operation, the attach operations as file-backlink writers, relative same-branch links, and the new ## Build evidence record section (357/7026 -> 357/7062); 0529 review: the backlink block names its PR-body writers beside artifact.backlink, one shared renderer (357/7004 -> 357/7026); 0515: the repair sign-off is retired; a green repair merges (357/7007 -> 357/7004); 0502 rebase onto 0510: kept the backlog-match follow-up clause in the results-artifact paragraph (357/7004 -> 357/7007); 0502 review: the review-tier dispatch is the controller's own (357/6995 -> 357/7004); 0502: configuration read paths corrected — operations read .docket.yml from origin's default-branch tip, the repository setup operations from the primary worktree (357/6959 -> 357/6995); 0502: "loop" means /loop only (357/7036 -> 357/7037); 0502: one metadata layout — the docket branch and the .docket/ worktree (357/7035 -> 357/7036); 0502: agent layer names user-level wrappers and global-only pins (357/7024 -> 357/7035); 0502: typed operations replace the Bash-era script names; ## Run halted facts corrected (359/7092 -> 357/7024); 0502: terminal publish, the learnings cap, and the repository auto_groom default are deleted (362/7256 -> 359/7092); 0502: the auto-capture export paragraph is deleted (370/7334 -> 362/7256); 0502: the configuration contract rewritten from the schema (371/7488 -> 370/7334); 0502: fixed role skills; halt posture (372/7660 -> 371/7488); 0502: record blocks mirror the renderers (367/7619 -> 372/7660); 0502: the dummy-mode shared definition is deleted (390/7848 -> 367/7619); 0410: +required-results lifecycle prose; 0399: +schema request/result contract prose; 0388: +sync-integration prose (see note above); 0502: drop change citations and Go v1 narration (357/7037 -> 357/6958); 0502: the harness adapter is named without a docket source path (357/6958 -> 357/6959) // 0154: docket-convention/github-board-mirror.md removed — the GitHub mirror is // retired (unsupported, mutation-blocking); its budget row is deleted with it. {"docket-convention/references/agent-layer.md", 214, 1990}, // 0552: the user-level settings.json also carries the finalize allow rules (212/1951 -> 214/1990); 0546: the per-agent cache_ttl pin, its shipped 1h default, and the machine-wide controls docket leaves unset (168/1593 -> 212/1951); 0538: init and repository.configure-harnesses set agent_harnesses; repository.check reports harnesses-unset (164/1553 -> 168/1593); 0535: a private repository's instructions file and its user-level triggers (148/1419 -> 164/1553); 0502: rewritten around user-level wrappers and global-only pins (202/2346 -> 148/1419); 0502: the legacy agents-file migration clause is deleted (202/2349 -> 202/2346) @@ -209,14 +209,14 @@ var skillBudgets = []skillBudget{ {"docket-finalize-change/SKILL.md", 242, 6269}, // 0571: the children-retarget-required closeout bullet is deleted; root-archived names who is carried (243/6254 -> 242/6269); 0567: step 10 cleans each carried_ids child after the root (243/6191 -> 243/6254); 0551: step 1 checks the change out into its own workspace first (241/6033 -> 243/6191); 0532 review: both finalize gate dispatches carry the Visibility payload line (239/6020 -> 241/6033); 0532: the private-repository writing rule and visibility hand-off (239/6000 -> 239/6020); 0529 review: the PR-backlink repoint is a best-effort follow-up after the archive push, for root-archived descendants too (239/5984 -> 239/6000); 0529: close-out repoints the merged PR description's backlink; pr-backlink-pending is a retryable warning (239/5936 -> 239/5984); 0525 review: workspace-remnant rides any finished-workspace disposition and is named in the final report; branch-rules-unavailable comes only from the probing run (239/5910 -> 239/5936); 0525: plan-gated merges carry branch-rules-unavailable into closeout notes; cleanup reports workspace-remnant and names what blocked a workspace (239/5820 -> 239/5910); 0515 review: the refused-notes fallback names every dropped note in the final report (238/5809 -> 239/5820); 0515 review: a repair whose run halts before closeout is named in finalize.block and carried into a later closeout (238/5708 -> 238/5809); 0515: the repair sign-off is retired; a green repair merges (238/5808 -> 238/5708); 0517: the repaired-head evidence.record carries --owner finalize and records finalize.test_command (238/5790 -> 238/5808); 0502 review: clear-block re-reads the revision after the block lands (238/5771 -> 238/5790); 0502: repair sign-off records finalize.block before publishing the repaired head (238/5733 -> 238/5771); 0502: "loop" means /loop only (238/5729 -> 238/5733); 0502: repair sign-off is the human running finalize.clear-block (238/5666 -> 238/5729); 0502: the repaired head is re-gated through the gate driver (236/5568 -> 238/5666); 0502: the dummy-mode paragraph is deleted (238/5641 -> 236/5568); 0455: +record-invalid refusal (structural scope, findings remedy, merged-outside-docket precedence) in step 8 (word ceiling 5520 -> 5647); 0442: +post-publication base-advance guidance (word ceiling 5421 -> 5520); de-duplicated the shared forward-rebase mechanic against the 0438 unpublished-case paragraph (reclaimed 57 words), but the distinct published-refresh facts plus the retained 0438 guidance cannot fit the old ceiling without deleting required guidance; 0411: +reconciliation-write recovery exception paragraph in the resolver loop (ceilings 238/5232 -> 239/5421); 0413: +generated-bundle mixed-conflict handoff sentence in the resolver-loop block (word ceiling 5200 -> 5232); 0419: +repair-attempt budget payload line and rewired repair contract (line ceiling 236 -> 238); 0393: +exact payload, marker, and direct-dispatch lines atop 0349/0410 (see note above) {"docket-finalize-change/references/gate-failure.md", 162, 2107}, // 0571: the children-retarget-required closeout halt is deleted (162/2111 -> 162/2107); 0532 review: the gate-agent payload names Visibility (161/2109 -> 162/2111); 0515 review: the refused-notes fallback names every dropped note in the final report (160/2098 -> 161/2109); 0515 review: a repair whose run halts before closeout is named in finalize.block and carried into a later closeout (153/2005 -> 160/2098); 0515: the repair sign-off is retired; a green repair merges (160/2086 -> 153/2005); 0517: the repaired-head evidence.record carries --owner finalize (159/2081 -> 160/2086); 0502 review: clear-block re-reads the revision after the block lands (157/2062 -> 159/2081); 0502: repair sign-off records finalize.block before publishing the repaired head (155/2028 -> 157/2062); 0502: the embedded-bundle rule is conditioned on docket's own repository (155/2024 -> 155/2028); 0502: "loop" means /loop only (155/2027 -> 155/2024); 0502: repair sign-off is the human running finalize.clear-block; the marker lifecycle names what removes it (154/2013 -> 155/2027); 0502: the repaired head is re-gated through the gate driver (148/1937 -> 154/2013); 0497: +wait-for-the-leftover-group sentence (146/1901 -> 148/1937); 0493: the gate relaunch is retired (145/1892 -> 146/1901); 0491: the run id is retired (145/1894 -> 145/1892); 0490: the shared-slot note became the shared worktree-lock note (147/1901 -> 145/1894); 0411: +reconciliation-write exception section and abort-set carve-out (ceilings 135/1472 -> 147/1901); 0413: +conflicted_paths-lists-authored-only rule in the resolver-report section (line ceiling 133 -> 135, word ceiling 1465 -> 1472); 0419: +repair-attempt budget payload and rewired repair contract prose (word ceiling 1450 -> 1465); 0349: +reserve-before-dispatch resolver protocol prose; 0375: +worktree-slot note for the scopeless finalize gate (120/1300 -> 133/1450) {"docket-groom-next/SKILL.md", 77, 2310}, // 0573: trivial retired; the brainstorm is told the artifact is always a spec (78/2377 -> 77/2310); 0560 review: a revise that sets or lifts a hold changes the row's readiness (78/2370 -> 78/2377); 0560: the Step-4 hold paragraph (76/2282 -> 78/2370); 0559: the Step-4 deliverable, type, and branch_prefix paragraph (78/2215 -> 76/2282); 0550: the Step-4 reprioritize paragraph and the stub-edit priority route (76/2141 -> 78/2215); 0532: the private-repository writing rule and visibility hand-off (76/2109 -> 76/2141); 0531: the metadata worktree and remote come from the repository.prepare context (76/2102 -> 76/2109); 0502 rebase onto 0509: carried the edit-a-stub revise route and groom-exit-scoped STOPs (76/2012 -> 76/2102); 0502: "loop" means /loop only (76/2011 -> 76/2012); 0502: one metadata layout — the docket branch and the .docket/ worktree (76/2010 -> 76/2011); 0502: selection bands key on auto_groomable itself (76/2009 -> 76/2010); 0502: invoke superpowers:brainstorming by name (76/2037 -> 76/2009); 0502: the dummy-mode pointer is deleted (78/2080 -> 76/2037); 0461: +Step-4 retitle paragraph (title on change.groom; lines 77 -> 78, words 1996 -> 2081); +not-retitleable refusal code (2081 -> 2082); 0382: +typed rearm exit (word ceiling 1889 -> 1996); 0445: +revise route for already-groomed explicit ids (Step 1) and the fifth Step-4 exit (word ceiling 1650 -> 1813); +spec_version pin for a spec-body revise (1813 -> 1849); +revise spec_markdown excludes the backlink block (1849 -> 1850); +revise in the description and the revise contended/board clauses (1850 -> 1889) - {"docket-implement-next/SKILL.md", 226, 8841}, // review: Step 7 names the Step 6 evidence file instead of verified bytes (226/8835 -> 226/8841); 0360 step wording: the PR-body rules moved in from edge-paths.md (which fell 222 words) plus the minimal reconcile request, evidence block file, and ADR producing-change pass-through; the raise is that moved text, compressed (220/8590 -> 226/8835); 0360: local revision lookups, no claim refreshes, fewer re-syncs; the line raise is the new standalone Revision lookups paragraph every post-claim write keys on, words fell (218/8612 -> 220/8590); 0573: trivial retired (218/8637 -> 218/8612); 0570: the --selection claim sentence and the run-next driver rule (218/8555 -> 218/8637); 0560 review: on the named path on-hold also qualifies at the Step-1 confirm (218/8548 -> 218/8555); 0560: on-hold joins the readiness vocabulary and skip reasons; a held change is built when named (218/8518 -> 218/8548); 0559: the results-artifact ending pointer, postcondition row, and advanced meaning (215/8411 -> 218/8518); 0532: the private-repository writing rule and visibility hand-off (212/8282 -> 215/8411); 0531: the metadata worktree and remote come from the repository.prepare context (216/8443 -> 212/8282); 0517: evidence.record reads the gate command from build configuration (216/8438 -> 216/8443); 0502 rebase onto 0510: carried the Step 6.5 Backlog match paragraph and verdict pointers (214/8039 -> 216/8438); 0502 review: the controller dispatches the review tier wrapper; the skill dispatches nothing (214/8023 -> 214/8039); 0502: "loop" means /loop only (214/8058 -> 214/8057); 0502: one metadata layout — the docket branch and the .docket/ worktree (214/8042 -> 214/8058); 0502: the review payload names the resolved build.gate value; build_gate spellings become build.gate (214/8020 -> 214/8042); 0502: change.reclaim replaces reclaim-claims; the claim removes a leftover ## Run halted (214/8009 -> 214/8020); 0502: terminal-publication narration is deleted (214/8037 -> 214/8009); 0502: the severity floor is read as review.min_fix_severity through diagnostic.config (214/8034 -> 214/8037); 0502: the fixed role skills replace the $SKILL_* sites (214/8257 -> 214/8034); 0502: the dummy-mode paragraph and PR-body clause are deleted (216/8356 -> 214/8257); 0497: +Step 5 halted-build evidence kept verbatim in ## Run halted (216/8325 -> 216/8356); 0498 review: checkpoint (ii) persist wording (8320 -> 8325); 0498: +Step 6.5 review-findings homes, condensation exception, Human-actions class rule (214/8161 -> 216/8320); 0491: the run id is retired (214/8183 -> 214/8161); 0488 review: build-owned starts carry --change-id/--run-context (word ceiling 8162 -> 8183); 0488: run context and run id name only build-owned starts (word ceiling 8175 -> 8162); 0467 review fix: +the repair worker's post-fix re-run is a build-owned start (word ceiling 8165 -> 8175); 0467: +run id threaded to prepare-scope and build-owned starts (word ceiling 8080 -> 8165); 0455: +pr.publish record-invalid refusal clause (word ceiling 8025 -> 8080); 0448: +named-invocation branch; bounded own-dependency closeout moved to edge-paths.md (ceilings 210/7716 -> 214/8270 -> 214/8025); 0393: +exact payload, marker, and direct-dispatch lines atop 0410/0354/0376; 0375: +run-tracker resume pointer (word ceiling 7530 -> 7547); 0440: reader-first results prose; 0502: drop change citations and Go v1 narration (214/8057 -> 214/8023) - {"docket-implement-next/references/edge-paths.md", 99, 1051}, // 0360: the PR-body assembly section moved into SKILL.md Step 7 (109/1273 -> 99/1051); 0360: the resume results load needs no extra re-sync (109/1276 -> 109/1273); 0571: the stack-base refusal names its true reason (109/1265 -> 109/1276); 0532: the private-repository writing rule and visibility hand-off (109/1226 -> 109/1265); 0531: the metadata worktree and remote come from the repository.prepare context (118/1499 -> 109/1226); 0502: one metadata layout — the docket branch and the .docket/ worktree (118/1507 -> 118/1509); 0502: run.verify replaces verify-run (118/1505 -> 118/1507); 0502: terminal-publication narration is deleted (118/1513 -> 118/1505); 0502: the deferred results-only permit clause is deleted (118/1546 -> 118/1513); 0502: no custom plan location (118/1547 -> 118/1546); 0491: the run id is retired (118/1554 -> 118/1547); 0410: +resume/recovery + required-results reconciliation; 0375: +run-tracker resume refusals (78/1091 -> 93/1261); 0448: +named own-dependency closeout moved from SKILL.md (93/1261 -> 118/1554); 0502: drop change citations and Go v1 narration (118/1509 -> 118/1499) + {"docket-implement-next/SKILL.md", 226, 8806}, // 0575: reclaim and the claim lease are retired (226/8841 -> 226/8806); review: Step 7 names the Step 6 evidence file instead of verified bytes (226/8835 -> 226/8841); 0360 step wording: the PR-body rules moved in from edge-paths.md (which fell 222 words) plus the minimal reconcile request, evidence block file, and ADR producing-change pass-through; the raise is that moved text, compressed (220/8590 -> 226/8835); 0360: local revision lookups, no claim refreshes, fewer re-syncs; the line raise is the new standalone Revision lookups paragraph every post-claim write keys on, words fell (218/8612 -> 220/8590); 0573: trivial retired (218/8637 -> 218/8612); 0570: the --selection claim sentence and the run-next driver rule (218/8555 -> 218/8637); 0560 review: on the named path on-hold also qualifies at the Step-1 confirm (218/8548 -> 218/8555); 0560: on-hold joins the readiness vocabulary and skip reasons; a held change is built when named (218/8518 -> 218/8548); 0559: the results-artifact ending pointer, postcondition row, and advanced meaning (215/8411 -> 218/8518); 0532: the private-repository writing rule and visibility hand-off (212/8282 -> 215/8411); 0531: the metadata worktree and remote come from the repository.prepare context (216/8443 -> 212/8282); 0517: evidence.record reads the gate command from build configuration (216/8438 -> 216/8443); 0502 rebase onto 0510: carried the Step 6.5 Backlog match paragraph and verdict pointers (214/8039 -> 216/8438); 0502 review: the controller dispatches the review tier wrapper; the skill dispatches nothing (214/8023 -> 214/8039); 0502: "loop" means /loop only (214/8058 -> 214/8057); 0502: one metadata layout — the docket branch and the .docket/ worktree (214/8042 -> 214/8058); 0502: the review payload names the resolved build.gate value; build_gate spellings become build.gate (214/8020 -> 214/8042); 0502: change.reclaim replaces reclaim-claims; the claim removes a leftover ## Run halted (214/8009 -> 214/8020); 0502: terminal-publication narration is deleted (214/8037 -> 214/8009); 0502: the severity floor is read as review.min_fix_severity through diagnostic.config (214/8034 -> 214/8037); 0502: the fixed role skills replace the $SKILL_* sites (214/8257 -> 214/8034); 0502: the dummy-mode paragraph and PR-body clause are deleted (216/8356 -> 214/8257); 0497: +Step 5 halted-build evidence kept verbatim in ## Run halted (216/8325 -> 216/8356); 0498 review: checkpoint (ii) persist wording (8320 -> 8325); 0498: +Step 6.5 review-findings homes, condensation exception, Human-actions class rule (214/8161 -> 216/8320); 0491: the run id is retired (214/8183 -> 214/8161); 0488 review: build-owned starts carry --change-id/--run-context (word ceiling 8162 -> 8183); 0488: run context and run id name only build-owned starts (word ceiling 8175 -> 8162); 0467 review fix: +the repair worker's post-fix re-run is a build-owned start (word ceiling 8165 -> 8175); 0467: +run id threaded to prepare-scope and build-owned starts (word ceiling 8080 -> 8165); 0455: +pr.publish record-invalid refusal clause (word ceiling 8025 -> 8080); 0448: +named-invocation branch; bounded own-dependency closeout moved to edge-paths.md (ceilings 210/7716 -> 214/8270 -> 214/8025); 0393: +exact payload, marker, and direct-dispatch lines atop 0410/0354/0376; 0375: +run-tracker resume pointer (word ceiling 7530 -> 7547); 0440: reader-first results prose; 0502: drop change citations and Go v1 narration (214/8057 -> 214/8023) + {"docket-implement-next/references/edge-paths.md", 99, 1044}, // 0575: reclaim and the claim lease are retired (99/1051 -> 99/1044); 0360: the PR-body assembly section moved into SKILL.md Step 7 (109/1273 -> 99/1051); 0360: the resume results load needs no extra re-sync (109/1276 -> 109/1273); 0571: the stack-base refusal names its true reason (109/1265 -> 109/1276); 0532: the private-repository writing rule and visibility hand-off (109/1226 -> 109/1265); 0531: the metadata worktree and remote come from the repository.prepare context (118/1499 -> 109/1226); 0502: one metadata layout — the docket branch and the .docket/ worktree (118/1507 -> 118/1509); 0502: run.verify replaces verify-run (118/1505 -> 118/1507); 0502: terminal-publication narration is deleted (118/1513 -> 118/1505); 0502: the deferred results-only permit clause is deleted (118/1546 -> 118/1513); 0502: no custom plan location (118/1547 -> 118/1546); 0491: the run id is retired (118/1554 -> 118/1547); 0410: +resume/recovery + required-results reconciliation; 0375: +run-tracker resume refusals (78/1091 -> 93/1261); 0448: +named own-dependency closeout moved from SKILL.md (93/1261 -> 118/1554); 0502: drop change citations and Go v1 narration (118/1509 -> 118/1499) {"docket-implement-next/references/fix-pass.md", 189, 1954}, // 0360: halts no longer claim a refreshed lease (189/1963 -> 189/1954); 0532: the private-repository writing rule and visibility hand-off (187/1943 -> 189/1963); 0502 rebase onto 0510: carried the backlog-verdict pointer for reported findings (186/1929 -> 187/1943); 0502: "loop" means /loop only (190/1962 -> 190/1967); 0502: undispatchable fix worker halts (192/1991 -> 190/1962); 0502: renamed from fix-loop.md; 0498 review: results-file antecedent (1989 -> 1991); 0498: +review-findings condensation at final consolidation (190/1958 -> 192/1989); 0410: +findings-to-results checkpoint linkage (see note above); 0502: drop change citations and Go v1 narration (190/1967 -> 186/1929) {"docket-implement-next/references/results-artifact.md", 76, 737}, // 0360: no claim refreshes; change.complete pins a locally looked-up revision (79/765 -> 76/737); 0573: trivial retired (79/775 -> 79/765); 0559: new — the results-artifact ending (no plan, build, or PR; review, complete, clean up) {"docket-implement-next/results-template.md", 70, 543}, // 0573: trivial retired (70/545 -> 70/543); 0502 rebase onto 0510: carried the backlog verdict and next action in the Known issues placeholder (68/506 -> 70/545); 0502: inline review replaces the custom review skill (68/511 -> 68/510); 0498: +whole-branch review summary line in Verification performed (64/446 -> 68/511); 0440: reader-first template — action statement + merged Known issues (see note above); 0502: drop change citations and Go v1 narration (68/510 -> 68/506) {"docket-review/SKILL.md", 127, 1054}, // 0573: trivial retired (127/1059 -> 127/1054); 0559: the results-artifact mode (114/966 -> 127/1049); 0559: Inputs and evidence sections defer to results-artifact mode (127/1049 -> 127/1059); 0531: the metadata worktree and remote come from the repository.prepare context (114/965 -> 114/966); 0502: the evidence rule keys on the payload's build.gate value; gate-off skipped records are expected (110/913 -> 114/965); 0410: +findings-return capture contract (see note above) {"docket-new-change/SKILL.md", 48, 1538}, // 0573: trivial retired; the trivial path is deleted and the brainstorm is told the artifact is always a spec (53/1636 -> 48/1538); 0560: suggest a hold; it rides change.create or change.groom (53/1598 -> 53/1636); 0559: the create request carries deliverable: results-artifact for findings-only work (57/1635 -> 53/1598); 0532: the private-repository writing rule and visibility hand-off (57/1603 -> 57/1635); 0531: the metadata worktree and remote come from the repository.prepare context (57/1596 -> 57/1603); 0502 review: omitted draft-time scalars are described exactly (57/1591 -> 57/1596); 0502: "loop" means /loop only (57/1593 -> 57/1591); 0502: one metadata layout — the docket branch and the .docket/ worktree (57/1590 -> 57/1593); 0502: terminal-publication narration and the repository auto_groom default are deleted (57/1609 -> 57/1590); 0502: invoke superpowers:brainstorming by name (57/1636 -> 57/1609); 0502: the dummy-mode pointer is deleted (59/1674 -> 57/1636); 0445: +pointer to the docket-groom-next revise path after landing (word ceiling 1700 -> 1706); 0382: draft-time scalars moved into change.create (ceiling 1706 -> 1675) - {"docket-status/SKILL.md", 126, 2990}, // 0573: trivial retired (126/2993 -> 126/2990); 0560: a held change shows on hold (126/2983 -> 126/2993); 0539: derived-view drift is named by family and each finding's own remedy is relayed instead of a code list (126/2923 -> 126/2983); 0531: the metadata worktree and remote come from the repository.prepare context (126/2921 -> 126/2923); 0530: artifact-missing names where a plan or results file may live — the docket branch, or the integration branch for a record closed before the move (126/2904 -> 126/2921); 0529 review: full-scope cleanup retries also repoint stale merged-PR description backlinks; repair --pr-backlinks previews them (126/2880 -> 126/2904); 0502: one metadata layout — the docket branch and the .docket/ worktree (126/2876 -> 126/2880); 0502: findings named as the binary emits them (126/2852 -> 126/2876); 0502: deferred learnings and publication narration is deleted (127/2956 -> 126/2852); 0502: the dummy-mode pointer is deleted (129/2985 -> 127/2956); 0388: +sync-integration prose (see note above) + {"docket-status/SKILL.md", 125, 2954}, // 0575: reclaim and the claim lease are retired (126/2990 -> 125/2954); 0573: trivial retired (126/2993 -> 126/2990); 0560: a held change shows on hold (126/2983 -> 126/2993); 0539: derived-view drift is named by family and each finding's own remedy is relayed instead of a code list (126/2923 -> 126/2983); 0531: the metadata worktree and remote come from the repository.prepare context (126/2921 -> 126/2923); 0530: artifact-missing names where a plan or results file may live — the docket branch, or the integration branch for a record closed before the move (126/2904 -> 126/2921); 0529 review: full-scope cleanup retries also repoint stale merged-PR description backlinks; repair --pr-backlinks previews them (126/2880 -> 126/2904); 0502: one metadata layout — the docket branch and the .docket/ worktree (126/2876 -> 126/2880); 0502: findings named as the binary emits them (126/2852 -> 126/2876); 0502: deferred learnings and publication narration is deleted (127/2956 -> 126/2852); 0502: the dummy-mode pointer is deleted (129/2985 -> 127/2956); 0388: +sync-integration prose (see note above) } // wcLines counts lines the way `wc -l` does: the number of newline bytes. diff --git a/internal/repoguard/prose_contracts_test.go b/internal/repoguard/prose_contracts_test.go index 8bfca0540..41d57cb82 100644 --- a/internal/repoguard/prose_contracts_test.go +++ b/internal/repoguard/prose_contracts_test.go @@ -502,8 +502,8 @@ var proseContracts = []proseContract{ present: []string{"a held change that would be build-ready shows **on hold**"}}, // change 0360 — the run looks its own record revision up locally before each // post-claim write, re-syncs only where a docket write it did not make could - // have moved the record, and no longer refreshes the claim lease around long - // dispatches (claimed_at is stamped by claim, reconcile, and resume-halted). + // have moved the record, and no longer refreshes the claim around long + // dispatches. {sentinel: "change_0360_revision_lookup", file: "skills/docket-implement-next/SKILL.md", present: []string{ "R=$(git -C rev-parse HEAD:)", @@ -529,8 +529,23 @@ var proseContracts = []proseContract{ present: []string{"the reason recorded"}, absent: []string{"`claimed_at` refreshed"}}, {sentinel: "change_0360_revision_lookup", file: "skills/docket-convention/SKILL.md", - present: []string{"stamped by claim, reconcile, and resume-halted"}, - absent: []string{"refreshed at phase boundaries"}}, + absent: []string{"refreshed at phase boundaries"}}, + // change 0575 — claim reclaim and the claimed_at lease are retired; a stranded + // run recovers only by resuming the change by id, with the run tracker deciding. + {sentinel: "change_0575_no_reclaim", file: "skills/docket-convention/SKILL.md", + present: []string{"and by the claim when a halted change is claimed again"}, + absent: []string{ + "`change.reclaim`", "## Reclaim log", "reclaim.lease_ttl", "lease_ttl:", + "claimed_at:", "self-heals", "Reclaim edge", + }}, + {sentinel: "change_0575_no_reclaim", file: "skills/docket-implement-next/SKILL.md", + present: []string{"the `run.start` operation with `implement-next --resume `"}, + absent: []string{"`change.reclaim`", "claimed_at", "refreshes the claim", "lease classification"}}, + {sentinel: "change_0575_no_reclaim", file: "skills/docket-implement-next/references/edge-paths.md", + present: []string{"the `run.start` operation with `implement-next --resume `"}, + absent: []string{"refreshes the claim", "no reclaim"}}, + {sentinel: "change_0575_no_reclaim", file: "skills/docket-status/SKILL.md", + absent: []string{"reclaim"}}, // change 0360 — Step 3 sends a minimal reconcile request when nothing // changed (the operation writes the dated heading); Step 6 writes the // evidence.record receipt's block to a file instead of a separate verify diff --git a/skills/docket-convention/SKILL.md b/skills/docket-convention/SKILL.md index 1deed7316..2cfc8e310 100644 --- a/skills/docket-convention/SKILL.md +++ b/skills/docket-convention/SKILL.md @@ -38,9 +38,6 @@ run: review: min_fix_severity: minor max_fix_tasks: 10 -reclaim: - lease_ttl: 72 - auto: false learnings: enabled: true # false = read/write gate, never a purge gate_observation_budget: 30 # minutes; enforced by the gate driver @@ -95,7 +92,7 @@ When dispatch is genuinely unavailable the kinds are **not** equivalent, so the |---|---|---| | **`inline` — deterministic** | the `docket-status` and `docket-adr` composition dispatches | Run the same work **inline** — a **first-class equivalent path**, neither a degradation nor a warning, because the contract is git state on the metadata branch, not an in-context return. Every obligation holds unchanged: re-sync before reading, derive from fresh origin, never adopt or commit another agent's uncommitted files. | | **`abstain` — adversarial** | the `docket-auto-groom-critic` gate | **Abstain**, per *Autonomous grooming*. Self-critique by the agent that drafted the spec is not an adversarial gate, and the abstain is a path that skill already owns. | -| **`halt` — discipline** | the **plan-writer dispatch**, the `build` role skill's required nested dispatches, the controller's own review-tier dispatch (the `docket-review` skill itself never dispatches), and the in-branch fix workers (which run the `build` role's own contract) | **`halt`** — the run stops: the change stays `in-progress` with the halt reason recorded through `change.halt`. **No new status, no new field** — the reclaim lease self-heals an abandoned claim. | +| **`halt` — discipline** | the **plan-writer dispatch**, the `build` role skill's required nested dispatches, the controller's own review-tier dispatch (the `docket-review` skill itself never dispatches), and the in-branch fix workers (which run the `build` role's own contract) | **`halt`** — the run stops: the change stays `in-progress` with the halt reason recorded through `change.halt`. **No new status, no new field** — the caller resumes it by id, through `change.resume-halted`. | **Outside the table — `no-fallback`.** `docket-finalize-change`'s two finalize-gate dispatches — `docket-rebase-resolver` and `docket-integration-repair` — sit **outside** this table rather than in a row of it, because their contract is an **in-context report** gating the merge, not git state on the metadata branch. Neither fallback can be borrowed for them: `inline`'s first-class-equivalent path presupposes a git-state transition to reproduce, and `halt` belongs to the workflow roles, and these dispatches are not a role. When dispatch is genuinely unavailable for either — established per the resolution rule above, never from a tool name — the posture is finalize's own pre-existing **abort-and-report**: the gate stops, the PR stays open, the change stays `implemented`, and the reason is recorded through the three channels `docket-finalize-change`'s failure reference owns. **Inline substitution is forbidden** for both, and that is the point of `no-fallback` rather than a table row: reconciling the conflict, or authoring the repair, inside the very agent that would then merge that work is the same self-approval shape `abstain` exists to avoid for the critic. @@ -189,12 +186,11 @@ plan: # plan FILE on the metadata branch; FILE and FIELD wri results: # results FILE on the metadata branch; FILE and FIELD written together by change.attach-results at the first checkpoint, required before the implemented transition auto_groomable: # `true` makes a stub auto-groomable; unset or `false` means not hold: # `true` keeps a groomed change out of autonomous build selection; naming it still builds it -branch_prefix: # optional one unqualified branch-path component; overrides at mint, consumed only at claim, inert once branch: is populated, survives reclaim +branch_prefix: # optional one unqualified branch-path component; overrides at mint, consumed only at claim, inert once branch: is populated branch: # minted / (or /) name, set on claim; sole feature-head source of truth after, never reconstructed; branch itself created at build (step 4) pr: # set when the PR is opened blocked_by: # free text; set only when status: blocked reconciled: false # set true after the just-in-time reconcile pass -claimed_at: # UTC ISO-8601 claim lease (YYYY-MM-DDTHH:MM:SSZ); stamped by claim, reconcile, and resume-halted; cleared on leaving in-progress --- ``` @@ -222,7 +218,6 @@ change, never in the frozen artifact. - `## Open questions` — unknowns to resolve during reconcile/design. - `## Reconcile log` — dated entries appended by the implementer's reconcile pass. - `## Closeout notes` — final-only, **optional**, and the **final authored body section** of an archived record. Written solely by the `finalize.closeout` operation from its structured request (`verification_outcomes` / `late_findings`, rendered as `### Verification` / `### Late findings` bullet lists); never hand-edited, copied to a stacked descendant, or a link-bearing artifact. The closed-out `results:` file stays a frozen build record — the freeze rule above is unchanged. -- `## Reclaim log` — dated entries appended by the `change.reclaim` operation when an expired-lease, no-branch claim self-heals back to `proposed`. - `## Auto-groom blocked` — dated abstain record written by `change.groom` `outcome: abstain`; contents and lifecycle (including removal by `outcome: re-enable`) are defined by the *Autonomous grooming* shared definition below. - `## Finalize blocked` — dated record appended by `docket-finalize-change` when a gate failure leaves a change needing a human; presence drives the board's `finalize blocked — needs you` cell. It is a visible note that never stops finalize selection or merge, so the next finalize run retries the change. The clearing rule is owned by `docket-finalize-change` and not restated here. - `## Run halted` — written by the `change.halt` operation when an autonomous run stops needing a human (the `halted` disposition); the heading is **bare**, never dated — the reader is a whole-line match, so the date sits inside the body. **Marker-section state**, in the same family as `## Auto-groom blocked` and `## Finalize blocked`: while the section is present the `run.verify` operation reports `run-halted`, which is what makes a `halted` disposition verifiable in git rather than a claim in a completion report. It is removed by the `change.resume-halted` operation, and by the claim when a halted change is claimed again. @@ -262,8 +257,7 @@ An `Accepted` ADR is immutable except its `status:` line; a non-reversing contex │ │ │ (archive/) │ ├──results attached + change.complete (results-artifact; also from proposed)──▶ done │ │ └──into stack parent──▶ stacked-merged ──root lands──▶ done - │ ├──blocker──▶ blocked ──clears──▶ in-progress - │ └──lease expired, no branch (reclaim)──▶ proposed + │ └──blocker──▶ blocked ──clears──▶ in-progress ├──── deferred (shelved; revive → proposed) └──── killed (obsolete — from proposed, or from in-progress via reconcile; → archive/) ────▶ ``` @@ -281,8 +275,6 @@ An `Accepted` ADR is immutable except its `status:` line; a non-reversing contex **Rules.** `active/` holds every non-final status; `archive/` holds the two final outcomes. `stacked-merged` is non-final for that reason: merged into its stack parent, not the integration branch, so it stays in `active/` until the stack close-out promotes it when the stack root lands. The single physical move (`active/ → archive/`, date-prefixed) happens once on the final transition and is **idempotent**: re-pull, re-read `status` on the metadata branch, no-op if already final. `deferred` is entered only from `proposed` (add `## Why deferred`; a change being built is blocked or killed instead) and revived to `proposed`; clear a blocker with `change.unblock` (`blocked` → `in-progress`, clearing `blocked_by`) and revive with `change.revive` (`deferred` → `proposed`) — typed operations, no file move. A change whose `depends_on` is unsatisfied is *implicitly* blocked — the selector skips it and the board shows it **waiting on #N**. A dependency is **satisfied when it reaches `done`**; if `#N` is still `implemented` the board flags **waiting on #N — needs your merge**, distinct from **waiting on #N — not yet built**. Reserve explicit `blocked` for external blockers the system can't infer. -**Reclaim edge (`in-progress → proposed`).** An `in-progress` change whose claim lease (`claimed_at:` + `reclaim.lease_ttl`) has expired AND that has no feature branch is flipped back to `proposed` by the reclaim operation (opt-in via `reclaim.auto`, or an explicit `change.reclaim`), clearing `branch:`/`claimed_at:` and resetting `reconciled: false` so a fresh reconcile runs on re-claim. The has-branch case is never auto-reclaimed (it may carry real work) — it stays flagged for a human. - **Board refresh on status writes.** Every board-authoritative typed mutation re-renders `BOARD.md` **atomically inside its own metadata commit** — the same commit that writes the change record it reflects — so there is **no separate Board pass**, and no skill hand-renders, hand-commits, or three-way-merges the board. The shared app-layer inclusion path owns the whole decision: it resolves the enabled surfaces (fail-closed), renders the `inline` surface, and writes `BOARD.md` only when it actually changed. **No surfaces value is ever passed or spelled by a skill**: the caller never resolves or forwards one — so an unresolved config can never be mistaken for a disabled board. A read-only `status` read never writes a board; a repo with `board_surfaces: []` renders and commits nothing, and a pre-existing `BOARD.md` is left untouched rather than truncated. Exceptional out-of-band board drift (a hand-edit, an interrupted legacy write) is surfaced by `repository.check` and repaired by the authorized `repository.repair` operation (resolve argv from the capability catalog; a human authorizes its `--yes` apply) — never a hand-render. The board is a derived view and must never trail the change files. ### Build-readiness & selection (shared definition) diff --git a/skills/docket-implement-next/SKILL.md b/skills/docket-implement-next/SKILL.md index d295618d6..4b70dc207 100644 --- a/skills/docket-implement-next/SKILL.md +++ b/skills/docket-implement-next/SKILL.md @@ -26,7 +26,7 @@ Before anything else in this skill, invoke the `docket-convention` skill via the Run the convention's **startup check** (load the convention; run the capability bootstrap; run the `repository.prepare` operation with `--repo-dir --json` as its own Bash call; validate the protocol-v1 envelope and carry its typed context values forward as literals; act on the disposition). All bookkeeping in this skill (claim, reconcile, `status`, `pr:`, `plan:`, `adrs:`, the plan and results files, build evidence) lands in the metadata worktree (`metadata_worktree_path` in the `repository.prepare` context) on the metadata branch, pushed to the metadata remote (`metadata_remote`) immediately; only the spec copy and the code land on the feature branch. -**Named invocation — no maintenance preflight.** When this run was invoked with exactly **one explicit change id** — an initial named call, an attributed retry carrying the id, or a named resume of an in-progress change — skip the implementation preflight and Step 1's status-digest certification entirely: after the `repository.prepare` operation succeeds, go **directly** to the authoritative `context.implementation` operation with `--id ` and the existing claim/resume path. The named path never runs `maintenance.preflight` or any maintenance sweep first — another change's failing closeout, cleanup, or reclaim can never halt this change before its own claim/gate; anyone who wants those maintenance outcomes runs the explicit `maintenance.preflight` or `maintenance.sweep` operation deliberately, where every problem stays visible. Every local check for the named change is kept — readiness, record revision, dependencies, effective base, claim eligibility, run context, and resume/cancellation; an `in-progress` id is served only to its own resume (Step 1). A held change (`on-hold`) is built when named. So a malformed, absent, not-ready, or improperly resumed id returns its existing typed refusal, reported with its reason exactly as a scoped-id skip is (ending `drained` when nothing else is in scope); a named request **never falls back to selecting another change**, and shared repository/configuration/transport failures keep the `halted` posture. +**Named invocation — no maintenance preflight.** When this run was invoked with exactly **one explicit change id** — an initial named call, an attributed retry carrying the id, or a named resume of an in-progress change — skip the implementation preflight and Step 1's status-digest certification entirely: after the `repository.prepare` operation succeeds, go **directly** to the authoritative `context.implementation` operation with `--id ` and the existing claim/resume path. The named path never runs `maintenance.preflight` or any maintenance sweep first — another change's failing closeout or cleanup can never halt this change before its own claim/gate; anyone who wants those maintenance outcomes runs the explicit `maintenance.preflight` or `maintenance.sweep` operation deliberately, where every problem stays visible. Every local check for the named change is kept — readiness, record revision, dependencies, effective base, claim eligibility, run context, and resume/cancellation; an `in-progress` id is served only to its own resume (Step 1). A held change (`on-hold`) is built when named. So a malformed, absent, not-ready, or improperly resumed id returns its existing typed refusal, reported with its reason exactly as a scoped-id skip is (ending `drained` when nothing else is in scope); a named request **never falls back to selecting another change**, and shared repository/configuration/transport failures keep the `halted` posture. **The named change's own merged dependencies.** Skipping the sweep never declares a dependency satisfied. When the named path's `context.implementation` read refuses `not-ready-waiting-dependency`, **read `references/edge-paths.md` now (blocking)** for the bounded closeout of the named change's own `implemented` dependencies — never any other change's. @@ -46,24 +46,24 @@ The digest is an **accelerator, not the sole channel**: the authoritative read i ### Step 2 — Claim (conflict-checked write) -Claim by transaction: the `change.claim` operation with `--id --revision ` (the exact revision from the step-1 bundle). When the dispatch prompt carried a **run context** token, pass it to the claim as --run-context : the claim validates it against the started run, records durable proof binding this dispatch to its successful claim, and the parent's keyed verdict resolves ownership from that proof; an invalid or conflicting run context is a typed refusal that writes nothing — never retried as an ungated claim. A claim without the token stays supported for ungated invocations. Also pass `--selection queue` on the selection path and `--selection named` on the named path: the run tracker counts a halt toward a loop's halt limit only for a change picked from the queue. In the **metadata working tree** the operation reloads fresh origin, re-proves the change is still `proposed`, uniquely identified, build-ready, and has a resolved effective base, then applies the landed claim (`status: in-progress` + `branch: /` + `updated:` + `claimed_at:` — the lease the `change.reclaim` operation and the maintenance sweep's reclaim key on) and updates the change record, `## Artifacts` block, and inline board **together in one metadata commit** on the metadata branch, pushed to the metadata remote. It returns the feature branch, lease classification, and a closed disposition; a wrong revision or a not-`proposed`/not-build-ready/duplicate/unresolved-base change returns `contended`/a typed refusal that **writes nothing and creates no workspace**. A lost-response retry converges by re-reading authority — an already-held matching claim returns the applied receipt or a typed `already-claimed`, a foreign claim returns `contended`; never adopt a branch or workspace as proof the claim landed. A `contended` result is the **`contended`** disposition (see *Terminal disposition*): a lost conflict-checked claim race is a normal, continue-able outcome a driver re-selects past, **never `halted`** — re-sync (re-run the `repository.prepare` operation) and re-select. No worktree yet. +Claim by transaction: the `change.claim` operation with `--id --revision ` (the exact revision from the step-1 bundle). When the dispatch prompt carried a **run context** token, pass it to the claim as --run-context : the claim validates it against the started run, records durable proof binding this dispatch to its successful claim, and the parent's keyed verdict resolves ownership from that proof; an invalid or conflicting run context is a typed refusal that writes nothing — never retried as an ungated claim. A claim without the token stays supported for ungated invocations. Also pass `--selection queue` on the selection path and `--selection named` on the named path: the run tracker counts a halt toward a loop's halt limit only for a change picked from the queue. In the **metadata working tree** the operation reloads fresh origin, re-proves the change is still `proposed`, uniquely identified, build-ready, and has a resolved effective base, then applies the landed claim (`status: in-progress` + `branch: /` + `updated:`) and updates the change record, `## Artifacts` block, and inline board **together in one metadata commit** on the metadata branch, pushed to the metadata remote. It returns the feature branch and a closed disposition; a wrong revision or a not-`proposed`/not-build-ready/duplicate/unresolved-base change returns `contended`/a typed refusal that **writes nothing and creates no workspace**. A lost-response retry converges by re-reading authority — an already-held matching claim returns the applied receipt or a typed `already-claimed`, a foreign claim returns `contended`; never adopt a branch or workspace as proof the claim landed. A `contended` result is the **`contended`** disposition (see *Terminal disposition*): a lost conflict-checked claim race is a normal, continue-able outcome a driver re-selects past, **never `halted`** — re-sync (re-run the `repository.prepare` operation) and re-select. No worktree yet. **Revision lookups.** The claim pins the pre-claim bundle's revision and `change.resume-halted` the context bundle's. Before every later write to its own record — `change.reconcile`, `change.halt`, a reconcile-kill's `change.kill`, `workspace.prepare`, the revision handed to the plan-writer, the producing-change revision handed to `docket-adr`, each `change.attach-results`, and `change.mark-implemented` — the run reads the revision from the local metadata checkout in the same shell call as the write (or immediately before the dispatch carrying it): `R=$(git -C rev-parse HEAD:)`, `` being the bundle's `change.path`, which does not move while the change is active. A receipt's `committed_revision` is the commit id, never a `--revision` value. On `contended`, re-sync once (the `repository.prepare` operation), look the revision up again, and retry the write once — except `change.reconcile`, which keeps its re-read-and-re-author rule (Step 3); a second `contended` follows the step's existing stop rule. -A claim of a `proposed` record that still carries a `## Run halted` section removes that section in the same transaction. **Resuming a halted in-progress change** — one the caller re-dispatches by id after a `run.verify` verdict of **`run-halted`** — goes through the `change.resume-halted` operation with `--id --revision --acknowledge-quiescent`, never a fresh claim: it requires the exact marked record and the explicit `--acknowledge-quiescent` acknowledgement that the prior worker is quiescent, reprobes the branch/workspace/live gate, refreshes the claim, and removes exactly the `## Run halted` marker section while preserving every other byte and checkpoint — it never resets or adopts a workspace whose writer may be live. It refuses (writing nothing) without the acknowledgement, on revision drift (`contended`), or on a live gate lock. A change that instead reached `proposed` through the `change.reclaim` operation carries no live claim, so it re-enters through the ordinary claim above. The claim and resume both render the inline board in their own transaction, so no separate Board pass runs here. Starting the resume also passes through the run tracker, which refuses a second run over one that has not verifiably stopped — **read `references/edge-paths.md` now (blocking)** for those run-tracker resume refusals and their remedies. +A claim of a `proposed` record that still carries a `## Run halted` section removes that section in the same transaction. **Resuming a halted in-progress change** — one the caller re-dispatches by id after a `run.verify` verdict of **`run-halted`** — goes through the `change.resume-halted` operation with `--id --revision --acknowledge-quiescent`, never a fresh claim: it requires the exact marked record and the explicit `--acknowledge-quiescent` acknowledgement that the prior worker is quiescent, reprobes the branch/workspace/live gate and removes exactly the `## Run halted` marker section while preserving every other byte and checkpoint — it never resets or adopts a workspace whose writer may be live. It refuses (writing nothing) without the acknowledgement, on revision drift (`contended`), or on a live gate lock. A stranded run recovers only by the caller resuming its change by id (the `run.start` operation with `implement-next --resume `), with the run tracker deciding. The claim and resume both render the inline board in their own transaction, so no separate Board pass runs here. Starting the resume also passes through the run tracker, which refuses a second run over one that has not verifiably stopped — **read `references/edge-paths.md` now (blocking)** for those run-tracker resume refusals and their remedies. > Two agents must NOT share one local clone — each needs its own. ### Step 3 — Reconcile ⭐ -Re-read the step-1 bundle's change + spec bytes against `related` + recently-archived changes, cited + recent ADRs, and CURRENT code, and decide NON-INTERACTIVELY what is true NOW (drop work done elsewhere, adjust scope, fold in new constraints). That judgment is yours; the write is a transaction. **Author** a reconcile request — structured replacement text for the owned proposal sections and still-mutable linked-spec content, the complete desired relations (`depends_on`/`stacked_on`/`related`/`adrs`/`discovered_from`) when reality requires them, and one dated `## Reconcile log` entry — and apply it with the `change.reconcile` operation with `--input ` (the request file carries `id`, the pinned `revision`, and the authored Markdown — never a shell-escaped flag). The `reconcile_log_entry` is the **section body only** — the operation writes the `### YYYY-MM-DD` heading. When nothing changed (spec, stack base, related changes, and scope all hold), send just `{id, revision, reconcile_log_entry}` with a one-line body such as "Unchanged against ``"; sections and relations go in only when reality requires a change. The transaction checks the exact revision and legal `in-progress` status, sets `reconciled: true`, refreshes the claim, rerenders backlinks/`## Artifacts` block/inline board, validates the whole repository, and commits atomically on the metadata branch, pushed to the metadata remote; unknown frontmatter, unlisted authored sections, line endings, and unrelated files stay byte-identical, and a request naming a non-owned field/section is a typed refusal that writes nothing. If fresh origin state diverges incompatibly, the operation returns `contended` and writes nothing — never a text-merge; re-read fresh context and re-author. +Re-read the step-1 bundle's change + spec bytes against `related` + recently-archived changes, cited + recent ADRs, and CURRENT code, and decide NON-INTERACTIVELY what is true NOW (drop work done elsewhere, adjust scope, fold in new constraints). That judgment is yours; the write is a transaction. **Author** a reconcile request — structured replacement text for the owned proposal sections and still-mutable linked-spec content, the complete desired relations (`depends_on`/`stacked_on`/`related`/`adrs`/`discovered_from`) when reality requires them, and one dated `## Reconcile log` entry — and apply it with the `change.reconcile` operation with `--input ` (the request file carries `id`, the pinned `revision`, and the authored Markdown — never a shell-escaped flag). The `reconcile_log_entry` is the **section body only** — the operation writes the `### YYYY-MM-DD` heading. When nothing changed (spec, stack base, related changes, and scope all hold), send just `{id, revision, reconcile_log_entry}` with a one-line body such as "Unchanged against ``"; sections and relations go in only when reality requires a change. The transaction checks the exact revision and legal `in-progress` status, sets `reconciled: true`, rerenders backlinks/`## Artifacts` block/inline board, validates the whole repository, and commits atomically on the metadata branch, pushed to the metadata remote; unknown frontmatter, unlisted authored sections, line endings, and unrelated files stay byte-identical, and a request naming a non-owned field/section is a typed refusal that writes nothing. If fresh origin state diverges incompatibly, the operation returns `contended` and writes nothing — never a text-merge; re-read fresh context and re-author. Adjacent follow-up work this pass surfaces is **noted for the final report** — nothing is minted automatically; a human captures reported work deliberately with `docket change create`, guided by the backlog verdict final consolidation attaches (Step 6.5 *Backlog match*). Two escape hatches: - Change now **OBSOLETE** → kill it via the convention's close-out (**read `../docket-convention/references/close-out.md` now — blocking**) — one atomic `change.kill` operation transaction that archives the record on `docket`, retargets the linked spec's back-link, and renders the inline board in its own metadata commit. Caller posture and the cleanup notes: **read `references/edge-paths.md` now (blocking)**. Because the `change.kill` operation renders the board atomically inside its own commit, **no separate Board pass follows** — the board already drops the killed change. Then return to Step 1. -- Design **FUNDAMENTALLY invalidated** (not just scope-adjustable) → STOP and escalate to the human — end the run with the **`halted`** disposition (see *Terminal disposition*), the driver's stop-and-surface signal — and **write that halt into git before stopping**: the `change.halt` operation with `--id --revision --input ` records a bounded authored run-halted report into a `## Run halted` section on the in-progress change in one exact-revision transaction, leaving the branch, lease, workspace, and evidence untouched (the authored Markdown travels as a request file, never a shell-escaped flag; a non-in-progress record is refused, writing nothing). The `report` is the section **body only** — the operation alone writes the `## Run halted` heading and dated `###` sub-heading, so the body starts with prose, a list, or a `###`-or-deeper subsection. A body carrying its own column-zero `## ` heading (a repeated or dated halt heading included) or an unterminated code fence is refused `invalid-input` (`invalid-section-markdown`, field `report`), writing nothing; keep heading examples inside closed code fences. This is the producer half of the section the convention defines: a `halted` disposition that exists only as a sentence in a completion report is exactly the untrusted self-report the `run.verify` operation was built to stop trusting. The same write is required for **any** hard error that ends the run `halted`, wherever it occurs. Any hard error that prevents reaching a PR is likewise `halted`. This skill cannot re-brainstorm alone; re-brainstorming is a human act handled by `superpowers:brainstorming` + `docket-new-change`. +- Design **FUNDAMENTALLY invalidated** (not just scope-adjustable) → STOP and escalate to the human — end the run with the **`halted`** disposition (see *Terminal disposition*), the driver's stop-and-surface signal — and **write that halt into git before stopping**: the `change.halt` operation with `--id --revision --input ` records a bounded authored run-halted report into a `## Run halted` section on the in-progress change in one exact-revision transaction, leaving the branch, workspace, and evidence untouched (the authored Markdown travels as a request file, never a shell-escaped flag; a non-in-progress record is refused, writing nothing). The `report` is the section **body only** — the operation alone writes the `## Run halted` heading and dated `###` sub-heading, so the body starts with prose, a list, or a `###`-or-deeper subsection. A body carrying its own column-zero `## ` heading (a repeated or dated halt heading included) or an unterminated code fence is refused `invalid-input` (`invalid-section-markdown`, field `report`), writing nothing; keep heading examples inside closed code fences. This is the producer half of the section the convention defines: a `halted` disposition that exists only as a sentence in a completion report is exactly the untrusted self-report the `run.verify` operation was built to stop trusting. The same write is required for **any** hard error that ends the run `halted`, wherever it occurs. Any hard error that prevents reaching a PR is likewise `halted`. This skill cannot re-brainstorm alone; re-brainstorming is a human act handled by `superpowers:brainstorming` + `docket-new-change`. ### Step 4 — Worktree + plan @@ -166,7 +166,7 @@ Each step below is complete only when its row holds — read from **git**, never | Step | Complete only when | |---|---| -| 2 Claim | `status: in-progress` + `branch:` + `updated:` + `claimed_at:` committed on the metadata branch **and landed** (an `applied` claim receipt). | +| 2 Claim | `status: in-progress` + `branch:` + `updated:` committed on the metadata branch **and landed** (an `applied` claim receipt). | | 3 Reconcile | `reconciled: true` and a dated `## Reconcile log` entry landed on the metadata branch — or, on the kill path, the change archived. | | 4 Worktree + plan | the spec copy committed as the first commit on `/`, then `plan:` and the plan file with its backlink landed on the metadata branch, the feature HEAD unchanged by planning. | | 5 Build | the executed plan committed on `/`, with a build-evidence record at `result: green` (or `skipped` / `build-gate-off` under `build.gate: off`) whose `head_sha` **equals branch HEAD**. | @@ -215,7 +215,7 @@ A change is drafted against a *snapshot* of the codebase, ADRs, and other in-fli ### The field-write rule -Every change-file field write in this run (claim's `status:`/`branch:`, reconcile, `plan:`, `adrs:`, `results:`, `pr:` + `status: implemented`) lands through a **`change.*` / attach / mark-implemented transaction** in the metadata worktree on the metadata branch — never a hand-edit, never in the feature worktree — which reloads fresh origin, checks the exact record revision, and commits and pushes atomically. The skill **never invokes a facade renderer and never hand-writes a derived view**: for any **link-bearing field** (`spec:`/`plan:`/`adrs:`/`pr:`/`results:`), the transaction regenerates the `## Artifacts` block and inline board in the same commit; `claimed_at` is stamped only by the claim, reconcile, and resume-halted transactions. The halt-path authored sections also land through transactions, never a hand-edit: the `change.halt` operation writes the `## Run halted` section (Step 3) and the `change.resume-halted` operation removes it on resume (Step 2), each an exact-revision transaction that renders the inline board in its own commit. The skill authors the halt report as a request file and hands it across; it never edits the section bytes itself. **Stage by explicit path** — that tree is shared, so a bare `add -A` commits another agent's staged work under your message. +Every change-file field write in this run (claim's `status:`/`branch:`, reconcile, `plan:`, `adrs:`, `results:`, `pr:` + `status: implemented`) lands through a **`change.*` / attach / mark-implemented transaction** in the metadata worktree on the metadata branch — never a hand-edit, never in the feature worktree — which reloads fresh origin, checks the exact record revision, and commits and pushes atomically. The skill **never invokes a facade renderer and never hand-writes a derived view**: for any **link-bearing field** (`spec:`/`plan:`/`adrs:`/`pr:`/`results:`), the transaction regenerates the `## Artifacts` block and inline board in the same commit. The halt-path authored sections also land through transactions, never a hand-edit: the `change.halt` operation writes the `## Run halted` section (Step 3) and the `change.resume-halted` operation removes it on resume (Step 2), each an exact-revision transaction that renders the inline board in its own commit. The skill authors the halt report as a request file and hands it across; it never edits the section bytes itself. **Stage by explicit path** — that tree is shared, so a bare `add -A` commits another agent's staged work under your message. ### Feature branch invariants diff --git a/skills/docket-implement-next/references/edge-paths.md b/skills/docket-implement-next/references/edge-paths.md index 40b85d961..9bfbafdc5 100644 --- a/skills/docket-implement-next/references/edge-paths.md +++ b/skills/docket-implement-next/references/edge-paths.md @@ -12,7 +12,7 @@ with `--json` (a write-free read) and take the named change's `unmet_dependencie For **each** id in that set — and never any other change — run one `finalize.closeout` operation with `--id ` (resolve argv from the capability catalog). The operation itself re-proves the -merged PR and applies the one verified final shape, so run no cleanup suffix and no reclaim, and +merged PR and applies the one verified final shape, so run no cleanup suffix, and never widen or recurse beyond this set. Map each envelope locally and key success on the envelope `result` `applied` or `no-op` — never on its `disposition` token: - Every closeout succeeds → re-run the `repository.prepare` operation and re-run @@ -47,15 +47,15 @@ non-interactive). `run-halted` verdict — resumes only through the `change.resume-halted` operation with `--id --revision --acknowledge-quiescent`, never a fresh claim or a hand-deleted section. The operation requires the exact marked record and the explicit acknowledgement that the prior -worker is quiescent, reprobes the branch/workspace/live gate, refreshes the claim, and removes +worker is quiescent, reprobes the branch/workspace/live gate, and removes exactly the marker section while preserving every other byte and checkpoint. It refuses (writing nothing) without the acknowledgement, on revision drift (`contended`), or on a live gate lock — it never resets or adopts a workspace whose writer may still be live. Once resumed, the change re-enters this resume path with its marker gone. -**Starting a resume over a live run.** Resuming a change starts the run tracker again too, and one -worktree carries at most one live run. When the caller starts the resume (`run.start … --resume -`), `run.start` refuses to open a second run over one that has not verifiably stopped: +**Starting a resume over a live run.** A stranded run recovers only by resuming its change by id +(the `run.start` operation with `implement-next --resume `); one worktree carries at most one +live run, so `run.start` refuses to open a second run over one that has not verifiably stopped: - Prior run still **active** (an undispatched earlier resume start counts) → refused `resume-active-run`, naming the change and run key, with the remedy: cancel the prior run via the @@ -94,6 +94,6 @@ rather than force-writing its local view. or a checkpoint boundary is reached while the ownership or gate-drive contract forbids a safe write, the results artifact cannot be captured yet. That case keeps its **existing disposition** (the halt or the continuation it was already going to take) and **reports the capture limitation through the -existing halt/continuation channel** — no fabricated results path, no stolen lease, and no delayed +existing halt/continuation channel** — no fabricated results path, no stolen claim, and no delayed gate handoff to make room for a write. The missing capture is a reported limitation, never a reason to force a workspace, a commit, or a HEAD move. diff --git a/skills/docket-status/SKILL.md b/skills/docket-status/SKILL.md index 74593aa07..c70489448 100644 --- a/skills/docket-status/SKILL.md +++ b/skills/docket-status/SKILL.md @@ -22,28 +22,27 @@ Invoke the `docket-convention` skill via the Skill tool first — unless already ## Mode choice -- **The user only wants to *see* the backlog** (no explicit refresh requested, nothing merged recently that you know of) ⇒ run the write-free read alone: the `status` operation (resolve argv from the capability catalog) with `--json`. It never merges, archives, reclaims, or renders a board. -- Implementation scope (`--scope implementation`) is the startup-preflight scope: current merged-work recovery plus reclaim gating, with independent historical cleanup retries deferred and counted in `deferred_historical_cleanups`. It is owned by the `maintenance.preflight` operation, which `docket-implement-next` runs inline at its Step 0 on its selection path (no id or an id set) — not a mode of this skill. This skill's two modes are the see-only read and the explicit `--scope full` refresh/cleanup. -- **An explicit refresh/cleanup request** — or a post-merge cleanup after a PR merged via the GitHub button ⇒ run the `maintenance.sweep` operation with `--scope full --json` first (merge sweep + historical cleanup retries + eligible reclaims + integration sync), then read the refreshed state with the `status` operation and `--json`. +- **The user only wants to *see* the backlog** (no explicit refresh requested, nothing merged recently that you know of) ⇒ run the write-free read alone: the `status` operation (resolve argv from the capability catalog) with `--json`. It never merges, archives, or renders a board. +- Implementation scope (`--scope implementation`) is the startup-preflight scope: current merged-work recovery, with independent historical cleanup retries deferred and counted in `deferred_historical_cleanups`. It is owned by the `maintenance.preflight` operation, which `docket-implement-next` runs inline at its Step 0 on its selection path (no id or an id set) — not a mode of this skill. This skill's two modes are the see-only read and the explicit `--scope full` refresh/cleanup. +- **An explicit refresh/cleanup request** — or a post-merge cleanup after a PR merged via the GitHub button ⇒ run the `maintenance.sweep` operation with `--scope full --json` first (merge sweep + historical cleanup retries + integration sync), then read the refreshed state with the `status` operation and `--json`. ## Maintenance sweep — the merged-PR recovery mutation (only when asked) The **read is separate from the mutation.** The human `status` read stays read-only: it -reports the backlog and never merges, archives, reclaims, or cleans up. When the caller explicitly +reports the backlog and never merges, archives, or cleans up. When the caller explicitly asks to refresh or clean up — a post-merge cleanup, an out-of-band merge to recover — run the `maintenance.sweep` operation (resolve argv from the capability catalog, scope per *Mode choice*) **before** the read, then read the refreshed state. Both maintenance-sweep scopes (full and implementation) run the `repository.sync-integration` operation once as their end-of-run suffix; status itself stays read-only and relies on maintenance's embedded sync when it requests a sweep, and it must not invoke a duplicate `repository.sync-integration`. The `maintenance.sweep` operation pins an initial inventory, walks it in deterministic order, and reloads fresh authority before **every** mutation. It closes out each `implemented` change whose PR merged -(stacked children before ancestors, then the root carrying its descendants), retries pending -backlink-repair and cleanup suffixes, and attempts an eligible reclaim only when `reclaim.auto` is -true. It emits one structured entry per item with a closed disposition — `applied` | `noop` | +(stacked children before ancestors, then the root carrying its descendants), and retries pending +backlink-repair and cleanup suffixes. It emits one structured entry per item with a closed disposition — `applied` | `noop` | `contended` | `blocked` | `unknown` | `failed` | `skipped`, each with its stable reason — never a collapsed boolean. It never merges an open PR, never overrides approval, never retargets an unauthorized child, and never edits authored results; a destructive suffix never runs after an `unknown` prerequisite, and one item's failure never stops the independent items. Surface the per-item report; act only on the `blocked`/`failed`/`unknown` entries a human must see. -`--scope` takes a fixed set of allowed values. `full` — the default when omitted — is the whole worklist, including cleanup retries for every `done`/`stacked-merged` record — which also repoint, unpreviewed, every merged PR description whose backlink still names an `active/` path (the `repository.repair` operation with `--pr-backlinks` previews that repair). `implementation` is the implementation-startup preflight: it still schedules every current merged-implemented closeout, the cleanup suffix such a closeout carries in the same invocation, and the `reclaim.auto`-gated reclaims, but it does not enqueue an independent cleanup for a record that was already final at the pinned inventory. Those are reported as a deferred COUNT — a population deliberately not probed, never evidence anything is dirty or blocked; explicit full maintenance owns those retries, and a failed or interrupted suffix stays recoverable through `--scope full` or the targeted finalize cleanup. +`--scope` takes a fixed set of allowed values. `full` — the default when omitted — is the whole worklist, including cleanup retries for every `done`/`stacked-merged` record — which also repoint, unpreviewed, every merged PR description whose backlink still names an `active/` path (the `repository.repair` operation with `--pr-backlinks` previews that repair). `implementation` is the implementation-startup preflight: it still schedules every current merged-implemented closeout and the cleanup suffix such a closeout carries in the same invocation, but it does not enqueue an independent cleanup for a record that was already final at the pinned inventory. Those are reported as a deferred COUNT — a population deliberately not probed, never evidence anything is dirty or blocked; explicit full maintenance owns those retries, and a failed or interrupted suffix stays recoverable through `--scope full` or the targeted finalize cleanup. ## Run the pass @@ -68,7 +67,7 @@ Starting the sweep command is not finishing it. If the shell tool's foreground w Only the sweep's actual terminal protocol-v1 envelope completes the command. Validate it and every entry: `protocol_version` `1`, `operation` `maintenance.sweep`, a `scope` equal to the one you requested, and each entry's closed disposition. Retain the original structured output — a harness result handle or a task-local output artifact — and extract the compact summary plus any problem entries in one read/parse rather than reopening the full output repeatedly; stdout is the JSON document, and any progress diagnostics belong on a separate channel. Only after that terminal validation run the post-sweep read: the `status` operation (resolve argv from the capability catalog) with `--json`. A read taken after a failed or unvalidated sweep is diagnostic only — label it as diagnostic; it can never authorize selection. -The envelope's top-level `applied` means some work applied, never that every item succeeded. A `blocked`, `failed`, or `unknown` entry — or a `contended` entry on work this preflight required — is a failed preflight even under an `applied` envelope: surface it per *Read the report* below and stop, per the *Scope of this stop* rule above. Intentional policy skips (`reclaim-auto-disabled`) and genuine no-ops remain non-errors — never collapse arbitrary `skipped` reasons into success. On cancellation, request cancellation of the exact owned task where the harness supports it, then observe its termination; never broadly kill processes, abandon a watcher, or spawn a replacement sweep while the prior one may still run. If quiescence cannot be established, halt naming the exact live task identity and preserve its output — an explicit failure here beats claiming an orphan-free exit. +The envelope's top-level `applied` means some work applied, never that every item succeeded. A `blocked`, `failed`, or `unknown` entry — or a `contended` entry on work this preflight required — is a failed preflight even under an `applied` envelope: surface it per *Read the report* below and stop, per the *Scope of this stop* rule above. Intentional policy skips and genuine no-ops remain non-errors — never collapse arbitrary `skipped` reasons into success. On cancellation, request cancellation of the exact owned task where the harness supports it, then observe its termination; never broadly kill processes, abandon a watcher, or spawn a replacement sweep while the prior one may still run. If quiescence cannot be established, halt naming the exact live task identity and preserve its output — an explicit failure here beats claiming an orphan-free exit. When a caller dispatched this skill, the final report must name: the resolved scope, the sweep's terminal envelope result, every problem entry, where the original sweep and status outputs live, and the post-sweep metadata revision (`git -C rev-parse HEAD`). The prose re-summary is never a second authority — the caller verifies against the originals. @@ -121,6 +120,6 @@ The pass reads nothing and writes nothing under `learnings/`, and nothing refres ### Findings -Flag what the pass reports (do not auto-fix unless asked). This skill never runs a checker directly — it invokes the `maintenance.sweep` / `status` operations and reads their `findings`. The `status` read reports configuration diagnostics, `parse-failed`, record validation findings (such as `change-stack-cycle`), `artifact-missing` for a spec/plan/results link on neither the metadata branch nor, for a plan or results closed before the move, the integration branch, and `branch-malformed`. Derived-view drift — the board, the ADR index, a change's `## Artifacts` block, or the backlink at the top of a spec, plan, or results file being out of date or broken — is reported by the `repository.check` operation. Each finding carries its own remedy: most clear with `repository.repair`; a broken marker, or a file linked from more than one change, needs a hand edit first. Relay the finding's remedy rather than telling the human to just run repair. A stale claim surfaces as a `maintenance.sweep` reclaim entry, applied only when `reclaim.auto` is true. A stalled dependency surfaces in the backlog digest as a change with `waiting-dependency` readiness and its `unmet_dependencies`. Each finding's code and shape are owned by the `schema` operation. +Flag what the pass reports (do not auto-fix unless asked). This skill never runs a checker directly — it invokes the `maintenance.sweep` / `status` operations and reads their `findings`. The `status` read reports configuration diagnostics, `parse-failed`, record validation findings (such as `change-stack-cycle`), `artifact-missing` for a spec/plan/results link on neither the metadata branch nor, for a plan or results closed before the move, the integration branch, and `branch-malformed`. Derived-view drift — the board, the ADR index, a change's `## Artifacts` block, or the backlink at the top of a spec, plan, or results file being out of date or broken — is reported by the `repository.check` operation. Each finding carries its own remedy: most clear with `repository.repair`; a broken marker, or a file linked from more than one change, needs a hand edit first. Relay the finding's remedy rather than telling the human to just run repair. A stalled dependency surfaces in the backlog digest as a change with `waiting-dependency` readiness and its `unmet_dependencies`. Each finding's code and shape are owned by the `schema` operation. One judgment check stays in-model, on top of the operations: `blocked_by:` re-examination (see *Judgment follow-ups* above) — warn-only, never auto-fix. From 6acaa907b59f60b205e78f5d28dfcc55d41a2b85 Mon Sep 17 00:00:00 2001 From: Daniel Hanold Date: Thu, 22 Oct 2026 07:41:51 -0400 Subject: [PATCH 6/7] refactor: make reclaim.lease_ttl and reclaim.auto obsolete tombstones --- .docket.example.yml | 14 ---- internal/app/config.go | 2 - internal/app/finalize_context.go | 22 +++--- ...ository_set_visibility_integration_test.go | 14 ++-- internal/assets/embedded/manifest.json | 6 +- .../assets/embedded/tree/.docket.example.yml | 14 ---- internal/config/capability_test.go | 8 +- internal/config/config.go | 6 -- internal/config/decode.go | 11 +++ internal/config/decode_test.go | 73 +++++++++++++++++-- internal/config/defaults.go | 4 - internal/config/defaults_test.go | 2 - internal/config/fixtures_test.go | 49 ++++++++++--- internal/config/resolve.go | 2 - internal/config/resolve_test.go | 38 +++++----- internal/config/schema.go | 14 ++-- internal/config/schema_test.go | 2 - internal/config/setting_paths_test.go | 3 +- internal/domain/entities.go | 1 - internal/domain/entities_test.go | 10 +-- internal/repository/build.go | 1 - internal/repository/build_test.go | 7 +- .../repository/transaction/loader_test.go | 3 +- testdata/repositories/configs/PROVENANCE.md | 5 +- 24 files changed, 178 insertions(+), 133 deletions(-) diff --git a/.docket.example.yml b/.docket.example.yml index 7030f29a4..edbcdf3e6 100644 --- a/.docket.example.yml +++ b/.docket.example.yml @@ -156,20 +156,6 @@ review: max_fix_tasks: 10 -# ═══ reclaim — releasing abandoned claims ═════════════════════════════════════════════════ - -reclaim: - # lease_ttl — hours a claim on an in-progress change lasts. A change whose lease has expired, - # with no feature branch and no workspace, is eligible to return to the backlog. - # scope: any layer - lease_ttl: 72 - - # auto — false (default): `docket maintenance sweep` reports an eligible change as skipped - # (reclaim-auto-disabled). true: the sweep reclaims it. - # scope: any layer - auto: false - - # ═══ leak_check — keeping docket out of a private repository's shared surfaces ═══════════ leak_check: diff --git a/internal/app/config.go b/internal/app/config.go index e8aa34b46..eb86e368c 100644 --- a/internal/app/config.go +++ b/internal/app/config.go @@ -252,8 +252,6 @@ func effectiveLines(eff *config.Effective) []effectiveLine { leafLine("run.max_attempts", strconv.Itoa(eff.Run.MaxAttempts.Value), eff.Run.MaxAttempts.Provenance), leafLine("run.max_consecutive_halts", strconv.Itoa(eff.Run.MaxConsecutiveHalts.Value), eff.Run.MaxConsecutiveHalts.Provenance), leafLine("learnings.enabled", strconv.FormatBool(eff.Learnings.Enabled.Value), eff.Learnings.Enabled.Provenance), - leafLine("reclaim.lease_ttl", strconv.Itoa(eff.Reclaim.LeaseTTL.Value), eff.Reclaim.LeaseTTL.Provenance), - leafLine("reclaim.auto", strconv.FormatBool(eff.Reclaim.Auto.Value), eff.Reclaim.Auto.Provenance), leafLine("leak_check.match_word", strconv.FormatBool(eff.LeakCheck.MatchWord.Value), eff.LeakCheck.MatchWord.Provenance), leafLine("open.artifacts", textValue(eff.Open.Artifacts.Value), eff.Open.Artifacts.Provenance), leafLine("review.min_fix_severity", textValue(eff.Review.MinFixSeverity.Value), eff.Review.MinFixSeverity.Provenance), diff --git a/internal/app/finalize_context.go b/internal/app/finalize_context.go index 0cc824c67..bab89f210 100644 --- a/internal/app/finalize_context.go +++ b/internal/app/finalize_context.go @@ -267,7 +267,7 @@ type FinalizeCandidateReport struct { } // FinalizePolicy is the repository-wide finalize configuration the bundle -// reports: refs and the resolved gate/suite/approval/reclaim policy. Go v1 +// reports: refs and the resolved gate/suite/approval policy. Go v1 // supports one metadata topology, so no mode-shaped field appears (change 0363). type FinalizePolicy struct { IntegrationBranch string `json:"integration_branch"` @@ -276,11 +276,9 @@ type FinalizePolicy struct { // 0374): finalize reads finalize.gate/finalize.test_command, independent of // the build role's pair. The generic gate/test_command keys are retired // (spec Touch point 3). - FinalizeGate string `json:"finalize_gate"` - FinalizeTestCommand string `json:"finalize_test_command,omitempty"` - RequirePRApproval bool `json:"require_pr_approval"` - ReclaimAuto bool `json:"reclaim_auto"` - ReclaimLeaseTTLHours int `json:"reclaim_lease_ttl_hours"` + FinalizeGate string `json:"finalize_gate"` + FinalizeTestCommand string `json:"finalize_test_command,omitempty"` + RequirePRApproval bool `json:"require_pr_approval"` } // FinalizeContextResult is the protocol-v1 document `context finalize` returns. @@ -579,13 +577,11 @@ func probeFinalizeFacts(ctx context.Context, prober FinalizePRProber, repoDir st func finalizePolicy(pin StatusPin) FinalizePolicy { eff := pin.Config.Effective return FinalizePolicy{ - IntegrationBranch: pin.IntegrationBranch, - Remote: string(originRemote), - FinalizeGate: eff.Finalize.Gate.Value, - FinalizeTestCommand: eff.Finalize.TestCommand.Value, - RequirePRApproval: eff.Finalize.RequirePRApproval.Value, - ReclaimAuto: eff.Reclaim.Auto.Value, - ReclaimLeaseTTLHours: eff.Reclaim.LeaseTTL.Value, + IntegrationBranch: pin.IntegrationBranch, + Remote: string(originRemote), + FinalizeGate: eff.Finalize.Gate.Value, + FinalizeTestCommand: eff.Finalize.TestCommand.Value, + RequirePRApproval: eff.Finalize.RequirePRApproval.Value, } } diff --git a/internal/app/repository_set_visibility_integration_test.go b/internal/app/repository_set_visibility_integration_test.go index a68b07fb9..d68f24c4e 100644 --- a/internal/app/repository_set_visibility_integration_test.go +++ b/internal/app/repository_set_visibility_integration_test.go @@ -251,7 +251,7 @@ const privateSwitchYML = defaultSetupYML + "agent_harnesses: [codex]\nbuild:\n // privateSwitchLocalYML is the clone-local configuration whose leaves must // survive the fold. -const privateSwitchLocalYML = "reclaim:\n auto: true\n" +const privateSwitchLocalYML = "finalize:\n require_pr_approval: true\n" // newPrivateSwitchRepo is a shared repository right after init whose init // output is committed and pushed (so the working tree is clean), with @@ -395,8 +395,8 @@ func TestIntegrationRepoVisibilityPrivateHappyPath(t *testing.T) { if v := snap.Effective.Build.TestCommand.Value; v != "make" { t.Errorf("build.test_command = %q, want make", v) } - if !snap.Effective.Reclaim.Auto.Value { - t.Errorf("reclaim.auto = false, want the local key carried:\n%s", folded) + if !snap.Effective.Finalize.RequirePRApproval.Value { + t.Errorf("finalize.require_pr_approval = false, want the local key carried:\n%s", folded) } if saved, err := os.ReadFile(filepath.Join(gitDir, "dckt", layout.PrivateLocalKeysFile)); err != nil || string(saved) != privateSwitchLocalYML { t.Errorf("local-keys.yml = %q (%v), want the old local file verbatim", saved, err) @@ -1282,12 +1282,12 @@ func TestIntegrationRepoVisibilitySharedRestoresLocalKeys(t *testing.T) { requireSwitchApplied(t, r.switchVisibility(t, SetVisibilityOptions{Target: "shared"}), "shared") local := mustReadFile(t, filepath.Join(r.invocation, localConfigRel)) - vals, err := reposetup.ConfigLeafValues(local, []string{"reclaim.auto", "visibility"}) + vals, err := reposetup.ConfigLeafValues(local, []string{"finalize.require_pr_approval", "visibility"}) if err != nil { t.Fatal(err) } - if vals["reclaim.auto"] != "true" { - t.Errorf(".docket.local.yml = %q, want reclaim.auto: true restored", local) + if vals["finalize.require_pr_approval"] != "true" { + t.Errorf(".docket.local.yml = %q, want finalize.require_pr_approval: true restored", local) } if _, ok := vals["visibility"]; ok { t.Errorf(".docket.local.yml = %q, want no visibility", local) @@ -1296,7 +1296,7 @@ func TestIntegrationRepoVisibilitySharedRestoresLocalKeys(t *testing.T) { string(mustReadFile(t, filepath.Join(r.invocation, ".docket.yml"))), runGit(t, r.invocation, "show", "HEAD:.docket.yml"), } { - if strings.Contains(yml, "reclaim") { + if strings.Contains(yml, "require_pr_approval") { t.Errorf(".docket.yml carries the clone-local key:\n%s", yml) } } diff --git a/internal/assets/embedded/manifest.json b/internal/assets/embedded/manifest.json index 4e575f17f..8356f038d 100644 --- a/internal/assets/embedded/manifest.json +++ b/internal/assets/embedded/manifest.json @@ -1,14 +1,14 @@ { "format_version": 1, "asset_protocol": 1, - "asset_set_id": "sha256:1e65c5a2c1efe6eaa89608a5f6390ba12e92ff1474c44cadb16a9236220ee4f1", + "asset_set_id": "sha256:c16389a50b055ae2272bcd529789e2c72535d72bcfc8b89d0d03862233d37ed3", "entries": [ { "path": ".docket.example.yml", "role": "config-schema", "mode": 420, - "size": 22191, - "sha256": "3ebda2ca57f6d67d526e8b5086f2370b9c61a3267ee2e1ac7e8fff8ccfa6355f" + "size": 21573, + "sha256": "b9c4126443fbd3fff300def014b4cf0204e972bad0e33d4e7d32ca14ca99e824" }, { "path": "agents/docket-adr.md", diff --git a/internal/assets/embedded/tree/.docket.example.yml b/internal/assets/embedded/tree/.docket.example.yml index 7030f29a4..edbcdf3e6 100644 --- a/internal/assets/embedded/tree/.docket.example.yml +++ b/internal/assets/embedded/tree/.docket.example.yml @@ -156,20 +156,6 @@ review: max_fix_tasks: 10 -# ═══ reclaim — releasing abandoned claims ═════════════════════════════════════════════════ - -reclaim: - # lease_ttl — hours a claim on an in-progress change lasts. A change whose lease has expired, - # with no feature branch and no workspace, is eligible to return to the backlog. - # scope: any layer - lease_ttl: 72 - - # auto — false (default): `docket maintenance sweep` reports an eligible change as skipped - # (reclaim-auto-disabled). true: the sweep reclaims it. - # scope: any layer - auto: false - - # ═══ leak_check — keeping docket out of a private repository's shared surfaces ═══════════ leak_check: diff --git a/internal/config/capability_test.go b/internal/config/capability_test.go index 2242fe8da..354d33ab0 100644 --- a/internal/config/capability_test.go +++ b/internal/config/capability_test.go @@ -128,10 +128,14 @@ func TestClassifyMatrix(t *testing.T) { want: []capWant{{"learnings.cap", Inert, false, false, LayerRepository}}, }, - // Rows 13-14 — reclaim is supported. + // Rows 13-14 — reclaim is an obsolete tombstone: inactive, never blocks. { - name: "reclaim classifies to nothing", + name: "reclaim leaves are obsolete", sources: []Source{srcR("reclaim:\n lease_ttl: 12\n auto: true\n")}, + want: []capWant{ + {"reclaim.auto", Obsolete, false, false, LayerRepository}, + {"reclaim.lease_ttl", Obsolete, false, false, LayerRepository}, + }, }, // Row 15 — build.checkpoint. diff --git a/internal/config/config.go b/internal/config/config.go index 0af3f74a2..c61c5b63a 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -128,7 +128,6 @@ type Effective struct { Build Build `json:"build"` Run Run `json:"run"` Learnings Learnings `json:"learnings"` - Reclaim Reclaim `json:"reclaim"` LeakCheck LeakCheck `json:"leak_check"` Open Open `json:"open"` Review Review `json:"review"` @@ -188,11 +187,6 @@ type Learnings struct { Enabled Value[bool] `json:"enabled"` } -type Reclaim struct { - LeaseTTL Value[int] `json:"lease_ttl"` // hours - Auto Value[bool] `json:"auto"` -} - type LeakCheck struct { MatchWord Value[bool] `json:"match_word"` } diff --git a/internal/config/decode.go b/internal/config/decode.go index a46717c7d..c54cdfe27 100644 --- a/internal/config/decode.go +++ b/internal/config/decode.go @@ -177,6 +177,17 @@ func (d *layerDecoder) decodeLeaf(path string, spec *pathSpec, key, val *yaml.No diag.Remedy = "remove finalize.skip_results_only_delta from " + d.src.Name d.diags = append(d.diags, diag) return + case "reclaim.lease_ttl", "reclaim.auto": + // Obsolete in EVERY layer: docket no longer returns a stale claim to the + // backlog, so neither the lease length nor the automatic return selects + // anything. A malformed value already failed its type check above. + diag := leafDiag(d.src, path, CodeObsoleteSetting, key, + "docket no longer returns claimed changes to the backlog; it is ignored") + diag.Severity = SeverityWarning + diag.Classification = Obsolete + diag.Remedy = "remove " + spec.path + " from " + d.src.Name + d.diags = append(d.diags, diag) + return case "board_surfaces": value = d.keepKnownSurfaces(path, val, value.([]string)) case "board.section_order": diff --git a/internal/config/decode_test.go b/internal/config/decode_test.go index f6c92135c..516b0cf47 100644 --- a/internal/config/decode_test.go +++ b/internal/config/decode_test.go @@ -86,9 +86,9 @@ func decodeAcceptanceCases() []decodeCase { block: "learnings:\n cap: 42\n", flow: "learnings: {cap: 42}\n", value: 42}, {row: "reclaim.lease_ttl", path: "reclaim.lease_ttl", - block: "reclaim:\n lease_ttl: 24\n", flow: "reclaim: {lease_ttl: 24}\n", value: 24}, + block: "reclaim:\n lease_ttl: 24\n", flow: "reclaim: {lease_ttl: 24}\n", obsolete: true}, {row: "reclaim.auto", path: "reclaim.auto", - block: "reclaim:\n auto: true\n", flow: "reclaim: {auto: true}\n", value: true}, + block: "reclaim:\n auto: true\n", flow: "reclaim: {auto: true}\n", obsolete: true}, {row: "leak_check.match_word", path: "leak_check.match_word", block: "leak_check:\n match_word: false\n", flow: "leak_check: {match_word: false}\n", value: false}, {row: "open.artifacts", path: "open.artifacts", @@ -472,6 +472,69 @@ func TestSkipResultsOnlyDeltaIsObsoleteTombstone(t *testing.T) { } } +// TestReclaimKeysAreObsoleteTombstones: reclaim.lease_ttl and reclaim.auto +// configured returning stale claims to the backlog, which docket no longer +// does, so in every layer each is one obsolete-setting warning naming its +// removal, never a resolved value, and never a mutation blocker. A malformed +// value still fails its type check first, exactly as before. +func TestReclaimKeysAreObsoleteTombstones(t *testing.T) { + const msg = "docket no longer returns claimed changes to the backlog; it is ignored" + for _, tc := range []struct { + path string + block, flow string + }{ + {"reclaim.lease_ttl", "reclaim:\n lease_ttl: 24\n", "reclaim: {lease_ttl: 24}\n"}, + {"reclaim.auto", "reclaim:\n auto: true\n", "reclaim: {auto: true}\n"}, + } { + path := tc.path + for _, src := range []Source{ + srcR(tc.block), srcR(tc.flow), + srcL(tc.block), srcL(tc.flow), + srcG(tc.block), srcG(tc.flow), + } { + t.Run(path+"/"+string(src.Layer), func(t *testing.T) { + res := mustResolve(t, []Source{src}, mainCtx) + if _, ok := res.declared[path]; ok { + t.Fatalf("%s resolved to a honored declaration; it must be excluded", path) + } + obs := diagsWithCode(res, CodeObsoleteSetting) + if len(obs) != 1 || obs[0].Path != path { + t.Fatalf("want exactly one obsolete-setting diagnostic on %s, got %v", path, diagSummary(res)) + } + if obs[0].Severity != SeverityWarning || obs[0].Classification != Obsolete { + t.Errorf("diagnostic = %s/%s, want warning/obsolete", obs[0].Severity, obs[0].Classification) + } + if !strings.Contains(obs[0].Message, msg) { + t.Errorf("message = %q, want it to contain %q", obs[0].Message, msg) + } + if want := "remove " + path + " from " + src.Name; obs[0].Remedy != want { + t.Errorf("remedy = %q, want %q", obs[0].Remedy, want) + } + for _, code := range []string{CodeDeferredSetting, CodeDeferredCapRequested, CodeSharedSettingIgnored} { + if got := diagsWithCode(res, code); len(got) != 0 { + t.Errorf("unexpected %s diagnostic: %v", code, diagSummary(res)) + } + } + snap := mustSnapshot(t, src) + if d := PreflightMutation(snap); !d.Allowed { + t.Errorf("preflight blocked on an obsolete setting: %+v", d.Blockers) + } + for _, c := range snap.Capabilities { + if c.Path == path && (c.Classification != Obsolete || c.Active || c.MutationBlock) { + t.Errorf("capability = %+v, want inactive non-blocking obsolete", c) + } + } + }) + } + } + + // A malformed value is still a type error, not a tombstone warning. + _, diags := decodeDoc(t, "reclaim:\n auto: maybe\n") + if len(diags) != 1 || diags[0].Path != "reclaim.auto" || diags[0].Code == CodeObsoleteSetting { + t.Fatalf("want one type-error diagnostic on reclaim.auto, got %+v", diags) + } +} + // TestDecodeObsoleteScalarAutoCaptureRemedy: the pre-0127 scalar shape must // tell the reader the nested replacement, not merely refuse. func TestDecodeObsoleteScalarAutoCaptureRemedy(t *testing.T) { @@ -527,12 +590,12 @@ func TestDecodeMultipleLeaves(t *testing.T) { // TestDecodeEmptySection: a section header with nothing under it declares // nothing — neither a leaf nor a complaint. func TestDecodeEmptySection(t *testing.T) { - leaves, diags := decodeDoc(t, "finalize:\nreclaim:\n auto: true\n") + leaves, diags := decodeDoc(t, "review:\nfinalize:\n require_pr_approval: true\n") if len(diags) != 0 { t.Fatalf("unexpected diagnostics %+v", diags) } - if len(leaves) != 1 || leaves[0].path != "reclaim.auto" { - t.Fatalf("want only reclaim.auto, got %+v", leaves) + if len(leaves) != 1 || leaves[0].path != "finalize.require_pr_approval" { + t.Fatalf("want only finalize.require_pr_approval, got %+v", leaves) } } diff --git a/internal/config/defaults.go b/internal/config/defaults.go index c1301e6f6..d375b3bc2 100644 --- a/internal/config/defaults.go +++ b/internal/config/defaults.go @@ -44,10 +44,6 @@ func builtinEffective() Effective { }, Run: Run{MaxAttempts: builtinValue(2), MaxConsecutiveHalts: builtinValue(2)}, Learnings: Learnings{Enabled: builtinValue(true)}, - Reclaim: Reclaim{ - LeaseTTL: builtinValue(72), - Auto: builtinValue(false), - }, LeakCheck: LeakCheck{MatchWord: builtinValue(true)}, Open: Open{Artifacts: builtinValue("github")}, Review: Review{ diff --git a/internal/config/defaults_test.go b/internal/config/defaults_test.go index b0a643905..7307795a3 100644 --- a/internal/config/defaults_test.go +++ b/internal/config/defaults_test.go @@ -169,8 +169,6 @@ func TestBuiltinEffectiveMatchesRegistryDefaults(t *testing.T) { "run.max_attempts": eff.Run.MaxAttempts.Value, "run.max_consecutive_halts": eff.Run.MaxConsecutiveHalts.Value, "learnings.enabled": eff.Learnings.Enabled.Value, - "reclaim.lease_ttl": eff.Reclaim.LeaseTTL.Value, - "reclaim.auto": eff.Reclaim.Auto.Value, "leak_check.match_word": eff.LeakCheck.MatchWord.Value, "open.artifacts": eff.Open.Artifacts.Value, "review.min_fix_severity": eff.Review.MinFixSeverity.Value, diff --git a/internal/config/fixtures_test.go b/internal/config/fixtures_test.go index 6ea8f8f15..ac05c656a 100644 --- a/internal/config/fixtures_test.go +++ b/internal/config/fixtures_test.go @@ -180,8 +180,6 @@ func TestFixtureSparseDefaults(t *testing.T) { {"finalize.test_command", eff.Finalize.TestCommand.Explicit, eff.Finalize.TestCommand.Provenance.Layer}, {"finalize.require_pr_approval", eff.Finalize.RequirePRApproval.Explicit, eff.Finalize.RequirePRApproval.Provenance.Layer}, {"learnings.enabled", eff.Learnings.Enabled.Explicit, eff.Learnings.Enabled.Provenance.Layer}, - {"reclaim.lease_ttl", eff.Reclaim.LeaseTTL.Explicit, eff.Reclaim.LeaseTTL.Provenance.Layer}, - {"reclaim.auto", eff.Reclaim.Auto.Explicit, eff.Reclaim.Auto.Provenance.Layer}, {"leak_check.match_word", eff.LeakCheck.MatchWord.Explicit, eff.LeakCheck.MatchWord.Provenance.Layer}, {"open.artifacts", eff.Open.Artifacts.Explicit, eff.Open.Artifacts.Provenance.Layer}, {"review.min_fix_severity", eff.Review.MinFixSeverity.Explicit, eff.Review.MinFixSeverity.Provenance.Layer}, @@ -246,8 +244,6 @@ func TestFixtureExampleActivated(t *testing.T) { check("finalize.test_command", eff.Finalize.TestCommand.Explicit, eff.Finalize.TestCommand.Provenance) check("finalize.require_pr_approval", eff.Finalize.RequirePRApproval.Explicit, eff.Finalize.RequirePRApproval.Provenance) check("learnings.enabled", eff.Learnings.Enabled.Explicit, eff.Learnings.Enabled.Provenance) - check("reclaim.lease_ttl", eff.Reclaim.LeaseTTL.Explicit, eff.Reclaim.LeaseTTL.Provenance) - check("reclaim.auto", eff.Reclaim.Auto.Explicit, eff.Reclaim.Auto.Provenance) check("review.min_fix_severity", eff.Review.MinFixSeverity.Explicit, eff.Review.MinFixSeverity.Provenance) check("review.max_fix_tasks", eff.Review.MaxFixTasks.Explicit, eff.Review.MaxFixTasks.Provenance) check("gate_observation_budget", eff.GateObservation.Explicit, eff.GateObservation.Provenance) @@ -268,8 +264,8 @@ func TestFixtureExampleActivated(t *testing.T) { if eff.IntegrationBranch.Value != "main" { t.Errorf("integration_branch = %q, want the context's default branch", eff.IntegrationBranch.Value) } - if !eff.Learnings.Enabled.Value || eff.Reclaim.LeaseTTL.Value != def.Reclaim.LeaseTTL.Value || eff.Reclaim.Auto.Value { - t.Errorf("learnings/reclaim drifted from the built-ins: %+v %+v", eff.Learnings, eff.Reclaim) + if !eff.Learnings.Enabled.Value { + t.Errorf("learnings drifted from the built-ins: %+v", eff.Learnings) } if eff.Review.MinFixSeverity.Value != def.Review.MinFixSeverity.Value || eff.Review.MaxFixTasks.Value != def.Review.MaxFixTasks.Value { t.Errorf("review drifted from the built-ins: %+v", eff.Review) @@ -283,6 +279,20 @@ func TestFixtureExampleActivated(t *testing.T) { if !PreflightMutation(snap).Allowed { t.Errorf("preflight blocked a fully supported configuration: %v", blockerPaths(snap)) } + + // The sample still declares the retired reclaim.* leaves: an old config + // keeps loading, each leaf is one obsolete warning, and neither blocks. + for _, p := range []string{"reclaim.lease_ttl", "reclaim.auto"} { + var obs []Diagnostic + for _, d := range snap.Diagnostics { + if d.Path == p && d.Code == CodeObsoleteSetting { + obs = append(obs, d) + } + } + if len(obs) != 1 || obs[0].Classification != Obsolete || obs[0].Severity != SeverityWarning { + t.Errorf("%s: want exactly one obsolete warning, got %s", p, formatDiags(obs)) + } + } } // TestFixtureFourLayerCollision: every layer declares something, and per-leaf @@ -314,13 +324,28 @@ func TestFixtureFourLayerCollision(t *testing.T) { t.Errorf("learnings.cap provenance source %q, want .docket.local.yml", capEntry.Provenance.Source) } - // Nested scalar collision the machine-local layer does NOT enter: the - // repository layer beats the global one and keeps the leaf. - if eff.Reclaim.LeaseTTL.Value != 200 { - t.Errorf("reclaim.lease_ttl = %d, want 200", eff.Reclaim.LeaseTTL.Value) + // The sample's nested reclaim.lease_ttl collision (repository 200, global + // 100) is now an obsolete setting: each file's declaration is one obsolete + // warning and none resolves. Repository-beats-global for a nested scalar + // the machine-local layer does not enter is carried by + // TestPrecedencePerLeaf's "repository beats global" case. + leaseObs := map[LayerKind]int{} + for _, d := range snap.Diagnostics { + if d.Path == "reclaim.lease_ttl" { + if d.Code != CodeObsoleteSetting || d.Classification != Obsolete || d.Provenance == nil { + t.Errorf("reclaim.lease_ttl: unexpected diagnostic %s", formatDiags([]Diagnostic{d})) + continue + } + leaseObs[d.Provenance.Layer]++ + } + } + if leaseObs[LayerRepository] != 1 || leaseObs[LayerGlobal] != 1 || len(leaseObs) != 2 { + t.Errorf("reclaim.lease_ttl obsolete warnings by layer = %v, want one each from repository and global", leaseObs) } - if eff.Reclaim.LeaseTTL.Provenance.Layer != LayerRepository { - t.Errorf("reclaim.lease_ttl provenance layer %q, want %q", eff.Reclaim.LeaseTTL.Provenance.Layer, LayerRepository) + for _, c := range snap.Capabilities { + if c.Path == "reclaim.lease_ttl" && c.Active { + t.Errorf("reclaim.lease_ttl capability is active: %+v", c) + } } // List collision: lists replace whole, so the repository's list wins diff --git a/internal/config/resolve.go b/internal/config/resolve.go index d08769cc3..a9e9fdfcc 100644 --- a/internal/config/resolve.go +++ b/internal/config/resolve.go @@ -316,8 +316,6 @@ func (r *resolution) assemble(byLayer map[LayerKind]map[string]leafDecl) (Effect set(assign(&eff.Run.MaxAttempts, r.declared, "run.max_attempts")) set(assign(&eff.Run.MaxConsecutiveHalts, r.declared, "run.max_consecutive_halts")) set(assign(&eff.Learnings.Enabled, r.declared, "learnings.enabled")) - set(assign(&eff.Reclaim.LeaseTTL, r.declared, "reclaim.lease_ttl")) - set(assign(&eff.Reclaim.Auto, r.declared, "reclaim.auto")) set(assign(&eff.LeakCheck.MatchWord, r.declared, "leak_check.match_word")) set(assign(&eff.Open.Artifacts, r.declared, "open.artifacts")) set(assign(&eff.Review.MinFixSeverity, r.declared, "review.min_fix_severity")) diff --git a/internal/config/resolve_test.go b/internal/config/resolve_test.go index d62e556f6..18f11400d 100644 --- a/internal/config/resolve_test.go +++ b/internal/config/resolve_test.go @@ -88,10 +88,6 @@ func effectiveLeaf(t *testing.T, eff Effective, path string) (any, Provenance, b return eff.Run.MaxConsecutiveHalts.Value, eff.Run.MaxConsecutiveHalts.Provenance, eff.Run.MaxConsecutiveHalts.Explicit case "learnings.enabled": return eff.Learnings.Enabled.Value, eff.Learnings.Enabled.Provenance, eff.Learnings.Enabled.Explicit - case "reclaim.lease_ttl": - return eff.Reclaim.LeaseTTL.Value, eff.Reclaim.LeaseTTL.Provenance, eff.Reclaim.LeaseTTL.Explicit - case "reclaim.auto": - return eff.Reclaim.Auto.Value, eff.Reclaim.Auto.Provenance, eff.Reclaim.Auto.Explicit case "leak_check.match_word": return eff.LeakCheck.MatchWord.Value, eff.LeakCheck.MatchWord.Provenance, eff.LeakCheck.MatchWord.Explicit case "open.artifacts": @@ -111,7 +107,7 @@ func effectiveLeaf(t *testing.T, eff Effective, path string) (any, Provenance, b return nil, Provenance{}, false } -func leaseTTL(n int) string { return fmt.Sprintf("reclaim:\n lease_ttl: %d\n", n) } +func maxFixTasks(n int) string { return fmt.Sprintf("review:\n max_fix_tasks: %d\n", n) } func resolverMax(n int) string { return fmt.Sprintf("finalize:\n resolver_max_attempts: %d\n", n) @@ -354,24 +350,24 @@ func TestPrecedencePerLeaf(t *testing.T) { layer LayerKind explicit bool }{ - {"nothing declared wins the built-in default", nil, 72, LayerBuiltIn, false}, - {"global alone", []Source{srcG(leaseTTL(10))}, 10, LayerGlobal, true}, - {"repository beats global", []Source{srcG(leaseTTL(10)), srcR(leaseTTL(20))}, 20, LayerRepository, true}, - {"repository-local beats everything", []Source{srcG(leaseTTL(10)), srcR(leaseTTL(20)), srcL(leaseTTL(30))}, 30, LayerRepositoryLocal, true}, - {"repository-local beats global with no repository layer", []Source{srcG(leaseTTL(10)), srcL(leaseTTL(30))}, 30, LayerRepositoryLocal, true}, + {"nothing declared wins the built-in default", nil, 10, LayerBuiltIn, false}, + {"global alone", []Source{srcG(maxFixTasks(3))}, 3, LayerGlobal, true}, + {"repository beats global", []Source{srcG(maxFixTasks(3)), srcR(maxFixTasks(4))}, 4, LayerRepository, true}, + {"repository-local beats everything", []Source{srcG(maxFixTasks(3)), srcR(maxFixTasks(4)), srcL(maxFixTasks(5))}, 5, LayerRepositoryLocal, true}, + {"repository-local beats global with no repository layer", []Source{srcG(maxFixTasks(3)), srcL(maxFixTasks(5))}, 5, LayerRepositoryLocal, true}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { res := mustResolve(t, tc.sources, mainCtx) - got := res.effective.Reclaim.LeaseTTL + got := res.effective.Review.MaxFixTasks if got.Value != tc.want { - t.Errorf("lease_ttl = %d, want %d", got.Value, tc.want) + t.Errorf("max_fix_tasks = %d, want %d", got.Value, tc.want) } if got.Provenance.Layer != tc.layer { - t.Errorf("lease_ttl provenance layer = %q, want %q", got.Provenance.Layer, tc.layer) + t.Errorf("max_fix_tasks provenance layer = %q, want %q", got.Provenance.Layer, tc.layer) } if got.Explicit != tc.explicit { - t.Errorf("lease_ttl explicit = %v, want %v", got.Explicit, tc.explicit) + t.Errorf("max_fix_tasks explicit = %v, want %v", got.Explicit, tc.explicit) } }) } @@ -379,7 +375,7 @@ func TestPrecedencePerLeaf(t *testing.T) { // TestPrecedenceResolverMaxAttempts pins finalize.resolver_max_attempts through // the full four-layer precedence (repository-local > repository-committed > -// global > built-in), the same shape as reclaim.lease_ttl and its finalize +// global > built-in), the same shape as review.max_fix_tasks and its finalize // sibling finalize.require_pr_approval. func TestPrecedenceResolverMaxAttempts(t *testing.T) { cases := []struct { @@ -568,19 +564,19 @@ func TestPrecedenceForNonEffectiveLeaf(t *testing.T) { } func TestExplicitDefaultProvenance(t *testing.T) { - res := mustResolve(t, []Source{srcR("reclaim:\n auto: false\n")}, mainCtx) - got := res.effective.Reclaim.Auto + res := mustResolve(t, []Source{srcR("finalize:\n require_pr_approval: false\n")}, mainCtx) + got := res.effective.Finalize.RequirePRApproval if got.Value != false { - t.Errorf("reclaim.auto = %v, want false", got.Value) + t.Errorf("finalize.require_pr_approval = %v, want false", got.Value) } if !got.Explicit { - t.Error("reclaim.auto explicit = false, want true: a declaration that repeats the default is still a declaration") + t.Error("finalize.require_pr_approval explicit = false, want true: a declaration that repeats the default is still a declaration") } if got.Provenance.Layer != LayerRepository || got.Provenance.Source != ".docket.yml" { - t.Errorf("reclaim.auto provenance = %+v, want the repository layer", got.Provenance) + t.Errorf("finalize.require_pr_approval provenance = %+v, want the repository layer", got.Provenance) } if got.Provenance.Line != 2 { - t.Errorf("reclaim.auto provenance line = %d, want 2", got.Provenance.Line) + t.Errorf("finalize.require_pr_approval provenance line = %d, want 2", got.Provenance.Line) } } diff --git a/internal/config/schema.go b/internal/config/schema.go index 654116e20..738e7d577 100644 --- a/internal/config/schema.go +++ b/internal/config/schema.go @@ -296,11 +296,15 @@ func buildRegistry() []pathSpec { {path: "learnings.cap", kind: kindInt, def: 300, merge: mergeScalar, scope: scopeAny, disp: dispInert, validate: intLeaf(0)}, - // 13-14: reclaim. - {path: "reclaim.lease_ttl", kind: kindInt, def: 72, - merge: mergeScalar, scope: scopeAny, disp: dispSupported, validate: intLeaf(0)}, - {path: "reclaim.auto", kind: kindBool, def: false, - merge: mergeScalar, scope: scopeAny, disp: dispSupported, validate: boolLeaf()}, + // reclaim.lease_ttl and reclaim.auto are obsolete tombstones: they set + // when a stale claim was returned to the backlog, and docket no longer + // returns claimed changes there. Like finalize.skip_results_only_delta + // they decode in every layer (default scopeAny) and decode excludes them + // as obsolete after the type check, so they never resolve and never block. + {path: "reclaim.lease_ttl", kind: kindInt, merge: mergeScalar, + disp: dispObsolete, validate: intLeaf(0)}, + {path: "reclaim.auto", kind: kindBool, merge: mergeScalar, + disp: dispObsolete, validate: boolLeaf()}, // leak_check: whether the private-repository leak check matches the bare // word "docket". A shared repository never runs the check. diff --git a/internal/config/schema_test.go b/internal/config/schema_test.go index 03e9e8b06..1bfb2da15 100644 --- a/internal/config/schema_test.go +++ b/internal/config/schema_test.go @@ -122,8 +122,6 @@ func TestRegistryDefaults(t *testing.T) { "finalize.repair_max_attempts": 6, "learnings.enabled": true, "learnings.cap": 300, - "reclaim.lease_ttl": 72, - "reclaim.auto": false, "leak_check.match_word": true, "open.artifacts": "github", "build.checkpoint": false, diff --git a/internal/config/setting_paths_test.go b/internal/config/setting_paths_test.go index ec09f2181..43cf6ebd5 100644 --- a/internal/config/setting_paths_test.go +++ b/internal/config/setting_paths_test.go @@ -46,7 +46,6 @@ func TestSettingPathsSupportSplit(t *testing.T) { "build.gate", "build.test_command", "build.max_attempts", "run.max_attempts", "run.max_consecutive_halts", "review.min_fix_severity", "review.max_fix_tasks", - "reclaim.lease_ttl", "reclaim.auto", "leak_check.match_word", "open.artifacts", "learnings.enabled", @@ -70,7 +69,7 @@ func TestSettingPathsSupportSplit(t *testing.T) { } // One sample per unsupported disposition family. for _, p := range []string{ - "metadata_branch", "runtime.bash", "finalize.skip_results_only_delta", // obsolete + "metadata_branch", "runtime.bash", "finalize.skip_results_only_delta", "reclaim.lease_ttl", "reclaim.auto", // obsolete "learnings.cap", "delegation_observation_budget", "github_project", // inert "build.checkpoint", "terminal_publish", "auto_groom", // deferred "auto_capture.types", "dummy_mode.persona", "runners.*.shim_model", // inert companion diff --git a/internal/domain/entities.go b/internal/domain/entities.go index 9836053f3..260d5499e 100644 --- a/internal/domain/entities.go +++ b/internal/domain/entities.go @@ -464,7 +464,6 @@ func (d DerivedView) Kind() DerivedViewKind { return d.spec.Kind } type RepositoryPolicy struct { IntegrationBranch string ChangeTypes []string - ReclaimTTLHours int LearningsEnabled bool } diff --git a/internal/domain/entities_test.go b/internal/domain/entities_test.go index f2fe23820..2afff8839 100644 --- a/internal/domain/entities_test.go +++ b/internal/domain/entities_test.go @@ -418,16 +418,14 @@ func TestNewRepositoryPolicyDefensiveCopies(t *testing.T) { in := RepositoryPolicy{ IntegrationBranch: "docket", ChangeTypes: []string{"feat", "fix"}, - ReclaimTTLHours: 24, LearningsEnabled: true, } p := NewRepositoryPolicy(in) - if p.IntegrationBranch != in.IntegrationBranch || p.ReclaimTTLHours != in.ReclaimTTLHours || - p.LearningsEnabled != in.LearningsEnabled { - t.Errorf("scalar fields = %q/%d/%v; want %q/%d/%v", - p.IntegrationBranch, p.ReclaimTTLHours, p.LearningsEnabled, - in.IntegrationBranch, in.ReclaimTTLHours, in.LearningsEnabled) + if p.IntegrationBranch != in.IntegrationBranch || p.LearningsEnabled != in.LearningsEnabled { + t.Errorf("scalar fields = %q/%v; want %q/%v", + p.IntegrationBranch, p.LearningsEnabled, + in.IntegrationBranch, in.LearningsEnabled) } if !slices.Equal(p.ChangeTypes, []string{"feat", "fix"}) { t.Fatalf("ChangeTypes = %v; want [feat fix]", p.ChangeTypes) diff --git a/internal/repository/build.go b/internal/repository/build.go index 0965a52cd..7c3e18818 100644 --- a/internal/repository/build.go +++ b/internal/repository/build.go @@ -84,7 +84,6 @@ func translatePolicy(cfg config.Effective) domain.RepositoryPolicy { return domain.RepositoryPolicy{ IntegrationBranch: cfg.IntegrationBranch.Value, ChangeTypes: cfg.ChangeTypes.Value, - ReclaimTTLHours: cfg.Reclaim.LeaseTTL.Value, LearningsEnabled: cfg.Learnings.Enabled.Value, } } diff --git a/internal/repository/build_test.go b/internal/repository/build_test.go index b2da47da3..a99a123c5 100644 --- a/internal/repository/build_test.go +++ b/internal/repository/build_test.go @@ -61,13 +61,12 @@ func classifyCorpusPath(rel string) (RecordKind, RecordLocation) { } } -// effectiveConfig is a resolved configuration with the four leaves the +// effectiveConfig is a resolved configuration with the three leaves the // repository policy is allowed to carry. func effectiveConfig() config.Effective { var cfg config.Effective cfg.IntegrationBranch.Value = "main" cfg.ChangeTypes.Value = []string{"feat", "fix", "chore", "docs"} - cfg.Reclaim.LeaseTTL.Value = 24 cfg.Learnings.Enabled.Value = true return cfg } @@ -179,7 +178,6 @@ func TestBuildSnapshotTranslatesPolicy(t *testing.T) { cfg := effectiveConfig() cfg.IntegrationBranch.Value = "trunk" cfg.ChangeTypes.Value = []string{"feat", "chore"} - cfg.Reclaim.LeaseTTL.Value = 6 cfg.Learnings.Enabled.Value = false result, err := BuildSnapshot(BuildInput{Config: cfg}) @@ -193,9 +191,6 @@ func TestBuildSnapshotTranslatesPolicy(t *testing.T) { if !slices.Equal(policy.ChangeTypes, []string{"feat", "chore"}) { t.Errorf("ChangeTypes = %v", policy.ChangeTypes) } - if policy.ReclaimTTLHours != 6 { - t.Errorf("ReclaimTTLHours = %d", policy.ReclaimTTLHours) - } if policy.LearningsEnabled { t.Error("LearningsEnabled = true, want false") } diff --git a/internal/repository/transaction/loader_test.go b/internal/repository/transaction/loader_test.go index c28889f43..8860f64f6 100644 --- a/internal/repository/transaction/loader_test.go +++ b/internal/repository/transaction/loader_test.go @@ -107,13 +107,12 @@ func classifyRecordPath(rel string) (repository.RecordKind, repository.RecordLoc } } -// loaderConfig is a resolved configuration carrying the four leaves repository +// loaderConfig is a resolved configuration carrying the three leaves repository // policy may consult, matching internal/repository's own test config. func loaderConfig() config.Effective { var cfg config.Effective cfg.IntegrationBranch.Value = "main" cfg.ChangeTypes.Value = []string{"feat", "fix", "chore", "docs"} - cfg.Reclaim.LeaseTTL.Value = 24 cfg.Learnings.Enabled.Value = true return cfg } diff --git a/testdata/repositories/configs/PROVENANCE.md b/testdata/repositories/configs/PROVENANCE.md index bf9bc8ebf..462ecd618 100644 --- a/testdata/repositories/configs/PROVENANCE.md +++ b/testdata/repositories/configs/PROVENANCE.md @@ -18,9 +18,12 @@ for docket at the time. None was captured from a real repository. Each holds a ` - `sparse-defaults/` — a repository with no configuration files at all (the `repo/.gitkeep` placeholder exists only so git tracks the empty directory). - `example-activated/` — every supported setting declared explicitly at its - shipped default. + shipped default. Its `reclaim.*` leaves are now obsolete settings, kept so + old configs are proven to keep loading. - `four-layer-collision/` — the same leaves declared in the global, repository, and repository-local layers, with scalar, list, nested, and agent collisions. + Its `reclaim.*` leaves are now obsolete settings, kept so old configs are + proven to keep loading. - `mode-main-custom-paths/` — main-mode repository with an explicit integration branch and all three docket directories relocated. - `mode-docket/` — docket-mode repository leaving `integration_branch: auto`. From 2a91537828af8b999fa91e01fbc390a862deafc2 Mon Sep 17 00:00:00 2001 From: Daniel Hanold Date: Thu, 22 Oct 2026 08:01:06 -0400 Subject: [PATCH 7/7] fix: address review findings on the reclaim retirement - docket-status: the intentional-skip sentence names its remaining examples again, snapshot-retained (policy skip) and snapshot-no-work (genuine no-op); embedded assets regenerated and the budget row pinned at the exact new count (125/2956). - repoguard: TestReclaimRetiredFromSkills rejects the word "reclaim" in any case or inflection across the four skills that described it, replacing the enumerated reclaim spellings in the change_0575 rows; the claimed_at, lease, and "refreshes the claim" pins stay. - app tests: fixture comments describe the current rule (claimed_at is neither required nor written; legacy lines are ignored), the pointless done-record claimed_at strip steps are gone, and runTrackerInProgressBlob loses its vestigial claimedAt parameter. --- .../app/finalize_closeout_integration_test.go | 4 -- internal/app/finalize_closeout_test.go | 5 +- internal/app/run_verify_test.go | 5 +- .../runtracker_ownership_integration_test.go | 4 +- .../app/runtracker_verdict_helpers_test.go | 19 +------ .../runtracker_verdict_integration_test.go | 2 +- internal/assets/embedded/manifest.json | 6 +- .../tree/skills/docket-status/SKILL.md | 2 +- internal/repoguard/budgets_test.go | 2 +- internal/repoguard/prose_contracts_test.go | 55 ++++++++++++++++--- skills/docket-status/SKILL.md | 2 +- 11 files changed, 63 insertions(+), 43 deletions(-) diff --git a/internal/app/finalize_closeout_integration_test.go b/internal/app/finalize_closeout_integration_test.go index 36b827afc..595fad2b0 100644 --- a/internal/app/finalize_closeout_integration_test.go +++ b/internal/app/finalize_closeout_integration_test.go @@ -552,10 +552,6 @@ func TestIntegrationFinalizeArchiveRootCarry(t *testing.T) { f := setupCloseoutFixture(t, m) desc := closeoutRecord(6, "gadget", descStatus, "github.com/acme/widget#8", "", descPlan, "") desc = strings.Replace(desc, "stacked_on:\n", "stacked_on: 5\n", 1) - if descStatus == "done" { - // A done record keeps its branch/PR history but drops the claim stamp. - desc = strings.Replace(desc, "claimed_at: 2026-08-02T00:00:00Z\n", "", 1) - } f.repo.writerAdvance(t, f.branch, map[string]string{ recPath: desc, descPlan: artifactWithBacklink(recPath, "Gadget plan", "The gadget plan."), diff --git a/internal/app/finalize_closeout_test.go b/internal/app/finalize_closeout_test.go index a64ed042d..2e6698148 100644 --- a/internal/app/finalize_closeout_test.go +++ b/internal/app/finalize_closeout_test.go @@ -96,8 +96,9 @@ type closeoutFixture struct { func closeoutRecord(id int, slug, status, pr, specPath, planPath, resultsPath string) string { // An implemented/stacked-merged record is coherent only when it carries the - // claim facts (branch, claimed_at, reconciled) an in-progress base supplies; a - // proposed base has none, which is what the illegal-source test wants. + // claim facts (branch, reconciled) an in-progress base supplies; a proposed + // base has none, which is what the illegal-source test wants. claimed_at is + // neither required nor written; the base's legacy line is ignored. base := status coherentClaim := status == "implemented" || status == "stacked-merged" if coherentClaim { diff --git a/internal/app/run_verify_test.go b/internal/app/run_verify_test.go index c5c79ba4b..efddf7bd7 100644 --- a/internal/app/run_verify_test.go +++ b/internal/app/run_verify_test.go @@ -337,13 +337,10 @@ func TestRunVerifyHaltedPrecedesMissingResults(t *testing.T) { // rvResultsArtifactRecord renders change 3 as a results-artifact change in the // given status, optionally linking results and carrying the ## Run halted -// marker. A done record drops claimed_at, as change complete leaves it. +// marker. Any claimed_at line the base carries is a legacy line nothing reads. func rvResultsArtifactRecord(status, results string, halted bool) []byte { src := lifecycleChange(3, rvSlug, status) src = strings.Replace(src, "type: feat\n", "type: feat\ndeliverable: results-artifact\n", 1) - if status == "done" { - src = strings.Replace(src, "claimed_at: 2026-08-02T00:00:00Z\n", "", 1) - } if results != "" { src = strings.Replace(src, "results:\n", "results: '"+results+"'\n", 1) } diff --git a/internal/app/runtracker_ownership_integration_test.go b/internal/app/runtracker_ownership_integration_test.go index b0fc39c37..5b420254a 100644 --- a/internal/app/runtracker_ownership_integration_test.go +++ b/internal/app/runtracker_ownership_integration_test.go @@ -258,8 +258,8 @@ func TestIntegrationRunFenceUnrelatedChurnDoesNotMoveOwnership(t *testing.T) { } churnedCorpus := []StatusBlob{ mxBlob(3, "widget", []byte(refreshed)), - runTrackerInProgressBlob(9, "sibling", "2026-09-01T00:00:00Z"), - runTrackerInProgressBlob(10, "sibling2", "2026-09-02T00:00:00Z"), + runTrackerInProgressBlob(9, "sibling"), + runTrackerInProgressBlob(10, "sibling2"), } churnedProofs := []ClaimProof{ {RequestID: "sib-9", ChangeID: 9, RunContextHash: "OTHER"}, diff --git a/internal/app/runtracker_verdict_helpers_test.go b/internal/app/runtracker_verdict_helpers_test.go index 8531475ad..31871ac0a 100644 --- a/internal/app/runtracker_verdict_helpers_test.go +++ b/internal/app/runtracker_verdict_helpers_test.go @@ -16,27 +16,14 @@ import ( // runtracker_verdict_integration_test.go (change 0465); these fixtures, fakes and // probes stay untagged because other untagged test files still reference them. -const runTrackerDefaultClaimedAt = "2026-08-02T00:00:00Z" - -// runTrackerInProgressBlob builds an in-progress change blob whose claimed_at is the -// default stamp ("keep"), removed (""), or replaced with the given raw value. -func runTrackerInProgressBlob(id int, slug, claimedAt string) StatusBlob { - src := lifecycleChange(id, slug, "in-progress") - const def = "claimed_at: " + runTrackerDefaultClaimedAt - switch claimedAt { - case "keep": - // leave the default stamp in place - case "": - src = strings.Replace(src, def+"\n", "", 1) - default: - src = strings.Replace(src, def, "claimed_at: "+claimedAt, 1) - } +// runTrackerInProgressBlob builds an in-progress change blob. +func runTrackerInProgressBlob(id int, slug string) StatusBlob { return StatusBlob{ Kind: repository.KindChange, Location: repository.LocationActive, Path: groomPath(id, slug), Revision: miRevision, - Data: []byte(src), + Data: []byte(lifecycleChange(id, slug, "in-progress")), } } diff --git a/internal/app/runtracker_verdict_integration_test.go b/internal/app/runtracker_verdict_integration_test.go index cdf2d37e1..0e4edf3e8 100644 --- a/internal/app/runtracker_verdict_integration_test.go +++ b/internal/app/runtracker_verdict_integration_test.go @@ -1018,7 +1018,7 @@ func TestIntegrationRunVerdictVerdictResumeBindingSkipsContinuity(t *testing.T) // Mutation partner: re-introducing run/before-set inference reddens exactly this. func TestIntegrationRunVerdictVerdictOwnershipIgnoresBeforeSetAndRun(t *testing.T) { repo := newRunTrackerRepo(t) - deps := runTrackerLightDeps(t, []StatusBlob{runTrackerInProgressBlob(9, "sibling", "keep")}) + deps := runTrackerLightDeps(t, []StatusBlob{runTrackerInProgressBlob(9, "sibling")}) key := runTrackerMintStarted(t, repo, nil, 1, "ha") wdeps := WorkspaceDeps{ClaimProofs: &fakeProofScanner{proofs: []ClaimProof{ {RequestID: "sib", ChangeID: 9, RunContextHash: "OTHER"}, diff --git a/internal/assets/embedded/manifest.json b/internal/assets/embedded/manifest.json index 8356f038d..62b5dc46d 100644 --- a/internal/assets/embedded/manifest.json +++ b/internal/assets/embedded/manifest.json @@ -1,7 +1,7 @@ { "format_version": 1, "asset_protocol": 1, - "asset_set_id": "sha256:c16389a50b055ae2272bcd529789e2c72535d72bcfc8b89d0d03862233d37ed3", + "asset_set_id": "sha256:1420334f0532bba222a5815126a5540db849ce1ea8dfd6400ec5259f6857ee0d", "entries": [ { "path": ".docket.example.yml", @@ -427,8 +427,8 @@ "path": "skills/docket-status/SKILL.md", "role": "skill", "mode": 420, - "size": 19831, - "sha256": "a106ef5c91e04efb6157a73d6910a1287e95db4530494c8a55888ba35318ec03" + "size": 19874, + "sha256": "5a326131973da1925bb1a5ada12ed520ab20d998fbad396cf971026a000faf59" } ] } diff --git a/internal/assets/embedded/tree/skills/docket-status/SKILL.md b/internal/assets/embedded/tree/skills/docket-status/SKILL.md index c70489448..5073c237e 100644 --- a/internal/assets/embedded/tree/skills/docket-status/SKILL.md +++ b/internal/assets/embedded/tree/skills/docket-status/SKILL.md @@ -67,7 +67,7 @@ Starting the sweep command is not finishing it. If the shell tool's foreground w Only the sweep's actual terminal protocol-v1 envelope completes the command. Validate it and every entry: `protocol_version` `1`, `operation` `maintenance.sweep`, a `scope` equal to the one you requested, and each entry's closed disposition. Retain the original structured output — a harness result handle or a task-local output artifact — and extract the compact summary plus any problem entries in one read/parse rather than reopening the full output repeatedly; stdout is the JSON document, and any progress diagnostics belong on a separate channel. Only after that terminal validation run the post-sweep read: the `status` operation (resolve argv from the capability catalog) with `--json`. A read taken after a failed or unvalidated sweep is diagnostic only — label it as diagnostic; it can never authorize selection. -The envelope's top-level `applied` means some work applied, never that every item succeeded. A `blocked`, `failed`, or `unknown` entry — or a `contended` entry on work this preflight required — is a failed preflight even under an `applied` envelope: surface it per *Read the report* below and stop, per the *Scope of this stop* rule above. Intentional policy skips and genuine no-ops remain non-errors — never collapse arbitrary `skipped` reasons into success. On cancellation, request cancellation of the exact owned task where the harness supports it, then observe its termination; never broadly kill processes, abandon a watcher, or spawn a replacement sweep while the prior one may still run. If quiescence cannot be established, halt naming the exact live task identity and preserve its output — an explicit failure here beats claiming an orphan-free exit. +The envelope's top-level `applied` means some work applied, never that every item succeeded. A `blocked`, `failed`, or `unknown` entry — or a `contended` entry on work this preflight required — is a failed preflight even under an `applied` envelope: surface it per *Read the report* below and stop, per the *Scope of this stop* rule above. Intentional policy skips (`snapshot-retained`) and genuine no-ops (`snapshot-no-work`) remain non-errors — never collapse arbitrary `skipped` reasons into success. On cancellation, request cancellation of the exact owned task where the harness supports it, then observe its termination; never broadly kill processes, abandon a watcher, or spawn a replacement sweep while the prior one may still run. If quiescence cannot be established, halt naming the exact live task identity and preserve its output — an explicit failure here beats claiming an orphan-free exit. When a caller dispatched this skill, the final report must name: the resolved scope, the sweep's terminal envelope result, every problem entry, where the original sweep and status outputs live, and the post-sweep metadata revision (`git -C rev-parse HEAD`). The prose re-summary is never a second authority — the caller verifies against the originals. diff --git a/internal/repoguard/budgets_test.go b/internal/repoguard/budgets_test.go index e3ec6835a..730f70231 100644 --- a/internal/repoguard/budgets_test.go +++ b/internal/repoguard/budgets_test.go @@ -216,7 +216,7 @@ var skillBudgets = []skillBudget{ {"docket-implement-next/results-template.md", 70, 543}, // 0573: trivial retired (70/545 -> 70/543); 0502 rebase onto 0510: carried the backlog verdict and next action in the Known issues placeholder (68/506 -> 70/545); 0502: inline review replaces the custom review skill (68/511 -> 68/510); 0498: +whole-branch review summary line in Verification performed (64/446 -> 68/511); 0440: reader-first template — action statement + merged Known issues (see note above); 0502: drop change citations and Go v1 narration (68/510 -> 68/506) {"docket-review/SKILL.md", 127, 1054}, // 0573: trivial retired (127/1059 -> 127/1054); 0559: the results-artifact mode (114/966 -> 127/1049); 0559: Inputs and evidence sections defer to results-artifact mode (127/1049 -> 127/1059); 0531: the metadata worktree and remote come from the repository.prepare context (114/965 -> 114/966); 0502: the evidence rule keys on the payload's build.gate value; gate-off skipped records are expected (110/913 -> 114/965); 0410: +findings-return capture contract (see note above) {"docket-new-change/SKILL.md", 48, 1538}, // 0573: trivial retired; the trivial path is deleted and the brainstorm is told the artifact is always a spec (53/1636 -> 48/1538); 0560: suggest a hold; it rides change.create or change.groom (53/1598 -> 53/1636); 0559: the create request carries deliverable: results-artifact for findings-only work (57/1635 -> 53/1598); 0532: the private-repository writing rule and visibility hand-off (57/1603 -> 57/1635); 0531: the metadata worktree and remote come from the repository.prepare context (57/1596 -> 57/1603); 0502 review: omitted draft-time scalars are described exactly (57/1591 -> 57/1596); 0502: "loop" means /loop only (57/1593 -> 57/1591); 0502: one metadata layout — the docket branch and the .docket/ worktree (57/1590 -> 57/1593); 0502: terminal-publication narration and the repository auto_groom default are deleted (57/1609 -> 57/1590); 0502: invoke superpowers:brainstorming by name (57/1636 -> 57/1609); 0502: the dummy-mode pointer is deleted (59/1674 -> 57/1636); 0445: +pointer to the docket-groom-next revise path after landing (word ceiling 1700 -> 1706); 0382: draft-time scalars moved into change.create (ceiling 1706 -> 1675) - {"docket-status/SKILL.md", 125, 2954}, // 0575: reclaim and the claim lease are retired (126/2990 -> 125/2954); 0573: trivial retired (126/2993 -> 126/2990); 0560: a held change shows on hold (126/2983 -> 126/2993); 0539: derived-view drift is named by family and each finding's own remedy is relayed instead of a code list (126/2923 -> 126/2983); 0531: the metadata worktree and remote come from the repository.prepare context (126/2921 -> 126/2923); 0530: artifact-missing names where a plan or results file may live — the docket branch, or the integration branch for a record closed before the move (126/2904 -> 126/2921); 0529 review: full-scope cleanup retries also repoint stale merged-PR description backlinks; repair --pr-backlinks previews them (126/2880 -> 126/2904); 0502: one metadata layout — the docket branch and the .docket/ worktree (126/2876 -> 126/2880); 0502: findings named as the binary emits them (126/2852 -> 126/2876); 0502: deferred learnings and publication narration is deleted (127/2956 -> 126/2852); 0502: the dummy-mode pointer is deleted (129/2985 -> 127/2956); 0388: +sync-integration prose (see note above) + {"docket-status/SKILL.md", 125, 2956}, // 0575: reclaim and the claim lease are retired, the intentional-skip example names snapshot-retained and snapshot-no-work (126/2990 -> 125/2956); 0573: trivial retired (126/2993 -> 126/2990); 0560: a held change shows on hold (126/2983 -> 126/2993); 0539: derived-view drift is named by family and each finding's own remedy is relayed instead of a code list (126/2923 -> 126/2983); 0531: the metadata worktree and remote come from the repository.prepare context (126/2921 -> 126/2923); 0530: artifact-missing names where a plan or results file may live — the docket branch, or the integration branch for a record closed before the move (126/2904 -> 126/2921); 0529 review: full-scope cleanup retries also repoint stale merged-PR description backlinks; repair --pr-backlinks previews them (126/2880 -> 126/2904); 0502: one metadata layout — the docket branch and the .docket/ worktree (126/2876 -> 126/2880); 0502: findings named as the binary emits them (126/2852 -> 126/2876); 0502: deferred learnings and publication narration is deleted (127/2956 -> 126/2852); 0502: the dummy-mode pointer is deleted (129/2985 -> 127/2956); 0388: +sync-integration prose (see note above) } // wcLines counts lines the way `wc -l` does: the number of newline bytes. diff --git a/internal/repoguard/prose_contracts_test.go b/internal/repoguard/prose_contracts_test.go index 41d57cb82..dbed28e8a 100644 --- a/internal/repoguard/prose_contracts_test.go +++ b/internal/repoguard/prose_contracts_test.go @@ -532,20 +532,16 @@ var proseContracts = []proseContract{ absent: []string{"refreshed at phase boundaries"}}, // change 0575 — claim reclaim and the claimed_at lease are retired; a stranded // run recovers only by resuming the change by id, with the run tracker deciding. + // Every spelling of the word itself is TestReclaimRetiredFromSkills's job. {sentinel: "change_0575_no_reclaim", file: "skills/docket-convention/SKILL.md", present: []string{"and by the claim when a halted change is claimed again"}, - absent: []string{ - "`change.reclaim`", "## Reclaim log", "reclaim.lease_ttl", "lease_ttl:", - "claimed_at:", "self-heals", "Reclaim edge", - }}, + absent: []string{"lease_ttl:", "claimed_at:", "self-heals"}}, {sentinel: "change_0575_no_reclaim", file: "skills/docket-implement-next/SKILL.md", present: []string{"the `run.start` operation with `implement-next --resume `"}, - absent: []string{"`change.reclaim`", "claimed_at", "refreshes the claim", "lease classification"}}, + absent: []string{"claimed_at", "refreshes the claim", "lease classification"}}, {sentinel: "change_0575_no_reclaim", file: "skills/docket-implement-next/references/edge-paths.md", present: []string{"the `run.start` operation with `implement-next --resume `"}, - absent: []string{"refreshes the claim", "no reclaim"}}, - {sentinel: "change_0575_no_reclaim", file: "skills/docket-status/SKILL.md", - absent: []string{"reclaim"}}, + absent: []string{"refreshes the claim"}}, // change 0360 — Step 3 sends a minimal reconcile request when nothing // changed (the operation writes the dated heading); Step 6 writes the // evidence.record receipt's block to a file instead of a separate verify @@ -687,6 +683,49 @@ func TestGroomSkillsNeverSayTrivial(t *testing.T) { }) } +// reclaimWord matches the word "reclaim" and every inflection of it in any case +// ("`change.reclaim`", "## Reclaim log", "reclaimed", "reclaims"), so no spelling +// of the retired recovery path needs enumerating. A word that merely contains it +// ("unreclaimable") is a different word and passes. +var reclaimWord = regexp.MustCompile(`(?i)\breclaim\w*`) + +// change 0575 — claim reclaim is retired; resuming the change by id is the only +// recovery, so the skills that described reclaim may not use the word at all. +var noReclaimSkills = []string{ + "skills/docket-convention/SKILL.md", + "skills/docket-implement-next/SKILL.md", + "skills/docket-implement-next/references/edge-paths.md", + "skills/docket-status/SKILL.md", +} + +func TestReclaimRetiredFromSkills(t *testing.T) { + root := guardRoot(t) + for _, rel := range noReclaimSkills { + b, err := os.ReadFile(filepath.Join(root, filepath.FromSlash(rel))) + if err != nil { + t.Fatalf("read %s: %v (fail closed)", rel, err) + } + for i, line := range strings.Split(string(b), "\n") { + if reclaimWord.MatchString(line) { + t.Errorf("%s: line %d uses the retired word \"reclaim\": %q", rel, i+1, line) + } + } + } + + t.Run("non_vacuity", func(t *testing.T) { + for _, hit := range []string{"`change.reclaim`", "## Reclaim log", "a reclaimed claim", "it reclaims", "RECLAIM edge", "reclaim.lease_ttl"} { + if !reclaimWord.MatchString(hit) { + t.Errorf("reclaimWord missed %q", hit) + } + } + for _, miss := range []string{"unreclaimable", "the claim", "claimed again"} { + if reclaimWord.MatchString(miss) { + t.Errorf("reclaimWord flagged %q", miss) + } + } + }) +} + // docSectionContract binds one or more load-bearing clauses to BOTH a named // section heading AND the heading that terminates it, so the assertion is "this // clause is present inside THIS section" — not the weaker "somewhere in the diff --git a/skills/docket-status/SKILL.md b/skills/docket-status/SKILL.md index c70489448..5073c237e 100644 --- a/skills/docket-status/SKILL.md +++ b/skills/docket-status/SKILL.md @@ -67,7 +67,7 @@ Starting the sweep command is not finishing it. If the shell tool's foreground w Only the sweep's actual terminal protocol-v1 envelope completes the command. Validate it and every entry: `protocol_version` `1`, `operation` `maintenance.sweep`, a `scope` equal to the one you requested, and each entry's closed disposition. Retain the original structured output — a harness result handle or a task-local output artifact — and extract the compact summary plus any problem entries in one read/parse rather than reopening the full output repeatedly; stdout is the JSON document, and any progress diagnostics belong on a separate channel. Only after that terminal validation run the post-sweep read: the `status` operation (resolve argv from the capability catalog) with `--json`. A read taken after a failed or unvalidated sweep is diagnostic only — label it as diagnostic; it can never authorize selection. -The envelope's top-level `applied` means some work applied, never that every item succeeded. A `blocked`, `failed`, or `unknown` entry — or a `contended` entry on work this preflight required — is a failed preflight even under an `applied` envelope: surface it per *Read the report* below and stop, per the *Scope of this stop* rule above. Intentional policy skips and genuine no-ops remain non-errors — never collapse arbitrary `skipped` reasons into success. On cancellation, request cancellation of the exact owned task where the harness supports it, then observe its termination; never broadly kill processes, abandon a watcher, or spawn a replacement sweep while the prior one may still run. If quiescence cannot be established, halt naming the exact live task identity and preserve its output — an explicit failure here beats claiming an orphan-free exit. +The envelope's top-level `applied` means some work applied, never that every item succeeded. A `blocked`, `failed`, or `unknown` entry — or a `contended` entry on work this preflight required — is a failed preflight even under an `applied` envelope: surface it per *Read the report* below and stop, per the *Scope of this stop* rule above. Intentional policy skips (`snapshot-retained`) and genuine no-ops (`snapshot-no-work`) remain non-errors — never collapse arbitrary `skipped` reasons into success. On cancellation, request cancellation of the exact owned task where the harness supports it, then observe its termination; never broadly kill processes, abandon a watcher, or spawn a replacement sweep while the prior one may still run. If quiescence cannot be established, halt naming the exact live task identity and preserve its output — an explicit failure here beats claiming an orphan-free exit. When a caller dispatched this skill, the final report must name: the resolved scope, the sweep's terminal envelope result, every problem entry, where the original sweep and status outputs live, and the post-sweep metadata revision (`git -C rev-parse HEAD`). The prose re-summary is never a second authority — the caller verifies against the originals.