diff --git a/docs/reference/glossary.md b/docs/reference/glossary.md index 99f58cbe3..c3b1c1da7 100644 --- a/docs/reference/glossary.md +++ b/docs/reference/glossary.md @@ -2133,7 +2133,7 @@ below. | `cancel_dispositions` | `cancelled` `already-cancelled` `cancellation-pending` `refused` | `run cancel` | | `claim_dispositions` | `applied` `already-claimed` `contended` `failed` `run-context-invalid` `run-context-conflict` | `change claim`, `change refresh-claim` | | `cleanup_dispositions` | `cleaned` `already-clean` `pending` `retained` `children-retarget-required` `rebase-scratch-cleared` | `finalize cleanup`, `gate cleanup` | -| `closeout_dispositions` | `done-archived` `stacked-merged` `root-archived` `already-closed-out` `children-retarget-required` `contended` `blocked` `unknown` `failed` | `finalize closeout` | +| `closeout_dispositions` | `done-archived` `stacked-merged` `root-archived` `already-closed-out` `contended` `blocked` `unknown` `failed` | `finalize closeout` | | `complete_dispositions` | `completed` `already-completed` `contended` `failed` | `change complete` | | `groom_outcomes` | `spec` `trivial` `revise` `abstain` `re-enable` | `change groom` (request `outcome`) | | `halt_dispositions` | `halted` `resumed` `contended` `refused` `failed` | `change halt`, `change resume-halted` | diff --git a/docs/superpowers/specs/2026-10-20-parent-closeout-waits-on-a-retargeted-child-so-a-parent-that-design.md b/docs/superpowers/specs/2026-10-20-parent-closeout-waits-on-a-retargeted-child-so-a-parent-that-design.md new file mode 100644 index 000000000..f527f368f --- /dev/null +++ b/docs/superpowers/specs/2026-10-20-parent-closeout-waits-on-a-retargeted-child-so-a-parent-that-design.md @@ -0,0 +1,203 @@ +# A landed stack parent closes out without waiting on children that never merged into it — design + +Change 0571 — Close out a landed stack parent without waiting on children that never merged into it + +Change #571, groomed 2026-10-19. Found while building #567 (PR #433). + +## The problem + +When a stacked parent's PR merges to the integration branch, `finalize closeout` takes the +integration-destination path (`closeoutIntegrationDestination`). That path asks +`domain.DeriveRootCloseoutSet` which descendants the parent carries. `DeriveRootCloseoutSet` walks +**every** change stacked on the parent, at any depth, active and archived alike +(`StackDescendantsParentFirst` over a corpus that includes `archive/`), and `proveCarry` refuses any +descendant whose status is not `stacked-merged` with the token `not-stacked-merged`. +`closeoutUnprovenDisposition` maps that token to the `children-retarget-required` disposition, and +the parent stays `implemented`. + +So a parent that has landed on main never reaches `done` while any change stacked on it is in any +other state: + +- a child whose PR finalize retargeted to main before the parent merged (the case #567's results + reported); +- a child that is only groomed (`proposed`), being built (`in-progress`), `blocked`, or `deferred`; +- a child that was `killed`; +- a child that already landed on main by itself and is `done` (this answers #567's open question: + the parent's closeout still refuses after the child lands). + +The sweep retries the parent every run and gets the same refusal every time. + +The rest of finalize already disagrees with closeout here: + +- `finalize merge` deliberately lets a retargeted child through: `probeUnretargetedOpenChildren` + counts only open child PRs that still target the parent's branch ("A retargeted child (its PR now + targets some other base) does not block"). +- The carry proof that rebase, publish, and merge run (`proveCarriedOnHead` over + `domain.DeriveCarriedSet`) counts only children connected to the parent by merged + `stacked-merged` links. An open or final child "claims no carry for this parent branch". +- The original stacks design said root closeout carries "every `stacked-merged` descendant", not + every descendant. + +The end-to-end test for the parent-landed-first flow (`TestE2EStackParentLandedFirst` in +`internal/app/finalize_e2e_test.go`) works around this by writing the parent's done record by hand +(`archiveAsDoneOnOrigin`). + +## The rule + +**A landed parent's closeout takes to `done` exactly the children whose PRs merged into it, down +the chain, once each one's work is proven on the integration branch. No other child can block it.** + +"Merged into it" is read from each child's live PR facts, which closeout already probes for every +descendant (`probeDescendantFacts`): the child's PR is merged and its base is the parent's recorded +`branch:`. That is the same link `walkCarryChain` and `DeriveCarriedSet` already check for +`stacked-merged` children. + +A child counts as carried when its status is `stacked-merged` **or** `implemented` and its live PR +merged into its parent's recorded branch. An `implemented` child whose PR is open, closed without +merging, or merged anywhere else (for example, retargeted to main and merged there before its own +closeout ran) is not carried and never blocks the parent; its own closeout handles it. An +`implemented` child with no usable PR reference is not carried either (grooming call: nothing docket can +see merged anywhere). The `implemented` case covers a child whose PR merged into +the parent's branch but whose own closeout never ran: it was merged by hand on GitHub, or its +closeout was interrupted. Today the parent refuses until that child's closeout runs. That closeout +needs the parent's branch to still exist (`requireStackedPreservation` fetches it), so in a +repository with GitHub's "automatically delete head branches" setting on, the child reports +`unknown` forever and the parent never reaches `done`. Under this rule the parent's closeout takes +that child straight from `implemented` to `done`, gated by the same Git content proof every carried +child already gets (`proveCarriedContent`: the child's merge result is reachable in the pinned +integration history, or exact-content at the parent's merge result). That proof reads the +integration branch, not the parent's branch, so a deleted parent branch doesn't matter. + +The walk descends through carried children only. Grandchildren beneath a child that is not carried +are not carried by this parent; they wait for their own parent. + +### Before and after + +| Situation when parent A lands on main | Today | After | +|---|---|---| +| Child B's PR was retargeted to main and is still open | A refuses (`children-retarget-required`) and stays `implemented` forever | A is archived as `done`; B is untouched. B's effective base becomes main (ADR-0092) and B is finalized later on its own | +| Child B is `proposed`, `in-progress`, `blocked`, `deferred`, or `killed` | A refuses forever | A is archived as `done`; B is untouched | +| Child B already landed on main and is `done` | A refuses forever | A is archived as `done` | +| Child B is `stacked-merged` into A's branch | A and B archived together (`root-archived`) | Unchanged | +| Child B's PR merged into A's branch but B still reads `implemented` | A refuses until B's own closeout runs; stuck forever if A's branch was deleted | A and B archived together (`root-archived`) after B's content is proven on main | +| B's PR merged into A's branch after A had already landed, so B's work is not on main | A refuses until B's own closeout marks it `stacked-merged`, then refuses again because B's work isn't on main (`blocked`, `descendant-carry-unproven`) | A refuses, naming B (`blocked`, `descendant-carry-unproven`). The content proof fails either way | +| Child B's PR still targets A's branch and is open (A was merged outside docket) | A refuses forever | A is archived as `done`. Cleanup keeps A's branch and reports `children-retarget-required` because an open child PR still targets it (unchanged) | + +### What else stays fail-closed + +- A `stacked-merged` child is a claim that it merged into its parent. If its live PR facts show a + different destination, or can't be established, it still refuses the parent's closeout with + today's tokens (`destination-mismatch` → `blocked`, `pr-unknown` → `unknown`). This applies to + `stacked-merged` children only: for an `implemented` child, merging into the parent's branch is + the test for being carried, so any other PR state just means "not carried". +- A GitHub lookup that fails is `unknown` and retried, as today. That is an observation failure, + not a child blocking the parent. To keep it from coming from children the rule ignores, look up + only descendants whose status is `implemented` or `stacked-merged` (grooming call). Today + `probeDescendantFacts` also looks up archived `done` and `killed` descendants, whose facts the + walk never reads. Filtering by status keeps the facts map built before the walk, so the + domain/app split stays as it is. +- A carried child whose work is not proven on main still refuses the parent (`blocked`, + `descendant-carry-unproven`), with zero descendant writes. The all-or-nothing transaction is + unchanged. +- A root whose own `stacked_on` ancestry cycles still refuses, as today (`rootAncestryCycles`). + +## One definition of "what a parent carries" + +Today two walks answer this question differently: `DeriveCarriedSet` (rebase, publish, merge) and +`DeriveRootCloseoutSet` (root closeout). After this change there is one rule, shared by all four +boundaries. Widening the shared walk to accept an `implemented`-but-merged child also means rebase, +publish, and merge prove that child's work survives in the head about to merge, so a rebase that +dropped it refuses before the irreversible merge instead of after it. + +Builder's call: whether `DeriveRootCloseoutSet` is retired in favour of `DeriveCarriedSet`, kept as +a thin wrapper, or both are rebuilt on one shared walk. What matters is that the four boundaries +cannot drift apart. `walkCarryChain` and `ProveDoneCarry` (the upward walk cleanup uses on `done` +children, from #567) are unaffected: after the parent's closeout every carried child is `done` with +a PR merged into its parent's branch, which is what that walk already expects. + +Fix the header comment of `internal/app/finalize_preservation.go` while there: it says +`proveCarriedOnHead` serves "FinalizeRebase, FinalizePublish, FinalizeMerge, and stacked closeout", +but its callers are rebase, publish, and merge only (root closeout uses its own derivation plus +`proveCarriedContent`; stacked closeout uses `requireStackedPreservation`). After this change it +should name what is actually shared. + +The archive transaction (`closeoutArchiveOp`) needs no new shape: it already applies +`domain.MarkDone` and clears `## Finalize blocked` per target, and `MarkDone` already accepts +`implemented` (the parent itself takes that path). + +## The `children-retarget-required` closeout disposition goes away + +With the rule above nothing produces the `not-stacked-merged` token or the closeout disposition +`children-retarget-required`. Remove both, and every place that documents them: + +- `CloseoutDispChildrenRetargetRequired` in `internal/app/finalize_closeout.go`, + `closeoutUnprovenDisposition`'s `not-stacked-merged` arm, and the `closeout_dispositions` set in + `internal/app/schema_vocab.go`; +- `docs/reference/glossary.md`'s `closeout_dispositions` row; +- `skills/docket-finalize-change/SKILL.md` step 9's `children-retarget-required` bullet, and + `skills/docket-finalize-change/references/gate-failure.md`'s "or a `children-retarget-required` + closeout" clause; +- `skills/docket-convention/references/stacked-changes.md`: the routing sentence in *The stack + close-out is idempotent*, the carried-descendant definition there (a carried child may come from + `implemented` as well as `stacked-merged`), and *The `stacked-merged` state*'s claim that root + closeout is the only consumer taking a change out of `stacked-merged` (it now also takes an + `implemented`-but-merged child straight to `done`); +- the embedded copies under `internal/assets/embedded/tree/` (regenerate with + `go generate ./internal/assets/`). + +Cleanup's own `children-retarget-required` disposition (`CleanupDispChildrenRetargetRequired`) is a +different thing and stays: there it means an open child PR still targets the branch, so the branch +is kept. + +`skills/docket-implement-next/references/edge-paths.md` gives a reason that becomes false: "an +ancestor's closeout cannot prove the carry of a named change not yet `stacked-merged` +(`children-retarget-required`)". Keep the behaviour (a `not-ready-stack-base-unresolved` refusal is +still never a closeout trigger, and `TestProseContracts`'s `change_0448_named_preflight_skip` +contract in `internal/repoguard/prose_contracts_test.go` still pins that sentence), but replace the +reason with a true one: the +bounded closeout covers only the named change's own `depends_on` set, and an unresolved stack base +clears through the parent's own finalize or the next sweep. Update the matching explanatory comments +in `internal/repoguard/prose_contracts_test.go` and `internal/repoguard/budgets_test.go`. Re-check +any prose budget those guards hold after the edit. + +## Tests + +- **Domain** (`internal/domain/stackcloseout_test.go`): the existing "descendant still in-progress is + not-stacked-merged" and "a gap mid-chain is chain-broken" cases now describe allowed situations. + Rewrite them to assert the new outcomes: a parent with an open, retargeted, `proposed`, + `in-progress`, `killed`, or `done` child has an empty carry set and is proven; a stacked-merged + grandchild beneath an open child is not carried. Add: an `implemented` child whose PR merged into + the parent's branch is carried; an `implemented` child whose PR merged into main (or is open, or + has no PR) is not carried and does not block; a `stacked-merged` child with mismatched or missing + facts still refuses; a three-level chain through an `implemented`-but-merged middle link is + carried end to end. +- **App** (closeout and the carry proof): parent closeout with a retargeted open child returns + `done-archived` and writes only the parent; parent closeout carries an `implemented`-but-merged + child to `done` (`root-archived`, the child in `carried_ids`), including when the parent's remote + branch no longer exists; the content-unproven case still refuses with zero descendant writes; + rebase, publish, and merge refuse when an `implemented`-but-merged child's work is not preserved + at the target head; a parent whose retargeted child already merged to main (child still + `implemented`) still merges and closes out; archived `done` and `killed` descendants are not + looked up on GitHub (adjust any test that counts lookups). +- **End to end** (`TestE2EStackParentLandedFirst`): replace `archiveAsDoneOnOrigin` with the real + parent closeout (`stackCloseout(t, s, parentID, "done-archived")`), then run the rest of the story + unchanged. Delete `archiveAsDoneOnOrigin` if nothing else uses it. +- Mutation-test each new guard: restoring the old "every descendant must be stacked-merged" rule + must redden the end-to-end test and the new domain cases; dropping the `implemented`-but-merged + arm must redden its cases; skipping the content proof for that arm must redden its refusal case. + +## Decision record + +This reverses a documented rule (root closeout required every descendant to be `stacked-merged`) +and widens what a parent carries. Record it as an ADR: a stack parent carries exactly the children +whose PRs merged into it, whether or not their own closeout ran, proven in Git before any write; no +other child blocks the parent's closeout. + +## Out of scope + +- How a child's PR is retargeted, including a child whose PR still targets a parent that already + landed (cleanup already keeps that parent's branch and reports it). +- Cleanup of carried children's branches and folders (done in #567). +- Letting implement-next's bounded closeout close out a stack ancestor to unblock a named stacked + child. +- The killed-parent policy. diff --git a/internal/app/finalize_closeout.go b/internal/app/finalize_closeout.go index d2bab419c..f87d6dce8 100644 --- a/internal/app/finalize_closeout.go +++ b/internal/app/finalize_closeout.go @@ -45,16 +45,19 @@ import ( // is NOT archived; its feature branch and workspace are retained. // // 3. Stack root carry: the destination is the integration branch AND the change -// roots a stack of stacked-merged descendants. domain.DeriveRootCloseoutSet -// proves, from the authoritative graph and live PR facts, the chain of merged -// destinations that establishes the carry RELATIONSHIP for every descendant -// into the root; each descendant is then proven in Git — its merge result -// reachable in the pinned integration history, or exact-content preserved at -// the root's own merge result — before any archive write, because a merged -// destination is a relationship, never evidence the content survived a -// stale-worktree rewrite. One transaction archives the root plus every proven -// descendant using the ROOT's merge date for every archive filename, and -// renders one board over the final population. A single unproven descendant +// roots a stack. The root carries exactly the descendants whose PRs merged +// into their parent's branch, transitively — stacked-merged children and +// implemented children whose own closeout never ran alike — and no other +// child blocks it. domain.DeriveRootCloseoutSet derives that carried set from +// the authoritative graph and live PR facts through the one walk rebase, +// publish, and merge also use (domain.DeriveCarriedSet); each carried +// descendant is then proven in Git — its merge result reachable in the pinned +// integration history, or exact-content preserved at the root's own merge +// result — before any archive write, because a merged destination is a +// relationship, never evidence the content survived a stale-worktree +// rewrite. One transaction archives the root plus every proven descendant +// using the ROOT's merge date for every archive filename, and renders one +// board over the final population. A single unproven carried descendant // keeps the whole root recoverable — zero descendant writes. // // Backlinks: every spec, plan, and results file lives on the metadata branch, @@ -85,9 +88,6 @@ const ( // CloseoutDispAlready: the promised final state already exists (a response- // lost replay); a verified no-op. CloseoutDispAlready = "already-closed-out" - // CloseoutDispChildrenRetargetRequired: a descendant is not yet stacked-merged, - // so the root cannot be carried; retarget/finish the descendants first. - CloseoutDispChildrenRetargetRequired = "children-retarget-required" // CloseoutDispContended: a lost race the caller resolves by re-reading context // (an unreachable merge commit, a stale record revision). CloseoutDispContended = "contended" @@ -606,16 +606,13 @@ func closeoutTargetFor(c domain.Change, changesDir, archiveDate string) closeout } // closeoutUnprovenDisposition maps the first descendant refusal token to a -// closeout disposition. A descendant that is not yet stacked-merged needs -// retargeting/finishing (children-retarget-required); an unknown PR is unknown; -// every other structural break is blocked. +// closeout disposition: a stacked-merged descendant whose PR facts cannot be +// established (pr-unknown) is unknown; every other refusal is blocked. func closeoutUnprovenDisposition(set []domain.CarriedDescendant) (string, string) { for _, d := range set { switch d.Proof { case "": continue - case "not-stacked-merged": - return CloseoutDispChildrenRetargetRequired, ReasonCloseoutChildUnproven case "pr-unknown": return CloseoutDispUnknown, ReasonCloseoutProbeUnknown default: @@ -626,9 +623,13 @@ func closeoutUnprovenDisposition(set []domain.CarriedDescendant) (string, string } // probeDescendantFacts reprobes the live PR of every transitive stack descendant -// so DeriveRootCloseoutSet reasons over authoritative facts. A descendant with no -// PR reference contributes no facts (DeriveRootCloseoutSet reads that as -// pr-unknown); a probe error is returned so the caller retains it as unknown. +// the carry walk can read facts for — status implemented or stacked-merged — so +// the carried set (domain.DeriveCarriedSet, through DeriveRootCloseoutSet here) +// reasons over authoritative facts. Any other descendant (unbuilt, in progress, +// or archived done/killed) is never carried and costs no GitHub lookup. A +// descendant with no PR reference contributes no facts (a stacked-merged one +// reads as pr-unknown, an implemented one as not carried); a probe error is +// returned so the caller retains it as unknown. func probeDescendantFacts(ctx context.Context, deps FinalizeDeps, ghRepo githubcli.Repository, snap domain.Snapshot, root domain.ChangeID) (map[domain.ChangeID]domain.PRFacts, error) { facts := map[domain.ChangeID]domain.PRFacts{} for _, id := range domain.StackDescendantsParentFirst(snap, root) { @@ -636,6 +637,9 @@ func probeDescendantFacts(ctx context.Context, deps FinalizeDeps, ghRepo githubc if out != domain.LookupFound { continue } + if st := d.Status(); st != domain.StatusImplemented && st != domain.StatusStackedMerged { + continue + } number, ok := parsePRNumber(d.PR().Value) if !finalizeHasPRRef(d) || !ok { continue diff --git a/internal/app/finalize_closeout_integration_test.go b/internal/app/finalize_closeout_integration_test.go index 3962b4b1c..43ffaaf1b 100644 --- a/internal/app/finalize_closeout_integration_test.go +++ b/internal/app/finalize_closeout_integration_test.go @@ -527,8 +527,10 @@ func (f *closeoutFixture) carryOntoRootFeature(t *testing.T, files map[string]st // TestCloseoutRootCarry proves a stack root merged to integration archives the // root plus every proven carried descendant in ONE transaction using the root's -// merge date for every filename; a single unproven descendant keeps the root -// recoverable with zero descendant writes; and — the change-0327 headline — the +// merge date for every filename; it carries exactly the children whose PRs merged +// into its branch (stacked-merged or still implemented), and no other child +// blocks it; a single unproven carried descendant keeps the root recoverable +// with zero descendant writes; and — the change-0327 headline — the // archive is refused unless every carried descendant's merged work is proven // PRESENT IN GIT (ancestry in the pinned integration history, or exact content at // the ROOT's merge result), never inferred from a metadata destination. @@ -543,19 +545,81 @@ func TestIntegrationFinalizeArchiveRootCarry(t *testing.T) { descPlan := "docs/superpowers/plans/2026-08-16-gadget-plan.md" - // seed returns a descendant record (id 6, gadget) stacked on the root (id 5) - // with the given status, carrying PR #8 whose destination is the root's branch. - seed := func(t *testing.T, descStatus string) *closeoutFixture { + // seedAt returns a descendant record (id 6, gadget) stacked on the root (id 5) + // with the given status at recPath, carrying PR #8. seed places it at the + // active path; an archived status (done, killed) lives at descArchived. + seedAt := func(t *testing.T, descStatus, recPath string) *closeoutFixture { f := setupCloseoutFixture(t, m) - recPath := groomPath(6, "gadget") 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."), }) return f } + seed := func(t *testing.T, descStatus string) *closeoutFixture { + return seedAt(t, descStatus, groomPath(6, "gadget")) + } + descArchived := "docs/changes/archive/2026-08-16-0006-gadget.md" + rootArchived := "docs/changes/archive/2026-08-18-0005-widget.md" + + // assertRootOnlyArchived pins a closeout that archives the root alone: the + // root is done at its archive path, nothing is carried, and the descendant's + // record at descPath is byte-identical to descBefore. + assertRootOnlyArchived := func(t *testing.T, f *closeoutFixture, res CloseoutResult, descPath, descBefore string) { + t.Helper() + if res.Result != ResultApplied || res.Disposition != CloseoutDispDoneArchived { + t.Fatalf("root closeout = %q disp %q (reason %q msg %q findings %+v), want applied/%s", res.Result, res.Disposition, res.Reason, res.Message, res.Findings, CloseoutDispDoneArchived) + } + if len(res.CarriedIDs) != 0 { + t.Errorf("carried ids = %v, want none", res.CarriedIDs) + } + archived, ok := originFile(t, f.repo.origin, f.branch, rootArchived) + if !ok { + t.Fatalf("root archive record absent at %q", rootArchived) + } + if !strings.Contains(archived, "status: 'done'") { + t.Errorf("root archive record not done:\n%s", archived) + } + if _, ok := originFile(t, f.repo.origin, f.branch, "docs/changes/archive/2026-08-18-0006-gadget.md"); ok { + t.Errorf("a non-carried descendant was archived with the root") + } + after, ok := originFile(t, f.repo.origin, f.branch, descPath) + if !ok { + t.Fatalf("the non-carried descendant's record left %q", descPath) + } + if after != descBefore { + t.Errorf("the non-carried descendant's record changed:\nbefore:\n%s\nafter:\n%s", descBefore, after) + } + assertBoardMatchesCommitted(t, f.repo.origin, f.branch, f.repo.invocation) + } + + // assertRefusedZeroWrites pins a blocked root carry: the metadata ref is + // byte-identical to before, nothing is archived, both active records remain. + assertRefusedZeroWrites := func(t *testing.T, f *closeoutFixture, res CloseoutResult, before string) { + t.Helper() + if res.Result != ResultBlocked || res.Disposition != CloseoutDispBlocked || res.Reason != ReasonCloseoutChildUnproven { + t.Fatalf("refused root carry = %q disp %q reason %q, want blocked/%s/%s", res.Result, res.Disposition, res.Reason, CloseoutDispBlocked, ReasonCloseoutChildUnproven) + } + if after := originTip(t, f.repo.origin, f.branch); after != before { + t.Errorf("a refused root carry moved the metadata ref: %q -> %q", before, after) + } + for _, p := range []string{rootArchived, "docs/changes/archive/2026-08-18-0006-gadget.md"} { + if _, ok := originFile(t, f.repo.origin, f.branch, p); ok { + t.Errorf("a refused root carry archived %q", p) + } + } + for _, p := range []string{groomPath(5, "widget"), groomPath(6, "gadget")} { + if _, ok := originFile(t, f.repo.origin, f.branch, p); !ok { + t.Errorf("a refused root carry removed the active record %q", p) + } + } + } // rootFake scripts PR #7 (root) merged into main at rootMerge and PR #8 // (descendant id 6) merged into the root's branch at childMerge. @@ -626,30 +690,103 @@ func TestIntegrationFinalizeArchiveRootCarry(t *testing.T) { } }) - t.Run("one-unproven-descendant-keeps-root-recoverable", func(t *testing.T) { - f := seed(t, "implemented") // NOT stacked-merged: carry unproven + t.Run("unmerged-implemented-child-does-not-block-root", func(t *testing.T) { + // An implemented child whose PR #8 never merged (the fake answers cleanly + // not merged) is not carried and does not hold the landed root back: the + // root archives alone and the child stays active and implemented. + f := seed(t, "implemented") + descBefore, _ := originFile(t, f.repo.origin, f.branch, groomPath(6, "gadget")) + if !strings.Contains(descBefore, "status: implemented") { + t.Fatalf("fixture child is not implemented:\n%s", descBefore) + } + mergeCommit := f.mergeIntoBase(t) + res := FinalizeCloseout(context.Background(), f.closeoutDeps(f.baselineMergedFake(f.head, mergeCommit)), f.repo.invocation, f.id, CloseoutNotes{}) + assertRootOnlyArchived(t, f, res, groomPath(6, "gadget"), descBefore) + }) + + t.Run("non-carried-children-do-not-block-root", func(t *testing.T) { + // A child that is not implemented or stacked-merged is never carried and + // never looked up: the only GitHub probe is the root's own reprobe. + for _, tc := range []struct{ status, path string }{ + {"proposed", groomPath(6, "gadget")}, + {"in-progress", groomPath(6, "gadget")}, + {"killed", descArchived}, + {"done", descArchived}, + } { + t.Run(tc.status, func(t *testing.T) { + f := seedAt(t, tc.status, tc.path) + descBefore, _ := originFile(t, f.repo.origin, f.branch, tc.path) + mergeCommit := f.mergeIntoBase(t) + gh := f.baselineMergedFake(f.head, mergeCommit) + res := FinalizeCloseout(context.Background(), f.closeoutDeps(gh), f.repo.invocation, f.id, CloseoutNotes{}) + assertRootOnlyArchived(t, f, res, tc.path, descBefore) + if gh.probes != 1 { + t.Errorf("GitHub probes = %d, want 1 (only the root's own reprobe; a child at status %s is never looked up)", gh.probes, tc.status) + } + }) + } + }) + + t.Run("implemented-child-merged-to-main-not-carried", func(t *testing.T) { + // The child was retargeted and its PR merged into main, not the root's + // branch: it is not the root's to carry, and it does not block the root. + f := seed(t, "implemented") + descBefore, _ := originFile(t, f.repo.origin, f.branch, groomPath(6, "gadget")) + childMerge := f.carryCommit(t, "gadget-mc", "main", map[string]string{"gadget.txt": "gadget work\n"}) mergeCommit := f.mergeIntoBase(t) + f.fetchAllIntoInvocation(t) gh := &fakeCloseoutGitHub{ repo: retargetRepo(), merged: map[int]closeoutProbe{ closeoutPR: {outcome: githubcli.MergeAlreadyMerged, facts: mergedFactsFor(f.head, "main", mergeCommit)}, + 8: {outcome: githubcli.MergeAlreadyMerged, facts: mergedFactsFor(childMerge, "main", childMerge)}, }, } - before := originTip(t, f.repo.origin, f.branch) res := FinalizeCloseout(context.Background(), f.closeoutDeps(gh), f.repo.invocation, f.id, CloseoutNotes{}) - if res.Result == ResultApplied || res.Result == ResultNoOp { - t.Fatalf("an unproven descendant let the root close out: %q", res.Result) + assertRootOnlyArchived(t, f, res, groomPath(6, "gadget"), descBefore) + if gh.probes != 2 { + t.Errorf("GitHub probes = %d, want 2 (the root and its implemented child)", gh.probes) } - if res.Disposition != CloseoutDispChildrenRetargetRequired { - t.Errorf("disposition = %q, want %q", res.Disposition, CloseoutDispChildrenRetargetRequired) - } - // Zero writes: neither record moved. - if after := originTip(t, f.repo.origin, f.branch); after != before { - t.Errorf("an unproven root carry moved the metadata ref: %q -> %q", before, after) - } - if _, ok := originFile(t, f.repo.origin, f.branch, groomPath(f.id, f.slug)); !ok { - t.Errorf("the recoverable root was archived away") + }) + + t.Run("implemented-merged-child-is-carried", func(t *testing.T) { + // The child's PR merged into the root's branch but its own closeout never + // ran (still implemented): the root carries it to done. + f := seed(t, "implemented") + childMerge := f.carryOntoRootFeature(t, map[string]string{"gadget.txt": "gadget work\n"}) + mergeCommit := f.mergeIntoBase(t) + f.fetchAllIntoInvocation(t) + res := FinalizeCloseout(context.Background(), f.closeoutDeps(rootFake(f, mergeCommit, childMerge)), f.repo.invocation, f.id, CloseoutNotes{}) + assertBothArchived(t, f, res) + }) + + t.Run("implemented-merged-child-parent-branch-deleted", func(t *testing.T) { + // The root's remote branch is gone (auto-delete after merge). The content + // proof reads the integration branch, so the implemented-but-merged child + // is still carried. + f := seed(t, "implemented") + childMerge := f.carryOntoRootFeature(t, map[string]string{"gadget.txt": "gadget work\n"}) + mergeCommit := f.mergeIntoBase(t) + runGit(t, f.repo.writer, "push", "-q", "origin", "--delete", "feat/"+f.slug) + runGit(t, f.repo.invocation, "fetch", "-q", "--prune", "origin", "+refs/heads/*:refs/remotes/origin/*") + if _, err := tryGit(f.repo.origin, "rev-parse", "--verify", "--quiet", "refs/heads/feat/"+f.slug); err == nil { + t.Fatalf("the root's remote branch must be deleted for this fixture") } + res := FinalizeCloseout(context.Background(), f.closeoutDeps(rootFake(f, mergeCommit, childMerge)), f.repo.invocation, f.id, CloseoutNotes{}) + assertBothArchived(t, f, res) + }) + + t.Run("implemented-merged-child-content-dropped-refuses", func(t *testing.T) { + // The implemented child's PR merged into the root's branch, but its work + // never reached the integration branch (a real merge object on a side + // branch, never on the root's branch): the root refuses, zero writes. + f := seed(t, "implemented") + childMerge := f.carryCommit(t, "gadget-mc", "main", map[string]string{"gadget.txt": "gadget work\n"}) + mergeCommit := f.mergeIntoBase(t) + f.fetchAllIntoInvocation(t) + before := originTip(t, f.repo.origin, f.branch) + res := FinalizeCloseout(context.Background(), f.closeoutDeps(rootFake(f, mergeCommit, childMerge)), f.repo.invocation, f.id, CloseoutNotes{}) + assertRefusedZeroWrites(t, f, res, before) }) t.Run("absent-merge-object-refuses", func(t *testing.T) { diff --git a/internal/app/finalize_e2e_test.go b/internal/app/finalize_e2e_test.go index ac5aa3d9a..32bd336fc 100644 --- a/internal/app/finalize_e2e_test.go +++ b/internal/app/finalize_e2e_test.go @@ -17,7 +17,6 @@ import ( "strings" "sync" "testing" - "time" "github.com/danielhanold/docket/internal/gitcli" "github.com/danielhanold/docket/internal/githubcli" @@ -1246,13 +1245,11 @@ func TestE2EStackParentLandedFirst(t *testing.T) { t.Fatalf("retarget-children disposition = %q, want retargeted\n%s", rt.str("disposition"), rt.stdout) } - // The parent lands first and is cleaned up. Its own closeout cannot run here: - // a root closeout requires every stacked descendant to be stacked-merged into - // it, so a retargeted, still-open child refuses it (children-retarget-required). - // The fixture writes the done record that closeout would have written, so the - // rest of the story — the child's own finalize — runs entirely through argv. + // The parent lands first and closes out through the real closeout. Its + // retargeted, still-open child was never merged into the parent's branch, so + // it is not carried and does not block the parent's closeout. stackMergeFromWorktree(t, s, parentID, parentSlug, parent.wp, parent.evidence) - archiveAsDoneOnOrigin(t, s, parentID, parentSlug) + stackCloseout(t, s, parentID, "done-archived") if cl := s.dk(t, "", "finalize", "cleanup", "--id", strconv.Itoa(parentID)); cl.str("disposition") != "cleaned" { t.Fatalf("parent cleanup disposition = %q, want cleaned\n%s", cl.str("disposition"), cl.stdout) } @@ -1269,56 +1266,6 @@ func TestE2EStackParentLandedFirst(t *testing.T) { assertStackMemberCleaned(t, s, "child", child.wp, childBranch) } -// archiveAsDoneOnOrigin writes, through the writer clone, the metadata state a -// done-archived closeout leaves for one change: its active record moved to the -// dated archive path with status done and no claim stamp, exactly the two field -// edits closeout's mark-done makes in the record's first frontmatter block. -func archiveAsDoneOnOrigin(t *testing.T, s *e2eState, id int, slug string) { - t.Helper() - w, branch := s.repo.writer, s.mode.branch - active := groomPath(id, slug) - archive := fmt.Sprintf("docs/changes/archive/%s-%s-%s.md", time.Now().UTC().Format("2006-01-02"), padID(id), slug) - runGit(t, w, "fetch", "-q", "origin", branch) - runGit(t, w, "checkout", "-q", "-B", branch, "FETCH_HEAD") - body, err := os.ReadFile(filepath.Join(w, active)) - if err != nil { - t.Fatalf("read %s: %v", active, err) - } - text := string(body) - if !strings.HasPrefix(text, "---\n") { - t.Fatalf("%s has no leading frontmatter block", active) - } - end := strings.Index(text[len("---\n"):], "\n---\n") - if end < 0 { - t.Fatalf("%s has an unterminated frontmatter block", active) - } - front := text[:len("---\n")+end+1] - var status string - for _, quoted := range []string{"\nstatus: implemented\n", "\nstatus: 'implemented'\n"} { - if strings.Count(front, quoted) == 1 { - status = quoted - } - } - if status == "" { - t.Fatalf("%s frontmatter carries no single implemented status:\n%s", active, front) - } - front = strings.Replace(front, status, "\nstatus: done\n", 1) - // A done record holds no claim lease: closeout's mark-done clears claimed_at. - lines := strings.SplitAfter(front, "\n") - kept := lines[:0] - for _, l := range lines { - if !strings.HasPrefix(l, "claimed_at:") { - kept = append(kept, l) - } - } - text = strings.Join(kept, "") + text[len("---\n")+end+1:] - runGit(t, w, "rm", "-q", active) - writeRepoFile(t, w, archive, text) - runGit(t, w, "add", "-A") - runGit(t, w, "commit", "-q", "-m", fmt.Sprintf("archive %04d as done", id)) - runGit(t, w, "push", "-q", "origin", branch) -} - // stackedBuildReadyChange is a build-ready change stacked on parent. func stackedBuildReadyChange(id int, slug string, parent int) string { return strings.Replace(buildReadyChange(id, slug), "stacked_on:\n", "stacked_on: "+strconv.Itoa(parent)+"\n", 1) diff --git a/internal/app/finalize_merge_integration_test.go b/internal/app/finalize_merge_integration_test.go index d4a1f92c9..c365e888c 100644 --- a/internal/app/finalize_merge_integration_test.go +++ b/internal/app/finalize_merge_integration_test.go @@ -706,6 +706,58 @@ func TestIntegrationFinalizeMergeCarryPreservation(t *testing.T) { } }) + t.Run("implemented-merged-child-lost-refuses-zero-merge-calls", func(t *testing.T) { + t.Parallel() + // An implemented child merged into the parent's branch is carried even + // though its own closeout never ran, so its lost work refuses the merge. + f := setupMergeFixtureWithNode(t, m, parallelPlanningNode) + seedRebaseCarryChildAt(t, f.rebaseFixture, "implemented") + dropped := carryDroppedCommit(t, f.rebaseFixture, map[string]string{"catalog.yaml": "Y\n"}) + if _, err := tryGit(f.repo.invocation, "cat-file", "-e", dropped); err != nil { + t.Fatalf("the child merge object must exist to pin a drop: %v", err) + } + gh := f.carryFake(t, true) + gh.merged[8] = closeoutProbe{outcome: githubcli.MergeAlreadyMerged, facts: mergedFactsFor(f.head, "feat/widget", dropped)} + gh.mergeOutcome = githubcli.MergeMerged + gh.mergeFacts = mergedFactsFor(f.head, "main", dropped) + + res := FinalizeMerge(ctx, f.mergeDeps(gh), f.repo.invocation, mergeReq(f, f.head, true, false)) + if res.Reason != ReasonCarryUnproven || res.Result != ResultBlocked || res.Disposition != MergeDispBlocked { + t.Fatalf("carry-lost merge = result %q disp %q reason %q, want blocked/blocked/%s", res.Result, res.Disposition, res.Reason, ReasonCarryUnproven) + } + if res.Merge != nil { + t.Fatalf("a carry refusal carried a VerifiedMerge") + } + if len(res.Findings) == 0 { + t.Fatalf("a carry refusal carried no findings naming the unproven descendant") + } + if gh.mergeCalls != 0 { + t.Fatalf("a carry refusal issued %d merge call(s); want 0 (witness: no external merge)", gh.mergeCalls) + } + }) + + t.Run("retargeted-child-merged-to-main-merges", func(t *testing.T) { + t.Parallel() + // An implemented child retargeted and merged to main is not the parent's to + // carry: its work (absent from the parent's head) never blocks the merge. + f := setupMergeFixtureWithNode(t, m, parallelPlanningNode) + seedRebaseCarryChildAt(t, f.rebaseFixture, "implemented") + dropped := carryDroppedCommit(t, f.rebaseFixture, map[string]string{"catalog.yaml": "R\n"}) + mergeCommit := f.mergeFeatureIntoBase(t) + gh := f.carryFake(t, true) + gh.merged[8] = closeoutProbe{outcome: githubcli.MergeAlreadyMerged, facts: mergedFactsFor(f.head, "main", dropped)} + gh.mergeOutcome = githubcli.MergeMerged + gh.mergeFacts = mergedFactsFor(f.head, "main", mergeCommit) + + res := FinalizeMerge(ctx, f.mergeDeps(gh), f.repo.invocation, mergeReq(f, f.head, true, false)) + if res.Result != ResultApplied || res.Disposition != MergeDispMerged || res.Merge == nil { + t.Fatalf("retargeted-child merge = %q disp %q merge %v (reason %q msg %q), want applied/merged verified", res.Result, res.Disposition, res.Merge, res.Reason, res.Message) + } + if gh.mergeCalls != 1 { + t.Fatalf("the retargeted-child merge issued %d merge call(s); want exactly 1", gh.mergeCalls) + } + }) + t.Run("ordinary-change-merges-witness-fires-on-happy-path", func(t *testing.T) { t.Parallel() // No stack descendants: the proof is vacuously satisfied with zero probes and diff --git a/internal/app/finalize_preservation.go b/internal/app/finalize_preservation.go index 7089ba1db..628006dec 100644 --- a/internal/app/finalize_preservation.go +++ b/internal/app/finalize_preservation.go @@ -10,15 +10,19 @@ import ( "github.com/danielhanold/docket/internal/githubcli" ) -// This file is the shared app-layer join that the four enforcement boundaries -// (FinalizeRebase, FinalizePublish, FinalizeMerge, and stacked closeout) reuse: -// it takes the descendants a live carrying branch PROMISES to carry -// (domain.DeriveCarriedSet over authoritative GitHub facts) and proves, in Git, -// that each one's merged work is preserved at exactly the immutable target commit -// (gitcli.ProvePreserved). A merged PR destination proves a relationship only; -// preservation of the CONTENT is this helper's separate obligation. Every refusal -// names its category and its ids so a stuck gate is self-diagnosing, and an -// observation error is returned as an error — never laundered into a verdict. +// This file is the shared app-layer join the rebase, publish, and merge +// enforcement boundaries (FinalizeRebase, FinalizePublish, FinalizeMerge) reuse +// through proveCarriedOnHead: it takes the descendants a live carrying branch +// PROMISES to carry (domain.DeriveCarriedSet over authoritative GitHub facts) and +// proves, in Git, that each one's merged work is preserved at exactly the +// immutable target commit (gitcli.ProvePreserved). Root closeout derives the same +// carried set (domain.DeriveRootCloseoutSet over domain.DeriveCarriedSet) and +// proves each child on the integration branch with proveCarriedContent; stacked +// closeout uses requireStackedPreservation. A merged PR destination proves a +// relationship only; preservation of the CONTENT is this helper's separate +// obligation. Every refusal names its category and its ids so a stuck gate is +// self-diagnosing, and an observation error is returned as an error — never +// laundered into a verdict. // The closed per-descendant preservation finding categories. Each names WHY one // carried descendant's preservation could not be established, keeping the missing @@ -37,9 +41,9 @@ const ( CarryFindingUnpreserved = "carry-content-unpreserved" ) -// ReasonCarryUnproven is the shared refusal reason the rebase, publish, merge, -// and stacked-closeout boundaries report when a carried descendant's preservation -// is not proven. Every carry finding carries it as its Code so a caller branches +// ReasonCarryUnproven is the shared refusal reason the rebase, publish, and +// merge boundaries report when a carried descendant's preservation is not proven +// (proveCarriedOnHead). Every carry finding carries it as its Code so a caller branches // on one stable token regardless of which boundary raised it. const ReasonCarryUnproven = "carried-descendant-unproven" diff --git a/internal/app/finalize_preservation_integration_test.go b/internal/app/finalize_preservation_integration_test.go index d91c1d4fb..ceb63a058 100644 --- a/internal/app/finalize_preservation_integration_test.go +++ b/internal/app/finalize_preservation_integration_test.go @@ -258,3 +258,88 @@ func TestIntegrationFinalizeRebaseRecoveryCarryHelperPreservation(t *testing.T) } }) } + +// TestIntegrationFinalizeRebaseRecoveryCarryHelperImplementedChild drives the +// carry helper over an "implemented" descendant: its own closeout never ran, so +// it is carried exactly when its PR merged into the parent's branch. Carried, its +// content is proven like any other carried child; not carried (merged elsewhere, +// or not merged), it contributes nothing and is never a relationship refusal. +func TestIntegrationFinalizeRebaseRecoveryCarryHelperImplementedChild(t *testing.T) { + requireRealGit(t) + ctx := context.Background() + + f := setupCloseoutFixture(t, planRepoModes()[0]) + seedCarryChild(t, f, "implemented") + + // ancestor line: mcAnc <- tgtAnc (tgtAnc descends mcAnc) + mcAnc := f.carryCommit(t, "line-anc", "main", map[string]string{"anc1.txt": "1\n"}) + tgtAnc := f.carryCommit(t, "line-anc", "", map[string]string{"anc2.txt": "2\n"}) + // content-dropped: source adds catalog.yaml=Y; target drops it + mcDropped := f.carryCommit(t, "line-srcd", "main", map[string]string{"catalog.yaml": "Y\n"}) + tgtDropped := f.carryCommit(t, "line-tgtd", "main", map[string]string{"other.txt": "o\n"}) + f.fetchAllIntoInvocation(t) + + cc, refusal := loadCloseoutContext(ctx, f.closeoutDeps(f.baselineMergedFake(f.head, mcAnc)), f.repo.invocation, f.id) + if refusal != nil { + t.Fatalf("loadCloseoutContext refused: %+v", *refusal) + } + childID := fmt.Sprintf("%04d", 6) + + run := func(gh *fakeCloseoutGitHub, target string) (carryProof, error) { + return proveCarriedOnHead(ctx, f.closeoutDeps(gh), f.repo.invocation, cc.repo, cc.snap, cc.change, gitcli.ObjectID(target)) + } + assertProvenNone := func(t *testing.T, proof carryProof, err error) { + t.Helper() + if err != nil { + t.Fatalf("errored: %v", err) + } + if !proof.Proven || len(proof.Findings) != 0 { + t.Fatalf("= proven %v findings %+v, want proven with none", proof.Proven, proof.Findings) + } + } + + t.Run("merged-into-parent-content-dropped", func(t *testing.T) { + if _, err := tryGit(f.repo.invocation, "cat-file", "-e", mcDropped); err != nil { + t.Fatalf("the source merge object must exist to pin a drop (not a missing object): %v", err) + } + proof, err := run(carryFake(f.head, "feat/widget", mcDropped), tgtDropped) + if err != nil { + t.Fatalf("content-dropped row errored: %v", err) + } + if proof.Proven || len(proof.Findings) != 1 { + t.Fatalf("content-dropped row = proven %v findings %+v, want unproven with one finding", proof.Proven, proof.Findings) + } + fd := proof.Findings[0] + if fd.Code != ReasonCarryUnproven { + t.Errorf("finding code = %q, want %q", fd.Code, ReasonCarryUnproven) + } + for _, want := range []string{CarryFindingUnpreserved, childID, mcDropped} { + if !strings.Contains(fd.Message, want) { + t.Errorf("finding does not name %q:\n%s", want, fd.Message) + } + } + }) + + t.Run("merged-into-parent-preserved", func(t *testing.T) { + proof, err := run(carryFake(f.head, "feat/widget", mcAnc), tgtAnc) + assertProvenNone(t, proof, err) + }) + + t.Run("merged-to-main-not-carried", func(t *testing.T) { + // Retargeted and merged to main: not the parent's to carry, so the dropped + // content against the target is never examined. + proof, err := run(carryFake(f.head, "main", mcDropped), tgtDropped) + assertProvenNone(t, proof, err) + }) + + t.Run("not-merged-pr-not-carried", func(t *testing.T) { + // #8 is not merged: an implemented child is simply not carried — never a + // relationship refusal the way an unconfirmed stacked-merged child is. + gh := &fakeCloseoutGitHub{repo: retargetRepo(), merged: map[int]closeoutProbe{}} + proof, err := run(gh, tgtDropped) + assertProvenNone(t, proof, err) + if gh.probes != 1 { + t.Fatalf("probes = %d, want 1: the child must be looked up, then dropped", gh.probes) + } + }) +} diff --git a/internal/app/finalize_rebase_integration_test.go b/internal/app/finalize_rebase_integration_test.go index 0fc20dd18..028153bae 100644 --- a/internal/app/finalize_rebase_integration_test.go +++ b/internal/app/finalize_rebase_integration_test.go @@ -1297,9 +1297,17 @@ func (f *fakeRebaseCarryGitHub) MergePullRequest(context.Context, githubcli.Repo // stacked on the rebase fixture's parent (id 5) onto the metadata branch, so the // snapshot the rebase reads promises to carry the child's merged work. func seedRebaseCarryChild(t *testing.T, f *rebaseFixture) { + t.Helper() + seedRebaseCarryChildAt(t, f, "stacked-merged") +} + +// seedRebaseCarryChildAt seeds the same descendant at the given lifecycle +// status. An "implemented" child is carried only when its PR merged into the +// parent's branch, so the scripted facts decide whether it is promised. +func seedRebaseCarryChildAt(t *testing.T, f *rebaseFixture, status string) { t.Helper() recPath := groomPath(6, "gadget") - desc := closeoutRecord(6, "gadget", "stacked-merged", "github.com/acme/widget#8", "", + desc := closeoutRecord(6, "gadget", status, "github.com/acme/widget#8", "", "docs/superpowers/plans/2026-08-16-gadget-plan.md", "") desc = strings.Replace(desc, "stacked_on:\n", "stacked_on: 5\n", 1) f.repo.writerAdvance(t, f.branch, map[string]string{recPath: desc}) @@ -1372,6 +1380,37 @@ func TestIntegrationFinalizeRebaseRecoveryCarryPreservation(t *testing.T) { } }) + t.Run("pre-rewrite-refusal-implemented-merged-child", func(t *testing.T) { + // An implemented child whose PR merged into the parent's branch is carried + // even though its own closeout never ran: a dropped merge refuses the same way. + f := setupRebaseFixture(t, main) + seedRebaseCarryChildAt(t, f, "implemented") + dropped := carryDroppedCommit(t, f, map[string]string{"catalog.yaml": "Y\n"}) + if _, err := tryGit(f.repo.invocation, "cat-file", "-e", dropped); err != nil { + t.Fatalf("the child merge object must exist to pin a drop (not a missing object): %v", err) + } + gh := &fakeRebaseCarryGitHub{ + repo: retargetRepo(), + prs: []githubcli.PullRequest{f.prForHead(f.head, "")}, + merged: map[int]closeoutProbe{8: {outcome: githubcli.MergeAlreadyMerged, facts: mergedFactsFor(f.head, "feat/widget", dropped)}}, + } + remoteBefore := originTip(t, f.repo.origin, "feat/"+f.slug) + res := FinalizeRebase(ctx, f.finalizeDeps(gh, &fakeGate{}), f.repo.invocation, + FinalizeRebaseRequest{ID: f.id, Revision: f.revision, Head: f.head}) + + assertRebaseRefused(t, res, ResultBlocked, ReasonCarryUnproven) + if len(res.Findings) == 0 { + t.Errorf("a carry refusal carried no findings naming the unproven descendant") + } + f.receiptAbsent(t) + if f.localHead() != f.head { + t.Errorf("a pre-rewrite carry refusal moved the workspace head: %q -> %q", f.head, f.localHead()) + } + if after := originTip(t, f.repo.origin, "feat/"+f.slug); after != remoteBefore { + t.Errorf("a pre-rewrite carry refusal touched the remote feature ref: %q -> %q", remoteBefore, after) + } + }) + t.Run("pre-rewrite-pass-through-when-carry-preserved", func(t *testing.T) { f := setupRebaseFixture(t, main) seedRebaseCarryChild(t, f) diff --git a/internal/app/finalize_state_integration_test.go b/internal/app/finalize_state_integration_test.go index 661ed6e0f..9e464242d 100644 --- a/internal/app/finalize_state_integration_test.go +++ b/internal/app/finalize_state_integration_test.go @@ -736,6 +736,46 @@ func TestIntegrationFinalizeStatePublishCarriedDescendant(t *testing.T) { } }) + t.Run("implemented-merged-child-dropped-refuses-before-rewrite", func(t *testing.T) { + // An implemented child merged into the parent's branch is carried even + // though its own closeout never ran: a dropped merge refuses the publish. + f := setupPublishFixture(t, m) + remoteBefore := f.remoteFeatureTip(t) + if remoteBefore != f.origHead { + t.Fatalf("precondition: remote tip = %q, want the original pre-rewrite head", remoteBefore) + } + seedRebaseCarryChildAt(t, f.rebaseFixture, "implemented") + dropped := carryDroppedCommit(t, f.rebaseFixture, map[string]string{"catalog.yaml": "Y\n"}) + if _, err := tryGit(f.repo.invocation, "cat-file", "-e", dropped); err != nil { + t.Fatalf("the child merge object must exist to pin a drop (not a missing object): %v", err) + } + gh := &fakePublishCarryGitHub{ + fakePublishGitHub: &fakePublishGitHub{repo: retargetRepo(), pr: f.openPRForPublish(f.rewritten, authoredPRBody(t, f.origHead))}, + merged: map[int]closeoutProbe{8: {outcome: githubcli.MergeAlreadyMerged, facts: mergedFactsFor(f.rewritten, "feat/widget", dropped)}}, + } + witness := &publishRewriteWitness{FinalizeWorkspace: f.svc} + deps := FinalizeDeps{Planning: f.deps, GitHub: gh, Workspace: witness} + _, evBytes := recFor(t, f.rewritten) + res := FinalizePublish(ctx, deps, f.repo.invocation, + FinalizePublishRequest{ID: f.id, Attempt: f.attempt, Head: f.rewritten, EvidenceRecord: evBytes}) + + if res.Result != ResultBlocked || res.Reason != ReasonCarryUnproven { + t.Fatalf("refusal = (%q, %q), want (%q, %q) [disp %q msg %q]", res.Result, res.Reason, ResultBlocked, ReasonCarryUnproven, res.Disposition, res.Message) + } + if res.Disposition != PublishDispBlocked { + t.Errorf("disposition = %q, want %q", res.Disposition, PublishDispBlocked) + } + if len(res.Findings) == 0 { + t.Errorf("a carry refusal carried no findings naming the unproven descendant") + } + if witness.calls != 0 { + t.Errorf("PublishRewrite ran %d time(s) on a carry refusal; want 0 (gate must precede the rewrite)", witness.calls) + } + if after := f.remoteFeatureTip(t); after != remoteBefore { + t.Errorf("a carry refusal touched the remote feature ref: %q -> %q", remoteBefore, after) + } + }) + t.Run("preserved-carry-publishes-and-fires-the-rewrite-witness", func(t *testing.T) { f := setupPublishFixture(t, m) seedRebaseCarryChild(t, f.rebaseFixture) diff --git a/internal/app/schema_vocab.go b/internal/app/schema_vocab.go index 1b7f238ae..c67234291 100644 --- a/internal/app/schema_vocab.go +++ b/internal/app/schema_vocab.go @@ -111,7 +111,7 @@ func SchemaVocabularies(effects []string) map[string]Vocabulary { }} v["closeout_dispositions"] = Vocabulary{Members: []string{ CloseoutDispDoneArchived, CloseoutDispStackedMerged, CloseoutDispRootArchived, - CloseoutDispAlready, CloseoutDispChildrenRetargetRequired, CloseoutDispContended, + CloseoutDispAlready, CloseoutDispContended, CloseoutDispBlocked, CloseoutDispUnknown, CloseoutDispFailed, }} v["merge_dispositions"] = Vocabulary{Members: []string{ diff --git a/internal/assets/embedded/manifest.json b/internal/assets/embedded/manifest.json index 09aa3e9a1..8f7e535ad 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:a387c735fef0b4929c67ec26af4ab7fe77364cf46cbdbcd02a16f2c08a184f32", + "asset_set_id": "sha256:9655f89087fb84ac2de7852c2c09408ec7636be9f76c084c4708e905c8947dce", "entries": [ { "path": ".docket.example.yml", @@ -350,22 +350,22 @@ "path": "skills/docket-convention/references/stacked-changes.md", "role": "skill", "mode": 420, - "size": 14498, - "sha256": "790b7ec65307eca34084a2e69b9744189100adca63a02a4a8eb1c78b4d3472e0" + "size": 14893, + "sha256": "6ee36fdb39e1fc16cf8088e3aca841c2d2b3ed49e6ec8e1e0aafaecc27bb0724" }, { "path": "skills/docket-finalize-change/SKILL.md", "role": "skill", "mode": 420, - "size": 43431, - "sha256": "771e9b70d3c2b93794178ae2d0e4b406f4822a461b85bc2a0b7b3d32bef95c67" + "size": 43498, + "sha256": "c8c0b0eb5033ca12dc69fb4d7411671e188aef9cf14e0d408a38c606aa4ffb63" }, { "path": "skills/docket-finalize-change/references/gate-failure.md", "role": "skill", "mode": 420, - "size": 14832, - "sha256": "7f531866048e6275c2c80097f9970f5d9224e4b04c2d552f6f85c2e36059c668" + "size": 14788, + "sha256": "77fc6724a62efdc7295a47e7590652afa128d6aa4514b51395cf931da8c09e12" }, { "path": "skills/docket-groom-next/SKILL.md", @@ -385,8 +385,8 @@ "path": "skills/docket-implement-next/references/edge-paths.md", "role": "skill", "mode": 420, - "size": 8662, - "sha256": "08c96bffc603a732a674e361e70b645b98b5ae1752520372027215446eaf2667" + "size": 8704, + "sha256": "a83e24ce2559df496643b2c79956cec0115a8b6c00768754335fb39ea168f930" }, { "path": "skills/docket-implement-next/references/fix-pass.md", diff --git a/internal/assets/embedded/tree/skills/docket-convention/references/stacked-changes.md b/internal/assets/embedded/tree/skills/docket-convention/references/stacked-changes.md index 2a2dad783..a0e0a317c 100644 --- a/internal/assets/embedded/tree/skills/docket-convention/references/stacked-changes.md +++ b/internal/assets/embedded/tree/skills/docket-convention/references/stacked-changes.md @@ -59,7 +59,8 @@ What it does **not** satisfy: The merge sweep (the `maintenance.sweep` operation) is the only producer of the state; the typed finalize close-out (the `finalize.closeout` operation's `root-archived` disposition) is the only consumer that takes -a change out of it, when the stack root reaches integration. See *The stack close-out is idempotent* +a change out of it, when the stack root reaches integration. That same root close-out also takes an +`implemented` child whose PR merged into its parent's branch straight to `done`. See *The stack close-out is idempotent* below. ## Resolving the base — `context.implementation` effective-base @@ -191,15 +192,18 @@ proposed one reads *stack parent #A killed — re-parent, un-stack, or kill*. It ## The stack close-out is idempotent When a stack **root** merges, the typed close-out — the `finalize.closeout` operation's **`root-archived`** -disposition — archives the root and every carried `stacked-merged` descendant to `done` in **one +disposition — archives the root and every carried descendant to `done` in **one transaction**, all under the **root's** merge date, and renders the root's marker-bounded **Stack carried** table on the root's archived record. A descendant counts as *carried* only when **both** -hold: its merged PR destinations establish the carry **relationship** into the root, **and** its work -is proven still present in Git — reachable in the pinned integration history, or exact-content at the +hold: its PR merged into its parent's branch (it reads `stacked-merged`, or still `implemented` +because its own close-out never ran), down an unbroken chain of such links from the root, **and** its +work is proven still present in Git — reachable in the pinned integration history, or exact-content at the root's merge result. A merged destination alone is only a relationship: a stale-worktree rebase can drop a descendant's work while every record still reads merged, so the Git carry is the promotion condition. One unproven descendant leaves the root recoverable with zero descendant writes -(fail-closed). +(fail-closed). A child in any other state — an open or retargeted PR, not yet built, killed, already +`done` — is not carried, never blocks the root, and is left alone; a child beneath it waits for its +own parent. Finalize and the sweep then clean each carried child's folder and branches right after the root's, once cleanup proves the child's work reached the integration branch. Until then the child keeps @@ -214,8 +218,8 @@ permanently. The transaction gates on the root actually carrying descendants, so pays nothing. The archive date is the root's `mergedAt` in **UTC**, derived inside the transaction, never `now()`, -so a re-run reuses the same descendant filenames. Route on the typed `disposition`: `root-archived` (every descendant proven), -`children-retarget-required` (one is not yet `stacked-merged`), or `contended`/`blocked`. +so a re-run reuses the same descendant filenames. Route on the typed `disposition`: `done-archived` (nothing carried), +`root-archived` (every carried descendant proven), or `contended`/`blocked`/`unknown`. Re-running it is the designed recovery from a partial pass: an `already-closed-out` disposition replays a response-lost success as a keyed no-op, keyed on the descendant already being **archived on the diff --git a/internal/assets/embedded/tree/skills/docket-finalize-change/SKILL.md b/internal/assets/embedded/tree/skills/docket-finalize-change/SKILL.md index d37088f36..82215a28f 100644 --- a/internal/assets/embedded/tree/skills/docket-finalize-change/SKILL.md +++ b/internal/assets/embedded/tree/skills/docket-finalize-change/SKILL.md @@ -164,9 +164,8 @@ UTC archive date from the verified `mergedAt`, and applies one atomic transactio - `done-archived` — an ordinary change merged to the integration branch: marked `done` (only after the merge-commit reachability proof), relocated to the dated archive path, artifact block + spec, plan, and results backlinks + inline board rerendered, validated, committed by explicit path, lease-pushed. Then, outside that transaction, a best-effort follow-up repoints the merged PR's backlink at the archived record. - `stacked-merged` — the PR merged into a live parent's branch: marked `stacked-merged` in place, not archived, branch and workspace retained until the root lands. -- `root-archived` — a stack root reached integration and every carried descendant is proven: its chain of merged PR destinations establishes the carry relationship AND its merged work is verified still present in Git — reachable in the pinned integration history, or exact-content at the root's merge result — since a merged destination alone is a relationship, never proof the content shipped. One transaction archives the root and every descendant using the root's merge date, one board render over the final population. One unproven descendant leaves the root recoverable, zero descendant writes. The same follow-up then repoints the root's and each descendant's PR. +- `root-archived` — a stack root reached integration and every carried descendant is proven. A descendant is carried only when its PR merged into its parent's branch, whether it reads `stacked-merged` or still `implemented`; any other child is left alone and never blocks the root. Proof: its chain of merged PR destinations establishes the carry relationship AND its merged work is verified still present in Git — reachable in the pinned integration history, or exact-content at the root's merge result — since a merged destination alone is a relationship, never proof the content shipped. One transaction archives the root and every descendant using the root's merge date, one board render over the final population. One unproven descendant leaves the root recoverable, zero descendant writes. The same follow-up then repoints the root's and each descendant's PR. - `already-closed-out` — the promised final state already exists (a response-lost success): a keyed no-op, never a duplicate transition. -- `children-retarget-required` — a descendant is not yet stacked-merged; return to step 2 (attended) or `halted` (autonomous). - `contended` / `blocked` / `unknown` — a lost race, an illegal source status or destination mismatch, or an unobservable probe; re-read context (`contended`) or stop (`halted`). Close-out is one metadata commit plus the best-effort PR-description backlink repoint; nothing touches the integration branch. A PR description that could not be repointed is a `pr-backlink-pending` warning on an otherwise-final result: report it, never redo the merge; cleanup (step 10) and the maintenance sweep retry it. ### 10. Cleanup — Docket-owned resources only diff --git a/internal/assets/embedded/tree/skills/docket-finalize-change/references/gate-failure.md b/internal/assets/embedded/tree/skills/docket-finalize-change/references/gate-failure.md index 52e3c46c0..a8f318e6c 100644 --- a/internal/assets/embedded/tree/skills/docket-finalize-change/references/gate-failure.md +++ b/internal/assets/embedded/tree/skills/docket-finalize-change/references/gate-failure.md @@ -92,7 +92,7 @@ Two outcomes look abort-shaped and are not: a `waiting` (`reason: gate-waiting`) - a **merge condition that fails at the fresh recheck** or an authoritatively **denied** merge — the `finalize.merge` operation returns the condition's token or `merge-denied`; a standing denial is `halted`, never retried; -- an **open unauthorized child** on an autonomous run, or a `children-retarget-required` closeout; +- an **open unauthorized child** on an autonomous run; - the **dispatch mechanism being unavailable** for either gate agent — the `no-fallback` posture, established only per the convention's *Dispatch-capability resolution*, never from a tool name, and never substituted inline; 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 e39198644..1f1804122 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 @@ -26,8 +26,8 @@ never widen or recurse beyond this set. Map each envelope locally and key succes An unrelated change's closeout is never attempted here, and a dependency unmet for any non-`implemented` reason keeps its ordinary local refusal unchanged. A `not-ready-stack-base-unresolved` refusal is never a closeout trigger and keeps its ordinary local -refusal: an ancestor's closeout cannot prove the carry of a named change not yet `stacked-merged` -(`children-retarget-required`). +refusal: the bounded closeout covers only the named change's own `depends_on` set, and an +unresolved stack base clears through the parent's own finalize or the next sweep. ## Reconcile-kill (Step 3, change OBSOLETE) diff --git a/internal/domain/stackcloseout.go b/internal/domain/stackcloseout.go index 1de9c347d..32b39bd93 100644 --- a/internal/domain/stackcloseout.go +++ b/internal/domain/stackcloseout.go @@ -1,23 +1,23 @@ package domain -// CarriedDescendant is one stacked descendant's share of a root closeout. Proof -// is empty when the descendant's carry RELATIONSHIP into the root is -// established — an unbroken chain of merged PR destinations matching the recorded -// parent branches; otherwise it is a closed refusal token naming the first broken -// link. A merged-destination chain proves that relationship only: that the code -// actually survived into the carrying head is proven separately, in Git, by the -// caller. The descendant is always surfaced — a refusal is reported, never -// dropped — so the caller can keep the whole root recoverable. +// CarriedDescendant is one stacked descendant a parent carries. A parent +// carries exactly the children whose pull requests merged into its recorded +// branch, transitively: a child is carried when its status is stacked-merged or +// implemented and its live PR facts show a merge whose base is its parent's +// recorded branch. Proof is empty when that carry RELATIONSHIP is established; +// otherwise it is a closed refusal token naming why a purported carried link +// could not be confirmed. A merged destination proves the relationship only: +// that the code actually survived into the carrying head or the integration +// branch is proven separately, in Git, by the caller. A refusal is reported, +// never dropped, so the caller can keep the whole parent recoverable. type CarriedDescendant struct { ID ChangeID Proof string // "" when proven; else closed refusal token } -// The closed set of root-closeout refusal tokens a CarriedDescendant.Proof -// carries. Each names exactly why one descendant's carry into the root could -// not be proven. +// The closed set of carry refusal tokens a CarriedDescendant.Proof or +// ProveDoneCarry returns. Each names exactly why one carry could not be proven. const ( - carryNotStackedMerged = "not-stacked-merged" // the descendant itself is not stacked-merged carryNotDone = "not-done" // a cleanup start record is not done carryDestinationMismatch = "destination-mismatch" // a merged PR landed on the wrong branch carryPRUnknown = "pr-unknown" // a carrying merge cannot be confirmed @@ -26,22 +26,19 @@ const ( carryKilledAncestor = "killed-ancestor" // a killed change sits on the carry chain ) -// DeriveRootCloseoutSet verifies, for every change stacked transitively on root, -// the chain of merged pull-request destinations that establishes its -// stacked-merged code's carry RELATIONSHIP up into the root. A merged destination -// proves that relationship only; that the code was actually preserved in Git — -// reachable in the pinned integration history, or exact-content at the root's own -// merge result — is the caller's separate obligation before any archive write. -// The returned slice is parent-first (StackDescendantsParentFirst -// order); each entry's Proof is empty when proven or a closed refusal token -// otherwise. facts supplies each change's live PR state; a missing or unknown -// entry is treated as an unconfirmable merge (pr-unknown), never a clean carry. +// DeriveRootCloseoutSet is the carried set a landed root's closeout archives +// with it: exactly DeriveCarriedSet's answer for root, so closeout and the +// live-branch boundaries (rebase, publish, merge) share one carry rule. A child +// the root does not carry never blocks the root's closeout. A merged destination +// proves the carry relationship only; that each carried child's code was +// actually preserved on the integration branch is the caller's separate +// obligation before any archive write. // // The *PolicyFailure return is reserved for a structural problem with the root // argument itself — an absent or ambiguous record — and is nil once the root -// resolves, in which case every per-descendant outcome travels through Proof. -// The derivation reads only the stacked_on graph and injected PR facts: a -// rendered relation (branch name, board table) never promotes a descendant. +// resolves. A root whose own stacked_on ancestry cycles has no clean base to +// carry into, so every descendant (StackDescendantsParentFirst order) refuses +// with cycle; otherwise every per-descendant outcome travels through Proof. func DeriveRootCloseoutSet(s Snapshot, root ChangeID, facts map[ChangeID]PRFacts) ([]CarriedDescendant, *PolicyFailure) { rootChange, out := s.Change(root) switch out { @@ -51,24 +48,16 @@ func DeriveRootCloseoutSet(s Snapshot, root ChangeID, facts map[ChangeID]PRFacts return nil, &PolicyFailure{Kind: FailInvalidInput, Change: root, Reason: "root-ambiguous"} } - descendants := StackDescendantsParentFirst(s, root) - set := make([]CarriedDescendant, 0, len(descendants)) - - // A root whose own stacked_on ancestry cycles has no clean base to carry - // into: every descendant refuses with cycle rather than the derivation - // looping. The check reuses the visited-set cycle-guard idiom from - // StackDescendantsParentFirst. if rootAncestryCycles(s, rootChange) { + descendants := StackDescendantsParentFirst(s, root) + set := make([]CarriedDescendant, 0, len(descendants)) for _, id := range descendants { set = append(set, CarriedDescendant{ID: id, Proof: carryCycle}) } return set, nil } - for _, id := range descendants { - set = append(set, CarriedDescendant{ID: id, Proof: proveCarry(s, root, id, facts)}) - } - return set, nil + return DeriveCarriedSet(s, root, facts) } // RootCloseoutProven reports whether every carried descendant is proven. It is @@ -84,16 +73,27 @@ func RootCloseoutProven(set []CarriedDescendant) bool { return true } -// DeriveCarriedSet selects, for a LIVE carrying change (a branch about to be -// rewritten, published, or merged), every descendant whose stacked-merged code -// that branch currently PROMISES to carry: children connected by an unbroken -// chain of stacked-merged changes whose verified PR destinations match their -// recorded parent branches. It stops descending into an open intermediate -// child — grandchildren merged into a still-open child are not yet promised by -// this branch. A purported carried link (a stacked-merged child) with unknown -// or mismatched facts is surfaced with a refusal token, never omitted. -// A merged PR destination proves a RELATIONSHIP only; Git preservation of the -// content is the caller's separate obligation. +// DeriveCarriedSet selects every descendant parent carries: the children whose +// pull requests merged into parent's recorded branch, transitively. It is the +// one carry rule rebase, publish, merge, and root closeout share. A child is +// carried when its live PR facts show a merge whose base is its parent's +// recorded branch and its status is either +// +// - stacked-merged: its own closeout recorded the merge. Because that status +// claims a carry, a stacked-merged child whose facts are missing or unmerged +// is surfaced with pr-unknown, and one whose merge landed elsewhere (or whose +// parent records no branch) with destination-mismatch — never omitted. +// - implemented: the merge happened but the child's own closeout never ran. +// Merging into the parent's branch is the test, so any other PR state, or no +// usable PR at all, just means "not carried": no entry and no token. +// +// Any other status is not carried. The walk is parent-first (pre-order depth +// first) and descends through carried children only: grandchildren beneath a +// child that is not carried are not this parent's to carry, and neither appear +// nor block. The walk reads only the stacked_on graph and the injected PR +// facts: a rendered relation (branch name, board table) never promotes a +// descendant. A merged PR destination proves a RELATIONSHIP only; Git +// preservation of the content is the caller's separate obligation. // // The *PolicyFailure return is reserved for a structural problem with the // parent argument itself — an absent or ambiguous record — and is nil once the @@ -124,23 +124,34 @@ func DeriveCarriedSet(s Snapshot, parent ChangeID, facts map[ChangeID]PRFacts) ( set = append(set, CarriedDescendant{ID: cid, Proof: carryChainBroken}) continue } - if c.Status() != StatusStackedMerged { - // An open or final child claims no carry for this parent - // branch; grandchildren beneath it are not descended. - continue - } - token := "" f, ok := facts[cid] branch := p.Branch() - switch { - case !ok || f.State != prStateMerged: - token = carryPRUnknown - case branch.State != FieldPresent || branch.Value == "" || f.BaseRef != branch.Value: - token = carryDestinationMismatch - } - set = append(set, CarriedDescendant{ID: cid, Proof: token}) - if token == "" { + switch c.Status() { + case StatusStackedMerged: + token := "" + switch { + case !ok || f.State != prStateMerged: + token = carryPRUnknown + case branch.State != FieldPresent || branch.Value == "" || f.BaseRef != branch.Value: + token = carryDestinationMismatch + } + set = append(set, CarriedDescendant{ID: cid, Proof: token}) + if token == "" { + walk(c) + } + case StatusImplemented: + if !ok || f.State != prStateMerged || + branch.State != FieldPresent || branch.Value == "" || f.BaseRef != branch.Value { + // Not merged into this parent's branch: not carried, and + // grandchildren beneath it are not descended. + continue + } + set = append(set, CarriedDescendant{ID: cid}) walk(c) + default: + // An open or final child claims no carry for this parent + // branch; grandchildren beneath it are not descended. + continue } } } @@ -148,32 +159,16 @@ func DeriveCarriedSet(s Snapshot, parent ChangeID, facts map[ChangeID]PRFacts) ( return set, nil } -// proveCarry proves that id's stacked-merged code is carried into the closeout -// root: the start must itself be stacked-merged, and walkCarryChain must reach -// root through stacked-merged intermediates. It returns the empty string when -// the chain reaches root cleanly, or the first refusal token otherwise. -func proveCarry(s Snapshot, root, id ChangeID, facts map[ChangeID]PRFacts) string { - start, out := s.Change(id) - if out != LookupFound { - return carryChainBroken - } - if start.Status() != StatusStackedMerged { - return carryNotStackedMerged - } - _, token := walkCarryChain(s, start, facts, StatusStackedMerged, func(parent Change) bool { - return parent.ID() == root - }) - return token -} - // ProveDoneCarry proves the carry RELATIONSHIP of a done change whose PR merged -// into its stack parent's branch rather than the integration branch: the same -// walk closeout uses (walkCarryChain), applied to a population that is now done -// rather than stacked-merged. Every link must be done, and the walk ends at the -// first done ancestor whose own PR merged into integration — the stack root, -// whose id is returned with an empty token. Any other outcome returns a zero -// root and the first refusal token: not-done when the start is not done, -// chain-broken when it is absent or the walk never meets such an ancestor. +// into its stack parent's branch rather than the integration branch, climbing +// its stacked_on chain with walkCarryChain. Once a root's closeout has archived +// everything it carried, each carried child is done with a PR merged into its +// parent's branch, which is the population this walk expects. Every link must +// be done, and the walk ends at the first done ancestor whose own PR merged +// into integration — the stack root, whose id is returned with an empty token. +// Any other outcome returns a zero root and the first refusal token: not-done +// when the start is not done, chain-broken when it is absent or the walk never +// meets such an ancestor. // // facts supplies each change's live PR state; a missing or unmerged entry is an // unconfirmable link, never a clean carry. A merged destination proves the @@ -196,11 +191,12 @@ func ProveDoneCarry(s Snapshot, id ChangeID, facts map[ChangeID]PRFacts, integra }) } -// walkCarryChain is the one stack carry walk closeout and cleanup share. It -// climbs start's stacked_on chain, verifying at each link that no node is -// revisited (cycle), the parent resolves (chain-broken), the parent is not -// killed (killed-ancestor), the current node's PR is merged (pr-unknown), and -// that merge landed on the parent's recorded branch (destination-mismatch). +// walkCarryChain is the upward carry walk ProveDoneCarry uses for cleanup; +// closeout, rebase, publish, and merge walk downward with DeriveCarriedSet +// instead. It climbs start's stacked_on chain, verifying at each link that no +// node is revisited (cycle), the parent resolves (chain-broken), the parent is +// not killed (killed-ancestor), the current node's PR is merged (pr-unknown), +// and that merge landed on the parent's recorded branch (destination-mismatch). // When isRoot accepts the parent, the walk returns its id with an empty token; // otherwise the parent must itself carry linkStatus — an intermediate carried // link — or the chain has a gap (chain-broken). On any refusal the returned id diff --git a/internal/domain/stackcloseout_test.go b/internal/domain/stackcloseout_test.go index bc95b7759..1a459710a 100644 --- a/internal/domain/stackcloseout_test.go +++ b/internal/domain/stackcloseout_test.go @@ -77,17 +77,6 @@ func TestDeriveRootCloseoutSetRefusals(t *testing.T) { check ChangeID reason string }{ - { - name: "descendant still in-progress is not-stacked-merged", - specs: []stackSpec{ - {id: 1, status: StatusImplemented, branch: "feat/1"}, - {id: 2, status: StatusInProgress, parent: parentEdge(1), branch: "feat/2"}, - }, - facts: map[ChangeID]PRFacts{2: mergedInto("feat/1")}, - root: 1, - check: 2, - reason: "not-stacked-merged", - }, { name: "merged into the wrong branch is destination-mismatch", specs: []stackSpec{ @@ -121,21 +110,6 @@ func TestDeriveRootCloseoutSetRefusals(t *testing.T) { check: 2, reason: "pr-unknown", }, - { - name: "a gap mid-chain is chain-broken for the node below it", - specs: []stackSpec{ - {id: 1, status: StatusImplemented, branch: "feat/1"}, - {id: 2, status: StatusInProgress, parent: parentEdge(1), branch: "feat/2"}, - {id: 3, status: StatusStackedMerged, parent: parentEdge(2), branch: "feat/3"}, - }, - facts: map[ChangeID]PRFacts{ - 2: mergedInto("feat/1"), - 3: mergedInto("feat/2"), - }, - root: 1, - check: 3, - reason: "chain-broken", - }, { name: "a cyclic stacked_on graph refuses with cycle and does not loop", specs: []stackSpec{ @@ -147,21 +121,6 @@ func TestDeriveRootCloseoutSetRefusals(t *testing.T) { check: 2, reason: "cycle", }, - { - name: "a killed ancestor mid-chain is killed-ancestor", - specs: []stackSpec{ - {id: 1, status: StatusImplemented, branch: "feat/1"}, - {id: 2, status: StatusKilled, parent: parentEdge(1), branch: "feat/2"}, - {id: 3, status: StatusStackedMerged, parent: parentEdge(2), branch: "feat/3"}, - }, - facts: map[ChangeID]PRFacts{ - 2: mergedInto("feat/1"), - 3: mergedInto("feat/2"), - }, - root: 1, - check: 3, - reason: "killed-ancestor", - }, } for _, tc := range tests { @@ -181,6 +140,245 @@ func TestDeriveRootCloseoutSetRefusals(t *testing.T) { } } +// carryFixture is one stack shape rooted at change 1 plus the live PR facts its +// carry derivation reads. +type carryFixture struct { + name string + specs []stackSpec + facts map[ChangeID]PRFacts +} + +// nonCarriedChildFixtures are the shapes in which root 1's only child (2) is +// not carried: it is neither stacked-merged nor an implemented change whose PR +// merged into the root's recorded branch. +func nonCarriedChildFixtures() []carryFixture { + child := func(name string, status Status, facts map[ChangeID]PRFacts) carryFixture { + return carryFixture{ + name: name, + specs: []stackSpec{ + {id: 1, status: StatusImplemented, branch: "feat/1"}, + {id: 2, status: status, parent: parentEdge(1), branch: "feat/2"}, + }, + facts: facts, + } + } + mergedFacts := func() map[ChangeID]PRFacts { return map[ChangeID]PRFacts{2: mergedInto("feat/1")} } + return []carryFixture{ + child("in-progress child", StatusInProgress, mergedFacts()), + child("proposed child", StatusProposed, mergedFacts()), + child("blocked child", StatusBlocked, mergedFacts()), + child("deferred child", StatusDeferred, mergedFacts()), + child("killed child", StatusKilled, mergedFacts()), + child("done child", StatusDone, mergedFacts()), + child("implemented child with no PR", StatusImplemented, map[ChangeID]PRFacts{}), + child("implemented child with an unmerged PR", StatusImplemented, + map[ChangeID]PRFacts{2: {State: "closed", Number: "8"}}), + child("implemented child merged into main", StatusImplemented, + map[ChangeID]PRFacts{2: mergedInto("main")}), + child("implemented child with an unknown-state probe", StatusImplemented, + map[ChangeID]PRFacts{2: {State: "unknown", BaseRef: "feat/1"}}), + } +} + +// openChildStopsDescentFixtures stack a stacked-merged grandchild (3) merged +// into child 2's branch, beneath a child 2 that root 1 does not carry. +func openChildStopsDescentFixtures() []carryFixture { + shape := func(name string, status Status, childFacts PRFacts) carryFixture { + return carryFixture{ + name: name, + specs: []stackSpec{ + {id: 1, status: StatusImplemented, branch: "feat/1"}, + {id: 2, status: status, parent: parentEdge(1), branch: "feat/2"}, + {id: 3, status: StatusStackedMerged, parent: parentEdge(2), branch: "feat/3"}, + }, + facts: map[ChangeID]PRFacts{2: childFacts, 3: mergedInto("feat/2")}, + } + } + return []carryFixture{ + shape("in-progress child", StatusInProgress, mergedInto("feat/1")), + shape("killed child", StatusKilled, mergedInto("feat/1")), + shape("implemented child merged into main", StatusImplemented, mergedInto("main")), + } +} + +// implementedMergedChildFixture is root 1 with an implemented child (2) whose +// PR merged into the root's recorded branch but whose own closeout never ran. +func implementedMergedChildFixture() carryFixture { + return carryFixture{ + name: "implemented child merged into the root's branch", + specs: []stackSpec{ + {id: 1, status: StatusImplemented, branch: "feat/1"}, + {id: 2, status: StatusImplemented, parent: parentEdge(1), branch: "feat/2"}, + }, + facts: map[ChangeID]PRFacts{2: mergedInto("feat/1")}, + } +} + +// chainThroughImplementedMiddleFixture alternates implemented and +// stacked-merged links, each merged into its parent's recorded branch. +func chainThroughImplementedMiddleFixture() carryFixture { + return carryFixture{ + name: "chain through an implemented middle", + specs: []stackSpec{ + {id: 1, status: StatusImplemented, branch: "feat/1"}, + {id: 2, status: StatusImplemented, parent: parentEdge(1), branch: "feat/2"}, + {id: 3, status: StatusStackedMerged, parent: parentEdge(2), branch: "feat/3"}, + {id: 4, status: StatusImplemented, parent: parentEdge(3), branch: "feat/4"}, + }, + facts: map[ChangeID]PRFacts{ + 2: mergedInto("feat/1"), + 3: mergedInto("feat/2"), + 4: mergedInto("feat/3"), + }, + } +} + +func TestDeriveRootCloseoutSetNonCarriedChildrenDoNotBlock(t *testing.T) { + for _, fx := range nonCarriedChildFixtures() { + t.Run(fx.name, func(t *testing.T) { + set, fail := DeriveRootCloseoutSet(stackSnapshot(fx.specs...), 1, fx.facts) + if fail != nil { + t.Fatalf("policy failure %+v; want nil", fail) + } + if len(set) != 0 { + t.Fatalf("carried set = %+v; want empty (a child that is not carried never blocks the root)", set) + } + if !RootCloseoutProven(set) { + t.Fatalf("RootCloseoutProven = false; want true") + } + }) + } +} + +func TestDeriveRootCloseoutSetOpenChildStopsDescent(t *testing.T) { + // A stacked-merged grandchild merged into a child the root does not carry + // is that child's to carry, not the root's: it is neither carried nor a + // blocker for the root. + for _, fx := range openChildStopsDescentFixtures() { + t.Run(fx.name, func(t *testing.T) { + set, fail := DeriveRootCloseoutSet(stackSnapshot(fx.specs...), 1, fx.facts) + if fail != nil { + t.Fatalf("policy failure %+v; want nil", fail) + } + if len(set) != 0 { + t.Fatalf("carried set = %+v; want empty (descent stops at a child that is not carried)", set) + } + if !RootCloseoutProven(set) { + t.Fatalf("RootCloseoutProven = false; want true") + } + }) + } +} + +func TestDeriveCarriedSetImplementedMergedChildIsCarried(t *testing.T) { + fx := implementedMergedChildFixture() + derivations := map[string]func(Snapshot, ChangeID, map[ChangeID]PRFacts) ([]CarriedDescendant, *PolicyFailure){ + "DeriveCarriedSet": DeriveCarriedSet, + "DeriveRootCloseoutSet": DeriveRootCloseoutSet, + } + for name, derive := range derivations { + t.Run(name, func(t *testing.T) { + set, fail := derive(stackSnapshot(fx.specs...), 1, fx.facts) + if fail != nil { + t.Fatalf("policy failure %+v; want nil", fail) + } + if want := []ChangeID{2}; !slices.Equal(idsOf(set), want) { + t.Fatalf("carried ids = %v; want %v", idsOf(set), want) + } + if got := proofOf(set, 2); got != "" { + t.Fatalf("descendant 2 proof = %q; want proven (empty)", got) + } + if !RootCloseoutProven(set) { + t.Fatalf("RootCloseoutProven = false; want true") + } + }) + } +} + +func TestDeriveCarriedSetChainThroughImplementedMiddle(t *testing.T) { + fx := chainThroughImplementedMiddleFixture() + set, fail := DeriveCarriedSet(stackSnapshot(fx.specs...), 1, fx.facts) + if fail != nil { + t.Fatalf("policy failure %+v; want nil", fail) + } + if want := []ChangeID{2, 3, 4}; !slices.Equal(idsOf(set), want) { + t.Fatalf("carried ids = %v; want %v", idsOf(set), want) + } + for _, d := range set { + if d.Proof != "" { + t.Fatalf("descendant %d proof = %q; want proven (empty)", d.ID, d.Proof) + } + } + if !RootCloseoutProven(set) { + t.Fatalf("RootCloseoutProven = false; want true") + } +} + +func TestDeriveCarriedSetImplementedChildUnderBranchlessParentIsNotCarried(t *testing.T) { + // With no recorded parent branch there is no destination to have merged + // into, so even a PR whose base is empty never matches. + s := stackSnapshot( + stackSpec{id: 1, status: StatusImplemented}, + stackSpec{id: 2, status: StatusImplemented, parent: parentEdge(1), branch: "feat/2"}, + ) + set, fail := DeriveCarriedSet(s, 1, map[ChangeID]PRFacts{2: mergedInto("")}) + if fail != nil { + t.Fatalf("policy failure %+v; want nil", fail) + } + if len(set) != 0 { + t.Fatalf("carried set = %+v; want empty (no recorded parent branch)", set) + } +} + +func TestDeriveRootCloseoutSetMatchesCarriedSet(t *testing.T) { + // The drift guard: root closeout and the live-branch boundaries (rebase, + // publish, merge) answer "what does this parent carry" with one rule, so on + // every non-cyclic shape the two derivations agree entry for entry. + fixtures := []carryFixture{ + { + name: "stacked-merged chain", + specs: []stackSpec{ + {id: 1, status: StatusImplemented, branch: "feat/1"}, + {id: 2, status: StatusStackedMerged, parent: parentEdge(1), branch: "feat/2"}, + {id: 3, status: StatusStackedMerged, parent: parentEdge(2), branch: "feat/3"}, + }, + facts: map[ChangeID]PRFacts{2: mergedInto("feat/1"), 3: mergedInto("feat/2")}, + }, + { + name: "stacked-merged child merged into the wrong branch", + specs: []stackSpec{ + {id: 1, status: StatusImplemented, branch: "feat/1"}, + {id: 2, status: StatusStackedMerged, parent: parentEdge(1), branch: "feat/2"}, + }, + facts: map[ChangeID]PRFacts{2: mergedInto("feat/wrong")}, + }, + } + fixtures = append(fixtures, nonCarriedChildFixtures()...) + fixtures = append(fixtures, openChildStopsDescentFixtures()...) + fixtures = append(fixtures, implementedMergedChildFixture(), chainThroughImplementedMiddleFixture()) + + proofsOf := func(set []CarriedDescendant) []string { + out := make([]string, 0, len(set)) + for _, d := range set { + out = append(out, d.Proof) + } + return out + } + for _, fx := range fixtures { + t.Run(fx.name, func(t *testing.T) { + s := stackSnapshot(fx.specs...) + root, rootFail := DeriveRootCloseoutSet(s, 1, fx.facts) + carried, carriedFail := DeriveCarriedSet(s, 1, fx.facts) + if rootFail != nil || carriedFail != nil { + t.Fatalf("policy failures root=%+v carried=%+v; want nil", rootFail, carriedFail) + } + if !slices.Equal(idsOf(root), idsOf(carried)) || !slices.Equal(proofsOf(root), proofsOf(carried)) { + t.Fatalf("DeriveRootCloseoutSet = %+v; DeriveCarriedSet = %+v; want equal", root, carried) + } + }) + } +} + func TestRootCloseoutProvenAllOrNothing(t *testing.T) { if !RootCloseoutProven(nil) { t.Fatalf("RootCloseoutProven(nil) = false; want true (vacuously proven)") @@ -442,8 +640,9 @@ func TestDeriveCarriedSetKilledOrProposedChildContributesNothing(t *testing.T) { } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - // The non-stacked-merged child (2) claims no carry and is not - // descended, so its own stacked-merged grandchild (3) never surfaces. + // A killed or proposed child (2) is never carried, whatever its PR + // facts, and is not descended, so its own stacked-merged grandchild + // (3) never surfaces. s := stackSnapshot( stackSpec{id: 1, status: StatusImplemented, branch: "feat/1"}, stackSpec{id: 2, status: tc.status, parent: parentEdge(1), branch: "feat/2"}, diff --git a/internal/repoguard/budgets_test.go b/internal/repoguard/budgets_test.go index 060acf46d..31288c65f 100644 --- a/internal/repoguard/budgets_test.go +++ b/internal/repoguard/budgets_test.go @@ -157,6 +157,9 @@ type skillBudget struct { // to `implemented` depends_on only (8223 -> 8233): a stack-base refusal never // triggers an ancestor closeout, because that closeout cannot prove the carry of a // not-yet-stacked-merged named change and returns children-retarget-required. +// (Change 0571 later retired that closeout disposition; edge-paths.md now gives +// the true reason — the bounded closeout covers only the named change's own +// depends_on set. The counts above are historical and stay as recorded.) // A second review fix named the real status field (8233 -> 8241): the closeout // set is read off `unmet_dependencies` (app.StatusChange), since the status // projection exposes no `depends_on` field. A third review fix keyed the closeout mapping on @@ -202,12 +205,12 @@ var skillBudgets = []skillBudget{ {"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) {"docket-convention/references/close-out.md", 174, 1722}, // 0567: a carried child whose stack relationship can't be proven stays pending (destination-mismatch) (174/1711 -> 174/1722); 0567: a carried stacked child is retried like any done change and stays pending (carry-unproven) with no delete advice (174/1704 -> 174/1711); 0559: change.complete is the third done driver; finalize.cleanup's no-PR path; kill takes --request and is not idempotent (141/1347 -> 174/1701); 0559: the sweep retries only a leftover worktree (174/1701 -> 174/1704); 0531: the metadata worktree and remote come from the repository.prepare context (141/1349 -> 141/1347); 0502: "loop" means /loop only (144/1375 -> 144/1374); 0502: one metadata layout — the docket branch and the .docket/ worktree (144/1376 -> 144/1375); 0502: the scripts/.md contract pointer becomes the schema operation (144/1374 -> 144/1376); 0502: the terminal-publication step is deleted (240/2150 -> 144/1374); 0474: reference renamed (ADR-0129 row 59a); ceilings unchanged; 0502: drop change citations and Go v1 narration (144/1374 -> 144/1356); 0502: the docket-source test citations are deleted (144/1356 -> 141/1349) {"docket-convention/references/learnings.md", 69, 487}, // 0535: promotion lands in the private instructions file in a private repository (66/457 -> 69/487); 0502: one metadata layout — the docket branch and the .docket/ worktree (66/455 -> 66/457); 0502: learning.record/learning.update are the writers; the capacity section is deleted (84/580 -> 66/455) - {"docket-convention/references/stacked-changes.md", 223, 2217}, // 0567: carried children are cleaned right after the root once their work is proven (219/2173 -> 223/2217); 0565: a kill refuses on built stacked descendants; the killed-parent board text and exits table (214/2149 -> 219/2173); 0502: typed operations and binary-emitted findings replace the Bash-era names (213/2125 -> 214/2149); 0502: the deferred descendant-publication sentence is deleted (215/2140 -> 213/2125); 0327: +carry-preservation contract prose (see note above) - {"docket-finalize-change/SKILL.md", 243, 6254}, // 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, 2111}, // 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-convention/references/stacked-changes.md", 227, 2290}, // 0571: a root carries exactly the children merged into it, stacked-merged or implemented; any other child never blocks it (223/2217 -> 227/2290); 0567: carried children are cleaned right after the root once their work is proven (219/2173 -> 223/2217); 0565: a kill refuses on built stacked descendants; the killed-parent board text and exits table (214/2149 -> 219/2173); 0502: typed operations and binary-emitted findings replace the Bash-era names (213/2125 -> 214/2149); 0502: the deferred descendant-publication sentence is deleted (215/2140 -> 213/2125); 0327: +carry-preservation contract prose (see note above) + {"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", 78, 2377}, // 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", 218, 8637}, // 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", 109, 1265}, // 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/edge-paths.md", 109, 1276}, // 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, 1963}, // 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", 79, 775}, // 0559: new — the results-artifact ending (no plan, build, or PR; review, complete, clean up) {"docket-implement-next/results-template.md", 70, 545}, // 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) diff --git a/internal/repoguard/prose_contracts_test.go b/internal/repoguard/prose_contracts_test.go index 9efc3fa33..19d7849cf 100644 --- a/internal/repoguard/prose_contracts_test.go +++ b/internal/repoguard/prose_contracts_test.go @@ -369,10 +369,11 @@ var proseContracts = []proseContract{ "## Named invocation's own merged dependencies (Step 0, bounded closeout)", "For **each** id in that set — and never any other change — run one `finalize.closeout` operation", "An unrelated change's closeout is never attempted here", - // A stack-base refusal never triggers closeout: closing out an - // ancestor while the named change is not yet stacked-merged fails - // its carry proof (children-retarget-required), so the only - // closeout trigger is the waiting-dependency refusal. + // A stack-base refusal never triggers closeout: the bounded + // closeout covers only the named change's own depends_on set, and + // an unresolved stack base clears through the parent's own + // finalize or the next sweep, so the only closeout trigger is the + // waiting-dependency refusal. "A `not-ready-stack-base-unresolved` refusal is never a closeout trigger", // The status projection exposes the unmet set as the id list // `unmet_dependencies` (app.StatusChange), never a `depends_on` diff --git a/skills/docket-convention/references/stacked-changes.md b/skills/docket-convention/references/stacked-changes.md index 2a2dad783..a0e0a317c 100644 --- a/skills/docket-convention/references/stacked-changes.md +++ b/skills/docket-convention/references/stacked-changes.md @@ -59,7 +59,8 @@ What it does **not** satisfy: The merge sweep (the `maintenance.sweep` operation) is the only producer of the state; the typed finalize close-out (the `finalize.closeout` operation's `root-archived` disposition) is the only consumer that takes -a change out of it, when the stack root reaches integration. See *The stack close-out is idempotent* +a change out of it, when the stack root reaches integration. That same root close-out also takes an +`implemented` child whose PR merged into its parent's branch straight to `done`. See *The stack close-out is idempotent* below. ## Resolving the base — `context.implementation` effective-base @@ -191,15 +192,18 @@ proposed one reads *stack parent #A killed — re-parent, un-stack, or kill*. It ## The stack close-out is idempotent When a stack **root** merges, the typed close-out — the `finalize.closeout` operation's **`root-archived`** -disposition — archives the root and every carried `stacked-merged` descendant to `done` in **one +disposition — archives the root and every carried descendant to `done` in **one transaction**, all under the **root's** merge date, and renders the root's marker-bounded **Stack carried** table on the root's archived record. A descendant counts as *carried* only when **both** -hold: its merged PR destinations establish the carry **relationship** into the root, **and** its work -is proven still present in Git — reachable in the pinned integration history, or exact-content at the +hold: its PR merged into its parent's branch (it reads `stacked-merged`, or still `implemented` +because its own close-out never ran), down an unbroken chain of such links from the root, **and** its +work is proven still present in Git — reachable in the pinned integration history, or exact-content at the root's merge result. A merged destination alone is only a relationship: a stale-worktree rebase can drop a descendant's work while every record still reads merged, so the Git carry is the promotion condition. One unproven descendant leaves the root recoverable with zero descendant writes -(fail-closed). +(fail-closed). A child in any other state — an open or retargeted PR, not yet built, killed, already +`done` — is not carried, never blocks the root, and is left alone; a child beneath it waits for its +own parent. Finalize and the sweep then clean each carried child's folder and branches right after the root's, once cleanup proves the child's work reached the integration branch. Until then the child keeps @@ -214,8 +218,8 @@ permanently. The transaction gates on the root actually carrying descendants, so pays nothing. The archive date is the root's `mergedAt` in **UTC**, derived inside the transaction, never `now()`, -so a re-run reuses the same descendant filenames. Route on the typed `disposition`: `root-archived` (every descendant proven), -`children-retarget-required` (one is not yet `stacked-merged`), or `contended`/`blocked`. +so a re-run reuses the same descendant filenames. Route on the typed `disposition`: `done-archived` (nothing carried), +`root-archived` (every carried descendant proven), or `contended`/`blocked`/`unknown`. Re-running it is the designed recovery from a partial pass: an `already-closed-out` disposition replays a response-lost success as a keyed no-op, keyed on the descendant already being **archived on the diff --git a/skills/docket-finalize-change/SKILL.md b/skills/docket-finalize-change/SKILL.md index d37088f36..82215a28f 100644 --- a/skills/docket-finalize-change/SKILL.md +++ b/skills/docket-finalize-change/SKILL.md @@ -164,9 +164,8 @@ UTC archive date from the verified `mergedAt`, and applies one atomic transactio - `done-archived` — an ordinary change merged to the integration branch: marked `done` (only after the merge-commit reachability proof), relocated to the dated archive path, artifact block + spec, plan, and results backlinks + inline board rerendered, validated, committed by explicit path, lease-pushed. Then, outside that transaction, a best-effort follow-up repoints the merged PR's backlink at the archived record. - `stacked-merged` — the PR merged into a live parent's branch: marked `stacked-merged` in place, not archived, branch and workspace retained until the root lands. -- `root-archived` — a stack root reached integration and every carried descendant is proven: its chain of merged PR destinations establishes the carry relationship AND its merged work is verified still present in Git — reachable in the pinned integration history, or exact-content at the root's merge result — since a merged destination alone is a relationship, never proof the content shipped. One transaction archives the root and every descendant using the root's merge date, one board render over the final population. One unproven descendant leaves the root recoverable, zero descendant writes. The same follow-up then repoints the root's and each descendant's PR. +- `root-archived` — a stack root reached integration and every carried descendant is proven. A descendant is carried only when its PR merged into its parent's branch, whether it reads `stacked-merged` or still `implemented`; any other child is left alone and never blocks the root. Proof: its chain of merged PR destinations establishes the carry relationship AND its merged work is verified still present in Git — reachable in the pinned integration history, or exact-content at the root's merge result — since a merged destination alone is a relationship, never proof the content shipped. One transaction archives the root and every descendant using the root's merge date, one board render over the final population. One unproven descendant leaves the root recoverable, zero descendant writes. The same follow-up then repoints the root's and each descendant's PR. - `already-closed-out` — the promised final state already exists (a response-lost success): a keyed no-op, never a duplicate transition. -- `children-retarget-required` — a descendant is not yet stacked-merged; return to step 2 (attended) or `halted` (autonomous). - `contended` / `blocked` / `unknown` — a lost race, an illegal source status or destination mismatch, or an unobservable probe; re-read context (`contended`) or stop (`halted`). Close-out is one metadata commit plus the best-effort PR-description backlink repoint; nothing touches the integration branch. A PR description that could not be repointed is a `pr-backlink-pending` warning on an otherwise-final result: report it, never redo the merge; cleanup (step 10) and the maintenance sweep retry it. ### 10. Cleanup — Docket-owned resources only diff --git a/skills/docket-finalize-change/references/gate-failure.md b/skills/docket-finalize-change/references/gate-failure.md index 52e3c46c0..a8f318e6c 100644 --- a/skills/docket-finalize-change/references/gate-failure.md +++ b/skills/docket-finalize-change/references/gate-failure.md @@ -92,7 +92,7 @@ Two outcomes look abort-shaped and are not: a `waiting` (`reason: gate-waiting`) - a **merge condition that fails at the fresh recheck** or an authoritatively **denied** merge — the `finalize.merge` operation returns the condition's token or `merge-denied`; a standing denial is `halted`, never retried; -- an **open unauthorized child** on an autonomous run, or a `children-retarget-required` closeout; +- an **open unauthorized child** on an autonomous run; - the **dispatch mechanism being unavailable** for either gate agent — the `no-fallback` posture, established only per the convention's *Dispatch-capability resolution*, never from a tool name, and never substituted inline; diff --git a/skills/docket-implement-next/references/edge-paths.md b/skills/docket-implement-next/references/edge-paths.md index e39198644..1f1804122 100644 --- a/skills/docket-implement-next/references/edge-paths.md +++ b/skills/docket-implement-next/references/edge-paths.md @@ -26,8 +26,8 @@ never widen or recurse beyond this set. Map each envelope locally and key succes An unrelated change's closeout is never attempted here, and a dependency unmet for any non-`implemented` reason keeps its ordinary local refusal unchanged. A `not-ready-stack-base-unresolved` refusal is never a closeout trigger and keeps its ordinary local -refusal: an ancestor's closeout cannot prove the carry of a named change not yet `stacked-merged` -(`children-retarget-required`). +refusal: the bounded closeout covers only the named change's own `depends_on` set, and an +unresolved stack base clears through the parent's own finalize or the next sweep. ## Reconcile-kill (Step 3, change OBSOLETE)