yadflow 4.5.2 → 4.7.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 (101) hide show
  1. package/CHANGELOG.md +206 -0
  2. package/README.md +4 -1
  3. package/bin/commands.mjs +5 -1
  4. package/bin/yad.mjs +174 -18
  5. package/cli/artifact-status.mjs +88 -20
  6. package/cli/build.mjs +1372 -0
  7. package/cli/checkpoint.mjs +2 -2
  8. package/cli/commit.mjs +1 -0
  9. package/cli/dial.mjs +21 -1
  10. package/cli/docs.mjs +6 -1
  11. package/cli/doctor.mjs +133 -26
  12. package/cli/epic-state.mjs +396 -123
  13. package/cli/errors.mjs +2 -0
  14. package/cli/find-product.mjs +36 -2
  15. package/cli/fold.mjs +9 -5
  16. package/cli/gate-local.mjs +9 -1
  17. package/cli/gate.mjs +442 -33
  18. package/cli/history.mjs +22 -2
  19. package/cli/hook.mjs +3 -1
  20. package/cli/index-command.mjs +2 -2
  21. package/cli/ledger.mjs +60 -0
  22. package/cli/lib.mjs +12 -1
  23. package/cli/lifecycle/defaults/1.json +96 -0
  24. package/cli/lifecycle/lifecycle.schema.json +121 -0
  25. package/cli/lifecycle.mjs +695 -0
  26. package/cli/next.mjs +34 -11
  27. package/cli/openpr.mjs +81 -5
  28. package/cli/platform.mjs +21 -0
  29. package/cli/pr-list.mjs +49 -3
  30. package/cli/product-index.mjs +6 -3
  31. package/cli/product-token.mjs +186 -0
  32. package/cli/productcommit.mjs +33 -0
  33. package/cli/recommend.mjs +3 -1
  34. package/cli/repo-publish.mjs +2 -2
  35. package/cli/run-checks.mjs +586 -0
  36. package/cli/ship-drift.mjs +384 -0
  37. package/cli/standup.mjs +1 -1
  38. package/cli/status.mjs +282 -0
  39. package/cli/test-build.mjs +1559 -0
  40. package/cli/test-run-checks.mjs +603 -0
  41. package/cli/test-worktree.mjs +520 -0
  42. package/cli/thread.mjs +50 -3
  43. package/cli/tidy.mjs +2 -2
  44. package/cli/toolbox.mjs +36 -5
  45. package/cli/workspace.mjs +4 -1
  46. package/cli/worktree-record.mjs +53 -0
  47. package/cli/worktree.mjs +379 -0
  48. package/package.json +4 -3
  49. package/skills/sdlc/config.yaml +28 -20
  50. package/skills/sdlc/module-help.csv +1 -1
  51. package/skills/yad-backfill/references/backfill.md +8 -1
  52. package/skills/yad-backfill/templates/checks/backfill-check.sh +54 -6
  53. package/skills/yad-change/SKILL.md +3 -0
  54. package/skills/yad-checks/SKILL.md +47 -5
  55. package/skills/yad-checks/references/check-gates.md +124 -12
  56. package/skills/yad-checks/templates/checks/build-test-lint.sh +22 -3
  57. package/skills/yad-checks/templates/checks/commit-message.sh +8 -2
  58. package/skills/yad-checks/templates/checks/contract-check.sh +354 -48
  59. package/skills/yad-checks/templates/checks/epic-open.sh +87 -14
  60. package/skills/yad-checks/templates/checks/ledger-guard.sh +3 -3
  61. package/skills/yad-checks/templates/checks/lineage-check.sh +88 -15
  62. package/skills/yad-checks/templates/checks/member-check.mjs +206 -35
  63. package/skills/yad-checks/templates/checks/package-manager.sh +41 -4
  64. package/skills/yad-checks/templates/checks/product-checkout.sh +161 -13
  65. package/skills/yad-checks/templates/checks/reconcile-debt-check.sh +94 -15
  66. package/skills/yad-checks/templates/checks/risk-map-check.sh +2 -2
  67. package/skills/yad-checks/templates/checks/spec-link.sh +63 -4
  68. package/skills/yad-checks/templates/checks/verified-commits.sh +23 -5
  69. package/skills/yad-checks/templates/github/yad-checks.yml +8 -8
  70. package/skills/yad-checks/templates/gitlab/.gitlab-ci.yml +3 -0
  71. package/skills/yad-checks/templates/gitlab/yad-checks.gitlab-ci.yml +4 -4
  72. package/skills/yad-checks/templates/gitlab/yad-product-checks.gitlab-ci.yml +16 -3
  73. package/skills/yad-checks/templates/gitlab/yad-update-guard.gitlab-ci.yml +5 -1
  74. package/skills/yad-checks/templates/gitlab/yad-verified-commits.gitlab-ci.yml +5 -1
  75. package/skills/yad-commit/SKILL.md +4 -2
  76. package/skills/yad-docs/templates/app/package-lock.json +395 -106
  77. package/skills/yad-docs/templates/app/package.json +2 -2
  78. package/skills/yad-engineer-review/SKILL.md +45 -20
  79. package/skills/yad-engineer-review/references/ship-and-record.md +42 -8
  80. package/skills/yad-epic/references/state-schema.md +83 -20
  81. package/skills/yad-implement/SKILL.md +75 -13
  82. package/skills/yad-implement/references/implement-conventions.md +8 -1
  83. package/skills/yad-implement/templates/.gitmessage +3 -0
  84. package/skills/yad-open-pr/SKILL.md +21 -0
  85. package/skills/yad-pr-template/SKILL.md +6 -2
  86. package/skills/yad-pr-template/templates/checks/pr-template.sh +85 -4
  87. package/skills/yad-pr-template/templates/checks/pr-title.sh +1 -1
  88. package/skills/yad-pr-template/templates/github/pull_request_template.md +1 -1
  89. package/skills/yad-pr-template/templates/gitlab/merge_request_templates/Default.md +1 -1
  90. package/skills/yad-product-bridge/SKILL.md +14 -1
  91. package/skills/yad-product-bridge/references/bridge.md +29 -5
  92. package/skills/yad-product-bridge/templates/gitlab/yad-gate-sync.gitlab-ci.yml +9 -4
  93. package/skills/yad-reconcile/SKILL.md +30 -0
  94. package/skills/yad-review-gate/SKILL.md +8 -2
  95. package/skills/yad-review-gate/references/gating.md +26 -1
  96. package/skills/yad-run/SKILL.md +52 -28
  97. package/skills/yad-run/references/run-loop.md +42 -21
  98. package/skills/yad-spec/SKILL.md +142 -17
  99. package/skills/yad-spec/references/spec-handoff.md +68 -5
  100. package/skills/yad-status/SKILL.md +7 -0
  101. package/skills/yad-stories/references/story-schema.md +1 -1
@@ -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';
@@ -10,6 +12,9 @@ import {
10
12
  ADVANCE_FROM_AUTOMATION, AUTOMATION_FROM_ADVANCE, DRIVER_FROM_ASSISTANCE, epicFiles, mirrorDrift, preferring,
11
13
  productDrift, PROJECT_FILES, SCHEMA_VERSION, stepAdvance,
12
14
  } from './manifest.mjs';
15
+ import {
16
+ DEFAULT_LIFECYCLE, expandRoutes, expandSteps, featurePhases, laneOrder, productPhases, SENTINELS,
17
+ } from './lifecycle.mjs';
13
18
 
14
19
  const RISK_ESCALATORS = ['contract', 'auth', 'payments'];
15
20
 
@@ -486,6 +491,12 @@ export function upsertProductPr(productPrs = [], rec) {
486
491
  return canonicalProductPrs([...productPrs.filter((p) => p.artifact !== rec.artifact), rec]);
487
492
  }
488
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
+
489
500
  // SHA-256 of the contract surface block (architecture only). Byte-for-byte identical to the recipe
490
501
  // yad-architecture/references/contract-format.md publishes — the one the architect runs to write
491
502
  // contract-lock.json:
@@ -951,6 +962,84 @@ export function acceptedHashes(epicDir, artifact) {
951
962
  // approval with no hash) or nothing can be fingerprinted — both are "no claim", as they always were.
952
963
  export const isStaleHash = (recorded, accepted) => !!recorded && accepted.length > 0 && !accepted.includes(recorded);
953
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
+
954
1043
  // Shape checks for the ledger files. Fail fast with the exact file named — a wrong-shape ledger
955
1044
  // silently treated as a default would be rewritten by the next sync, destroying the real data.
956
1045
  const badShape = (file, what) => err('YAD-STATE-002', `${file}: ${what}`, 'fix the file or restore it from git');
@@ -1593,9 +1682,9 @@ function closeAuthorStep(state, reviewStep, closed = null) {
1593
1682
  // Absent when no cap applied — the count of people was unknown, or it lowered nothing — and
1594
1683
  // in solo mode, where nothing was counted. Never on the author step, as `waived`.
1595
1684
  //
1596
- // FIRST CLOSE WINS: a step that already carries one keeps it. Nothing moves a `done` step back today,
1597
- // so nothing has to remove one; a writer that ever does must take `closed` with it, as `record` goes
1598
- // 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
1599
1688
  // `done` differently because this is present. Steps finished before it carry none, and nothing asks.
1600
1689
  // `approved` is written by `yad gate advance` (E112): a gate passed on recorded approvals on a Product with
1601
1690
  // no platform, where nothing merges. Before E112 the `yad-review-gate` skill wrote it by hand.
@@ -2030,6 +2119,12 @@ const otherWay = (as) => (as === 'skipped' ? 'deferred' : 'skipped');
2030
2119
  // worded. The gate itself is not waived: `gatePredicate` still reports a deferred step's review as owed.
2031
2120
  function setAsideStep(state, stepId, as, { reason, by = null, at = null, debt = false, profiles = LIFECYCLE_PROFILES } = {}) {
2032
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
+ }
2033
2128
  // DEBT IS OWED WORK, and a skip says the step does not apply (E36/E37), so nothing is owed back. Asked
2034
2129
  // first, before any chain question: it is a wrong command, whatever state the chain is in.
2035
2130
  if (debt && !V.carriesDebt) {
@@ -2252,6 +2347,215 @@ export function unblockStep(state, stepId) {
2252
2347
  return state;
2253
2348
  }
2254
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
+
2255
2559
  // Mark a step in-review (idempotent) and point currentStep at it — EXCEPT once the epic is
2256
2560
  // `ready-for-build`: the parallel `test-cases` track must not pull currentStep back (Build
2257
2561
  // runs alongside the tester, and only the test-cases review is in flight at that point).
@@ -2284,6 +2588,12 @@ export function markInReview(state, step, close = null) {
2284
2588
  // skill files — so "which phase is `stories` in", "which skill authors it", "what does it produce"
2285
2589
  // and "what reviews it" were four separate lookups that nothing held together.
2286
2590
  //
2591
+ // THE DATA IS IN JSON NOW (E134). The rows are no longer written here: they are built from the shipped
2592
+ // lifecycle default, `cli/lifecycle/defaults/1.json`, by `expandSteps` (cli/lifecycle.mjs). In that file
2593
+ // an author step names its gate once (`gate: { riskTags }`) and its gate row is derived from that.
2594
+ // The rows, their fields and their order are exactly what this table held before; a test compares them
2595
+ // with a frozen copy (`cli/fixtures/lifecycle-v4-catalogue.json`).
2596
+ //
2287
2597
  // Everything below this constant is DERIVED from it. `STEP_SKILL`, `BUILD_STEP_SKILL`,
2288
2598
  // `BUILD_STEP_ORDER`, `SHAPE_STEP_PHASE` and `BUILD_STEP_PHASE` are still exported under the names
2289
2599
  // they had, because ~20 call sites and the golden test use them — but they are now VIEWS of this
@@ -2303,8 +2613,8 @@ export function markInReview(state, step, close = null) {
2303
2613
  // `yad foundation new` (E75), and `yad-change` runs `yad epic new --parent` for a threaded change-epic
2304
2614
  // (E42).
2305
2615
  //
2306
- // IT IS CODE, NOT A FILE. Nothing here is written to disk, so no file shape changes and there is
2307
- // nothing to migrate. When a project's `state.json` disagrees with the catalogue, THE FILE WINS for
2616
+ // NOTHING IS WRITTEN TO A PROJECT. The default ships inside the package and no project file holds
2617
+ // these rows, so no file shape changes and there is nothing to migrate. When a project's `state.json` disagrees with the catalogue, THE FILE WINS for
2308
2618
  // this whole major (rule 3): a project may hold a step from a newer yadflow, and a hand-written chain
2309
2619
  // is allowed to be ahead of the tool reading it. `yad doctor` reports the disagreement and changes
2310
2620
  // nothing — the same discipline as `workItemType`.
@@ -2324,7 +2634,7 @@ export function markInReview(state, step, close = null) {
2324
2634
  // placed in the Foundation phase, which belongs to no Part (E75)). This field was called
2325
2635
  // `chain` when E4 landed and was renamed before any release carried it — `chain` is the
2326
2636
  // word for an ordered LIST of steps, which is what a lifecycle profile holds (E5).
2327
- // risk_tags the DEFAULT tags a seed gives this step, copied into the epic's `state.json` where a team
2637
+ // risk_tags the DEFAULT tags a seed gives this step (from its author step's `gate.riskTags`), copied into the epic's `state.json` where a team
2328
2638
  // may add to them by hand. `architecture-review` carries `contract`, which does two separate
2329
2639
  // things: it marks the step escalated (`isEscalated`, so its review PR names the touched
2330
2640
  // repos), and it sets the step's E7 RISK STEP — `contract` +2,
@@ -2335,40 +2645,7 @@ export function markInReview(state, step, close = null) {
2335
2645
  // `spec` and `tasks` are two legs of the same yad-spec ceremony (run-loop.md) and share a skill; the
2336
2646
  // chain renderer collapses the consecutive duplicate. `ready-for-build` and the other SENTINELS are
2337
2647
  // not steps and are not here.
2338
- export const STEPS = [
2339
- // Foundation — the Product level (E75). `yad-discovery` stays the skill name: renaming a skill folder
2340
- // is its own change, with an install migration of its own (LEGACY_SKILLS), and it is not this one.
2341
- { id: 'foundation', phase: 'foundation', kind: 'author', artifact: 'foundation/', skill: 'yad-discovery', level: 'product', risk_tags: [] },
2342
- { id: 'foundation-review', phase: 'foundation', kind: 'review', artifact: 'foundation/', reviews: 'foundation', level: 'product', risk_tags: [] },
2343
- // The OLD spelling of the same level, kept for this whole major (rule 3): a project that has not
2344
- // converted still carries these ids, and dropping the rows would report every step of it as
2345
- // `phase:unknown`. They move into the Foundation phase with the level they always were.
2346
- { id: 'discovery', phase: 'foundation', kind: 'author', artifact: 'discovery/', skill: 'yad-discovery', level: 'product', risk_tags: [] },
2347
- { id: 'discovery-review', phase: 'foundation', kind: 'review', artifact: 'discovery/', reviews: 'discovery', level: 'product', risk_tags: [] },
2348
- // Discover
2349
- { id: 'analysis', phase: 'discover', kind: 'author', artifact: 'analysis.md', skill: 'yad-analysis', level: 'feature', risk_tags: [] },
2350
- { id: 'analysis-review', phase: 'discover', kind: 'review', artifact: 'analysis.md', reviews: 'analysis', level: 'feature', risk_tags: [] },
2351
- { id: 'epic', phase: 'discover', kind: 'author', artifact: 'epic.md', skill: 'yad-epic', level: 'feature', risk_tags: [] },
2352
- { id: 'epic-review', phase: 'discover', kind: 'review', artifact: 'epic.md', reviews: 'epic', level: 'feature', risk_tags: [] },
2353
- // Design
2354
- { id: 'architecture', phase: 'design', kind: 'author', artifact: 'architecture.md', skill: 'yad-architecture', level: 'feature', risk_tags: [] },
2355
- { id: 'architecture-review', phase: 'design', kind: 'review', artifact: 'architecture.md', reviews: 'architecture', level: 'feature', risk_tags: ['contract'] },
2356
- { id: 'ui-design', phase: 'design', kind: 'author', artifact: 'ui-design.md', skill: 'yad-ui', level: 'feature', risk_tags: [] },
2357
- { id: 'ui-design-review', phase: 'design', kind: 'review', artifact: 'ui-design.md', reviews: 'ui-design', level: 'feature', risk_tags: [] },
2358
- // Plan
2359
- { id: 'stories', phase: 'plan', kind: 'author', artifact: 'stories/', skill: 'yad-stories', level: 'feature', risk_tags: [] },
2360
- { id: 'stories-review', phase: 'plan', kind: 'review', artifact: 'stories/', reviews: 'stories', level: 'feature', risk_tags: [] },
2361
- { id: 'test-cases', phase: 'plan', kind: 'author', artifact: 'test-cases.md', skill: 'yad-test-cases', level: 'feature', risk_tags: [] },
2362
- { id: 'test-cases-review', phase: 'plan', kind: 'review', artifact: 'test-cases.md', reviews: 'test-cases', level: 'feature', risk_tags: [] },
2363
- // Build — these run per story per code repo, recorded in build-state/, not in the epic's steps[]
2364
- { id: 'spec', phase: 'build', kind: 'author', artifact: null, skill: 'yad-spec', level: 'feature', risk_tags: [] },
2365
- { id: 'tasks', phase: 'build', kind: 'author', artifact: null, skill: 'yad-spec', level: 'feature', risk_tags: [] },
2366
- { id: 'implement', phase: 'build', kind: 'author', artifact: null, skill: 'yad-implement', level: 'feature', risk_tags: [] },
2367
- { id: 'checks', phase: 'build', kind: 'author', artifact: null, skill: 'yad-checks', level: 'feature', risk_tags: [] },
2368
- // Not the review of a step called `engineer` — a step in its own right, and the one Build step that
2369
- // is a gate. It carries no `reviews`, which is what keeps `checks-review` from resolving.
2370
- { id: 'engineer-review', phase: 'build', kind: 'review', artifact: null, skill: 'yad-engineer-review', level: 'feature', risk_tags: [] },
2371
- ];
2648
+ export const STEPS = expandSteps(DEFAULT_LIFECYCLE);
2372
2649
 
2373
2650
  // ---- lifecycle profiles (E5) ---------------------------------------------------------------------
2374
2651
  //
@@ -2383,6 +2660,13 @@ export const STEPS = [
2383
2660
  // code, and `next.mjs` reads the other one through `setupProfileOf`. Two different things under one
2384
2661
  // word is a trap for whoever reads this next; two clearly different names is not.
2385
2662
  //
2663
+ // THE DATA IS IN JSON NOW (E134). The profiles are built from the `routes` of the shipped lifecycle
2664
+ // default, `cli/lifecycle/defaults/1.json`, by `expandRoutes` (cli/lifecycle.mjs). There, a route lists
2665
+ // only its author steps and the engine adds each step's gate; a route's `name` is the `title` here. The
2666
+ // default also holds one more route, `lane` — the Build order one story walks in one repo — which is not
2667
+ // a profile, because an epic never walks it; it is `BUILD_STEP_ORDER` below. A test compares the
2668
+ // profiles with a frozen copy of the list as it stood before.
2669
+ //
2386
2670
  // THE FIRST THREE WERE NOT NEW ROUTES. They predate this table — they were seeded by hand, in five
2387
2671
  // skill files, until `yad epic new` took over the two feature ones. `yad-analysis`'s own description already calls them "the 12-step chain" and "the 10-step
2388
2672
  // chain". E5 wrote them down in one place and checks projects against them; it did not change what
@@ -2442,68 +2726,11 @@ export const STEPS = [
2442
2726
  // WHAT IS AND IS NOT HERE. Seeding a chain from a profile is `seedState` below, driven by
2443
2727
  // `yad epic new` (E17, cli/epic.mjs); shape 6 is where an epic first RECORDS which profile it is on,
2444
2728
  // and an epic seeded before that field existed still has its route derived by matching its chain
2445
- // (`matchLifecycleProfile`). Which steps are optional per route already lives here and is read per
2729
+ // (`matchLifecycleProfile`). Which steps are optional per route lives in the routes too and is read per
2446
2730
  // EPIC (E35, `optionalStepsFor`); the short chore and spike lanes are E40. Which skill runs a step
2447
2731
  // is bound per project (E6, below) and, more specifically, per route (E51) — both in
2448
2732
  // `.sdlc/skills.json`, never here, so two routes can run different skills for the same step.
2449
- export const LIFECYCLE_PROFILES = [
2450
- {
2451
- id: 'classic',
2452
- title: 'the 10-step chain',
2453
- level: 'feature',
2454
- steps: [
2455
- 'epic', 'epic-review',
2456
- 'architecture', 'architecture-review',
2457
- { id: 'ui-design', optional: true }, { id: 'ui-design-review', optional: true },
2458
- 'stories', 'stories-review',
2459
- 'test-cases', 'test-cases-review',
2460
- ],
2461
- },
2462
- {
2463
- id: 'analysis-first',
2464
- title: 'the 12-step chain',
2465
- level: 'feature',
2466
- steps: [
2467
- 'analysis', 'analysis-review',
2468
- 'epic', 'epic-review',
2469
- 'architecture', 'architecture-review',
2470
- { id: 'ui-design', optional: true }, { id: 'ui-design-review', optional: true },
2471
- 'stories', 'stories-review',
2472
- 'test-cases', 'test-cases-review',
2473
- ],
2474
- },
2475
- {
2476
- id: 'chore',
2477
- title: 'the upkeep lane',
2478
- level: 'feature',
2479
- steps: [
2480
- 'epic', 'epic-review',
2481
- 'stories', 'stories-review',
2482
- ],
2483
- },
2484
- {
2485
- id: 'spike',
2486
- title: 'the investigation lane',
2487
- level: 'feature',
2488
- steps: [
2489
- 'analysis', 'analysis-review',
2490
- 'epic', 'epic-review',
2491
- 'stories', 'stories-review',
2492
- ],
2493
- },
2494
- {
2495
- id: 'discovery',
2496
- title: 'the product front-zero',
2497
- level: 'product',
2498
- steps: ['discovery', 'discovery-review'],
2499
- },
2500
- {
2501
- id: 'foundation',
2502
- title: 'the Product Foundation',
2503
- level: 'product',
2504
- steps: ['foundation', 'foundation-review'],
2505
- },
2506
- ];
2733
+ export const LIFECYCLE_PROFILES = expandRoutes(DEFAULT_LIFECYCLE);
2507
2734
 
2508
2735
  // One profile's steps as plain rows: `{ id, optional }`, in chain order.
2509
2736
  //
@@ -2857,8 +3084,9 @@ export const STEP_SKILL = catalogueSkills(false);
2857
3084
  export const BUILD_STEP_SKILL = catalogueSkills(true);
2858
3085
 
2859
3086
  // The fixed Build order. Used to derive the "remaining chain" from the active step onward even if a
2860
- // repo's `steps` array is partial or out of order. The catalogue's own order IS this order.
2861
- const BUILD_STEP_ORDER = STEPS.filter((s) => s.phase === 'build').map((s) => s.id);
3087
+ // repo's `steps` array is partial or out of order. It is the `lane` route of the lifecycle default
3088
+ // (E134), which lists the same five steps in the catalogue's own order.
3089
+ const BUILD_STEP_ORDER = laneOrder(DEFAULT_LIFECYCLE);
2862
3090
 
2863
3091
  // ---- skill binding (E6) --------------------------------------------------------------------------
2864
3092
  //
@@ -3092,7 +3320,8 @@ export const skillFields = (ids) => ({
3092
3320
  //
3093
3321
  // Release and Operate are NAMED and not built. No step, skill or gate exists for either, and none is
3094
3322
  // invented: `built: false` is the whole of what is known about them. (`skills/sdlc/config.yaml`
3095
- // carries the same table for the skills to read, and a test holds the two together row for row.) They are listed
3323
+ // carries the same table for the skills to read, generated from the lifecycle default by
3324
+ // `scripts/lifecycle-config.mjs`, and a test fails when the two differ.) They are listed
3096
3325
  // rather than left out because a person has to be able to see that the lifecycle does not stop at
3097
3326
  // merge — and a renderer that shows them as planned tells the truth, while one that hides them
3098
3327
  // implies the work ends at Build.
@@ -3108,23 +3337,18 @@ export const skillFields = (ids) => ({
3108
3337
  // * `docs/phase-N-build-plan.md` are the development phases of yadflow itself.
3109
3338
  // So the phase NUMBER is deliberately never printed: "Phase 4" already means something else to anyone
3110
3339
  // who has read those. The name is what is shown.
3111
- export const PHASES = [
3112
- { id: 'discover', name: 'Discover', part: 'Shape', built: true },
3113
- { id: 'design', name: 'Design', part: 'Shape', built: true },
3114
- { id: 'plan', name: 'Plan', part: 'Shape', built: true },
3115
- { id: 'build', name: 'Build', part: 'Build', built: true },
3116
- { id: 'release', name: 'Release', part: 'Run', built: false },
3117
- { id: 'operate', name: 'Operate', part: 'Run', built: false },
3118
- ];
3340
+ //
3341
+ // Built from the `phases` of the lifecycle default (`cli/lifecycle/defaults/1.json`, E134) by
3342
+ // `featurePhases`. There each phase also says whether it runs once or in a loop (`runs`, `over`); those
3343
+ // fields are not part of this view, which keeps exactly the fields it always had.
3344
+ export const PHASES = featurePhases(DEFAULT_LIFECYCLE);
3119
3345
 
3120
3346
  // The PRODUCT level's phase (E75). Kept out of `PHASES` on purpose, because the roadmap's two levels
3121
3347
  // are two different ladders: a feature epic walks the six phases above, once per epic, and the
3122
3348
  // Foundation runs once per product, before any of them. It belongs to no Part — Shape, Build and Run
3123
3349
  // are the rhythms of FEATURE work — so it has no `part`, and a renderer printing the six-phase strip
3124
- // for a Foundation would claim a journey it never takes.
3125
- export const PRODUCT_PHASES = [
3126
- { id: 'foundation', name: 'Foundation', level: 'product', built: true },
3127
- ];
3350
+ // for a Foundation would claim a journey it never takes. Built from the default by `productPhases`.
3351
+ export const PRODUCT_PHASES = productPhases(DEFAULT_LIFECYCLE);
3128
3352
 
3129
3353
  // Which phase each step belongs to. Split in two on purpose, because the `-review` rule differs.
3130
3354
  //
@@ -3140,7 +3364,8 @@ export const PRODUCT_PHASES = [
3140
3364
  //
3141
3365
  // The roadmap also names a `feasibility` step in Discover. Nothing implements it — no skill, no step
3142
3366
  // id, no gate — so it is deliberately absent from the catalogue rather than declared and dead. A new
3143
- // step is added by adding a row to `STEPS`; RENAMING one means adding the new row beside the old and
3367
+ // step is added by adding it to the lifecycle default (a new default file, since a shipped one never
3368
+ // changes); RENAMING one means adding the new row beside the old and
3144
3369
  // keeping both for a major (rule 3), because a project still carrying the old id would otherwise trip
3145
3370
  // `phase:unknown` on every `yad doctor` run until it is migrated.
3146
3371
  //
@@ -3156,8 +3381,9 @@ const STEP_PHASE = { ...SHAPE_STEP_PHASE, ...BUILD_STEP_PHASE };
3156
3381
 
3157
3382
  // `currentStep` markers that are NOT steps: they never appear in `steps[]`, and no phase claims them.
3158
3383
  // `ready-for-build` is the one with a phase anyway — see `currentPhase` below, which is where an epic's
3159
- // position is decided rather than a step's.
3160
- export const SENTINELS = ['ready-for-build', 'backfill-pending', 'backfill-done', 'discovery-done', 'foundation-done'];
3384
+ // position is decided rather than a step's. Defined in cli/lifecycle.mjs, whose validator refuses a
3385
+ // step that takes one of these names, and re-exported here under the name every reader imports.
3386
+ export { SENTINELS };
3161
3387
 
3162
3388
  // The phase a STEP id belongs to, or null for anything this engine does not recognise — a sentinel, a
3163
3389
  // step from a future profile, a typo. Null, never a guess: a renderer showing the wrong phase is worse
@@ -3234,6 +3460,8 @@ export function dedupeConsecutive(skills) {
3234
3460
  // `shipped: true` only when there ARE steps and every one is `done`; an empty/missing steps array is
3235
3461
  // `unknown` (not-started), NEVER shipped — otherwise a half-seeded file would render a false "shipped ✓".
3236
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 = {};
3237
3465
  // A whole lane SKIPPED (E39): nothing to drive and nothing shipped. A lane on disk carries a `status` only
3238
3466
  // when it is skipped; this RESULT always has a `status`, so the skip reuses that key, and `record` is added
3239
3467
  // ONLY here, which keeps a frozen v3 lane's output byte-identical. The word is honoured only over a lane
@@ -3243,7 +3471,9 @@ export function buildNextForRepo(repoState = {}, { bindings = null } = {}) {
3243
3471
  return { step: null, status: 'skipped', shipped: false, skill: null, automation: null, locked: false, chain: [],
3244
3472
  ...(isPlainObject(repoState.record) ? { record: repoState.record } : {}) };
3245
3473
  }
3246
- 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)) : [];
3247
3477
  const byId = new Map(steps.map((s) => [s.id, s]));
3248
3478
  // Empty/half-seeded file ⇒ unknown (not-started), NEVER shipped. Every step done ⇒ shipped.
3249
3479
  if (!steps.length) {
@@ -3420,7 +3650,11 @@ export function nextAction(ledger, opts = {}) {
3420
3650
  if (!state || !Array.isArray(state.steps) || isProductLevel(state) || backfillAnchorKind(state)) return a;
3421
3651
  const lanes = reopenedLanes(ledger, { epicId: a.epicId, currentStep: state.currentStep, bindings: opts.bindings ?? null });
3422
3652
  const debt = owedSteps(state).map((s) => ({ step: s.id, status: stepStatus(s) ?? s.status, record: s.record || null }));
3423
- 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 } : {}) };
3424
3658
  }
3425
3659
 
3426
3660
  // The steps still OWED AS DEBT (E41): flagged `debt: true` and not yet written here. One entry per pair —
@@ -4167,8 +4401,12 @@ const strOrNull = (v) => (typeof v === 'string' && v.trim() ? v.trim() : null);
4167
4401
  // `error`, and `killSwitchOn` reads an error as ON: of the two ways to be wrong about a safety switch,
4168
4402
  // holding everything at `human` is the one nobody gets hurt by. `steps` keeps its values as written, so
4169
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.
4170
4408
  export function normalizeAutomation(raw) {
4171
- const out = { kill: null, steps: {}, error: null };
4409
+ const out = { kill: null, steps: {}, actions: {}, error: null };
4172
4410
  if (raw == null) return out;
4173
4411
  if (!isPlainObject(raw)) return { ...out, error: 'is not a JSON object' };
4174
4412
  if (raw.kill != null) {
@@ -4185,6 +4423,10 @@ export function normalizeAutomation(raw) {
4185
4423
  if (!isPlainObject(raw.steps)) return { ...out, error: 'has a `steps` that is not an object' };
4186
4424
  for (const [id, v] of Object.entries(raw.steps)) out.steps[id] = v;
4187
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
+ }
4188
4430
  return out;
4189
4431
  }
4190
4432
 
@@ -4192,7 +4434,7 @@ export function loadAutomation(root) {
4192
4434
  try {
4193
4435
  return normalizeAutomation(readJSONStrict(path.join(root, PROJECT_FILES.automationConfig), null));
4194
4436
  } catch {
4195
- return { kill: null, steps: {}, error: 'does not parse' };
4437
+ return { kill: null, steps: {}, actions: {}, error: 'does not parse' };
4196
4438
  }
4197
4439
  }
4198
4440
 
@@ -4200,8 +4442,37 @@ export function loadAutomation(root) {
4200
4442
  export const serializeAutomation = (a) => ({
4201
4443
  ...(a.kill ? { kill: a.kill } : {}),
4202
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))) } : {}),
4203
4446
  });
4204
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
+
4205
4476
  export const killSwitchOn = (a) => !!a && (a.error != null || a.kill?.on === true);
4206
4477
 
4207
4478
  // A step's advance as it will actually be applied: `{ advance, set, why }`. `set` is what the team chose;
@@ -4227,6 +4498,7 @@ const buildAuthorIds = () => STEPS.filter((d) => d.kind === 'author' && d.phase
4227
4498
 
4228
4499
  // Set a Shape author step's dial for the whole project. PURE: takes and returns the automation object.
4229
4500
  export function planShapeDial(automation, { step, to }) {
4501
+ if (ACTION_DIALS.includes(step)) return planActionDial(automation, { action: step, to });
4230
4502
  const def = stepDef(step);
4231
4503
  if (!def) return refusal(`unknown step: ${step}`, `a Shape step's dial is one of ${shapeAuthorIds().join(' · ')}`);
4232
4504
  // "Shape author steps" means a feature's chain. The Foundation is the Product level, reviewed once per
@@ -4250,11 +4522,12 @@ export function planShapeDial(automation, { step, to }) {
4250
4522
  // turned on.
4251
4523
  if (to === 'auto') steps[step] = 'auto';
4252
4524
  else delete steps[step];
4253
- 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) } };
4254
4526
  }
4255
4527
 
4256
4528
  // Set one Build step's dial on one lane. PURE: takes the parsed build-state, returns a new one.
4257
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'}`);
4258
4531
  const def = stepDef(step);
4259
4532
  if (def && def.phase !== 'build' && def.kind === 'author') {
4260
4533
  return refusal(`${step} is a Shape step — its dial is set for the whole project`, `yad dial ${step} --to ${to || 'auto'}`);
@@ -4295,7 +4568,7 @@ export function planKill(automation, { on, reason = null, by = null, date = null
4295
4568
  // The record being replaced is kept as `previous`, without its own `previous` — one level is the audit
4296
4569
  // trail a person reads; the rest is git history.
4297
4570
  const replaced = automation?.kill ? (({ previous: _previous, ...rest }) => rest)(automation.kill) : null;
4298
- return { ok: true, already: false, automation: { steps: { ...(automation?.steps || {}) }, kill: {
4571
+ return { ok: true, already: false, automation: { steps: { ...(automation?.steps || {}) }, ...keepActions(automation), kill: {
4299
4572
  on, reason: why, by: by || null, date: date || null, ...(replaced ? { previous: replaced } : {}),
4300
4573
  } } };
4301
4574
  }