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
@@ -2,7 +2,9 @@
2
2
  // source of truth; the platform PR/MR is only an input path. Everything here is pure / filesystem —
3
3
  // no gh/glab — so the predicate is unit-testable without a network. Node built-ins only.
4
4
  import path from 'node:path';
5
+ import os from 'node:os';
5
6
  import { createHash } from 'node:crypto';
7
+ import { spawnSync } from 'node:child_process';
6
8
  import fs from 'node:fs';
7
9
  import { isPlainObject, readJSON, readJSONStrict, writeJSON, fileSha } from './lib.mjs';
8
10
  import { err } from './errors.mjs';
@@ -489,6 +491,12 @@ export function upsertProductPr(productPrs = [], rec) {
489
491
  return canonicalProductPrs([...productPrs.filter((p) => p.artifact !== rec.artifact), rec]);
490
492
  }
491
493
 
494
+ // Split the review PR pointers: the ones `take` picks come out, the rest stay (`yad gate reopen`, #322).
495
+ export function removeProductPrs(productPrs = [], take) {
496
+ const list = Array.isArray(productPrs) ? productPrs : [];
497
+ return { kept: canonicalProductPrs(list.filter((p) => !take(p))), taken: list.filter((p) => take(p)) };
498
+ }
499
+
492
500
  // SHA-256 of the contract surface block (architecture only). Byte-for-byte identical to the recipe
493
501
  // yad-architecture/references/contract-format.md publishes — the one the architect runs to write
494
502
  // contract-lock.json:
@@ -954,6 +962,84 @@ export function acceptedHashes(epicDir, artifact) {
954
962
  // approval with no hash) or nothing can be fingerprinted — both are "no claim", as they always were.
955
963
  export const isStaleHash = (recorded, accepted) => !!recorded && accepted.length > 0 && !accepted.includes(recorded);
956
964
 
965
+ // A done review step whose artifact changed after it was approved (#418): it holds approvals, and none of
966
+ // them is live against the artifact as it stands. → { count } (the step's approvals), or null. `yad doctor`,
967
+ // the gate and `yad status` ask this one question. A done step with no approval at all is a different
968
+ // finding (doctor's `:unapproved`), and nothing to fingerprint is no staleness claim.
969
+ export function doneStepUnapproved(epicDir, step, approvals) {
970
+ if (!step || step.type !== 'review+approve' || stepStatus(step) !== 'done' || typeof step.artifact !== 'string') return null;
971
+ const forStep = (Array.isArray(approvals) ? approvals : []).filter((a) => a?.step === step.id && a.status === 'approved');
972
+ if (!forStep.length) return null;
973
+ // A read-only question: an artifact that cannot be read (a hand-edited path naming a folder) is no claim.
974
+ let accepted;
975
+ try { accepted = acceptedHashes(epicDir, step.artifact); } catch { return null; }
976
+ if (!accepted.length) return null;
977
+ return forStep.some((a) => !isStaleHash(a.artifactHash, accepted)) ? null : { count: forStep.length };
978
+ }
979
+
980
+ // The fingerprint of `artifact` as it stands at the git commit `rev` (#366): the head a review approved.
981
+ // The review's files (`artifactPaths`) are copied out of the commit into a scratch epic folder and
982
+ // fingerprinted by `artifactHash` itself, so a commit and the disk are never hashed by two copies of the
983
+ // rules. Each file is read through git's checkout filters (`cat-file --filters`), so line-ending
984
+ // conversion (`core.autocrlf`, an `eol` attribute) gives the bytes a checkout would put on disk. Only
985
+ // regular files are copied: a link or a submodule there leaves the copy different, so it can only fail
986
+ // to match. `rev` must be a full SHA — a name could be a branch or tag standing in for another
987
+ // commit (#410). `root` is the Product's checkout, and `epicDir` a folder inside it.
988
+ // → { ok: true, hash, copied } (`hash` null when there is nothing to fingerprint, as `artifactHash`; `copied`
989
+ // the number of files found there), or
990
+ // { ok: false, reason } when the commit cannot be read here.
991
+ export function artifactHashAt(root, epicDir, artifact, rev) {
992
+ if (!/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/.test(rev || '')) return { ok: false, reason: `'${rev ?? ''}' is not a full commit SHA` };
993
+ const git = (...args) => spawnSync('git', ['--literal-pathspecs', ...args], { cwd: root, maxBuffer: 256 * 1024 * 1024, env: { ...process.env, GIT_OPTIONAL_LOCKS: '0' } });
994
+ if (git('cat-file', '-e', `${rev}^{commit}`).status !== 0) return { ok: false, missing: true, reason: `commit ${rev.slice(0, 12)} is not in this clone` };
995
+ const rel = path.relative(root, epicDir).split(path.sep).join('/');
996
+ // `--filters` needs each path as the repository names it, from its top, not from `root`.
997
+ const prefix = git('rev-parse', '--show-prefix').stdout.toString('utf8').trim();
998
+ const top = `${prefix}${rel ? `${rel}/` : ''}`;
999
+ const listed = git('ls-tree', '-r', '-z', '--full-name', rev, '--', ...artifactPaths(artifactBase(artifact)).map((p) => (rel ? `${rel}/${p}` : p)));
1000
+ if (listed.status !== 0) return { ok: false, reason: `git could not list ${rel || '.'} at ${rev.slice(0, 12)}` };
1001
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'yad-at-'));
1002
+ try {
1003
+ const dir = path.join(tmp, 'epic');
1004
+ fs.mkdirSync(dir);
1005
+ let copied = 0;
1006
+ // A name this disk cannot hold (a Windows-invalid one) is an unreadable head, not a crash.
1007
+ try {
1008
+ for (const entry of listed.stdout.toString('utf8').split('\0')) {
1009
+ const m = entry.match(/^(\d{6}) (\w+) ([0-9a-f]+)\t([\s\S]+)$/);
1010
+ if (!m || m[2] !== 'blob' || !['100644', '100755'].includes(m[1])) continue;
1011
+ if (!m[4].startsWith(top)) continue;
1012
+ const blob = git('cat-file', '--filters', `--path=${m[4]}`, m[3]);
1013
+ if (blob.status !== 0) return { ok: false, reason: `git could not read ${m[4]} at ${rev.slice(0, 12)}` };
1014
+ const out = path.join(dir, ...m[4].slice(top.length).split('/'));
1015
+ fs.mkdirSync(path.dirname(out), { recursive: true });
1016
+ fs.writeFileSync(out, blob.stdout);
1017
+ copied++;
1018
+ }
1019
+ } catch (e) { return { ok: false, reason: `the files at ${rev.slice(0, 12)} could not be copied (${e.code || e.message})` }; }
1020
+ return { ok: true, hash: artifactHash(dir, artifact), copied };
1021
+ } finally {
1022
+ fs.rmSync(tmp, { recursive: true, force: true });
1023
+ }
1024
+ }
1025
+
1026
+ // How to review an artifact as it already stands on the default branch (#366): `yad gate open` needs a review
1027
+ // branch on origin, and a PR/MR needs a commit on it, so an empty one is made.
1028
+ export function reviewAsItStands(epic, artifact, trunk) {
1029
+ // A command the person is invited to paste: each name goes in only as a plain path — `state.json` and the
1030
+ // Product settings are files a person can edit, and `x; curl …|sh/architecture.md` must never reach a
1031
+ // shell (the `asArg` rule in lib.mjs). Anything else is shown as a placeholder.
1032
+ const plain = (s) => typeof s === 'string' && /^\w[\w./-]*$/.test(s) && !s.includes('..');
1033
+ const art = plain(artifact) ? artifact : '<artifact>';
1034
+ const base = plain(artifact) ? artifactBase(artifact) : '<artifact>';
1035
+ const ep = plain(epic) ? epic : '<epic>';
1036
+ const branch = `review/${ep}/${base}`;
1037
+ // `-C` and a forced push: the merged review's branch is usually still there, and its PR/MR is done with.
1038
+ // The fetch first: a branch the platform deleted at merge is still in the clone's remote refs, and
1039
+ // --force-with-lease would refuse against it.
1040
+ return `review ${art} as it stands on a fresh PR/MR: \`git fetch --prune origin\`, \`git switch -C ${branch} origin/${plain(trunk) ? trunk : '<default branch>'}\`, \`git commit --allow-empty -m "docs(${ep.toLowerCase()}): review ${base} as merged"\`, \`git push --force-with-lease -u origin ${branch}\`, then \`yad gate open ${ep} ${art}\``;
1041
+ }
1042
+
957
1043
  // Shape checks for the ledger files. Fail fast with the exact file named — a wrong-shape ledger
958
1044
  // silently treated as a default would be rewritten by the next sync, destroying the real data.
959
1045
  const badShape = (file, what) => err('YAD-STATE-002', `${file}: ${what}`, 'fix the file or restore it from git');
@@ -1596,9 +1682,9 @@ function closeAuthorStep(state, reviewStep, closed = null) {
1596
1682
  // Absent when no cap applied — the count of people was unknown, or it lowered nothing — and
1597
1683
  // in solo mode, where nothing was counted. Never on the author step, as `waived`.
1598
1684
  //
1599
- // FIRST CLOSE WINS: a step that already carries one keeps it. Nothing moves a `done` step back today,
1600
- // so nothing has to remove one; a writer that ever does must take `closed` with it, as `record` goes
1601
- // with `blocked`. No shape change: an older release ignores a key it does not know, and nothing reads
1685
+ // FIRST CLOSE WINS: a step that already carries one keeps it. One writer moves a `done` step back:
1686
+ // `yad gate reopen` (`reopenStep`, #322), and it takes `closed` with it, as `record` goes with `blocked` —
1687
+ // into the epic's `reopens[]` audit, so the record of who closed the step and how is kept, not lost. No shape change: an older release ignores a key it does not know, and nothing reads
1602
1688
  // `done` differently because this is present. Steps finished before it carry none, and nothing asks.
1603
1689
  // `approved` is written by `yad gate advance` (E112): a gate passed on recorded approvals on a Product with
1604
1690
  // no platform, where nothing merges. Before E112 the `yad-review-gate` skill wrote it by hand.
@@ -2033,6 +2119,12 @@ const otherWay = (as) => (as === 'skipped' ? 'deferred' : 'skipped');
2033
2119
  // worded. The gate itself is not waived: `gatePredicate` still reports a deferred step's review as owed.
2034
2120
  function setAsideStep(state, stepId, as, { reason, by = null, at = null, debt = false, profiles = LIFECYCLE_PROFILES } = {}) {
2035
2121
  const V = SET_ASIDE[as];
2122
+ // A step `yad gate reopen` walked back (#322) is reviewed again before it is set aside: setting it aside
2123
+ // would lift the hold on the later reviews without retiring the PRs opened during it.
2124
+ if (reopenedAndOpen(state, stepId)) {
2125
+ throw err('YAD-STATE-004', `${stepId} was reopened with \`yad gate reopen\` and has not passed its review again`,
2126
+ 'pass its review again first; or, if the change makes the step not apply, thread it as a change epic with the yad-change skill');
2127
+ }
2036
2128
  // DEBT IS OWED WORK, and a skip says the step does not apply (E36/E37), so nothing is owed back. Asked
2037
2129
  // first, before any chain question: it is a wrong command, whatever state the chain is in.
2038
2130
  if (debt && !V.carriesDebt) {
@@ -2255,6 +2347,215 @@ export function unblockStep(state, stepId) {
2255
2347
  return state;
2256
2348
  }
2257
2349
 
2350
+ // PURE (on copies). Reopen an APPROVED Shape step before Build starts (`yad gate reopen`, #322). The one
2351
+ // writer that moves a `done` step back. It walks the chain back to the step, so every gate after it must be
2352
+ // approved again, and keeps what it undid in `state.reopens[]` — an audit list that only grows.
2353
+ //
2354
+ // REVOKE BY MOVING, NOT MARKING. Every reader of `approvals.json`, in this release and every earlier one,
2355
+ // counts a record whose `status` is `approved`. A record marked revoked in place would still be counted by
2356
+ // an older yad, and the platform sync (`upsertBridge`) would write it back. So the walked-back reviews'
2357
+ // approvals LEAVE `approvals.json` and are kept, unchanged, in the audit entry; nothing counts them there.
2358
+ // The same for their review PR pointers (`product-prs.json`): they are RETIRED, so a later sync or the CI
2359
+ // reconcile replay cannot read the old merged PR and pass the gate again (`retiredPr`).
2360
+ //
2361
+ // What moves: the author step goes back to `in_progress` (the parallel `test-cases` track keeps the epic at
2362
+ // `ready-for-build`; see below), and every later step that has STARTED here
2363
+ // (`in_progress`, `in_review`, `done`) goes back to `todo`, its review included. A later step SET ASIDE —
2364
+ // skipped, deferred, satisfied (inherited) or blocked — keeps its state and its record: it is a person's
2365
+ // decision, not work built on the step, and it is listed as `kept`. A kept BLOCKED review still loses its
2366
+ // approvals and review PRs: blocked is a wait, not a decision that the step does not apply. `debt` stays on every step.
2367
+ // `currentStep` becomes the step — from `ready-for-build` too, since that claim rested on the approvals now
2368
+ // withdrawn — except for the parallel `test-cases` track, which runs beside Build. Returns `{ state, approvals, productPrs, audit }`; the inputs are not changed.
2369
+ export function reopenStep(state, stepId, { reason, by = null, at = null, approvals = [], productPrs = [], buildStates = [], shipped = [], contractLockHash = null, upTo = null } = {}) {
2370
+ const fail = (msg, hint) => { throw err('YAD-STATE-004', msg, hint); };
2371
+ requireChain(state, 'reopen a step in');
2372
+ if (isProductLevel(state)) fail('the Foundation is not reopened with this command', 'it runs once per product; change it through its own review');
2373
+ if (backfillAnchorKind(state)) fail('a brownfield anchor has no approved Shape step to reopen', 'thread a change off it with the yad-change skill');
2374
+ const next = JSON.parse(JSON.stringify(state));
2375
+ const steps = next.steps;
2376
+ const ai = steps.findIndex((s) => s?.id === stepId);
2377
+ if (ai === -1) fail(`step '${stepId}' is not in this epic's chain`, `its steps: ${steps.map((s) => s?.id).filter(Boolean).join(', ')}`);
2378
+ const step = steps[ai];
2379
+ if (isGateStep(step)) {
2380
+ const author = authorStepFor(next, step);
2381
+ fail(`${stepId} is a review gate — name the step it reviews`, author ? `yad gate reopen <epic> ${author.id} --reason "<why>"` : 'reopen the author step the gate reviews');
2382
+ }
2383
+ if (stepPhase(stepId) === 'build') fail(`${stepId} is a Build step — only a Shape step is reopened`, 'a Build lane moves with `yad build step`');
2384
+ const st = stepStatus(step);
2385
+ if (claimsInherited(step)) fail(`${stepId} was carried from a parent epic, not approved here`, 'thread a change with the yad-change skill');
2386
+ if (st === 'skipped') fail(`${stepId} is skipped, not approved`, `put it back with \`yad unskip <epic> ${stepId}\``);
2387
+ if (st === 'deferred') fail(`${stepId} is deferred, not approved`, `put it back with \`yad undefer <epic> ${stepId}\``);
2388
+ if (st === 'blocked') fail(`${stepId} is blocked, not approved`, `clear it with \`yad unblock <epic> ${stepId}\``);
2389
+ const ri = steps.findIndex((s, k) => k > ai && isGateStep(s) && authorStepFor(next, s)?.id === stepId);
2390
+ const review = ri === -1 ? null : steps[ri];
2391
+ if (!review || st !== 'done' || stepStatus(review) !== 'done') {
2392
+ const rs = review ? stepStatus(review) : null;
2393
+ fail(`${stepId} has not been approved yet${review ? ` (${review.id} is '${rs ?? review.status ?? 'no status'}')` : ''} — nothing to reopen`,
2394
+ rs === 'in_review' ? 'its review is still open: push the change to the review branch, and the approvals bound to the old text no longer count' : 'finish it and its review the usual way');
2395
+ }
2396
+ if (reason == null || reason === true || !String(reason).trim()) fail('a reopen needs a reason', `yad gate reopen <epic> ${stepId} --reason "<what changed, and why the approval no longer holds>"`);
2397
+ // The parallel `test-cases` track runs BESIDE Build (the stories gate is what lets Build start), so
2398
+ // reopening it never stops Build and is allowed while Build runs; every other step needs Build not begun.
2399
+ const parallel = stepId === 'test-cases';
2400
+ // Build has begun once any story has a Build lane — `yad build start` writes one, and nothing checks the
2401
+ // stories gate after that — or anything shipped. Code then rests on the approved Shape, and changing it
2402
+ // is a new change, threaded (yad-change), not a reopen. A lane skipped whole holds no work, and a skip may
2403
+ // be written before Build begins (E39), so it does not count.
2404
+ const lanes = (Array.isArray(buildStates) ? buildStates : []).flatMap((bs) => Object.entries(isPlainObject(bs?.repos) ? bs.repos : {})
2405
+ .filter(([, lane]) => isPlainObject(lane) && (lane.status !== 'skipped' || laneStarted(lane))).map(([repo]) => `${bs?.story ?? '?'} in ${repo}`));
2406
+ if (!parallel && (lanes.length || (Array.isArray(shipped) && shipped.length))) {
2407
+ fail(`Build has begun (${lanes.length ? `a Build lane for ${lanes.join(', ')}` : `${shipped.length} ship(s) recorded`}) — a reopen is only for before Build`,
2408
+ 'thread the change as a new change epic with the yad-change skill');
2409
+ }
2410
+ // A later step in a state this release cannot name was written by a newer yadflow: walking it back would
2411
+ // overwrite a word this release does not understand, so refuse rather than guess.
2412
+ const unknown = steps.slice(ai + 1).find((s) => isPlainObject(s) && s.status != null && stepStatus(s) === null);
2413
+ if (unknown) fail(`${unknown.id} is '${unknown.status}', a state this yadflow does not know`, 'run the newer yadflow that wrote it, or `yad doctor`');
2414
+
2415
+ const from = next.currentStep ?? null;
2416
+ const walked = [];
2417
+ const kept = [];
2418
+ const back = (s, to) => {
2419
+ walked.push({ id: s.id, status: s.status, ...(s.closed ? { closed: s.closed } : {}) });
2420
+ const n = { ...s, status: to };
2421
+ delete n.closed;
2422
+ return n;
2423
+ };
2424
+ steps[ai] = back(step, 'in_progress');
2425
+ for (let j = ai + 1; j < steps.length; j++) {
2426
+ const s = steps[j];
2427
+ if (!isPlainObject(s)) continue;
2428
+ if (hasStarted(s)) steps[j] = back(s, 'todo');
2429
+ else if (stepStatus(s) !== 'todo') kept.push({ id: s.id, status: stepStatus(s) ?? s.status ?? null });
2430
+ }
2431
+ // From `ready-for-build`, the test-cases track does not pull the epic back from Build (`markInReview` and
2432
+ // `advanceState` keep the same rule).
2433
+ if (!(parallel && from === 'ready-for-build')) next.currentStep = stepId;
2434
+
2435
+ // The reviews walked back, and a later review kept as BLOCKED (a wait, not a decision that it does not
2436
+ // apply): their approvals and their review PRs leave the live files, so each is approved again.
2437
+ const reviews = new Set([...walked.map((w) => w.id), ...kept.filter((k) => k.status === 'blocked').map((k) => k.id)]
2438
+ .filter((id) => isGateStep(steps.find((s) => s?.id === id))));
2439
+ const list = Array.isArray(approvals) ? approvals : [];
2440
+ const revoked = list.filter((a) => reviews.has(a?.step));
2441
+ const live = list.filter((a) => !reviews.has(a?.step));
2442
+ // A pointer names its review by `step`, or by artifact: a per-story review (`stories/EP-x-S01.md`) is the
2443
+ // stories review's too.
2444
+ const reviewOf = (artifact) => {
2445
+ if (typeof artifact !== 'string' || !artifact) return null;
2446
+ const b = artifactBase(artifact).replace(/-S\d+$/i, '');
2447
+ return steps.find((s) => s?.type === 'review+approve' && typeof s.artifact === 'string' && artifactBase(s.artifact) === b)?.id ?? null;
2448
+ };
2449
+ const prs = removeProductPrs(productPrs, (p) => reviews.has(p?.step) || reviews.has(reviewOf(p?.artifact)));
2450
+ // Every review after the step, kept ones too: a step skipped or deferred now may be put back later, and then
2451
+ // it holds the reviews after it like any other (a retired PR of a step still set aside is never read).
2452
+ const later = [...new Set(steps.slice(ai + 1).filter((s) => isGateStep(s) && typeof s.artifact === 'string')
2453
+ .map((s) => artifactBase(s.artifact).replace(/-S\d+$/i, '')))];
2454
+ const audit = {
2455
+ step: stepId, date: at, by, reason: String(reason).trim(), from,
2456
+ steps: walked, kept, revokedApprovals: revoked,
2457
+ retiredPrs: prs.taken.map((p) => ({ step: p.step ?? null, artifact: p.artifact ?? null, platform: p.platform ?? null, number: p.number ?? null, branch: p.branch ?? null, url: p.url ?? null })),
2458
+ // Every review PR of the reopened step or a later one numbered up to the platform's newest at the reopen
2459
+ // (`upTo`) is retired too: one the ledger never recorded — on a verified Product a pointer is written only
2460
+ // at merge — would otherwise merge on approvals given before the reopen.
2461
+ // The artifacts whose reviews the reopen touches: the reopened step's own review and every later one, set
2462
+ // aside or not. `retiredUpTo` and, each time a later review passes, `passes[]` (`stampPassed`) cover them.
2463
+ laterArtifacts: later,
2464
+ ...(upTo && Number.isInteger(upTo.number) && upTo.number > 0 ? { retiredUpTo: { platform: upTo.platform ?? null, number: upTo.number, artifacts: later } } : {}),
2465
+ contractLock: contractLockHash,
2466
+ };
2467
+ next.reopens = [...(Array.isArray(next.reopens) ? next.reopens : []), audit];
2468
+ return { state: next, approvals: live, productPrs: prs.kept, audit };
2469
+ }
2470
+
2471
+ // Was this review PR retired by `yad gate reopen` (#322)? Then it must never pass its gate again — not
2472
+ // when a sync finds it on the review branch, and not when the CI reconcile replays its merge. A PR numbered
2473
+ // at or below a retired one for the same artifact is retired too: numbers only grow within one repo, so it
2474
+ // is an older review of the same text. A pointer from another platform is not compared.
2475
+ export function retiredPr(state, artifact, number, platform = null) {
2476
+ const n = Number(number);
2477
+ if (!Number.isInteger(n) || n <= 0 || !artifact) return false;
2478
+ const base = artifactBase(artifact).replace(/-S\d+$/i, '');
2479
+ let top = 0;
2480
+ for (const r of Array.isArray(state?.reopens) ? state.reopens : []) {
2481
+ for (const p of Array.isArray(r?.retiredPrs) ? r.retiredPrs : []) {
2482
+ if (!p?.artifact || artifactBase(p.artifact).replace(/-S\d+$/i, '') !== base) continue;
2483
+ if (platform && p.platform && p.platform !== platform) continue;
2484
+ if (Number.isInteger(p.number) && p.number > top) top = p.number;
2485
+ }
2486
+ for (const u of [r?.retiredUpTo, ...(Array.isArray(r?.passes) ? r.passes : [])]) {
2487
+ if (isPlainObject(u) && Number.isInteger(u.number) && Array.isArray(u.artifacts) && u.artifacts.includes(base)
2488
+ && !(platform && u.platform && u.platform !== platform) && u.number > top) top = u.number;
2489
+ }
2490
+ }
2491
+ return top > 0 && n <= top;
2492
+ }
2493
+
2494
+ // Does this review come after the step a `yad gate reopen` reopened, with no `passes[]` row for it yet (#322)?
2495
+ // Every review after the reopened step does — walked back, todo at the reopen, or kept and put back later —
2496
+ // because any of them can hold the reviews after it (`heldByReopen`). When it passes, `stampPassed` retires
2497
+ // the later reviews opened before that moment. Except a review whose author step was resumed BEHIND finished
2498
+ // work (E41): it runs beside the chain, held nothing, and its pass must not re-open that work.
2499
+ const coveredBy = (state, r, reviewStepId) => {
2500
+ const steps = Array.isArray(state?.steps) ? state.steps : [];
2501
+ const ri = steps.findIndex((s) => s?.id === r?.step);
2502
+ const ti = steps.findIndex((s) => s?.id === reviewStepId);
2503
+ if (ri === -1 || ti <= ri || !isGateStep(steps[ti]) || typeof steps[ti].artifact !== 'string') return false;
2504
+ const ai = steps.findIndex((s) => s?.id === authorStepFor(state, steps[ti])?.id);
2505
+ return !(ai !== -1 && behindFinishedWork(steps, ai));
2506
+ };
2507
+ export function reopenStampDue(state, reviewStepId) {
2508
+ return (Array.isArray(state?.reopens) ? state.reopens : []).some((r) => isPlainObject(r) && coveredBy(state, r, reviewStepId)
2509
+ && !(Array.isArray(r.passes) ? r.passes : []).some((p) => p?.step === reviewStepId));
2510
+ }
2511
+
2512
+ // A review after a reopened step passed (#322): every review PR of a LATER step opened before now — during
2513
+ // the hold, by hand, or merged while it was held — is retired, up to the platform's newest number. Their
2514
+ // approvals were given before the step they rest on was approved again, so each later step is reviewed afresh,
2515
+ // on a new PR/MR. Recorded per walked-back review (`passes[]`), so a reopen of `epic` closes its hold step by
2516
+ // step. Mutates `state`; true when it recorded one.
2517
+ export function stampPassed(state, reviewStepId, { platform = null, number } = {}) {
2518
+ if (!reopenStampDue(state, reviewStepId) || !Number.isInteger(number) || number <= 0) return false;
2519
+ const steps = state.steps;
2520
+ const at = steps.findIndex((s) => s?.id === reviewStepId);
2521
+ const after = new Set(steps.slice(at + 1).filter((s) => isGateStep(s) && typeof s.artifact === 'string')
2522
+ .map((s) => artifactBase(s.artifact).replace(/-S\d+$/i, '')));
2523
+ for (const r of state.reopens) {
2524
+ if (!isPlainObject(r) || !coveredBy(state, r, reviewStepId)) continue;
2525
+ const passes = Array.isArray(r.passes) ? r.passes : [];
2526
+ if (passes.some((p) => p?.step === reviewStepId)) continue;
2527
+ r.passes = [...passes, { step: reviewStepId, platform, number, artifacts: [...after] }];
2528
+ }
2529
+ return true;
2530
+ }
2531
+
2532
+ // Is this step walked back by a reopen, and its review not passed again (#322)? Then it is not set aside. Read
2533
+ // from the review's state now, so a Product with no platform (no `passes[]` rows) is not held for ever.
2534
+ function reopenedAndOpen(state, stepId) {
2535
+ // Asked before the chain is validated, so it never reads a malformed ledger it does not need.
2536
+ if (!Array.isArray(state?.reopens) || !state.reopens.length || !Array.isArray(state.steps) || !state.steps.every(isPlainObject)) return false;
2537
+ const review = state.steps.find((s) => isGateStep(s) && authorStepFor(state, s)?.id === stepId);
2538
+ if (review && isPassed(review)) return false;
2539
+ return state.reopens.some((r) => isPlainObject(r) && (Array.isArray(r.steps) ? r.steps : []).some((w) => w?.id === stepId || (review && w?.id === review.id)));
2540
+ }
2541
+
2542
+ // After `yad gate reopen` (#322) the gates pass again IN ORDER: on an epic that has been reopened, a review may
2543
+ // not open or pass while any earlier step has not passed. Without this a later review PR merging first
2544
+ // (opened after the reopen, or one nobody recorded) would carry the chain past an unapproved step. Returns
2545
+ // the id of the step it waits on, or null.
2546
+ export function heldByReopen(state, reviewStepId) {
2547
+ const steps = Array.isArray(state?.steps) ? state.steps : [];
2548
+ if (!Array.isArray(state?.reopens) || !state.reopens.length) return null;
2549
+ const ti = steps.findIndex((s) => s?.id === reviewStepId);
2550
+ if (ti === -1) return null;
2551
+ // EVERY earlier step must have passed — not only the reopened one: a reopen of `epic` walks `architecture`
2552
+ // back too, and stacked reopens walk back more. Its own author step is not counted (on a verified Product it
2553
+ // closes only when this review passes), nor a step re-opened beside finished work (E41), which runs aside.
2554
+ const author = authorStepFor(state, steps[ti]);
2555
+ const waiting = steps.slice(0, ti).find((s) => isPlainObject(s) && s.id !== author?.id && !isPassed(s) && !isReopenedStep(state, s.id));
2556
+ return waiting ? waiting.id : null;
2557
+ }
2558
+
2258
2559
  // Mark a step in-review (idempotent) and point currentStep at it — EXCEPT once the epic is
2259
2560
  // `ready-for-build`: the parallel `test-cases` track must not pull currentStep back (Build
2260
2561
  // runs alongside the tester, and only the test-cases review is in flight at that point).
@@ -2288,7 +2589,7 @@ export function markInReview(state, step, close = null) {
2288
2589
  // and "what reviews it" were four separate lookups that nothing held together.
2289
2590
  //
2290
2591
  // THE DATA IS IN JSON NOW (E134). The rows are no longer written here: they are built from the shipped
2291
- // lifecycle default, `cli/lifecycle/defaults/1.json`, by `expandSteps` (cli/lifecycle.mjs). In that file
2592
+ // lifecycle default, `cli/lifecycle/defaults/2.json`, by `expandSteps` (cli/lifecycle.mjs). In that file
2292
2593
  // an author step names its gate once (`gate: { riskTags }`) and its gate row is derived from that.
2293
2594
  // The rows, their fields and their order are exactly what this table held before; a test compares them
2294
2595
  // with a frozen copy (`cli/fixtures/lifecycle-v4-catalogue.json`).
@@ -2360,7 +2661,7 @@ export const STEPS = expandSteps(DEFAULT_LIFECYCLE);
2360
2661
  // word is a trap for whoever reads this next; two clearly different names is not.
2361
2662
  //
2362
2663
  // THE DATA IS IN JSON NOW (E134). The profiles are built from the `routes` of the shipped lifecycle
2363
- // default, `cli/lifecycle/defaults/1.json`, by `expandRoutes` (cli/lifecycle.mjs). There, a route lists
2664
+ // default, `cli/lifecycle/defaults/2.json`, by `expandRoutes` (cli/lifecycle.mjs). There, a route lists
2364
2665
  // only its author steps and the engine adds each step's gate; a route's `name` is the `title` here. The
2365
2666
  // default also holds one more route, `lane` — the Build order one story walks in one repo — which is not
2366
2667
  // a profile, because an epic never walks it; it is `BUILD_STEP_ORDER` below. A test compares the
@@ -3037,7 +3338,7 @@ export const skillFields = (ids) => ({
3037
3338
  // So the phase NUMBER is deliberately never printed: "Phase 4" already means something else to anyone
3038
3339
  // who has read those. The name is what is shown.
3039
3340
  //
3040
- // Built from the `phases` of the lifecycle default (`cli/lifecycle/defaults/1.json`, E134) by
3341
+ // Built from the `phases` of the lifecycle default (`cli/lifecycle/defaults/2.json`, E134; the step facts of E157) by
3041
3342
  // `featurePhases`. There each phase also says whether it runs once or in a loop (`runs`, `over`); those
3042
3343
  // fields are not part of this view, which keeps exactly the fields it always had.
3043
3344
  export const PHASES = featurePhases(DEFAULT_LIFECYCLE);
@@ -3159,6 +3460,8 @@ export function dedupeConsecutive(skills) {
3159
3460
  // `shipped: true` only when there ARE steps and every one is `done`; an empty/missing steps array is
3160
3461
  // `unknown` (not-started), NEVER shipped — otherwise a half-seeded file would render a false "shipped ✓".
3161
3462
  export function buildNextForRepo(repoState = {}, { bindings = null } = {}) {
3463
+ // A lane that is not an object (`null` in a hand-edited file) reads as a lane with no steps, never a crash.
3464
+ if (!isPlainObject(repoState)) repoState = {};
3162
3465
  // A whole lane SKIPPED (E39): nothing to drive and nothing shipped. A lane on disk carries a `status` only
3163
3466
  // when it is skipped; this RESULT always has a `status`, so the skip reuses that key, and `record` is added
3164
3467
  // ONLY here, which keeps a frozen v3 lane's output byte-identical. The word is honoured only over a lane
@@ -3168,7 +3471,9 @@ export function buildNextForRepo(repoState = {}, { bindings = null } = {}) {
3168
3471
  return { step: null, status: 'skipped', shipped: false, skill: null, automation: null, locked: false, chain: [],
3169
3472
  ...(isPlainObject(repoState.record) ? { record: repoState.record } : {}) };
3170
3473
  }
3171
- const steps = Array.isArray(repoState.steps) ? repoState.steps : [];
3474
+ // Only entries that are steps: build-state is advisory, and a `null` or a bare word in a hand-edited list
3475
+ // must not stop `yad next` (a valid file reads exactly as before).
3476
+ const steps = Array.isArray(repoState.steps) ? repoState.steps.filter((s) => isPlainObject(s)) : [];
3172
3477
  const byId = new Map(steps.map((s) => [s.id, s]));
3173
3478
  // Empty/half-seeded file ⇒ unknown (not-started), NEVER shipped. Every step done ⇒ shipped.
3174
3479
  if (!steps.length) {
@@ -3345,7 +3650,11 @@ export function nextAction(ledger, opts = {}) {
3345
3650
  if (!state || !Array.isArray(state.steps) || isProductLevel(state) || backfillAnchorKind(state)) return a;
3346
3651
  const lanes = reopenedLanes(ledger, { epicId: a.epicId, currentStep: state.currentStep, bindings: opts.bindings ?? null });
3347
3652
  const debt = owedSteps(state).map((s) => ({ step: s.id, status: stepStatus(s) ?? s.status, record: s.record || null }));
3348
- return { ...a, ...(lanes.length ? { reopened: lanes } : {}), ...(debt.length ? { debt } : {}) };
3653
+ // The last `yad gate reopen` (#322), so the next action says why the chain walked back. Only when there
3654
+ // is one: a key on every action would break the frozen `yad next --json` answers of every older epic.
3655
+ const r = Array.isArray(state.reopens) ? state.reopens[state.reopens.length - 1] : null;
3656
+ const lastReopen = isPlainObject(r) ? { step: r.step ?? null, date: r.date ?? null, by: r.by ?? null, reason: r.reason ?? null } : null;
3657
+ return { ...a, ...(lanes.length ? { reopened: lanes } : {}), ...(debt.length ? { debt } : {}), ...(lastReopen ? { lastReopen } : {}) };
3349
3658
  }
3350
3659
 
3351
3660
  // The steps still OWED AS DEBT (E41): flagged `debt: true` and not yet written here. One entry per pair —
@@ -4092,8 +4401,12 @@ const strOrNull = (v) => (typeof v === 'string' && v.trim() ? v.trim() : null);
4092
4401
  // `error`, and `killSwitchOn` reads an error as ON: of the two ways to be wrong about a safety switch,
4093
4402
  // holding everything at `human` is the one nobody gets hurt by. `steps` keeps its values as written, so
4094
4403
  // `yad doctor` can name a bad one; the readers honour only `auto`.
4404
+ //
4405
+ // `actions` (issue #356) holds the dials of the ACTIONS the project allows without asking — today only
4406
+ // `open-pr`, a standing approval to open a task's PR/MR once its checks pass. Not under `steps`: an action
4407
+ // is not a step of any chain, so nothing that walks the catalogue sees it.
4095
4408
  export function normalizeAutomation(raw) {
4096
- const out = { kill: null, steps: {}, error: null };
4409
+ const out = { kill: null, steps: {}, actions: {}, error: null };
4097
4410
  if (raw == null) return out;
4098
4411
  if (!isPlainObject(raw)) return { ...out, error: 'is not a JSON object' };
4099
4412
  if (raw.kill != null) {
@@ -4110,6 +4423,10 @@ export function normalizeAutomation(raw) {
4110
4423
  if (!isPlainObject(raw.steps)) return { ...out, error: 'has a `steps` that is not an object' };
4111
4424
  for (const [id, v] of Object.entries(raw.steps)) out.steps[id] = v;
4112
4425
  }
4426
+ if (raw.actions != null) {
4427
+ if (!isPlainObject(raw.actions)) return { ...out, error: 'has an `actions` that is not an object' };
4428
+ for (const [id, v] of Object.entries(raw.actions)) out.actions[id] = v;
4429
+ }
4113
4430
  return out;
4114
4431
  }
4115
4432
 
@@ -4117,7 +4434,7 @@ export function loadAutomation(root) {
4117
4434
  try {
4118
4435
  return normalizeAutomation(readJSONStrict(path.join(root, PROJECT_FILES.automationConfig), null));
4119
4436
  } catch {
4120
- return { kill: null, steps: {}, error: 'does not parse' };
4437
+ return { kill: null, steps: {}, actions: {}, error: 'does not parse' };
4121
4438
  }
4122
4439
  }
4123
4440
 
@@ -4125,8 +4442,37 @@ export function loadAutomation(root) {
4125
4442
  export const serializeAutomation = (a) => ({
4126
4443
  ...(a.kill ? { kill: a.kill } : {}),
4127
4444
  steps: Object.fromEntries(Object.entries(a.steps || {}).sort(([x], [y]) => cmp(x, y))),
4445
+ ...(a.actions && Object.keys(a.actions).length ? { actions: Object.fromEntries(Object.entries(a.actions).sort(([x], [y]) => cmp(x, y))) } : {}),
4128
4446
  });
4129
4447
 
4448
+ // The `actions` a writer carries over: only when there are some, so a file that never had any keeps its shape.
4449
+ const keepActions = (a) => (a?.actions && Object.keys(a.actions).length ? { actions: { ...a.actions } } : {});
4450
+
4451
+ // The actions a project may allow without asking (#356), each set with `yad dial <action> --to auto|human`.
4452
+ export const ACTION_DIALS = ['open-pr'];
4453
+
4454
+ // An action's dial as it will be applied: `{ advance, set, why }`, `why` `project` or `kill`. `human` is the
4455
+ // key's absence; only the exact value `auto` turns it on, and the kill switch (or a broken file) holds it.
4456
+ export function effectiveAction(automation, id) {
4457
+ const set = automation?.actions && Object.hasOwn(automation.actions, id) && automation.actions[id] === 'auto' ? 'auto' : 'human';
4458
+ if (set === 'auto' && killSwitchOn(automation)) return { advance: 'human', set, why: 'kill' };
4459
+ return { advance: set, set, why: 'project' };
4460
+ }
4461
+
4462
+ // Set an action's dial for the whole project. PURE: takes and returns the automation object.
4463
+ export function planActionDial(automation, { action, to }) {
4464
+ if (!ACTION_DIALS.includes(action)) return refusal(`unknown action: ${action}`, `an action's dial is one of ${ACTION_DIALS.join(' · ')}`);
4465
+ if (!ADVANCE_VALUES.includes(to)) return refusal(`--to must be human or auto, not ${to}`);
4466
+ const actions = { ...(automation?.actions || {}) };
4467
+ const before = actions[action] === 'auto' ? 'auto' : 'human';
4468
+ if (to === 'auto') actions[action] = 'auto';
4469
+ else delete actions[action];
4470
+ return {
4471
+ ok: true, before, changed: before !== to || (to === 'human' && Object.hasOwn(automation?.actions || {}, action)),
4472
+ automation: { kill: automation?.kill || null, steps: { ...(automation?.steps || {}) }, actions },
4473
+ };
4474
+ }
4475
+
4130
4476
  export const killSwitchOn = (a) => !!a && (a.error != null || a.kill?.on === true);
4131
4477
 
4132
4478
  // A step's advance as it will actually be applied: `{ advance, set, why }`. `set` is what the team chose;
@@ -4152,6 +4498,7 @@ const buildAuthorIds = () => STEPS.filter((d) => d.kind === 'author' && d.phase
4152
4498
 
4153
4499
  // Set a Shape author step's dial for the whole project. PURE: takes and returns the automation object.
4154
4500
  export function planShapeDial(automation, { step, to }) {
4501
+ if (ACTION_DIALS.includes(step)) return planActionDial(automation, { action: step, to });
4155
4502
  const def = stepDef(step);
4156
4503
  if (!def) return refusal(`unknown step: ${step}`, `a Shape step's dial is one of ${shapeAuthorIds().join(' · ')}`);
4157
4504
  // "Shape author steps" means a feature's chain. The Foundation is the Product level, reviewed once per
@@ -4175,11 +4522,12 @@ export function planShapeDial(automation, { step, to }) {
4175
4522
  // turned on.
4176
4523
  if (to === 'auto') steps[step] = 'auto';
4177
4524
  else delete steps[step];
4178
- return { ok: true, before, changed: before !== to || (to === 'human' && Object.hasOwn(automation?.steps || {}, step)), automation: { kill: automation?.kill || null, steps } };
4525
+ return { ok: true, before, changed: before !== to || (to === 'human' && Object.hasOwn(automation?.steps || {}, step)), automation: { kill: automation?.kill || null, steps, ...keepActions(automation) } };
4179
4526
  }
4180
4527
 
4181
4528
  // Set one Build step's dial on one lane. PURE: takes the parsed build-state, returns a new one.
4182
4529
  export function planLaneDial(buildState, { story, repo, step, to, declared = [] }) {
4530
+ if (ACTION_DIALS.includes(step)) return refusal(`${step} is set for the whole project, not per lane`, `yad dial ${step} --to ${to || 'auto'}`);
4183
4531
  const def = stepDef(step);
4184
4532
  if (def && def.phase !== 'build' && def.kind === 'author') {
4185
4533
  return refusal(`${step} is a Shape step — its dial is set for the whole project`, `yad dial ${step} --to ${to || 'auto'}`);
@@ -4220,7 +4568,7 @@ export function planKill(automation, { on, reason = null, by = null, date = null
4220
4568
  // The record being replaced is kept as `previous`, without its own `previous` — one level is the audit
4221
4569
  // trail a person reads; the rest is git history.
4222
4570
  const replaced = automation?.kill ? (({ previous: _previous, ...rest }) => rest)(automation.kill) : null;
4223
- return { ok: true, already: false, automation: { steps: { ...(automation?.steps || {}) }, kill: {
4571
+ return { ok: true, already: false, automation: { steps: { ...(automation?.steps || {}) }, ...keepActions(automation), kill: {
4224
4572
  on, reason: why, by: by || null, date: date || null, ...(replaced ? { previous: replaced } : {}),
4225
4573
  } } };
4226
4574
  }
package/cli/errors.mjs CHANGED
@@ -16,6 +16,7 @@ export const CODES = {
16
16
  'YAD-ENV-001': 'git is not installed or not on PATH',
17
17
  'YAD-ENV-002': 'the platform CLI (gh/glab) is missing or not authenticated',
18
18
  'YAD-ENV-003': 'Node.js is older than the supported range (>=18)',
19
+ 'YAD-ENV-004': 'Node.js is end of life (18 to 21): yadflow 4 still runs on it, but it gets no security fixes, and yadflow 5 needs Node 22 or newer',
19
20
  'YAD-STATE-001': 'a ledger/config JSON file exists but does not parse',
20
21
  'YAD-STATE-002': 'a ledger/config JSON file parses but has the wrong shape',
21
22
  'YAD-STATE-003': 'a registered repo path is missing or not a git repository',
@@ -24,6 +25,8 @@ export const CODES = {
24
25
  'YAD-STATE-006': 'a Build ledger is locked by another yad process that is writing it',
25
26
  'YAD-STATE-007': 'an epic cannot be seeded — the profile, the type or the existing ledger refuses it',
26
27
  'YAD-STATE-008': 'a file kept under two names (product.json + hub.json, or product-prs.json + hub-prs.json) says different things under each',
28
+ 'YAD-STATE-009': 'a Build record cannot be written in its current state (no lane yet, a step out of order, a PR not merged, a task not shipped)',
29
+ 'YAD-STATE-010': 'an epic worktree cannot be added or removed in its current state (a path taken, no origin, uncommitted or unpushed work, a lock)',
27
30
  'YAD-CFG-001': 'the Product settings (product.json, or hub.json on a Product that has only that name) name an unknown platform (expected github, gitlab, or null)',
28
31
  'YAD-CFG-002': 'design.json names an unknown design tool (expected one of config.yaml design.tools, or none)',
29
32
  'YAD-CFG-003': 'testing.json names an unknown testing tool (expected one of config.yaml testing.tools, or none)',
@@ -26,6 +26,7 @@ import os from 'node:os';
26
26
  import path from 'node:path';
27
27
  import { exists, readJSON, writeJSON } from './lib.mjs';
28
28
  import { productConfigPath, PROJECT_FILES } from './manifest.mjs';
29
+ import { worktreeAt, sameDir } from './worktree-record.mjs';
29
30
 
30
31
  export const WORKSPACE_FILE = '.yad-workspace.json';
31
32
  export const WORKSPACE_VERSION = 1;
@@ -94,7 +95,15 @@ export function findProduct(start) {
94
95
  if (ws.problem) return { problem: ws.problem };
95
96
  // Only for a repo this Product registers — never for any folder that happens to sit beside it.
96
97
  const repo = registeredRepoHolding(ws.product, from);
97
- return repo ? { root: ws.product, via: 'workspace', workspace: d, repo } : { elsewhere: ws.product };
98
+ if (repo) return { root: ws.product, via: 'workspace', workspace: d, repo };
99
+ // An epic's worktree of a registered repo (#115), beside it: that repo — and the Product commands go
100
+ // to the same epic's Product worktree when there is one, so its Build records stay in its own tree.
101
+ const wt = codeWorktreeOf(ws.product, from);
102
+ if (wt) {
103
+ const epicTree = epicProductWorktree(ws.product, wt.epic);
104
+ return { root: epicTree ?? ws.product, via: 'workspace', workspace: d, repo: wt.meta, ...(epicTree ? { worktree: wt.epic } : {}) };
105
+ }
106
+ return { elsewhere: ws.product };
98
107
  }
99
108
  if (fs.existsSync(path.join(d, '.git'))) crossedRepo = true;
100
109
  if (path.dirname(d) === d) return null;
@@ -121,6 +130,27 @@ export function registeredRepoHolding(productRoot, dir) {
121
130
  return best;
122
131
  }
123
132
 
133
+ // The registered repo whose epic worktree (#115) holds `dir`: yad made it (its record names the repo), and
134
+ // its common git folder IS that repo's — a record copied into some other clone maps nothing.
135
+ // → { meta, epic, top } or null.
136
+ export function codeWorktreeOf(productRoot, dir) {
137
+ const top = gitTopOf(dir);
138
+ const rec = worktreeAt(top);
139
+ if (!rec || typeof rec.repo !== 'string') return null;
140
+ const reg = readJSON(path.join(productRoot, PROJECT_FILES.reposRegistry), null);
141
+ const meta = (Array.isArray(reg?.repos) ? reg.repos : []).find((r) => r?.name === rec.repo && typeof r.path === 'string');
142
+ if (!meta || !sameDir(rec.main, path.resolve(productRoot, meta.path))) return null;
143
+ return { meta, epic: rec.epic, top };
144
+ }
145
+
146
+ // The epic's Product worktree beside the Product, when yad made one; else null.
147
+ export function epicProductWorktree(productRoot, epic) {
148
+ const root = path.resolve(productRoot);
149
+ const at = path.join(path.dirname(root), `${path.basename(root)}--${epic}`);
150
+ const rec = worktreeAt(at);
151
+ return rec && rec.repo === null && rec.epic === epic && sameDir(rec.main, root) && hasProduct(at) ? at : null;
152
+ }
153
+
124
154
  // Folders a workspace file is never written into: the home folder, the temp folder and the top of a disk.
125
155
  // A file there would be found from every folder below it — every project, every test's temp folder.
126
156
  function sharedFolder(dir) {
@@ -214,7 +244,11 @@ export function registryEntryFor(productRoot, dir) {
214
244
  const top = gitTopOf(dir);
215
245
  if (!top) return null;
216
246
  const meta = registeredRepoHolding(productRoot, top);
217
- if (!meta) return null;
247
+ if (!meta) {
248
+ // The one worktree that IS the registered repo's: an epic worktree yad made of it (#115).
249
+ const wt = codeWorktreeOf(productRoot, dir);
250
+ return wt && sameDir(wt.top, top) ? { meta: wt.meta, top } : null;
251
+ }
218
252
  const at = real(path.resolve(productRoot, meta.path));
219
253
  const topAt = real(top);
220
254
  return at && topAt && fold(at) === fold(topAt) ? { meta, top } : null;