yadflow 4.6.0 → 4.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/CHANGELOG.md +259 -0
  2. package/README.md +46 -4
  3. package/bin/commands.mjs +9 -2
  4. package/bin/yad.mjs +309 -30
  5. package/cli/agent-guard.mjs +511 -0
  6. package/cli/agent-guide.mjs +83 -0
  7. package/cli/agent-rules.mjs +381 -0
  8. package/cli/argv-flags.mjs +7 -0
  9. package/cli/artifact-status.mjs +88 -20
  10. package/cli/build.mjs +1372 -0
  11. package/cli/checkpoint.mjs +2 -2
  12. package/cli/ci-check.mjs +492 -0
  13. package/cli/commit.mjs +1 -0
  14. package/cli/dial.mjs +21 -1
  15. package/cli/docs.mjs +7 -2
  16. package/cli/doctor.mjs +176 -33
  17. package/cli/epic-state.mjs +360 -12
  18. package/cli/errors.mjs +3 -0
  19. package/cli/find-product.mjs +36 -2
  20. package/cli/fold.mjs +9 -5
  21. package/cli/gate-local.mjs +9 -1
  22. package/cli/gate.mjs +364 -22
  23. package/cli/guide.mjs +549 -0
  24. package/cli/history.mjs +22 -2
  25. package/cli/hook.mjs +35 -4
  26. package/cli/index-command.mjs +2 -2
  27. package/cli/ledger.mjs +60 -0
  28. package/cli/lib.mjs +46 -0
  29. package/cli/lifecycle/defaults/2.json +124 -0
  30. package/cli/lifecycle/lifecycle.schema.json +5 -2
  31. package/cli/lifecycle.mjs +16 -3
  32. package/cli/manifest.mjs +75 -0
  33. package/cli/marked-block.mjs +48 -0
  34. package/cli/members.mjs +19 -5
  35. package/cli/migrate.mjs +17 -19
  36. package/cli/next.mjs +35 -12
  37. package/cli/openpr.mjs +81 -5
  38. package/cli/plan.mjs +326 -22
  39. package/cli/platform.mjs +21 -0
  40. package/cli/pr-list.mjs +5 -3
  41. package/cli/product-index.mjs +6 -3
  42. package/cli/product-token.mjs +186 -0
  43. package/cli/productcommit.mjs +33 -0
  44. package/cli/protection.mjs +50 -0
  45. package/cli/recommend.mjs +3 -1
  46. package/cli/reconcile.mjs +187 -26
  47. package/cli/repo-publish.mjs +2 -2
  48. package/cli/report.mjs +62 -14
  49. package/cli/run-checks.mjs +586 -0
  50. package/cli/setup.mjs +244 -25
  51. package/cli/ship-drift.mjs +49 -18
  52. package/cli/signing.mjs +377 -0
  53. package/cli/standup.mjs +1 -1
  54. package/cli/status.mjs +282 -0
  55. package/cli/test-agents-file.mjs +993 -0
  56. package/cli/test-build.mjs +1559 -0
  57. package/cli/test-ci-check.mjs +616 -0
  58. package/cli/test-guide.mjs +1267 -0
  59. package/cli/test-node.mjs +129 -0
  60. package/cli/test-run-checks.mjs +603 -0
  61. package/cli/test-setup-agent.mjs +352 -0
  62. package/cli/test-signing.mjs +524 -0
  63. package/cli/test-worktree.mjs +520 -0
  64. package/cli/thread.mjs +4 -0
  65. package/cli/tidy.mjs +2 -2
  66. package/cli/toolbox.mjs +37 -6
  67. package/cli/update-commit.mjs +313 -11
  68. package/cli/workspace.mjs +38 -10
  69. package/cli/worktree-record.mjs +53 -0
  70. package/cli/worktree.mjs +379 -0
  71. package/package.json +6 -4
  72. package/skills/sdlc/config.yaml +5 -5
  73. package/skills/sdlc/module-help.csv +2 -1
  74. package/skills/yad-backfill/templates/checks/backfill-check.sh +9 -9
  75. package/skills/yad-change/SKILL.md +5 -1
  76. package/skills/yad-checks/SKILL.md +61 -12
  77. package/skills/yad-checks/references/check-gates.md +78 -14
  78. package/skills/yad-checks/templates/checks/build-test-lint.sh +22 -3
  79. package/skills/yad-checks/templates/checks/commit-message.sh +8 -2
  80. package/skills/yad-checks/templates/checks/contract-check.sh +61 -33
  81. package/skills/yad-checks/templates/checks/epic-open.sh +87 -14
  82. package/skills/yad-checks/templates/checks/ledger-guard.sh +3 -3
  83. package/skills/yad-checks/templates/checks/lineage-check.sh +88 -15
  84. package/skills/yad-checks/templates/checks/member-check.mjs +206 -35
  85. package/skills/yad-checks/templates/checks/package-manager.sh +42 -5
  86. package/skills/yad-checks/templates/checks/product-checkout.sh +161 -13
  87. package/skills/yad-checks/templates/checks/reconcile-debt-check.sh +94 -15
  88. package/skills/yad-checks/templates/checks/risk-map-check.sh +2 -2
  89. package/skills/yad-checks/templates/checks/spec-link.sh +63 -4
  90. package/skills/yad-checks/templates/checks/verified-commits.sh +23 -5
  91. package/skills/yad-checks/templates/github/yad-checks.yml +9 -9
  92. package/skills/yad-checks/templates/gitlab/.gitlab-ci.yml +4 -1
  93. package/skills/yad-checks/templates/gitlab/yad-checks.gitlab-ci.yml +5 -5
  94. package/skills/yad-checks/templates/gitlab/yad-product-checks.gitlab-ci.yml +16 -3
  95. package/skills/yad-checks/templates/gitlab/yad-update-guard.gitlab-ci.yml +5 -1
  96. package/skills/yad-checks/templates/gitlab/yad-verified-commits.gitlab-ci.yml +5 -1
  97. package/skills/yad-checks/templates/hooks/agent-guard.mjs +116 -0
  98. package/skills/yad-commit/SKILL.md +8 -5
  99. package/skills/yad-connect-repos/SKILL.md +5 -3
  100. package/skills/yad-connect-repos/references/code-context.md +2 -1
  101. package/skills/yad-connect-repos/references/repos-registry.md +2 -1
  102. package/skills/yad-docs/templates/app/package-lock.json +395 -106
  103. package/skills/yad-docs/templates/app/package.json +2 -2
  104. package/skills/yad-docs-overview/references/pipeline-model.md +2 -2
  105. package/skills/yad-engineer-review/SKILL.md +55 -25
  106. package/skills/yad-engineer-review/references/ship-and-record.md +49 -12
  107. package/skills/yad-epic/SKILL.md +2 -1
  108. package/skills/yad-epic/references/state-schema.md +76 -17
  109. package/skills/yad-guide/SKILL.md +192 -0
  110. package/skills/yad-implement/SKILL.md +75 -13
  111. package/skills/yad-implement/references/implement-conventions.md +8 -1
  112. package/skills/yad-implement/templates/.gitmessage +3 -0
  113. package/skills/yad-open-pr/SKILL.md +21 -0
  114. package/skills/yad-pair-review/SKILL.md +14 -5
  115. package/skills/yad-pr-template/SKILL.md +6 -2
  116. package/skills/yad-pr-template/templates/checks/pr-template.sh +85 -4
  117. package/skills/yad-pr-template/templates/checks/pr-title.sh +1 -1
  118. package/skills/yad-pr-template/templates/github/pull_request_template.md +1 -1
  119. package/skills/yad-pr-template/templates/gitlab/merge_request_templates/Default.md +1 -1
  120. package/skills/yad-product-bridge/SKILL.md +44 -12
  121. package/skills/yad-product-bridge/references/bridge.md +11 -5
  122. package/skills/yad-product-bridge/templates/github/yad-gate-sync.yml +2 -2
  123. package/skills/yad-product-bridge/templates/gitlab/yad-gate-sync.gitlab-ci.yml +9 -4
  124. package/skills/yad-reconcile/SKILL.md +9 -3
  125. package/skills/yad-report/SKILL.md +15 -0
  126. package/skills/yad-review-companion/SKILL.md +5 -3
  127. package/skills/yad-review-gate/SKILL.md +16 -8
  128. package/skills/yad-review-gate/references/gating.md +26 -1
  129. package/skills/yad-run/SKILL.md +61 -33
  130. package/skills/yad-run/references/run-loop.md +44 -22
  131. package/skills/yad-spec/SKILL.md +137 -16
  132. package/skills/yad-spec/references/spec-handoff.md +50 -3
  133. package/skills/yad-status/SKILL.md +7 -0
  134. package/skills/yad-stories/references/story-schema.md +1 -1
  135. package/skills/yad-sync-repos/SKILL.md +2 -1
  136. package/skills/yad-ui/SKILL.md +2 -2
package/cli/gate.mjs CHANGED
@@ -5,27 +5,30 @@
5
5
  import fs from 'node:fs';
6
6
  import path from 'node:path';
7
7
  import {
8
- c, log, ok, info, warn, hand, fail, note, quietly, readJSON, readJSONStrict, writeJSON, run, pushWithRebase, isPlainObject, writeMirrored, emitJSON, refuse, collectWarning,
8
+ c, log, ok, info, warn, hand, fail, note, quietly, readJSON, readJSONStrict, writeJSON, run, pushWithRebase, isPlainObject, writeMirrored, emitJSON, refuse, collectWarning, forTerminal,
9
9
  } from './lib.mjs';
10
10
  import { OWNING_COMMIT_ENV } from './hook.mjs';
11
- import { PROJECT_FILES, isVerifiedLedger , productConfigPath, settingsEditHint } from './manifest.mjs';
11
+ import { PROJECT_FILES, VERSION, isVerifiedLedger , productConfigPath, settingsEditHint } from './manifest.mjs';
12
12
  import {
13
- epicIds, epicRel, epicRoot, loadLedger, findReviewStep, artifactBase, artifactHash, acceptedHashes, isStaleHash, gatePredicate, printable,
13
+ epicIds, epicRel, epicRoot, loadLedger, findReviewStep, artifactBase, artifactHash, artifactHashAt, acceptedHashes, doneStepUnapproved, reviewAsItStands, isStaleHash, gatePredicate, printable,
14
14
  advanceState, closingRecord, markInReview, isEscalated, gateRuleFor, gateCapFor, gateReach, uniqueReach, peopleWord, capSeat, gateRuleSum, gateRuleEnforced, parseReviewBranch, artifactFromBase, legacyLogins,
15
15
  upsertProductPr, stateInvariants, repairState, DISCOVERY_FILES, FOUNDATION_REQUIRED, unwrittenSections,
16
16
  canonicalApprovals, canonicalComments, canonicalProductPrs, optionalStepsFor, isSkippableStep, writeState, routeLacksStep,
17
17
  isPassed, stepStatus, claimsSkipped, claimsInherited, DISCOVERY_EPIC, FOUNDATION_DIR, FOUNDATION_EPIC, staleFoundationGuards,
18
+ reopenStep, retiredPr, epicLineage, heldByReopen, reopenStampDue, stampPassed, isGateStep,
18
19
  } from './epic-state.mjs';
20
+ import { readShips } from './ledger.mjs';
19
21
  import { activePeople, activeSum, activeBasis, approverCount, printTeamHint, soloTeamHint } from './people.mjs';
20
22
  import { applyProductMove, planProductMove } from './migrate.mjs';
21
- import { productGit, preflightGuardReadiness, resolveDefaultBranch, guardDefaultBranch } from './productcommit.mjs';
23
+ import { productGit, preflightGuardReadiness, resolveDefaultBranch, guardDefaultBranch, branchToCommitOn, onlyYadCommitsAhead } from './productcommit.mjs';
24
+ import { worktreeAt } from './worktree-record.mjs';
22
25
  import {
23
26
  readPr, mapApprovers, createPr, platformLogin, actorName, ambiguousLegacyNames, prNumberFromUrl,
24
- getPrBody, editPrBody, postComment, findPrForBranch, prBranch, branchExists,
27
+ getPrBody, editPrBody, postComment, findPrForBranch, prBranch, branchExists, newestPrNumber,
25
28
  } from './platform.mjs';
26
29
  import { isNoBlock, upsertTrailerBlock, nudgeMessage, parseEngagement } from './companion.mjs';
27
30
  import { sequenceDiff } from './walkthrough.mjs';
28
- import { syncStatuses } from './artifact-status.mjs';
31
+ import { syncStatuses, lowerStatuses } from './artifact-status.mjs';
29
32
  import { writeIndex, refreshIndexAfterWrite, uncommittedIndexInputs, INDEX_FILE } from './product-index.mjs';
30
33
  import { err } from './errors.mjs';
31
34
 
@@ -219,8 +222,40 @@ export { legacyLogins };
219
222
  // entry for the same review would count one person twice), and an open step records the approval
220
223
  // against a STALE fingerprint from those older records when one exists — the approval must be given
221
224
  // again, on a new review, rather than pass on content one of those people may never have seen.
222
- function upsertBridge(approvals, recs, { stepId, artifact, curHash, today, prNumber = null, closed = false, aliases = new Map(), clashed = new Map(), accepted = null }) {
223
- const live = accepted ?? (curHash ? [curHash] : []);
225
+ // What a review approved (#366): the artifact as it stands at the PR/MR's head, never the default branch's
226
+ // content when the gate happens to read it — another review merged in between may have changed that, and
227
+ // its approvals would then pass content they never saw. A squash-merged review's head is on no branch here
228
+ // and its source branch may be gone, so the platform's own ref for it is fetched (into FETCH_HEAD only: no
229
+ // branch moves). → artifactHashAt's answer: { ok, hash } or { ok: false, reason }.
230
+ // The Product level moved from epics/EP-discovery/ to foundation/ (shape 8). A review opened before the move
231
+ // still holds its files in the old folder at its head, so when the new one is empty there, the old is read.
232
+ export function approvedContent(contentAt, { root, epic, epicDir, ...rest }) {
233
+ const at = contentAt({ root, epicDir, ...rest });
234
+ if (!at?.ok || at.copied !== 0 || epic !== FOUNDATION_EPIC) return at;
235
+ const old = contentAt({ root, epicDir: epicRoot(root, DISCOVERY_EPIC), ...rest });
236
+ return old?.ok && old.hash != null ? old : at;
237
+ }
238
+ export function headContentHash({ root, epicDir, artifact, platform, number, headOid }) {
239
+ const first = artifactHashAt(root, epicDir, artifact, headOid);
240
+ if (first.ok || !first.missing || !Number.isInteger(Number(number)) || Number(number) <= 0) return first;
241
+ const ref = platform === 'gitlab' ? `refs/merge-requests/${Number(number)}/head` : `refs/pull/${Number(number)}/head`;
242
+ const fetched = run('git', ['fetch', '--quiet', '--no-tags', 'origin', ref], { cwd: root });
243
+ const second = artifactHashAt(root, epicDir, artifact, headOid);
244
+ if (second.ok || fetched.ok) return second;
245
+ return { ...second, reason: `${second.reason}; fetching ${ref} failed: ${String(fetched.stderr || fetched.stdout || 'no answer').split('\n')[0]}` };
246
+ }
247
+
248
+ // The fingerprint new approvals take when the approved head held none of the artifact while the default
249
+ // branch does: no claim (`null`) would count everywhere, so it is a value no content can hash to.
250
+ const NOTHING_AT_HEAD = 'sha256:none-at-the-approved-head';
251
+ // And the other way round: the default branch holds nothing to fingerprint (every story deleted, a contract
252
+ // with no END marker) while the approved head did. No accepted hash at all would make every approval count,
253
+ // so the gate is judged against a value no approval is bound to.
254
+ const NOTHING_ON_DEFAULT = 'sha256:none-on-the-default-branch';
255
+
256
+ // `bindHash` is what a new approval is bound to: the content its review approved (#366, `headContentHash`).
257
+ function upsertBridge(approvals, recs, { stepId, artifact, bindHash, today, prNumber = null, closed = false, merged = false, aliases = new Map(), clashed = new Map(), accepted = null }) {
258
+ const live = accepted ?? (bindHash ? [bindHash] : []);
224
259
  const stale = (a) => !!a.artifactHash && isStaleHash(a.artifactHash, live);
225
260
  // A submission TIME, not a date. Every GitLab record written before E64 read `approved_at` holds the
226
261
  // day it was synced (`today`), and as text `2026-09-15T10:00:00Z` sorts after `2026-09-15` — so a
@@ -343,9 +378,9 @@ function upsertBridge(approvals, recs, { stepId, artifact, curHash, today, prNum
343
378
  for (const r of recs) {
344
379
  if (closed && ambiguous.has(r)) continue;
345
380
  const was = matchOf.get(r);
346
- // first time we see this approval => bind to current content; an ambiguous one => to the stale print
381
+ // first time we see this approval => bind to the content it approved; an ambiguous one => to the stale print
347
382
  const staleOrphan = ambiguous.has(r) ? staleFor(r) : null;
348
- let artHash = staleOrphan ? staleOrphan.artifactHash : curHash;
383
+ let artHash = staleOrphan ? staleOrphan.artifactHash : bindHash;
349
384
  let approvedAt = r.submittedAt || today;
350
385
  let recordedOn = today;
351
386
  if (was) {
@@ -361,7 +396,14 @@ function upsertBridge(approvals, recs, { stepId, artifact, curHash, today, prNum
361
396
  const newerReview = hasTime(r.submittedAt) && hasTime(was.approvedAt) && Date.parse(r.submittedAt) > Date.parse(was.approvedAt);
362
397
  const newerPr = prNumber != null && was.pr != null && was.pr !== prNumber;
363
398
  if (!newerReview && !newerPr) {
364
- artHash = was.artifactHash ?? curHash;
399
+ artHash = was.artifactHash ?? bindHash;
400
+ // Recorded by a release before #366, bound to the default branch's content when it was read rather
401
+ // than to what the review approved: when that record still counts and the review approved other
402
+ // content, the content it approved wins, so it stops counting. A stale record stays as it is.
403
+ // Never on a closed step: its approvals are its history, and the gate already decided it. Only for a
404
+ // merged review: before the merge the head can still move, and a GitLab approval carries no commit, so
405
+ // a record bound to an earlier head must stay there and go stale.
406
+ if (!closed && merged && was.artifactHash && bindHash && !stale(was) && !live.includes(bindHash)) artHash = bindHash;
365
407
  // A record holding only a date takes the platform's time once (E64) and keeps its fingerprint: the
366
408
  // time is evidence of when, the fingerprint is what the gate decides on. Then it is byte-stable.
367
409
  approvedAt = !hasTime(was.approvedAt) && hasTime(r.submittedAt) ? r.submittedAt : (was.approvedAt ?? approvedAt);
@@ -573,7 +615,14 @@ function resolveTargets(productPrs, { epic, artifact, state, platform, number, f
573
615
  if (named !== null && (!Number.isInteger(named) || named <= 0)) {
574
616
  return { targets: [], discovered: false, reason: `--pr must be a positive integer, got '${number}'` };
575
617
  }
576
- if (named === null && recorded.length) return { targets: recorded, discovered: false };
618
+ // A review PR `yad gate reopen` retired never passes its gate again (#322): not as a recorded pointer an
619
+ // older yad put back, not when named with --pr, and not when found on the review branch below.
620
+ const retired = (n) => retiredPr(state, artifact || recorded[0]?.artifact, n, platform);
621
+ const retiredWhy = (n) => `#${n} was retired by \`yad gate reopen\` — it no longer counts for this review; open a fresh one with \`yad gate open ${epic} ${artifact || recorded[0]?.artifact || '<artifact>'}\``;
622
+ if (named !== null && retired(named)) return { targets: [], discovered: false, reason: retiredWhy(named) };
623
+ const live = recorded.filter((p) => !retiredPr(state, p.artifact, p.number, p.platform || platform));
624
+ if (named === null && recorded.length && !live.length) return { targets: [], discovered: false, reason: retiredWhy(recorded[0].number) };
625
+ if (named === null && live.length) return { targets: live, discovered: false };
577
626
  if (!artifact) return { targets: [], discovered: false, reason: 'name the artifact to resolve its review PR' };
578
627
  const step = findReviewStep(state, artifact);
579
628
  if (!step) return { targets: [], discovered: false, reason: `no review step for ${artifact}` };
@@ -601,6 +650,7 @@ function resolveTargets(productPrs, { epic, artifact, state, platform, number, f
601
650
  }
602
651
  const found = finder(platform, branch, { cwd });
603
652
  if (!found.ok) return { targets: [], discovered: false, reason: found.reason };
653
+ if (retired(found.number)) return { targets: [], discovered: false, reason: retiredWhy(found.number) };
604
654
  info(`no recorded review PR — resolved #${found.number}${found.state ? ` (${found.state})` : ''} from ${branch}`);
605
655
  return { targets: entry(found.number, found.url), discovered: true };
606
656
  }
@@ -633,7 +683,7 @@ function stageIndexIfClean(root, git, commits = null) {
633
683
  return !git('diff', '--cached', '--quiet', '--', INDEX_FILE).ok;
634
684
  }
635
685
 
636
- export async function gateSync(root, { epic, artifact, today, reader = readPr, finder = findPrForBranch, branchOf = prBranch, poster = postComment, number = null, local = false, dryRun = false, headCount = null, probe = null } = {}) {
686
+ export async function gateSync(root, { epic, artifact, today, reader = readPr, finder = findPrForBranch, branchOf = prBranch, poster = postComment, number = null, local = false, dryRun = false, headCount = null, probe = null, newest = newestPrNumber, contentAt = headContentHash } = {}) {
637
687
  const { productConfig } = loadProduct(root);
638
688
  if (!productConfig?.platform) { warn(`no Product platform configured (${settingsEditHint(root)}) — local gate, nothing to sync`); return { epic, synced: 0, advanced: 0, written: false, gates: [] }; }
639
689
  const platform = productConfig.platform;
@@ -709,7 +759,11 @@ export async function gateSync(root, { epic, artifact, today, reader = readPr, f
709
759
  // A pointer resolved from the platform is adopted into the ledger on the WRITER path only. In
710
760
  // verified mode this run is advisory and writes nothing, so the human never ends up with a gate-state
711
761
  // file in their working tree for the ledger-guard check to reject.
712
- if (resolved.discovered && !readOnly) productPrs = upsertProductPr(productPrs, targets[0]);
762
+ // Not for a review held behind a reopen (#322): a pointer recorded during the hold would be read once it lifts.
763
+ if (resolved.discovered && !readOnly) {
764
+ const held = findReviewStep(state, targets[0].artifact);
765
+ if (!held || isPassed(held) || !heldByReopen(state, held.id)) productPrs = upsertProductPr(productPrs, targets[0]);
766
+ }
713
767
 
714
768
  let synced = 0;
715
769
  let advanced = 0;
@@ -743,12 +797,53 @@ export async function gateSync(root, { epic, artifact, today, reader = readPr, f
743
797
  // and write nothing but the PR pointer. The step then read `done` while its approvals were all
744
798
  // stale: work proceeded on an audit trail saying the re-review never happened (issue #156).
745
799
  const alreadyDone = isPassed(step);
800
+ // After a reopen the gates pass again in order (#322). Asked of the LIVE state on every pass: an earlier
801
+ // target in this same run may have just passed a walked-back review and retired this PR (`stampPassed`).
802
+ if (!alreadyDone && retiredPr(state, pr.artifact, pr.number, platform)) {
803
+ info(`${step.id}: PR #${pr.number} was retired by \`yad gate reopen\` — not read; review ${pr.artifact} again on a fresh PR/MR: \`yad gate open ${epic} ${step.artifact}\``);
804
+ productPrs = canonicalProductPrs(productPrs.filter((p) => !(p.artifact === pr.artifact && p.number === pr.number)));
805
+ gates.push({ step: step.id, artifact: pr.artifact, pr: pr.number ?? null, merged: null, rule: null, passed: false, alreadyDone: false, retired: true, have: null, gateRule: null, cap: null, short: null, missing: ['a fresh review'], staleDropped: 0, differs: false, changedSinceApproved: false });
806
+ continue;
807
+ }
808
+ // A held review is not read, and once the step it waits on passes, its PR is retired with every later
809
+ // review opened before then (`stampPassed`), so nothing given during the hold counts.
810
+ const holdFor = alreadyDone ? null : heldByReopen(state, step.id);
811
+ if (holdFor) {
812
+ warn(`${step.id} waits for ${holdFor}, an earlier step not passed since \`yad gate reopen\` — PR #${pr.number} is not read`);
813
+ hand(`once ${holdFor} passes, review ${step.artifact} again on a fresh PR/MR: \`yad gate open ${epic} ${step.artifact}\``);
814
+ gates.push({ step: step.id, artifact: pr.artifact, pr: pr.number ?? null, merged: null, rule: null, passed: false, alreadyDone: false, held: holdFor, have: null, gateRule: null, cap: null, short: null, missing: [`${holdFor} must pass first`], staleDropped: 0, differs: false, changedSinceApproved: false });
815
+ continue;
816
+ }
746
817
  const pull = reader(platform, pr.number, { cwd: root });
747
818
  // A failed platform read must not pass as a green no-op: flag the run non-zero so CI surfaces it
748
819
  // (the wired workflow's reconcile/sweep aggregates this exit) instead of silently not advancing.
749
820
  if (!pull.ok) { fail(`${pr.artifact}: ${pull.reason} — skipping (local)`); process.exitCode = 1; continue; }
750
821
 
751
822
  const curHash = artifactHash(epicDir, pr.artifact);
823
+ // New approvals bind to what the review approved (#366); see headContentHash. Unknown is never
824
+ // taken as approved: nothing is bound, and the run goes red so CI tries again.
825
+ const at = approvedContent(contentAt, { root, epic, epicDir, artifact: pr.artifact, platform, number: pr.number, headOid: pull.headOid });
826
+ if (!at?.ok && alreadyDone) {
827
+ // A done step only records what arrives: nothing is bound, and the run is not failed for it.
828
+ warn(`${pr.artifact}: could not read what PR #${pr.number} approved (${at?.reason || 'no answer'}) — ${step.id} is already done; no approval was recorded this time — a later sweep tries again`);
829
+ continue;
830
+ }
831
+ if (!at?.ok) {
832
+ fail(`${pr.artifact}: could not read what PR #${pr.number} approved (${at?.reason || 'no answer'}) — nothing was recorded`);
833
+ hand('run it again; CI needs the full history (fetch-depth: 0, or GIT_DEPTH: "0") and must be able to fetch the PR/MR');
834
+ process.exitCode = 1;
835
+ continue;
836
+ }
837
+ const approvedHash = at.hash ?? (curHash ? NOTHING_AT_HEAD : null);
838
+ // Merged, and the default branch holds something else: another merge changed it after this review.
839
+ // Solo mode counts no approvals, so there is nothing to say there.
840
+ const differs = !!pull.merged && approvedHash !== curHash;
841
+ // Not on a step already done: the gate decided it, and a re-sync only records what arrives.
842
+ if (differs && !solo && !alreadyDone) {
843
+ const trunk = resolveDefaultBranch(productGit(root), productConfig);
844
+ warn(`${pr.artifact}: PR #${pr.number} approved a different ${pr.artifact} than the default branch holds now — another merge changed it after that review, so its approvals do not pass the gate${local ? ` (or this checkout's ${trunk} is behind origin: pull it first)` : ''}`);
845
+ hand(forTerminal(reviewAsItStands(epic, step.artifact, trunk)));
846
+ }
752
847
  warnUnlockedContract(epicDir, pr.artifact);
753
848
  warnIncompleteDiscovery(epicDir, pr.artifact);
754
849
  const approvalsBefore = JSON.stringify(approvals);
@@ -756,7 +851,7 @@ export async function gateSync(root, { epic, artifact, today, reader = readPr, f
756
851
  const stateBefore = JSON.stringify(state);
757
852
  const nudgedBefore = JSON.stringify(pr.nudged || []);
758
853
  const recs = mapApprovers(pull.reviews, { headOid: pull.headOid });
759
- approvals = upsertBridge(approvals, recs, { stepId: step.id, artifact: pr.artifact, curHash, today, prNumber: pr.number ?? null, closed: alreadyDone, aliases, clashed, accepted: acceptedHashes(epicDir, pr.artifact) });
854
+ approvals = upsertBridge(approvals, recs, { stepId: step.id, artifact: pr.artifact, bindHash: approvedHash, today, prNumber: pr.number ?? null, closed: alreadyDone, merged: !!pull.merged, aliases, clashed, accepted: acceptedHashes(epicDir, pr.artifact) });
760
855
 
761
856
  const changeRequested = pull.reviews.filter((r) => r.state === 'CHANGES_REQUESTED');
762
857
  // 2f: companion scaffolding + nudge threads carry the noblock marker and are EXCLUDED from the
@@ -800,13 +895,20 @@ export async function gateSync(root, { epic, artifact, today, reader = readPr, f
800
895
  const pred = gatePredicate({
801
896
  // E72: caps the reported ask at `active − 1`; `null` (not counted) gives no cap. Only the base holds.
802
897
  active: people.capacity.active,
803
- step, approvals, currentHash: curHash, acceptedHashes: acceptedHashes(epicDir, pr.artifact),
898
+ // An open review is judged against its own head — what it will merge — and a merged one against the
899
+ // default branch (#366).
900
+ step, approvals, currentHash: curHash,
901
+ acceptedHashes: !pull.merged && approvedHash ? [approvedHash]
902
+ : differs && curHash === null ? [NOTHING_ON_DEFAULT] : acceptedHashes(epicDir, pr.artifact),
804
903
  threadsResolved, merged: pull.merged, solo, requireEngagement: reqEng,
805
904
  // Which steps may be skipped is a fact about THIS epic's route (E35), so it is resolved from the
806
905
  // ledger here rather than from a module-level set that answered the same for every epic.
807
906
  optional: optionalStepsFor(state),
808
907
  });
809
908
 
909
+ // #418: a done step whose artifact a merge changed, with no approval covering it now (or null).
910
+ const changedSinceApproved = alreadyDone && pull.merged && !pred.passed ? doneStepUnapproved(epicDir, step, approvals) : null;
911
+
810
912
  // Say the arithmetic, not just the verdict (rule 6): the count, the cap when the people were counted,
811
913
  // and which half of it holds the gate — only the base until E108 — labelled so nobody reads a number
812
914
  // the gate is not enforcing as the reason it did or did not pass.
@@ -821,6 +923,10 @@ export async function gateSync(root, { epic, artifact, today, reader = readPr, f
821
923
  step: step.id, artifact: pr.artifact, pr: pr.number ?? null, merged: !!pull.merged, rule: pred.rule,
822
924
  passed: !!pred.passed, alreadyDone: !!alreadyDone, have: pred.have, gateRule: pred.gateRule ?? null,
823
925
  cap: pred.cap ?? null, short: pred.short ?? null, missing: pred.missing, staleDropped: pred.staleDropped ?? 0,
926
+ // #366: merged, and the default branch holds other content than this review approved.
927
+ differs,
928
+ // #418: a done step whose artifact changed after it was approved — said, never enforced.
929
+ changedSinceApproved: !!changedSinceApproved,
824
930
  });
825
931
  // E73: why this gate may not pass — reported only, never enforced. Only on a gate that counted
826
932
  // (`rule: 'count'`, so never in solo mode) and is still open: not one already done (`alreadyDone` —
@@ -843,6 +949,11 @@ export async function gateSync(root, { epic, artifact, today, reader = readPr, f
843
949
  if (stepStatus(step) === 'deferred') {
844
950
  info(`${step.id} is deferred — approvals re-synced, chain not re-advanced; its review is still owed`);
845
951
  for (const m of pred.missing) hand(`still owed: ${m}`);
952
+ } else if (changedSinceApproved) {
953
+ // #418: a merge changed the artifact and no approval covers it now. The gate stays one-way — the step
954
+ // is not reopened and nothing is refused — so this is said loudly, with the way to review it again.
955
+ warn(forTerminal(`${step.id} is done, but ${step.artifact} changed after it was approved — none of its ${changedSinceApproved.count} approval(s) covers it as it stands now; the step stays done`));
956
+ hand(forTerminal(reviewAsItStands(epic, step.artifact, resolveDefaultBranch(productGit(root), productConfig))));
846
957
  } else {
847
958
  const verdict = pred.passed ? 'the rule still holds' : `the rule no longer holds${pred.staleDropped ? ` (${pred.staleDropped} stale)` : ''}`;
848
959
  info(`${step.id} already done — approvals re-synced, chain not re-advanced; ${verdict}`);
@@ -864,6 +975,21 @@ export async function gateSync(root, { epic, artifact, today, reader = readPr, f
864
975
  });
865
976
  advanced++;
866
977
  ok(`gate PASSED — ${step.id} → done; next: ${state.currentStep}`);
978
+ // A review after a reopened step passed (#322): the later reviews opened before now are retired, so
979
+ // each is reviewed afresh. The platform's newest number bounds them; this PR's own number when the
980
+ // platform cannot answer — said, and the CI run goes red, since a later PR above it is then not covered.
981
+ // Not on a read-only run: nothing it records is kept.
982
+ // Nothing to retire when no review comes after this one (`test-cases-review`): no question, no red run.
983
+ const laterReview = state.steps.slice(state.steps.findIndex((s) => s?.id === step.id) + 1).some((s) => isGateStep(s));
984
+ if (!readOnly && laterReview && reopenStampDue(state, step.id)) {
985
+ const got = newest(platform, { cwd: root });
986
+ if (!got?.ok) {
987
+ warn(`could not ask the platform for its newest PR/MR (${String(got?.reason ?? 'no answer').split('\n')[0]}) — the later reviews are retired only up to #${pr.number}; close any later review PR/MR opened since by hand`);
988
+ if (!local) process.exitCode = 1;
989
+ }
990
+ const n = Math.max(got?.ok && Number.isInteger(got.number) ? got.number : 0, Number(pr.number) || 0);
991
+ if (stampPassed(state, step.id, { platform, number: n })) info(`${step.id} passed again after \`yad gate reopen\` — the later steps' review PRs up to #${n} are retired; review each again on a fresh PR/MR`);
992
+ }
867
993
  } else {
868
994
  state = markInReview(state, step, { by, date: today, pr: pr.number ?? null, hash: curHash });
869
995
  for (const m of pred.missing) hand(`still needed: ${m}`);
@@ -975,11 +1101,31 @@ export function convertProductLevel(root, productConfig, { git = (...a) => run('
975
1101
  }
976
1102
  }
977
1103
 
978
- export async function gateCi(root, { branch, pr, merged = false, today, push = true, reader = readPr, branchOf = prBranch } = {}) {
1104
+ export async function gateCi(root, { branch, pr, merged = false, today, push = true, reader = readPr, branchOf = prBranch, newest = newestPrNumber, contentAt = headContentHash } = {}) {
979
1105
  const { productConfig } = loadProduct(root);
980
1106
  if (!productConfig?.platform) { warn(`no Product platform configured (${settingsEditHint(root)}) — nothing to sync`); return { synced: 0, committed: false, pushed: false }; }
981
1107
  const git = (...args) => run('git', args, { cwd: root });
982
1108
  const defaultBranch = productConfig.default_branch || (() => { const h = git('rev-parse', '--abbrev-ref', 'HEAD').stdout; return h && h !== 'HEAD' ? h : 'main'; })();
1109
+ // #115: a run that pushes (a merge, or the sweep) pushes HEAD to the default branch. From an epic's
1110
+ // worktree on a step branch that would publish the step's unreviewed commits, so a NAMED branch other
1111
+ // than the default is refused. A detached HEAD is allowed: some CI checks out that way (the shipped
1112
+ // workflows check out the default branch by name). Compared with the configured default or origin/HEAD —
1113
+ // never the current-branch fallback above, which always matches.
1114
+ if (push && (merged || !branch)) {
1115
+ const head = git('rev-parse', '--abbrev-ref', 'HEAD').stdout;
1116
+ const originHead = git('symbolic-ref', '--short', 'refs/remotes/origin/HEAD');
1117
+ const trunk = productConfig.default_branch || (originHead.ok && originHead.stdout ? originHead.stdout.replace(/^origin\//, '') : null);
1118
+ // An epic's Product worktree sits detached: there, the same rule as the other default-branch commands.
1119
+ // In a worktree the default branch is never left unknown: a missing setting must not skip this check.
1120
+ const wtTrunk = trunk || resolveDefaultBranch(git, productConfig);
1121
+ const detachedWorktree = head === 'HEAD' && worktreeAt(root)?.repo === null && !onlyYadCommitsAhead(git, wtTrunk);
1122
+ if ((head && head !== 'HEAD' && trunk && head !== trunk) || detachedWorktree) {
1123
+ fail(`on '${forTerminal(head === 'HEAD' ? 'a detached HEAD with commits of its own' : head)}', not the default branch '${forTerminal(trunk || wtTrunk)}' — yad gate ci pushes HEAD to the default branch, and this branch's commits are not reviewed`);
1124
+ hand(`run it from the default branch: \`git switch ${forTerminal(trunk || wtTrunk)}\` (in an epic worktree, \`git fetch origin ${forTerminal(trunk || wtTrunk)}\` then \`git switch --detach origin/${forTerminal(trunk || wtTrunk)}\`)`);
1125
+ process.exitCode = 1;
1126
+ return { synced: 0, committed: false, pushed: false };
1127
+ }
1128
+ }
983
1129
  // Push is decided AFTER the sync, once we know whether any step advanced: a held step (no advance,
984
1130
  // not merged) is read-only and pushes nothing; an advance lands on the default branch (see below).
985
1131
 
@@ -1063,6 +1209,18 @@ export async function gateCi(root, { branch, pr, merged = false, today, push = t
1063
1209
  }
1064
1210
  const step = findReviewStep(ledger.state, job.artifact);
1065
1211
  if (!step) { warn(`${job.epic}: no review step for ${job.artifact} — skipping`); continue; }
1212
+ // A review `yad gate reopen` retired (#322) never passes its gate again. Without this the reconcile run,
1213
+ // which replays every review merged in the last days, would read the old merge and undo the reopen.
1214
+ if (!isPassed(step) && Number(job.pr) > 0 && retiredPr(ledger.state, job.artifact, Number(job.pr), productConfig.platform)) {
1215
+ info(`${job.epic}: PR #${job.pr} was retired by \`yad gate reopen\` — it does not pass ${step.id} again; a fresh review does`);
1216
+ continue;
1217
+ }
1218
+ // A review held behind a reopened step (#322) is not recorded either: it is retired once that step passes.
1219
+ const holdFor = !isPassed(step) ? heldByReopen(ledger.state, step.id) : null;
1220
+ if (holdFor) {
1221
+ info(`${job.epic}: ${step.id} waits for ${holdFor}, an earlier step not passed since \`yad gate reopen\` — PR #${job.pr} is not recorded, and is retired once ${holdFor} passes`);
1222
+ continue;
1223
+ }
1066
1224
 
1067
1225
  // The merge event may fire before any hub-prs record exists (Path B never wrote one pre-merge) —
1068
1226
  // build the entry from the event itself so the advance commit carries it onto the default branch.
@@ -1080,12 +1238,14 @@ export async function gateCi(root, { branch, pr, merged = false, today, push = t
1080
1238
  let older = merged && existing?.number != null && Number(job.pr) > 0 && Number(job.pr) < existing.number
1081
1239
  && (existing.platform == null || existing.platform === productConfig.platform);
1082
1240
  let unread = false;
1241
+ let trialDiffers = false;
1083
1242
  if (older && !isPassed(step)) {
1084
1243
  // Silenced: its verdict is only this decision's input, and would read as a second verdict in the
1085
1244
  // CI log. Its exit code is this decision's too — a failed read is said, and failed, below.
1086
1245
  const code = process.exitCode;
1087
- const trial = await quietly(() => gateSync(root, { epic: job.epic, artifact: job.artifact, today, reader, dryRun: true, probe: Number(job.pr), headCount: sweepCount }));
1246
+ const trial = await quietly(() => gateSync(root, { epic: job.epic, artifact: job.artifact, today, reader, dryRun: true, probe: Number(job.pr), headCount: sweepCount, contentAt }));
1088
1247
  process.exitCode = code;
1248
+ trialDiffers = trial.gates.some((g) => g.differs);
1089
1249
  if (trial.gates.some((g) => g.passed)) older = false;
1090
1250
  else if (!trial.gates.length) {
1091
1251
  // A failed platform read is not "does not pass": the gate cannot tell, so the run goes red.
@@ -1095,6 +1255,12 @@ export async function gateCi(root, { branch, pr, merged = false, today, push = t
1095
1255
  }
1096
1256
  }
1097
1257
  if (older && !unread) info(`${job.epic}: PR #${job.pr} is older than #${existing.number}, the review recorded for ${job.artifact}, and ${isPassed(step) ? `the step is already ${stepStatus(step) === 'deferred' ? 'deferred' : stepStatus(step) === 'skipped' ? 'skipped' : 'done'}` : 'does not pass the gate'} — syncing #${existing.number}`);
1258
+ // The trial ran silenced: say why when it was the content (#366), or the team chases approvals on the
1259
+ // newer review when only a fresh review of the artifact as it stands can pass.
1260
+ if (older && !unread && trialDiffers) {
1261
+ warn(`${job.epic}: PR #${job.pr} approved a different ${job.artifact} than the default branch holds now — another merge changed it after that review`);
1262
+ hand(forTerminal(reviewAsItStands(job.epic, step.artifact, resolveDefaultBranch(productGit(root), productConfig))));
1263
+ }
1098
1264
  // Before the pointer moves to a number other than the one it holds, ask the platform that the PR/MR is on
1099
1265
  // this review branch: a mistyped `--pr` on the manual recovery would otherwise become the pointer,
1100
1266
  // and with numbers that only grow it could stay there (issue #362 review). A platform that cannot
@@ -1145,7 +1311,7 @@ export async function gateCi(root, { branch, pr, merged = false, today, push = t
1145
1311
  try {
1146
1312
  // A branch event that is not a merge can never advance (the predicate requires merged), so it
1147
1313
  // is read-only under Path B — run it as a dry sync that persists nothing to the working tree.
1148
- const r = await gateSync(root, { epic: job.epic, artifact: job.artifact, today, reader, dryRun: !!branch && !merged, headCount: sweepCount });
1314
+ const r = await gateSync(root, { epic: job.epic, artifact: job.artifact, today, reader, dryRun: !!branch && !merged, headCount: sweepCount, newest, contentAt });
1149
1315
  synced += r.synced;
1150
1316
  // When the step actually ADVANCED (the merge phase, or a swept merge the schedule observed),
1151
1317
  // reflect it in the artifact frontmatter (draft → approved). Keyed off the advance, not the
@@ -1274,8 +1440,8 @@ export async function gateCi(root, { branch, pr, merged = false, today, push = t
1274
1440
  // back to the current branch when hub.json names none, and a person may run this from any checkout
1275
1441
  // (E19 review). `stageIndexIfClean` keeps it out of a commit that does not hold what it read.
1276
1442
  const onDefault = (() => {
1277
- const head = git('rev-parse', '--abbrev-ref', 'HEAD');
1278
- return head.ok && head.stdout === resolveDefaultBranch(git, productConfig);
1443
+ const trunk = resolveDefaultBranch(git, productConfig);
1444
+ return branchToCommitOn(root, git, trunk) === trunk; // an epic Product worktree's detached HEAD too (#115)
1279
1445
  })();
1280
1446
  const indexStaged = onDefault ? stageIndexIfClean(root, git) : false;
1281
1447
  if (!onDefault) info(`${INDEX_FILE} not rebuilt — this checkout is not on the default branch, the only place it is written`);
@@ -1369,6 +1535,12 @@ export async function gateStatus(root, { epic, headCount: given = null } = {}) {
1369
1535
  // E74: in solo mode, suggest `yad mode team` when the count shows more than one person may work here.
1370
1536
  // An unknown count is already said by `activeSum` just above, so only a known suggestion prints.
1371
1537
  printTeamHint(soloTeamHint(root, productConfig, { solo, headCount }));
1538
+ // The approvals `yad gate reopen` revoked are no longer in approvals.json, so they are not counted below;
1539
+ // say where they went (#322).
1540
+ for (const r of (Array.isArray(ledger.state.reopens) ? ledger.state.reopens : []).slice(-1)) {
1541
+ if (!isPlainObject(r)) continue;
1542
+ log(` ${c.dim(`reopened ${printable(r.step) ?? '?'}${r.date ? ` on ${printable(r.date)}` : ''}${r.by ? ` by ${printable(r.by)}` : ''}${r.reason ? ` — ${printable(r.reason)}` : ''}: ${Array.isArray(r.revokedApprovals) ? r.revokedApprovals.length : 0} approval(s) revoked, kept in state.json reopens[]`)}`);
1543
+ }
1372
1544
  const reachSeen = new Set(); // E73: each warning line once per view, not once per step
1373
1545
  const gates = []; // the --json answer (E1): each review step as this view reads it
1374
1546
  for (const s of ledger.state.steps.filter((x) => x.type === 'review+approve')) {
@@ -1504,8 +1676,8 @@ export async function gateRepair(root, { epic, push = false, allowBranch = false
1504
1676
  // --- publish: narrow, default-branch-only commit of the one repaired file ---
1505
1677
  preflightGuardReadiness(root);
1506
1678
  const git = productGit(root);
1507
- const branch = git('rev-parse', '--abbrev-ref', 'HEAD').stdout;
1508
1679
  const defaultBranch = resolveDefaultBranch(git, loadProduct(root).productConfig);
1680
+ const branch = branchToCommitOn(root, git, defaultBranch);
1509
1681
  if (!guardDefaultBranch(branch, defaultBranch, { allowBranch, cmd: 'yad gate repair', root })) return did(true);
1510
1682
 
1511
1683
  const spec = path.relative(root, ledger.files.state);
@@ -1536,6 +1708,168 @@ export async function gateRepair(root, { epic, push = false, allowBranch = false
1536
1708
  return did(true, true, false);
1537
1709
  }
1538
1710
 
1711
+ // PURE — the audit-trail commit message for a reopen (#322), in the same form as the repair's. The reason
1712
+ // is the person's, kept to one line in the subject; the body lists what was undone.
1713
+ export function buildReopenMessage({ epic, step, reason, walked = [], revoked = 0, retired = [] }) {
1714
+ const one = String(reason).replace(/\s+/g, ' ').trim();
1715
+ const subject = `chore(gate): reopen ${epic}/${step} — ${one.length > 72 ? `${one.slice(0, 71)}…` : one} [skip ci]`;
1716
+ return `${subject}\n\nEpic: ${epic}\nReopened: ${step}\nWalked back: ${walked.join(', ') || 'none'}\nRevoked approvals: ${revoked}\nRetired review PRs: ${retired.length ? retired.map((n) => `#${n}`).join(', ') : 'none'}\nReason: ${one}`;
1717
+ }
1718
+
1719
+ // The exact yadflow the wired gate-sync job runs, when the Product pins one: `gate_sync_version`, else the
1720
+ // `.sdlc/cli-version.json` stamp — the workflow's own order, an exact release of this major only (else it
1721
+ // floats on the major). A `YAD_VERSION` variable on the platform overrides both and cannot be seen here.
1722
+ function ciPin(root, productConfig) {
1723
+ const major = String(VERSION).split('.')[0];
1724
+ const exact = (v) => typeof v === 'string' && /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(v) && v.split('.')[0] === major;
1725
+ for (const v of [productConfig?.gate_sync_version, readJSON(path.join(root, PROJECT_FILES.version), null)?.version]) if (exact(v)) return v;
1726
+ return null;
1727
+ }
1728
+ // Is `a` an older release than `b`? x.y.z compared as numbers; a prerelease is older than its release, and
1729
+ // two prereleases compare part by part (`next.2` is older than `next.10`).
1730
+ export function olderThan(a, b) {
1731
+ const parse = (v) => { const i = String(v).indexOf('-'); const core = i === -1 ? String(v) : String(v).slice(0, i); return { n: core.split('.').map(Number), pre: i === -1 ? null : String(v).slice(i + 1).split('.') }; };
1732
+ const x = parse(a); const y = parse(b);
1733
+ for (let i = 0; i < 3; i++) if (x.n[i] !== y.n[i]) return x.n[i] < y.n[i];
1734
+ if (x.pre === null || y.pre === null) return x.pre !== null && y.pre === null;
1735
+ for (let i = 0; i < Math.max(x.pre.length, y.pre.length); i++) {
1736
+ const p = x.pre[i]; const q = y.pre[i];
1737
+ if (p === undefined) return true;
1738
+ if (q === undefined) return false;
1739
+ const np = /^\d+$/.test(p); const nq = /^\d+$/.test(q);
1740
+ if (np && nq && Number(p) !== Number(q)) return Number(p) < Number(q);
1741
+ if (np !== nq) return np;
1742
+ if (p !== q) return p < q;
1743
+ }
1744
+ return false;
1745
+ }
1746
+ // The first release whose `yad gate ci` / `yad gate sync` know a retired review PR (#322). A CI pinned
1747
+ // below it would replay the old merge and pass the gate again.
1748
+ export const REOPEN_SINCE = '4.7.0';
1749
+
1750
+ // `yad gate reopen <epic> <step> --reason "<why>"` (#322) — reopen an approved Shape step before Build
1751
+ // starts. The step goes back to `in_progress`, every later step that started goes back to `todo`, and the
1752
+ // walked-back reviews' approvals and review PRs move into `state.json`'s `reopens[]` audit, so every gate
1753
+ // from the step on must be approved again. The rules are `reopenStep`'s (cli/epic-state.mjs); this loads,
1754
+ // writes and, with --push, commits.
1755
+ //
1756
+ // ON A VERIFIED PRODUCT only CI writes the ledger, and a hand commit of it is refused. As with `gate repair`,
1757
+ // the commit this command makes with --push is the owning one; without --push nothing is written, because a
1758
+ // reopen left on disk could not be committed any other way. And CI must run a yadflow that knows about
1759
+ // reopens: an older `gate ci` would replay the retired review's merge and pass the gate again.
1760
+ export async function gateReopen(root, { epic, step, reason, push = false, allowBranch = false, dryRun = false, today = new Date().toISOString().slice(0, 10), newest = newestPrNumber } = {}) {
1761
+ const none = { epic, step: step ?? null, currentStep: null, walkedBack: [], kept: [], revoked: 0, retiredPrs: [], retiredUpTo: null, written: [], dryRun, committed: false, pushed: false };
1762
+ if (!step) { fail('usage: yad gate reopen <epic> <step> --reason "<why>" [--push]'); process.exitCode = 1; return none; }
1763
+ const epicDir = epicRoot(root, epic);
1764
+ const ledger = loadLedger(epicDir);
1765
+ if (!ledger.state) { fail(`no epic state at ${epicDir}/.sdlc/state.json`); process.exitCode = 1; return none; }
1766
+ const productConfig = readJSON(productConfigPath(root), null);
1767
+ const verified = isVerifiedLedger(productConfig);
1768
+
1769
+ log(c.bold(`\nyad gate reopen ${c.dim(`${epic} ${step}`)}`));
1770
+ // The rules throw a YadError with its fix; the top-level handler prints it.
1771
+ const opts = {
1772
+ reason, by: closingActor(root, productConfig), at: today,
1773
+ approvals: ledger.approvals, productPrs: ledger.productPrs, buildStates: ledger.buildStates,
1774
+ shipped: readShips(epicDir), contractLockHash: ledger.contractLock?.hash ?? null,
1775
+ };
1776
+ const first = reopenStep(ledger.state, step, opts);
1777
+ // A review PR of a later step that the ledger never recorded — on a verified Product CI writes a pointer
1778
+ // only at merge — would merge on approvals given before the reopen. Numbers only grow, so the platform's
1779
+ // newest number now bounds every review opened before this moment: all of them, for the reopened step and
1780
+ // every later one, are retired (`retiredUpTo`). A platform that cannot answer leaves that unknown:
1781
+ // refused on a verified Product, where only CI's merge advances the chain.
1782
+ let upTo = null;
1783
+ const platform = productConfig?.platform || null;
1784
+ if (platform) {
1785
+ const got = newest(platform, { cwd: root });
1786
+ if (got.ok) upTo = got.number ? { platform, number: got.number } : null;
1787
+ else {
1788
+ const say = `the platform could not say which review PRs were opened before now (${String(got.reason ?? 'no answer').split('\n')[0]})`;
1789
+ if (verified) {
1790
+ fail(`${forTerminal(say)} — one of them could pass its gate on approvals from before the reopen; nothing is written`);
1791
+ hand('check the platform CLI is installed and logged in (`yad doctor`), then reopen again');
1792
+ process.exitCode = 1;
1793
+ return none;
1794
+ }
1795
+ warn(`${forTerminal(say)} — a review PR opened before the reopen and never recorded is not retired; close it by hand`);
1796
+ }
1797
+ }
1798
+ const r = upTo ? reopenStep(ledger.state, step, { ...opts, upTo }) : first;
1799
+ const a = r.audit;
1800
+ const walkedBack = a.steps.map((x) => x.id);
1801
+ const retiredNos = a.retiredPrs.map((p) => p.number).filter((n) => n != null);
1802
+ const answer = (extra = {}) => ({ ...none, currentStep: r.state.currentStep, walkedBack, kept: a.kept.map((k) => k.id), revoked: a.revokedApprovals.length, retiredPrs: retiredNos, retiredUpTo: a.retiredUpTo?.number ?? null, ...extra });
1803
+ info(forTerminal(`${walkedBack.join(', ')} go back (${step} to in_progress, the rest to todo); currentStep ${a.from ?? '—'} → ${r.state.currentStep}`));
1804
+ if (a.kept.length) info(forTerminal(`kept as they are (set aside, not built on ${step}): ${a.kept.map((k) => `${k.id} (${k.status})`).join(', ')}`));
1805
+ info(`${a.revokedApprovals.length} approval(s) revoked and ${retiredNos.length} review PR(s) retired${a.retiredUpTo ? `, with every review PR up to #${a.retiredUpTo.number} for ${a.retiredUpTo.artifacts.join(', ')}` : ''} — kept in ${epicRel(epic)}/.sdlc/state.json reopens[]`);
1806
+
1807
+ // Child epics that inherit a step walked back here carry an approval that no longer stands upstream.
1808
+ const children = epicIds(root).filter((id) => id !== epic).filter((id) => {
1809
+ try { const l = epicLineage(root, id); return l.parent === epic && l.inherits.some((x) => walkedBack.includes(x)); } catch { return false; }
1810
+ });
1811
+ if (children.length) warn(`${children.join(', ')} inherit${children.length === 1 ? 's' : ''} a step walked back here — check ${children.length === 1 ? 'it' : 'them'} with \`yad doctor\` once the new review passes`);
1812
+
1813
+ if (verified) {
1814
+ const pin = ciPin(root, productConfig);
1815
+ if (pin && olderThan(pin, REOPEN_SINCE)) {
1816
+ fail(`CI runs yadflow@${pin}, older than ${REOPEN_SINCE}, the first release that knows about reopens — it would replay the retired review's merge and pass the gate again; nothing is written`);
1817
+ hand(`run \`yad update\`, commit and push ${PROJECT_FILES.version} (the CI pin), then reopen`);
1818
+ process.exitCode = 1;
1819
+ return answer();
1820
+ }
1821
+ if (!pin) warn(`CI's yadflow version is not pinned here, so it floats on the latest release of this major — reopen needs ${REOPEN_SINCE} or later there (a YAD_VERSION variable on the platform overrides this, and cannot be seen from here)`);
1822
+ }
1823
+ if (dryRun) { info('dry run — nothing written'); return answer(); }
1824
+ if (verified && !push) {
1825
+ fail('on a verified Product only the commit yad makes may change the ledger — nothing is written');
1826
+ hand(`re-run with --push: \`yad gate reopen ${epic} ${step} --reason "…" --push\``);
1827
+ process.exitCode = 1;
1828
+ return answer();
1829
+ }
1830
+
1831
+ writeState(ledger.files.state, r.state);
1832
+ writeJSON(ledger.files.approvals, canonicalApprovals(r.approvals));
1833
+ writeMirrored(ledger.files.productPrs, ledger.files.productPrsLegacy, canonicalProductPrs(r.productPrs));
1834
+ const statusFiles = lowerStatuses(root, epic, r.state);
1835
+ const rel = (f) => path.relative(root, f);
1836
+ const written = [rel(ledger.files.state), rel(ledger.files.approvals), rel(ledger.files.productPrs), rel(ledger.files.productPrsLegacy), ...statusFiles];
1837
+ ok(`${step} reopened — ${walkedBack.length - 1} later step(s) back to todo, ${a.revokedApprovals.length} approval(s) revoked`);
1838
+ for (const f of statusFiles) info(`${f}: status lowered to match`);
1839
+ const open = a.retiredPrs.filter((p) => p.number != null);
1840
+ if (open.length) hand(`close the retired review PR(s) on the platform if still open: ${open.map((p) => `#${p.number}`).join(', ')} — yad does not close them`);
1841
+ hand(`next: author ${step} again, then \`yad gate open ${epic} <artifact>\` for a fresh review`);
1842
+
1843
+ if (!push) {
1844
+ refreshIndexAfterWrite(root, productConfig);
1845
+ hand(`commit ${written.join(', ')} (or re-run with --push)`);
1846
+ return answer({ written });
1847
+ }
1848
+ preflightGuardReadiness(root);
1849
+ const git = productGit(root);
1850
+ const defaultBranch = resolveDefaultBranch(git, loadProduct(root).productConfig);
1851
+ const branch = branchToCommitOn(root, git, defaultBranch);
1852
+ if (!guardDefaultBranch(branch, defaultBranch, { allowBranch, cmd: 'yad gate reopen', root })) return answer({ written });
1853
+ // Only the files this run wrote, and only those git sees (a legacy mirror never committed is left out).
1854
+ const specs = written.filter((f) => git('add', '--', f).ok);
1855
+ if (git('diff', '--cached', '--quiet', '--', ...specs).ok) { info('nothing changed on disk — nothing to commit'); return answer({ written }); }
1856
+ const all = [...specs, ...(branch === defaultBranch && !verified && stageIndexIfClean(root, git, specs) ? [INDEX_FILE] : [])];
1857
+ const message = buildReopenMessage({ epic, step, reason: a.reason, walked: walkedBack, revoked: a.revokedApprovals.length, retired: retiredNos });
1858
+ const cm = run('git', ['commit', '-m', message, '--', ...all], { cwd: root, env: OWNING_COMMIT_ENV() });
1859
+ if (!cm.ok) {
1860
+ git('reset', '-q', '--', ...all);
1861
+ fail(`git commit failed — ${cm.stderr.split('\n')[0] || cm.code}`);
1862
+ process.exitCode = 1;
1863
+ return answer({ written });
1864
+ }
1865
+ ok(`committed the reopen: ${c.dim(message.split('\n')[0])}`);
1866
+ if (pushWithRebase(root, branch).ok) { ok(`pushed to origin/${branch}`); return answer({ written, committed: true, pushed: true }); }
1867
+ fail(`could not push to origin/${branch} — a protected branch, or an unresolvable rebase conflict`);
1868
+ hand('run `git pull --rebase`, then `git push` — the reopen is committed locally');
1869
+ process.exitCode = 1;
1870
+ return answer({ written, committed: true });
1871
+ }
1872
+
1539
1873
  // `head` overrides the review branch the PR is opened against — `open-pr` delegates here after pushing
1540
1874
  // the user's checked-out branch, which for a per-story review (review/EP-*/stories-S01) does NOT equal
1541
1875
  // the branch this would otherwise recompute (artifactFromBase collapses stories-S01 → stories/). Pass
@@ -1561,6 +1895,14 @@ export async function gateOpen(root, { epic, artifact, head, creator = createPr,
1561
1895
  process.exitCode = 1;
1562
1896
  return;
1563
1897
  }
1898
+ // After a reopen the gates pass again in order (#322): no later review opens before the reopened step passes.
1899
+ const held = heldByReopen(ledger.state, step.id);
1900
+ if (held) {
1901
+ fail(`${step.id} waits for ${held}, an earlier step not passed since \`yad gate reopen\` — no review is opened`);
1902
+ hand(`pass ${held} first; the gates from a reopened step pass again in order`);
1903
+ process.exitCode = 1;
1904
+ return;
1905
+ }
1564
1906
  const b = base(artifact);
1565
1907
  const branch = head || `review/${epic}/${b}`;
1566
1908
  const domains = touchedDomains(epicDir, step);