yadflow 4.6.0 → 4.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/CHANGELOG.md +259 -0
  2. package/README.md +46 -4
  3. package/bin/commands.mjs +9 -2
  4. package/bin/yad.mjs +309 -30
  5. package/cli/agent-guard.mjs +511 -0
  6. package/cli/agent-guide.mjs +83 -0
  7. package/cli/agent-rules.mjs +381 -0
  8. package/cli/argv-flags.mjs +7 -0
  9. package/cli/artifact-status.mjs +88 -20
  10. package/cli/build.mjs +1372 -0
  11. package/cli/checkpoint.mjs +2 -2
  12. package/cli/ci-check.mjs +492 -0
  13. package/cli/commit.mjs +1 -0
  14. package/cli/dial.mjs +21 -1
  15. package/cli/docs.mjs +7 -2
  16. package/cli/doctor.mjs +176 -33
  17. package/cli/epic-state.mjs +360 -12
  18. package/cli/errors.mjs +3 -0
  19. package/cli/find-product.mjs +36 -2
  20. package/cli/fold.mjs +9 -5
  21. package/cli/gate-local.mjs +9 -1
  22. package/cli/gate.mjs +364 -22
  23. package/cli/guide.mjs +549 -0
  24. package/cli/history.mjs +22 -2
  25. package/cli/hook.mjs +35 -4
  26. package/cli/index-command.mjs +2 -2
  27. package/cli/ledger.mjs +60 -0
  28. package/cli/lib.mjs +46 -0
  29. package/cli/lifecycle/defaults/2.json +124 -0
  30. package/cli/lifecycle/lifecycle.schema.json +5 -2
  31. package/cli/lifecycle.mjs +16 -3
  32. package/cli/manifest.mjs +75 -0
  33. package/cli/marked-block.mjs +48 -0
  34. package/cli/members.mjs +19 -5
  35. package/cli/migrate.mjs +17 -19
  36. package/cli/next.mjs +35 -12
  37. package/cli/openpr.mjs +81 -5
  38. package/cli/plan.mjs +326 -22
  39. package/cli/platform.mjs +21 -0
  40. package/cli/pr-list.mjs +5 -3
  41. package/cli/product-index.mjs +6 -3
  42. package/cli/product-token.mjs +186 -0
  43. package/cli/productcommit.mjs +33 -0
  44. package/cli/protection.mjs +50 -0
  45. package/cli/recommend.mjs +3 -1
  46. package/cli/reconcile.mjs +187 -26
  47. package/cli/repo-publish.mjs +2 -2
  48. package/cli/report.mjs +62 -14
  49. package/cli/run-checks.mjs +586 -0
  50. package/cli/setup.mjs +244 -25
  51. package/cli/ship-drift.mjs +49 -18
  52. package/cli/signing.mjs +377 -0
  53. package/cli/standup.mjs +1 -1
  54. package/cli/status.mjs +282 -0
  55. package/cli/test-agents-file.mjs +993 -0
  56. package/cli/test-build.mjs +1559 -0
  57. package/cli/test-ci-check.mjs +616 -0
  58. package/cli/test-guide.mjs +1267 -0
  59. package/cli/test-node.mjs +129 -0
  60. package/cli/test-run-checks.mjs +603 -0
  61. package/cli/test-setup-agent.mjs +352 -0
  62. package/cli/test-signing.mjs +524 -0
  63. package/cli/test-worktree.mjs +520 -0
  64. package/cli/thread.mjs +4 -0
  65. package/cli/tidy.mjs +2 -2
  66. package/cli/toolbox.mjs +37 -6
  67. package/cli/update-commit.mjs +313 -11
  68. package/cli/workspace.mjs +38 -10
  69. package/cli/worktree-record.mjs +53 -0
  70. package/cli/worktree.mjs +379 -0
  71. package/package.json +6 -4
  72. package/skills/sdlc/config.yaml +5 -5
  73. package/skills/sdlc/module-help.csv +2 -1
  74. package/skills/yad-backfill/templates/checks/backfill-check.sh +9 -9
  75. package/skills/yad-change/SKILL.md +5 -1
  76. package/skills/yad-checks/SKILL.md +61 -12
  77. package/skills/yad-checks/references/check-gates.md +78 -14
  78. package/skills/yad-checks/templates/checks/build-test-lint.sh +22 -3
  79. package/skills/yad-checks/templates/checks/commit-message.sh +8 -2
  80. package/skills/yad-checks/templates/checks/contract-check.sh +61 -33
  81. package/skills/yad-checks/templates/checks/epic-open.sh +87 -14
  82. package/skills/yad-checks/templates/checks/ledger-guard.sh +3 -3
  83. package/skills/yad-checks/templates/checks/lineage-check.sh +88 -15
  84. package/skills/yad-checks/templates/checks/member-check.mjs +206 -35
  85. package/skills/yad-checks/templates/checks/package-manager.sh +42 -5
  86. package/skills/yad-checks/templates/checks/product-checkout.sh +161 -13
  87. package/skills/yad-checks/templates/checks/reconcile-debt-check.sh +94 -15
  88. package/skills/yad-checks/templates/checks/risk-map-check.sh +2 -2
  89. package/skills/yad-checks/templates/checks/spec-link.sh +63 -4
  90. package/skills/yad-checks/templates/checks/verified-commits.sh +23 -5
  91. package/skills/yad-checks/templates/github/yad-checks.yml +9 -9
  92. package/skills/yad-checks/templates/gitlab/.gitlab-ci.yml +4 -1
  93. package/skills/yad-checks/templates/gitlab/yad-checks.gitlab-ci.yml +5 -5
  94. package/skills/yad-checks/templates/gitlab/yad-product-checks.gitlab-ci.yml +16 -3
  95. package/skills/yad-checks/templates/gitlab/yad-update-guard.gitlab-ci.yml +5 -1
  96. package/skills/yad-checks/templates/gitlab/yad-verified-commits.gitlab-ci.yml +5 -1
  97. package/skills/yad-checks/templates/hooks/agent-guard.mjs +116 -0
  98. package/skills/yad-commit/SKILL.md +8 -5
  99. package/skills/yad-connect-repos/SKILL.md +5 -3
  100. package/skills/yad-connect-repos/references/code-context.md +2 -1
  101. package/skills/yad-connect-repos/references/repos-registry.md +2 -1
  102. package/skills/yad-docs/templates/app/package-lock.json +395 -106
  103. package/skills/yad-docs/templates/app/package.json +2 -2
  104. package/skills/yad-docs-overview/references/pipeline-model.md +2 -2
  105. package/skills/yad-engineer-review/SKILL.md +55 -25
  106. package/skills/yad-engineer-review/references/ship-and-record.md +49 -12
  107. package/skills/yad-epic/SKILL.md +2 -1
  108. package/skills/yad-epic/references/state-schema.md +76 -17
  109. package/skills/yad-guide/SKILL.md +192 -0
  110. package/skills/yad-implement/SKILL.md +75 -13
  111. package/skills/yad-implement/references/implement-conventions.md +8 -1
  112. package/skills/yad-implement/templates/.gitmessage +3 -0
  113. package/skills/yad-open-pr/SKILL.md +21 -0
  114. package/skills/yad-pair-review/SKILL.md +14 -5
  115. package/skills/yad-pr-template/SKILL.md +6 -2
  116. package/skills/yad-pr-template/templates/checks/pr-template.sh +85 -4
  117. package/skills/yad-pr-template/templates/checks/pr-title.sh +1 -1
  118. package/skills/yad-pr-template/templates/github/pull_request_template.md +1 -1
  119. package/skills/yad-pr-template/templates/gitlab/merge_request_templates/Default.md +1 -1
  120. package/skills/yad-product-bridge/SKILL.md +44 -12
  121. package/skills/yad-product-bridge/references/bridge.md +11 -5
  122. package/skills/yad-product-bridge/templates/github/yad-gate-sync.yml +2 -2
  123. package/skills/yad-product-bridge/templates/gitlab/yad-gate-sync.gitlab-ci.yml +9 -4
  124. package/skills/yad-reconcile/SKILL.md +9 -3
  125. package/skills/yad-report/SKILL.md +15 -0
  126. package/skills/yad-review-companion/SKILL.md +5 -3
  127. package/skills/yad-review-gate/SKILL.md +16 -8
  128. package/skills/yad-review-gate/references/gating.md +26 -1
  129. package/skills/yad-run/SKILL.md +61 -33
  130. package/skills/yad-run/references/run-loop.md +44 -22
  131. package/skills/yad-spec/SKILL.md +137 -16
  132. package/skills/yad-spec/references/spec-handoff.md +50 -3
  133. package/skills/yad-status/SKILL.md +7 -0
  134. package/skills/yad-stories/references/story-schema.md +1 -1
  135. package/skills/yad-sync-repos/SKILL.md +2 -1
  136. package/skills/yad-ui/SKILL.md +2 -2
package/cli/guide.mjs ADDED
@@ -0,0 +1,549 @@
1
+ // `yad guide` — the step brief an AI coding agent reads before each step (E157). Read-only.
2
+ //
3
+ // `yad next` says WHAT comes next. The guide adds what an agent needs to do it for a person without
4
+ // guessing: what the step is for, whether it is mandatory or can be skipped (and the skip command, which is
5
+ // the person's decision), who does the work, the skills and tools that fit, what the agent runs now, and
6
+ // what only the person can do, with the exact steps and the command that confirms it was done. It also
7
+ // carries the rules (cli/agent-rules.mjs), so an agent with no AGENTS.md yet still has them.
8
+ //
9
+ // yad guide [--json] the step to work on here
10
+ // yad guide <epic> [--json] that epic's step
11
+ //
12
+ // It never picks an epic for the person. With several open epics and none named (no epic argument, and
13
+ // not on a task branch), it lists them and says to ask which one.
14
+ //
15
+ // The facts come from the lifecycle default (`description`, `driver`, and a gate's `advance`, cli/lifecycle.mjs),
16
+ // the action from `nextAction` (the same answer `yad next --json` gives, whose keys are frozen), and
17
+ // where the person is from `yad status`. Text from the Product's own files passes through `forTerminal`:
18
+ // it reaches a model, and a control character there is never wanted.
19
+ import fs from 'node:fs';
20
+ import path from 'node:path';
21
+ import { c, log, info, hand, readJSON, forTerminal, exists } from './lib.mjs';
22
+ import { VERSION, isVerifiedLedger, productConfigPath } from './manifest.mjs';
23
+ import { DEFAULT_LIFECYCLE, DRIVERS, GATE_SUFFIX } from './lifecycle.mjs';
24
+ import { PRODUCT_EPICS, artifactBase, epicRoot, isValidEpicId, isPassed, loadLedger, optionalStepsFor, epicIds } from './epic-state.mjs';
25
+ import { epicAction, soloOf } from './next.mjs';
26
+ import { buildStatus } from './status.mjs';
27
+ import { recommendationsFor, bindCommand } from './recommend.mjs';
28
+ import { TOOLBOX, parseVersion, compare as compareVersions } from './toolbox.mjs';
29
+ import { productGit } from './productcommit.mjs';
30
+ import { updateTargets } from './update-commit.mjs';
31
+ import { RULES, HUMAN_ONLY_ACTS, NEVER, classify, askFor, reaches } from './agent-rules.mjs';
32
+ import { seededSlugs } from './hook.mjs';
33
+ import { setupQuestions } from './setup.mjs';
34
+ import { reposBeside, insideGitRepo, PRODUCT_DIR } from './workspace.mjs';
35
+
36
+ export const GUIDE_VERSION = 1;
37
+
38
+ const clean = (s) => (typeof s === 'string' ? forTerminal(s) : s);
39
+
40
+ // The lifecycle's facts for one step id: an author or lane step by its own id, a gate by `<id>-review`.
41
+ // Null for an id the lifecycle does not define (a sentinel such as `ready-for-build`).
42
+ export function stepFacts(stepId, def = DEFAULT_LIFECYCLE) {
43
+ const partOf = (phase) => def.phases.find((p) => p.id === phase)?.part ?? null;
44
+ const own = def.steps.find((s) => s.id === stepId);
45
+ if (own) {
46
+ return { id: own.id, name: own.name, phase: own.phase, part: partOf(own.phase), kind: own.kind,
47
+ description: own.description ?? null, driver: own.driver ?? null, gate: false, reviews: null };
48
+ }
49
+ if (typeof stepId === 'string' && stepId.endsWith(GATE_SUFFIX)) {
50
+ const base = def.steps.find((s) => s.gate && `${s.id}${GATE_SUFFIX}` === stepId);
51
+ if (base) {
52
+ return { id: stepId, name: `${base.name} review`, phase: base.phase, part: partOf(base.phase), kind: 'review',
53
+ description: base.gate.description ?? null, driver: 'human', advance: base.gate.advance ?? 'human', gate: true, reviews: base.id };
54
+ }
55
+ }
56
+ return null;
57
+ }
58
+
59
+ // The Build phase, for an epic at `ready-for-build`: the step is the whole Build loop, its lanes below.
60
+ function buildFacts(def = DEFAULT_LIFECYCLE) {
61
+ const ph = def.phases.find((p) => p.part === 'Build' && p.runs === 'loop');
62
+ return ph ? { id: 'ready-for-build', name: ph.name, phase: ph.id, part: 'Build', kind: 'loop', description: ph.description ?? null, driver: null, gate: false, reviews: null } : null;
63
+ }
64
+
65
+ // The driver an epic records on a step (the shape-4 dial), when it records a word the lifecycle knows.
66
+ const recordedDriver = (state, stepId) => {
67
+ const s = Array.isArray(state?.steps) ? state.steps.find((x) => x?.id === stepId) : null;
68
+ return typeof s?.driver === 'string' && DRIVERS.includes(s.driver) ? s.driver : null;
69
+ };
70
+
71
+ // A word read from the ledger that goes into a command the agent or the person will type: a plain path or
72
+ // id, or the placeholder. Anything else (a space, a quote, a `;`) never reaches a command line.
73
+ export const tok = (x, placeholder) => (typeof x === 'string' && /^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(x.replace(/_/g, '-')) && !x.split('/').includes('..') ? x : placeholder);
74
+
75
+ // A folder for a command line: as it is when it is a plain path, else in single quotes (nothing inside them
76
+ // is expanded, `!` included), a `'` written as `'\''`.
77
+ const shellPath = (p) => (/^[A-Za-z0-9._/~-]+$/.test(p) ? p : `'${p.replace(/'/g, "'\\''")}'`);
78
+
79
+ // One command the agent runs, with what the rules let it do with it.
80
+ export const agentRun = (line, why) => {
81
+ const words = line.replace(/^yad\s+/, '').split(/\s+/);
82
+ const flags = words.filter((w) => w.startsWith('--')).map((w) => w.slice(2).split('=')[0]);
83
+ const cmd = words.filter((w) => !w.startsWith('-')).slice(0, 2);
84
+ const cls = classify(cmd, flags);
85
+ // A flag that needs the person to have asked, under a stronger class (a push): said, never dropped.
86
+ const onRequest = cls !== 'on-request' && cls !== 'human-only' && reaches(cmd, flags).includes('on-request');
87
+ return { run: line, class: cls, ask: askFor(cls), ...(onRequest ? { onRequest: true } : {}), why };
88
+ };
89
+ // A skill the agent runs. Its class is what the skill does at most: `yad-run` opens task PRs/MRs.
90
+ const agentSkill = (skill, why, cls = 'local-write') => ({ skill: clean(skill), class: cls, ask: askFor(cls), why });
91
+
92
+ const WHY_APPROVAL = 'an approval is a person\'s act: the record of who approved what rests on it';
93
+
94
+ // What only the person does, for a review gate, on this Product. `opening`: the review is not open yet,
95
+ // so the person acts once the agent has opened it.
96
+ function reviewHandOff(a, { verified, platform, solo, epic, opening = false }) {
97
+ const art = tok(a.artifact, '<artifact>');
98
+ if (platform) {
99
+ const what = platform === 'gitlab' ? 'merge request' : 'pull request';
100
+ return [{
101
+ act: 'approve-merge',
102
+ why: WHY_APPROVAL,
103
+ steps: [
104
+ `${opening ? 'Once the agent has opened it, open' : 'Open'} the review ${what}${a.pr ? ` #${a.pr}` : ''} for ${art} on ${platform === 'gitlab' ? 'GitLab' : 'GitHub'}.`,
105
+ solo ? 'Read it. In solo mode no approval is counted, so merging it is the decision.' : 'Read it, comment where needed, and approve it (each reviewer the gate asks for).',
106
+ 'Merge it when the checks pass.',
107
+ ...(verified ? ['On a verified Product, CI writes the approval into the ledger at the merge: the agent then pulls the Product\'s default branch to see it.'] : []),
108
+ ],
109
+ commands: [],
110
+ verify: `yad gate sync ${epic} ${art}`,
111
+ }];
112
+ }
113
+ return [{
114
+ act: 'approve-merge',
115
+ why: WHY_APPROVAL,
116
+ steps: [
117
+ `${opening ? 'Once the agent has marked the review open, read' : 'Read'} ${art}.`,
118
+ solo ? 'In solo mode no approval is counted: advance it when you are happy with it.' : 'Each reviewer records an approval under their own name.',
119
+ 'Then advance the step. In Claude Code, type the commands with a leading `!` so they run as you.',
120
+ ],
121
+ commands: [
122
+ ...(solo ? [] : [`yad gate approve ${epic} ${art} --by "<your name>"`]),
123
+ `yad gate advance ${epic} ${art}`,
124
+ ],
125
+ verify: `yad guide ${epic} --json`,
126
+ }];
127
+ }
128
+
129
+ // A review gate: what the agent runs and what the person does. With no platform, `yad gate open` only marks
130
+ // the review open here, and the review stays a `review-open` action until the person advances it: once it
131
+ // is open there is nothing left for the agent to run. On a verified Product the PR/MR is recorded only at the
132
+ // merge, so the review stays `review-open` while it is open: the agent opens it once.
133
+ function reviewWork(a, ctx, epic, also = null) {
134
+ const art = tok(a.artifact, '<artifact>');
135
+ const add = (w) => (also ? `${also}: ${w}` : w);
136
+ if (a.kind === 'review-sync') {
137
+ return {
138
+ agent: [agentRun(`yad gate sync ${epic} ${art}`, add('read the review\'s state back after the person acted; it advances the step only once the review passed'))],
139
+ person: reviewHandOff(a, { ...ctx, epic }),
140
+ };
141
+ }
142
+ const branch = `review/${epic}/${tok(artifactBase(String(a.artifact ?? '')), '<artifact>')}`;
143
+ return {
144
+ agent: !ctx.platform && a.status === 'in_review' ? []
145
+ : [agentRun(`yad gate open ${epic} ${art}`, add(ctx.platform
146
+ ? `open the review PR/MR. Its branch \`${branch}\` must be on origin first: it is the agent's own branch, so push it (\`git push -u origin ${branch}\`); \`yad gate open\` never pushes it. If the review is already open, do not open another: \`yad gate sync\` finds it from the review branch`
147
+ : 'mark the review open; with no platform nothing leaves this machine'))],
148
+ person: reviewHandOff(a, { ...ctx, epic, opening: !!ctx.platform || a.status !== 'in_review' }),
149
+ };
150
+ }
151
+
152
+ // Two cautions for a skip or an unblock on a verified Product, where CI owns an epic's ledger once its first
153
+ // review PR/MR merges. UNREAD: origin cannot be read, so nobody can tell (`yad skip` and `yad unblock` warn
154
+ // the same, cli/skip.mjs). ASFETCHED: the ledger is not on origin as last fetched, and the fetch may be
155
+ // behind a review that merged since (`yad skip` says so; `yad unblock` does not, so the guide does).
156
+ const UNREAD = 'origin could not be read, so it is not known whether CI already owns this epic\'s ledger; if its first review PR/MR has merged, the command is refused';
157
+ const ASFETCHED = 'checked against origin as last fetched: run `git fetch origin` first if the epic\'s first review PR/MR may have merged, because CI then owns its ledger and the command is refused';
158
+
159
+ // A blocked step: the person resolves it, and the agent clears it only when asked. On a verified Product
160
+ // `yad unblock` refuses once the epic's ledger is on the default branch, and CI has no step for it yet (the
161
+ // same words `yad next` prints). Before that, the ledger is still the person's to write.
162
+ function blockedWork(a, ctx, epic, also = null) {
163
+ const reason = a.record?.reason ? `: ${clean(a.record.reason)}` : '';
164
+ const why = also ? `${also}, and is blocked` : 'the step waits on something outside the agent\'s reach';
165
+ if (ctx.ciOwns) {
166
+ return { agent: [], person: [{ act: 'unblock', why, steps: [`Resolve the blocker${reason}.`, 'On a verified Product only CI can clear it once the epic\'s ledger is on the default branch, and CI has no step for that yet (`yad unblock` refuses). Decide with the team how to go on.'], commands: [], verify: null }] };
167
+ }
168
+ return {
169
+ agent: [agentRun(`yad unblock ${epic} ${tok(a.step, '<step>')}`, `only after the person says the blocker is gone and asks to clear it${ctx.originAsFetched ? `; ${ASFETCHED}` : ctx.originUnread ? `; ${UNREAD}` : ''}`)],
170
+ person: [{ act: 'unblock', why, steps: [`Resolve the blocker${reason}, then tell the agent to clear it.`], commands: [], verify: `yad guide ${epic} --json` }],
171
+ };
172
+ }
173
+
174
+ // The agent's commands and the person's steps for one action (the action kinds of `nextAction`).
175
+ export function playbook(a, ctx) {
176
+ const epic = a.epicId;
177
+ const art = tok(a.artifact, '<artifact>');
178
+ const step = tok(a.step, '<step>');
179
+ const skills = Array.isArray(a.skills) ? a.skills : a.skill ? [a.skill] : [];
180
+ const runSkills = (why) => skills.map((s) => agentSkill(s, why));
181
+ const base = (() => {
182
+ switch (a.kind) {
183
+ case 'new':
184
+ return {
185
+ agent: runSkills('seed the epic: the skill asks the person what the change is, then writes epic.md and the ledger'),
186
+ person: [{ act: 'answer', why: 'the epic is the person\'s change: the agent asks, never assumes', steps: ['Answer the agent\'s questions about the change.'], commands: [], verify: null }],
187
+ };
188
+ case 'author':
189
+ return {
190
+ agent: [
191
+ agentRun(`yad next ${epic} --check ${step}`, 'confirm the step may run now, before writing'),
192
+ ...runSkills(`write ${art}, asking the person every question only they can answer`),
193
+ ],
194
+ person: [{ act: 'answer', why: 'the artifact records the person\'s decisions', steps: ['Answer the agent\'s questions, and read the draft before it goes to review.'], commands: [], verify: null }],
195
+ };
196
+ case 'review-open':
197
+ case 'review-sync':
198
+ return reviewWork(a, ctx, epic);
199
+ case 'blocked':
200
+ return blockedWork(a, ctx, epic);
201
+ case 'build': {
202
+ // A lane yad-run halted (`blocked`) waits for the person, like a blocked Shape step.
203
+ const halted = (a.builds || []).flatMap((b) => (b.repos || []).filter((r) => r.status === 'blocked').map((r) => ({
204
+ act: 'unblock',
205
+ why: 'yad-run halted this Build step: a person must resolve it',
206
+ // The lane summary carries no record for a halted step (its keys are frozen); the build-state does.
207
+ steps: [`Resolve the halt on ${tok(b.story, '<story>')} in ${tok(r.repo, '<repo>')} (${tok(r.step, '<step>')})${(() => { const why = ctx.haltReason?.(b.story, r.repo, r.step); return why ? `: ${clean(why)}` : ''; })()}, then tell the agent to move it on.`],
208
+ commands: [],
209
+ verify: `yad guide ${epic} --json`,
210
+ })));
211
+ return {
212
+ agent: [agentSkill('yad-run', 'drive the Build lanes one step at a time; it stops at every step a person must decide, and asks before opening a task PR/MR unless `yad dial open-pr` is `auto`', 'task-pr')],
213
+ person: [...halted, { act: 'approve-merge', why: 'the engineer review and every merge are a person\'s', steps: ['Review and merge each task PR/MR the agent opens.'], commands: [], verify: 'yad build sync' }],
214
+ };
215
+ }
216
+ case 'foundation-done':
217
+ case 'discovery-done':
218
+ return {
219
+ agent: [agentSkill('yad-epic', 'seed the next feature epic from the approved roadmap, once the person picks which item')],
220
+ person: [{ act: 'choose', why: 'which roadmap item comes next is the person\'s call', steps: ['Pick the roadmap item to start.'], commands: [], verify: null }],
221
+ };
222
+ case 'backfill-pending':
223
+ return { agent: [agentSkill('yad-backfill', 'document the code that already exists, then promote the anchor')], person: [] };
224
+ case 'backfill-done':
225
+ return { agent: [agentSkill('yad-change', 'thread a change or defect off the documented feature, when the person has one')], person: [] };
226
+ default:
227
+ return { agent: [agentRun(`yad next ${epic} --json`, 'read the action and follow its `why`')], person: [] };
228
+ }
229
+ })();
230
+ // Work open beside the chain's own step: the test-cases track, and steps re-opened behind finished work.
231
+ const beside = [];
232
+ if (a.parallel?.skill) beside.push(agentSkill(a.parallel.skill, `the ${tok(a.parallel.step, 'parallel')} track runs beside this step: write ${tok(a.parallel.artifact, 'its artifact')}`));
233
+ const besidePerson = [];
234
+ for (const l of Array.isArray(a.reopened) ? a.reopened : []) {
235
+ const ls = tok(l?.step, '<step>');
236
+ const why = `${ls} was re-opened behind finished work`;
237
+ if (l?.kind === 'author') {
238
+ const chain = Array.isArray(l.skills) ? l.skills : l.skill ? [l.skill] : [];
239
+ for (const sk of chain) beside.push(agentSkill(sk, `${why}: write ${tok(l.artifact, 'its artifact')} again`));
240
+ } else if (l?.kind === 'review-open' || l?.kind === 'review-sync') {
241
+ const w = reviewWork({ ...l, epicId: epic }, ctx, epic, why);
242
+ beside.push(...w.agent);
243
+ besidePerson.push(...w.person);
244
+ } else if (l?.kind === 'blocked') {
245
+ const w = blockedWork(l, ctx, epic, why);
246
+ beside.push(...w.agent);
247
+ besidePerson.push(...w.person);
248
+ }
249
+ }
250
+ return { agent: [...base.agent, ...beside], person: [...base.person, ...besidePerson] };
251
+ }
252
+
253
+ // The step block: the facts, mandatory or skippable, who does it, and the skills and tools that fit.
254
+ function stepBlock(a, state, ctx = {}) {
255
+ const facts = a.kind === 'build' ? buildFacts() : stepFacts(a.step);
256
+ const authorId = facts?.gate ? facts.reviews : a.step;
257
+ const author = Array.isArray(state?.steps) ? state.steps.find((s) => s?.id === authorId) : null;
258
+ // A step may be skipped only on a route that marks it optional, and only while it is not written yet:
259
+ // `yad skip` refuses an authored step.
260
+ const skippable = !!facts && facts.part === 'Shape' && optionalStepsFor(state ?? {}).includes(authorId) && !(author && isPassed(author));
261
+ // The Foundation is the Product level: optional for the Product, so neither mandatory nor skippable here.
262
+ const productLevel = !!facts && facts.part === null && a.kind !== 'build';
263
+ const skills = (Array.isArray(a.skills) ? a.skills : a.skill ? [a.skill] : []).map(clean);
264
+ const tools = TOOLBOX.filter((t) => Array.isArray(t.usedBy) && t.usedBy.some((u) => skills.includes(u)))
265
+ .map((t) => ({ id: t.id, name: t.name, role: t.role, fallback: t.fallback ?? null }));
266
+ return {
267
+ epic: a.epicId,
268
+ id: clean(a.step ?? null),
269
+ name: facts?.name ?? null,
270
+ phase: facts?.phase ?? null,
271
+ part: facts?.part ?? null,
272
+ actionKind: a.kind,
273
+ brief: facts?.description ?? null,
274
+ mandatory: !facts || productLevel ? null : !skippable,
275
+ // On a verified Product whose ledger CI already owns, `yad skip` refuses (cli/skip.mjs): said, not offered.
276
+ skip: !skippable ? null : ctx.ciOwns
277
+ ? { command: null, decidedBy: 'human', note: 'on this verified Product the epic\'s ledger is on the default branch, and only CI writes it; CI has no step for a skip yet (`yad skip` refuses)' }
278
+ : { command: `yad skip ${a.epicId} ${tok(authorId, '<step>')} --reason "<why>"`, decidedBy: 'human',
279
+ // `yad skip` warns the same way when it cannot read origin (cli/skip.mjs).
280
+ ...(ctx.originUnread ? { note: UNREAD } : {}),
281
+ ...(ctx.originAsFetched ? { note: ASFETCHED } : {}) },
282
+ driver: facts?.gate ? 'human' : recordedDriver(state, a.step) ?? facts?.driver ?? null,
283
+ ...(facts?.gate ? { advance: facts.advance } : {}),
284
+ status: clean(a.status ?? null),
285
+ artifact: clean(a.artifact ?? null),
286
+ why: clean(a.why ?? null),
287
+ skills: {
288
+ bound: skills,
289
+ recommended: facts && !facts.gate ? recommendationsFor(authorId).map((r) => ({ skill: r.skill, why: r.reason, bind: bindCommand(r), decidedBy: 'human' })) : [],
290
+ },
291
+ tools,
292
+ ...(a.parallel ? { parallel: { step: clean(a.parallel.step), skill: clean(a.parallel.skill ?? null), artifact: clean(a.parallel.artifact ?? null) } } : {}),
293
+ ...(Array.isArray(a.reopened) && a.reopened.length ? { reopened: a.reopened.map((l) => ({ step: clean(l?.step ?? null), kind: l?.kind ?? null, status: clean(l?.status ?? null) })) } : {}),
294
+ ...(Array.isArray(a.debt) && a.debt.length ? { debt: a.debt.map((d) => ({ step: clean(d?.step ?? null), status: clean(d?.status ?? null) })) } : {}),
295
+ ...(a.builds ? { lanes: lanesOf(a) } : {}),
296
+ };
297
+ }
298
+
299
+ // Each Build lane: its step's facts, and whether a person moves it on (the epic's `advance` dial).
300
+ function lanesOf(a) {
301
+ return (a.builds || []).flatMap((b) => (b.repos || []).map((r) => {
302
+ const facts = stepFacts(r.step);
303
+ const open = !r.shipped && r.status !== 'skipped';
304
+ return {
305
+ story: clean(b.story), repo: clean(r.repo), step: clean(r.step ?? null), status: clean(r.status ?? null), shipped: !!r.shipped,
306
+ brief: facts?.description ?? null, driver: facts?.driver ?? null,
307
+ advance: r.automation === 'machine_advance' ? 'auto' : 'human',
308
+ skill: clean(r.skill ?? null),
309
+ skip: open ? { command: `yad skip ${a.epicId} ${tok(b.story, '<story>')} --repo ${tok(r.repo, '<repo>')} --reason "<why>"`, decidedBy: 'human', when: 'the story needs no change in this repo' } : null,
310
+ };
311
+ }));
312
+ }
313
+
314
+ // The answer before any Product exists here (E159): the command this folder calls for, and the questions it
315
+ // asks, each with the flag that answers it. The agent asks the person each one in chat (they may take the
316
+ // defaults), then runs the command with `--json` and the flags; a missing answer is refused before anything is
317
+ // written, with the same list. `root` is a Product folder not set up yet, if there is one.
318
+ // - a Product folder not set up yet: `yad setup` there;
319
+ // - inside one git repo: `yad setup` (one repo holding all the code);
320
+ // - beside git repos: `yad init`, which offers each of them;
321
+ // - anywhere else: `yad new <name>`, which makes the workspace.
322
+ // Joining a team that already uses yadflow is `yad join <url>`, whose one question is the AI tools.
323
+ function noProduct(cwd, root = null) {
324
+ let command;
325
+ let questions;
326
+ if (root) {
327
+ command = 'setup';
328
+ questions = setupQuestions(root, {});
329
+ } else if (insideGitRepo(cwd).ok) {
330
+ command = 'setup';
331
+ questions = setupQuestions(cwd, {});
332
+ } else {
333
+ const { discovered } = reposBeside(cwd);
334
+ command = discovered.length ? 'init' : 'new <name>';
335
+ const product = discovered.length ? path.join(cwd, PRODUCT_DIR) : path.join(cwd, '<name>', PRODUCT_DIR);
336
+ // The answers each command gives itself: `new` is greenfield, `init` brownfield with separate repos (unless told).
337
+ questions = setupQuestions(product, { ...(discovered.length ? { brownfield: true, separate: true, discovered } : { greenfield: true }), gitInit: true });
338
+ }
339
+ // Only what the person must answer: a question the command answers itself (`new` is greenfield) is left out.
340
+ questions = questions.filter((q) => !q.given).map(({ given: _given, ...q }) => ({ ...q, text: clean(q.text) }));
341
+ // yadflow may not be installed yet: the commands run it through npx. Classed as the yad command it is.
342
+ const npx = 'npx -y yadflow@4';
343
+ const agent = agentRun(`yad ${command} --json`, 'with a flag for each answer in `questions`, only once the person has answered them (or said to take the defaults)');
344
+ agent.run = `${npx} ${command} --json`;
345
+ return {
346
+ step: null,
347
+ questions,
348
+ agent: [agent],
349
+ person: [{
350
+ act: 'answer',
351
+ why: 'how yadflow is set up is the person\'s decision: ask, never assume',
352
+ steps: [
353
+ `Ask the person which applies: ${command === 'init' ? 'connect the repos found here (`init`)' : command === 'setup' ? 'set up yadflow in this folder (`setup`)' : 'a new project (`new <name>`)'}, or joining a team that already uses yadflow (\`${npx} join <the Product's git URL> --ide-targets <a,b> --json\`).`,
354
+ 'Ask each question in `questions`, one at a time, showing its default; the person may say to take the defaults.',
355
+ 'Run the command with `--json` and the flag for each answer. A refusal lists any question still unanswered.',
356
+ ],
357
+ commands: [`${npx} ${command} --json <flags>`, `${npx} join <url> --ide-targets <a,b> --json`],
358
+ verify: 'yad guide --json',
359
+ }],
360
+ then: 'run `yad guide --json` again once the Product exists',
361
+ };
362
+ }
363
+
364
+ // Is the install behind this yadflow? The Product's stamp (`.sdlc/cli-version.json`) and each connected
365
+ // repo's managed ledger (`.sdlc/managed.json`) name the yadflow that last wrote their files. They are read
366
+ // as COMMITTED (`HEAD`), so an update left uncommitted in a working tree still counts as behind. A connected
367
+ // repo with no ledger has never had its checks wired, which `yad update` never does: not counted.
368
+ //
369
+ // That is all the guide decides. Whether the update can run now, is already on review or already merged,
370
+ // is the run's to say (`yad update --open-pr`, E157 update review 5): it fetches, checks every repo, and
371
+ // answers with a reason and a hint per repo, which the agent passes to the person. A guide that predicted
372
+ // the run would be a second copy of its rules, and drift from it.
373
+ const behindOf = (stamped, running) => {
374
+ const a = parseVersion(stamped);
375
+ const b = parseVersion(running);
376
+ return a && b ? compareVersions(a, b) < 0 : null;
377
+ };
378
+ const versionIn = (text) => { try { const v = JSON.parse(text)?.version; return typeof v === 'string' ? v : null; } catch { return null; } };
379
+ function committedVersion(root, file) {
380
+ const shown = productGit(root)('show', `HEAD:${file}`);
381
+ if (shown.ok) return versionIn(shown.stdout);
382
+ try { return versionIn(fs.readFileSync(path.join(root, file), 'utf8')); } catch { return null; }
383
+ }
384
+
385
+ export function installState(root, running = VERSION) {
386
+ const rows = updateTargets(root).map((t) => {
387
+ const version = committedVersion(t.root, t.file);
388
+ return { repo: t.product ? 'product' : clean(t.name), version: version ? clean(version) : null, behind: !t.product && !version ? null : behindOf(version, running) };
389
+ });
390
+ const product = rows.find((r) => r.repo === 'product');
391
+ return { project: product?.version ?? null, yadflow: running, behind: rows.some((r) => r.behind) ? true : product?.behind ?? null, repos: rows.filter((r) => r.behind) };
392
+ }
393
+
394
+ function upkeepFor(install, { platform }) {
395
+ if (!install.behind) return null;
396
+ const which = install.repos.map((r) => (r.repo === 'product' ? 'the Product' : r.repo)).join(', ');
397
+ if (!platform) {
398
+ return { agent: [], person: [{ act: 'choose', why: 'there is no platform to open an update PR/MR on, so how it is published is the person\'s call', steps: ['Run `yad update`, then commit and share the changes the way this team does.'], commands: ['yad update'], verify: 'yad guide --json' }] };
399
+ }
400
+ return {
401
+ agent: [agentRun('yad update --open-pr --json', `the files yadflow manages in ${which} were written by an older yadflow, and this is v${install.yadflow}: bring them up to date on a branch in each repo, with a PR/MR for each. Do this before the step below. Show the person every \`commits[]\` row that has a \`hint\`, with its \`reason\`, wait for them, then run it again`)],
402
+ person: [{ act: 'approve-merge', why: 'the update lands through review, like any change', steps: ['Merge each `chore(yad-update)` PR/MR it opens once its checks pass.', 'If it says a repo was refused or held back, do what its hint says, then tell the agent.'], commands: [], verify: 'yad update --open-pr --json' }],
403
+ };
404
+ }
405
+
406
+ // The Product's open epics with their next step, as `yad status` lists them, for "which one?".
407
+ const epicChoices = (m) => (m.epics || []).filter((e) => !e.problem).map((e) => ({ epic: e.epic, product: !!e.product, step: e.step, kind: e.kind, next: clean(e.next) }));
408
+
409
+ // An epic whose ledger does not load: the answer is `yad doctor`, never "start another epic".
410
+ const broken = (base, situation, problems, epics = []) => ({
411
+ ...base, situation: { ...situation, stage: 'broken' }, problems, epics, step: null,
412
+ agent: [agentRun('yad doctor', 'find what is wrong with the ledger; it names the fix')],
413
+ person: [{ act: 'choose', why: 'a ledger that does not load is not fixed by guessing', steps: ['Read what `yad doctor` reports with the agent, and decide the fix.', ...(epics.length ? ['Or pick one of the other open epics to work on meanwhile (`yad guide <epic> --json`).'] : [])], commands: [], verify: 'yad guide --json' }],
414
+ then: 'run `yad guide --json` again once `yad doctor` is clean',
415
+ });
416
+
417
+ const thenFor = (person, epic) => (person.some((p) => p.verify)
418
+ ? 'wait for the person to say it is done, then run the `verify` command; never go on from their word alone'
419
+ : person.length ? `wait for the person's answer, then go on; run \`yad guide ${epic} --json\` again after this step`
420
+ : `run \`yad guide ${epic} --json\` again after this step`);
421
+
422
+ // Build the guide. `root` is the Product, or null when there is none here. `cwd` is where the agent is.
423
+ // `productElsewhere`: no Product here, but one is a `cd` away (bin/yad.mjs finds it).
424
+ export function buildGuide(root, { epic = null, cwd = root ?? process.cwd(), runner, productElsewhere = null } = {}) {
425
+ const base = { guideVersion: GUIDE_VERSION, rules: RULES, humanOnly: HUMAN_ONLY_ACTS, never: NEVER };
426
+ if (!root && productElsewhere) {
427
+ const where = clean(productElsewhere);
428
+ const q = shellPath(where);
429
+ return { ...base, situation: { stage: 'product-elsewhere', product: where }, step: null,
430
+ agent: [agentRun(`yad guide --dir ${q} --json`, 'the Product is one folder away: read it from there, never start a second one')],
431
+ person: [], then: `work from the Product (cd ${q}), or pass --dir ${q}` };
432
+ }
433
+ if (!root) return { ...base, situation: { stage: 'no-product', product: null }, ...noProduct(cwd) };
434
+ const productConfig = readJSON(productConfigPath(root), null);
435
+ const platform = typeof productConfig?.platform === 'string' && productConfig.platform ? productConfig.platform : null;
436
+ const solo = soloOf(productConfig);
437
+ const verified = isVerifiedLedger(productConfig);
438
+ const m = buildStatus(root, { cwd, fetch: false, runner });
439
+ const rel = path.relative(cwd, root) || '.';
440
+ const install = installState(root, VERSION);
441
+ const situation = { stage: 'ready', product: rel, platform, ledger: platform && verified ? 'verified' : 'local', solo, here: m.here ?? null, install };
442
+ if (!m.setUp) return { ...base, situation: { ...situation, stage: 'no-product' }, ...noProduct(cwd, root) };
443
+ // Upkeep rides every answer about this Product until it is done.
444
+ base.upkeep = upkeepFor(install, { platform });
445
+
446
+ const ctx = { verified, platform, solo };
447
+ const chosen = epic ?? m.here?.epic ?? null;
448
+ if (chosen) {
449
+ if (!isValidEpicId(chosen) || !exists(path.join(epicRoot(root, chosen), '.sdlc', 'state.json'))) {
450
+ return { ...base, ok: false, error: `no epic ${clean(chosen)} here`, code: null, hint: 'ask the person which epic they mean; `epics` lists the open ones',
451
+ situation: { ...situation, stage: 'unknown-epic' }, epics: epicChoices(m), step: null, agent: [], person: [], then: 'ask the person which epic they mean' };
452
+ }
453
+ let state;
454
+ let action;
455
+ let ledger;
456
+ try {
457
+ ledger = loadLedger(epicRoot(root, chosen));
458
+ state = ledger?.state;
459
+ if (!state || typeof state !== 'object' || Array.isArray(state) || !Array.isArray(state.steps)) throw new Error('its state.json is not a ledger');
460
+ ({ action } = epicAction(root, chosen));
461
+ } catch {
462
+ return broken(base, situation, [{ epic: chosen, problem: 'its ledger does not load — run `yad doctor`' }]);
463
+ }
464
+ // Does CI already own this epic's ledger (verified, and the ledger is on origin's default branch)? The
465
+ // same read `yad skip` and `yad unblock` make (cli/skip.mjs). Unknown (origin not read) is not "yes".
466
+ const seeded = verified ? seededSlugs(root, productConfig, runner) : null;
467
+ // `originAsFetched`: read from origin as last fetched, which may be behind the platform.
468
+ // Why yad-run halted a Build step: read from the build-state, where the skill records it.
469
+ const haltReason = (story, repo, step) => {
470
+ const bs = (ledger?.buildStates || []).find((b) => b?.story === story);
471
+ const steps = bs?.repos?.[repo]?.steps;
472
+ const st = Array.isArray(steps) ? steps.find((x) => x?.id === step) : null;
473
+ return typeof st?.record?.reason === 'string' ? st.record.reason : null;
474
+ };
475
+ const ectx = { ...ctx, haltReason, ciOwns: !!seeded && seeded.has(chosen.toLowerCase()), originUnread: verified && seeded === null, originAsFetched: !!seeded && !seeded.has(chosen.toLowerCase()) };
476
+ const { agent, person } = playbook(action, ectx);
477
+ return { ...base, situation: { ...situation, stage: 'in-epic' }, step: stepBlock(action, state, ectx), agent, person, then: thenFor(person, chosen) };
478
+ }
479
+ const problems = (m.epics || []).filter((e) => e.problem).map((e) => ({ epic: e.epic, problem: clean(e.problem) }));
480
+ if (problems.length) return broken(base, situation, problems, epicChoices(m));
481
+ const open = epicChoices(m);
482
+ if (open.length > 1) {
483
+ return { ...base, situation: { ...situation, stage: 'choose-epic' }, epics: open, step: null, agent: [],
484
+ person: [{ act: 'choose', why: 'several epics are open; which to work on is the person\'s call', steps: ['Pick the epic to work on.'], commands: [], verify: null }],
485
+ then: 'run `yad guide <epic> --json` for the epic the person picked' };
486
+ }
487
+ if (open.length === 1) return buildGuide(root, { epic: open[0].epic, cwd, runner });
488
+ // Nothing open: the Foundation (optional) or the first epic.
489
+ const brownfield = productConfig?.profile?.codebase === 'brownfield';
490
+ const hasFoundation = epicIds(root).some((id) => PRODUCT_EPICS.includes(id));
491
+ return { ...base, situation, step: null,
492
+ agent: [
493
+ ...(brownfield ? [agentSkill('yad-backfill', 'existing code: document what is already built first, so new epics can thread off it')] : []),
494
+ ...(hasFoundation ? [] : [{ ...agentRun('yad foundation new', 'only once the person says they want the Foundation: frame the whole product once (purpose, scope, MVP, roadmap, stack), then run its skill'), optional: true }]),
495
+ agentSkill('yad-epic', 'start the first feature epic, from what the person wants built'),
496
+ ],
497
+ person: [{ act: 'choose', why: 'what to build first is the person\'s call', steps: [hasFoundation ? 'Say which roadmap item to start.' : 'Say whether to write the Foundation first (optional), and what the first epic is.'], commands: [], verify: null }],
498
+ then: 'run `yad guide --json` again once the epic exists' };
499
+ }
500
+
501
+ // The printed form: the brief a person would read, in the order the agent would say it.
502
+ export function printGuide(g) {
503
+ const s = g.step;
504
+ if (g.upkeep) {
505
+ log(`\n ${c.bold(`Upkeep first: yadflow is v${g.situation.install.yadflow}, and ${g.situation.install.repos.map((r) => `${r.repo} is on v${r.version ?? '?'}`).join(', ')}.`)}`);
506
+ for (const a of g.upkeep.agent) hand(`${c.bold(a.run)} ${c.dim(`— ${a.why}`)}`);
507
+ for (const p of g.upkeep.person) for (const st of p.steps) info(st);
508
+ }
509
+ if (s) {
510
+ log(`\n ${c.bold(`${s.epic} · ${s.name ?? s.id}`)}${s.part ? c.dim(` (${s.part}${s.phase ? ` · ${s.phase}` : ''})`) : ''}`);
511
+ if (s.brief) info(s.brief);
512
+ if (s.mandatory === true) info(c.dim('mandatory'));
513
+ else if (s.mandatory === false) info(c.dim(s.skip?.command ? `can be skipped — the person decides: ${s.skip.command}${s.skip.note ? ` (${s.skip.note})` : ''}` : `optional, but it cannot be skipped here: ${s.skip?.note ?? ''}`));
514
+ else if (s.name && !s.part) info(c.dim('the Product level: optional for the Product; once started, it is finished and reviewed'));
515
+ if (s.driver) info(c.dim(`who: ${s.driver === 'pair' ? 'the agent drafts, the person decides' : s.driver === 'agent' ? 'the agent' : 'a person'}`));
516
+ if (s.why) info(c.dim(s.why));
517
+ } else if (g.situation?.stage === 'choose-epic') {
518
+ log(`\n ${c.bold('Several epics are open:')}`);
519
+ for (const e of g.epics) info(`${e.epic} ${c.dim(e.next ?? '')}`);
520
+ } else if (g.situation?.stage === 'no-product') {
521
+ log(`\n ${c.bold('No yadflow Product here yet.')}`);
522
+ } else if (g.situation?.stage === 'unknown-epic') {
523
+ log(`\n ${c.bold(g.error)}`);
524
+ if (g.epics.length) {
525
+ info('The open epics:');
526
+ for (const e of g.epics) info(`${e.epic} ${c.dim(e.next ?? '')}`);
527
+ } else info('No epic is open.');
528
+ } else if (g.situation?.stage === 'product-elsewhere') {
529
+ log(`\n ${c.bold(`The Product is at ${g.situation.product}.`)}`);
530
+ } else if (g.situation?.stage === 'broken') {
531
+ log(`\n ${c.bold('An epic\'s ledger does not load:')}`);
532
+ for (const e of g.problems) info(`${e.epic} ${c.dim(e.problem)}`);
533
+ }
534
+ for (const a of g.agent || []) hand(`${a.run ? c.bold(a.run) : `the ${c.bold(a.skill)} skill`} ${c.dim(`— ${a.why}`)}`);
535
+ for (const p of g.person || []) {
536
+ info(`${c.bold('person:')} ${p.why}`);
537
+ for (const st of p.steps) info(` ${st}`);
538
+ for (const cmd of p.commands) info(` ${c.bold(cmd)}`);
539
+ }
540
+ if (g.then) info(c.dim(`then: ${g.then}`));
541
+ }
542
+
543
+ export async function runGuide(root, { epic = null, cwd, json = false, runner, productElsewhere = null } = {}) {
544
+ const g = buildGuide(root, { epic, cwd, runner, productElsewhere });
545
+ if (g.ok === false) process.exitCode = 1;
546
+ if (json) return g;
547
+ printGuide(g);
548
+ return undefined;
549
+ }
package/cli/history.mjs CHANGED
@@ -133,7 +133,7 @@ const fold = (s) => s.normalize('NFKC').toLowerCase();
133
133
  // and a digit or two does not match half the hashes in the Product.
134
134
  // Only text is matched, and a PR only as a whole number: `String()` of any other value would match text
135
135
  // that is not in the file (`[object Object]`).
136
- export function searchMatches(item, steps, text) {
136
+ export function searchMatches(item, steps, text, reopens = null) {
137
137
  const needle = fold(String(text).trim());
138
138
  // `12`, `#12`, `PR 12`, `pr12` and `PR #12` all name PR 12.
139
139
  const prWanted = needle.replace(/^(pr\s*#?|#)\s*/, '');
@@ -156,6 +156,13 @@ export function searchMatches(item, steps, text) {
156
156
  if (pr !== null && prQuery !== null && Number(pr) === prQuery) hit('closed.pr', pr, id);
157
157
  if (typeof k.commit === 'string' && needle.length >= 4 && fold(k.commit).startsWith(needle)) hit('closed.commit', k.commit, id);
158
158
  }
159
+ // A reopen (#322) is found by its reason and by who made it.
160
+ for (const r of Array.isArray(reopens) ? reopens : []) {
161
+ if (!isPlainObject(r)) continue;
162
+ const step = typeof r.step === 'string' ? r.step : null;
163
+ words('reopen.reason', r.reason, step);
164
+ words('reopen.by', r.by, step);
165
+ }
159
166
  return hits;
160
167
  }
161
168
 
@@ -322,8 +329,17 @@ export function itemHistory(root, item, { productConfig = null, productConfigWhy
322
329
  thread = { root: null, broken: `the thread could not be walked (${e.code || e.message})` };
323
330
  }
324
331
  }
332
+ // Each `yad gate reopen` (#322): what walked back, and the approvals it revoked — kept here, no longer counted.
333
+ const reopens = (Array.isArray(stateRead.state?.reopens) ? stateRead.state.reopens : []).filter(isPlainObject).map((x) => ({
334
+ step: typeof x.step === 'string' ? x.step : null, date: typeof x.date === 'string' ? x.date : null,
335
+ by: typeof x.by === 'string' ? x.by : null, reason: typeof x.reason === 'string' ? x.reason : null,
336
+ walkedBack: (Array.isArray(x.steps) ? x.steps : []).map((w) => (typeof w?.id === 'string' ? w.id : null)).filter(Boolean),
337
+ revoked: (Array.isArray(x.revokedApprovals) ? x.revokedApprovals : []).filter(isPlainObject)
338
+ .map((a) => ({ step: typeof a.step === 'string' ? a.step : null, approver: typeof a.approver === 'string' ? a.approver : null })),
339
+ }));
325
340
  return {
326
341
  thread,
342
+ reopens,
327
343
  steps: stateRead.steps ? out : null,
328
344
  stepsWhy: stateRead.steps ? null : stateRead.why,
329
345
  approvalsWhy,
@@ -426,7 +442,7 @@ function searchCmd(root, read, keep, text, { json, thread, threadNote }) {
426
442
  for (const item of newestFirst(read.items.filter(keep))) {
427
443
  const r = readState(root, item.id);
428
444
  if (!r.steps) summaryOnly.push({ id: item.id, why: r.why });
429
- const matches = searchMatches(item, r.steps || null, text);
445
+ const matches = searchMatches(item, r.steps || null, text, r.state?.reopens ?? null);
430
446
  if (matches.length) found.push({ ...withShapeDone(item), matches });
431
447
  }
432
448
  if (json) {
@@ -493,6 +509,10 @@ function showCmd(root, read, id, { json }) {
493
509
  for (const a of s.approvals || []) log(` ${c.dim(approvalLine(a))}`);
494
510
  if (s.staleUnknown) log(` ${c.dim(`whether these approvals are stale cannot be told — ${printable(s.staleUnknown)}`)}`);
495
511
  }
512
+ for (const x of story.reopens || []) {
513
+ log(` ${c.dim(`reopened ${printable(x.step) ?? '?'}${x.date ? ` on ${printable(x.date)}` : ''}${x.by ? ` by ${printable(x.by)}` : ''}${x.reason ? ` — ${printable(x.reason)}` : ''}`)}`);
514
+ log(` ${c.dim(`walked back: ${x.walkedBack.map((id) => printable(id)).join(', ') || 'none'}; revoked (not counted): ${x.revoked.length ? x.revoked.map((a) => `${printable(a.approver) ?? '?'} on ${printable(a.step) ?? '?'}`).join(', ') : 'none'}`)}`);
515
+ }
496
516
  const closedCount = story.steps.filter((s) => s.closed).length;
497
517
  info(`${plural(closedCount, 'step')} of ${story.steps.length} ${closedCount === 1 ? 'has' : 'have'} a closing record`);
498
518
  }