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/hook.mjs CHANGED
@@ -29,6 +29,7 @@ import { fileURLToPath } from 'node:url';
29
29
  import { note, readJSON, run } from './lib.mjs';
30
30
  import { isVerifiedLedger, mirrorDrift, productConfigPath, HOOK_PROJECT_DIR_ENVS, PROJECT_FILES } from './manifest.mjs';
31
31
  import { DISCOVERY_EPIC, FOUNDATION_DIR, FOUNDATION_EPIC } from './epic-state.mjs';
32
+ import { agentGuardDecision, payloadCommand, isCursorPayload } from './agent-guard.mjs';
32
33
 
33
34
  // The CI-owned files, exactly as `templates/checks/ledger-guard.sh` lists them. NOT `contract-lock.json`
34
35
  // (artifact-side: the architect commits it with the architecture) and NOT `change.json` — both are a
@@ -292,7 +293,7 @@ export function guardConfig(productRoot) {
292
293
  }
293
294
 
294
295
  const driftLine = (productRoot) =>
295
- `note: ${path.join(productRoot, PROJECT_FILES.productConfig)} and ${PROJECT_FILES.productConfigLegacy} say different things, and one of them is verified, so this edit is guarded — run \`yad migrate\` to choose the copy to keep`;
296
+ `note: ${path.join(productRoot, PROJECT_FILES.productConfig)} and ${PROJECT_FILES.productConfigLegacy} say different things, and one of them is verified, so this edit is guarded — run \`yad migrate --apply --keep product\` (or \`--keep hub\`) to choose the copy to keep`;
296
297
 
297
298
  // What the agent is told when the edit is refused. Names the command that owns each transition —
298
299
  // the whole point of #171 was that the ledger write had no command behind it.
@@ -308,6 +309,9 @@ export function denyMessage({ epic, rel, productRoot }) {
308
309
  ` author step done → review opened yad gate open ${epic} <artifact>`,
309
310
  ' the full advance at merge CI runs `yad gate ci --merged` — nothing to do locally',
310
311
  ` a genuinely broken ledger yad gate repair ${epic} --push`,
312
+ ' (it pushes to the default branch: an AI agent asks the person first)',
313
+ ` an approved step to change yad gate reopen ${epic} <step> --reason "<why>" --push`,
314
+ ' (the person\'s: an AI agent hands it to them, `!` in front in Claude Code)',
311
315
  '',
312
316
  'Commit the ARTIFACT only (the .md you authored) and hand off to `yad-review-gate`; the ledger',
313
317
  'follows on merge.',
@@ -457,14 +461,19 @@ export function commitDenyMessage({ hits, top }) {
457
461
  ` author step done → review opened yad gate open ${epic} <artifact>`,
458
462
  ' the full advance at merge CI runs `yad gate ci --merged` — nothing to do locally',
459
463
  ` a genuinely broken ledger yad gate repair ${epic} --push`,
464
+ ' (it pushes to the default branch: an AI agent asks the person first)',
465
+ ` an approved step to change yad gate reopen ${epic} <step> --reason "<why>" --push`,
466
+ ' (the person\'s: an AI agent hands it to them, `!` in front in Claude Code)',
460
467
  ] : []),
461
468
  ...(index ? [' the Product index CI rebuilds it at merge; read it with `yad index --json`'] : []),
462
469
  '',
463
470
  ...[...new Set(hits.filter((h) => h.drift).map((h) => h.productRoot))].map((r) => `${driftLine(r)}\n`),
464
471
  'Amending a commit to UNDO a ledger change it made? `git commit --amend` is compared with the commit it',
465
- 'replaces, so this hook cannot tell. Run it as `YAD_HOOK_DISABLE=1 git commit --amend`; the check on the',
466
- 'pull request judges the result against its parent.',
467
- 'To commit anyway, with the reason recorded in the commit (it adds a `Ledger-Override:` line):',
472
+ 'replaces, so this hook cannot tell. The person runs it as `YAD_HOOK_DISABLE=1 git commit --amend` (an AI',
473
+ 'agent hands it to them: `!` in front in Claude Code); the check on the pull request judges the result',
474
+ 'against its parent.',
475
+ 'To commit anyway, the person runs this (an AI agent hands it to them), with the reason recorded in the',
476
+ 'commit (it adds a `Ledger-Override:` line):',
468
477
  ' yad commit --manual --reason "<why>" --type <type> -m "<subject>" (add --force above 3 files)',
469
478
  'The check on the pull request still fails it, and quotes the reason.',
470
479
  `product: ${roots.join(', ')}`,
@@ -604,3 +613,25 @@ export function runLedgerGuardHook({ paths = [], format = 'exit' } = {}) {
604
613
  process.exitCode = 2;
605
614
  return 2;
606
615
  }
616
+
617
+ // The `yad hook agent-guard` entry point (E158): the shell command in the payload, judged by
618
+ // `agentGuardDecision`, answered in the protocol the payload names (Cursor's `beforeShellExecution` wants a
619
+ // JSON verdict; Claude Code reads the exit code) unless `--format` says which. `YAD_HOOK_DISABLE` turns it
620
+ // off, as it does the ledger guard. Fail-open: no payload, or no command in it, is allowed.
621
+ export function runAgentGuardHook({ format = null } = {}) {
622
+ const payload = readPayload();
623
+ const cursor = format ? format === 'cursor' : isCursorPayload(payload);
624
+ if (format && !HOOK_FORMATS.includes(format)) {
625
+ note(`yad hook: unknown --format '${format}' — using '${HOOK_FORMATS[0]}' (known: ${HOOK_FORMATS.join(', ')})`);
626
+ }
627
+ const verdict = process.env.YAD_HOOK_DISABLE ? { allow: true } : agentGuardDecision(payloadCommand(payload));
628
+ if (cursor) {
629
+ process.stdout.write(`${verdict.allow ? CURSOR_ALLOW : cursorDeny(verdict.message)}\n`);
630
+ if (!verdict.allow) console.error(verdict.message);
631
+ return 0;
632
+ }
633
+ if (verdict.allow) return 0;
634
+ console.error(verdict.message);
635
+ process.exitCode = 2;
636
+ return 2;
637
+ }
@@ -15,7 +15,7 @@ import { c, log, ok, info, warn, fail, hand, exists, emitJSON } from './lib.mjs'
15
15
  import path from 'node:path';
16
16
  import { productConfigPath, isVerifiedLedger, SCHEMA_VERSION, settingsEditHint } from './manifest.mjs';
17
17
  import { loadProduct } from './gate.mjs';
18
- import { productGit, resolveDefaultBranch } from './productcommit.mjs';
18
+ import { productGit, resolveDefaultBranch, branchToCommitOn } from './productcommit.mjs';
19
19
  import { buildIndex, writeIndex, indexFreshness, INDEX_FILE } from './product-index.mjs';
20
20
  import { printable } from './epic-state.mjs';
21
21
 
@@ -58,8 +58,8 @@ export async function runIndex(root, { json = false } = {}) {
58
58
  return;
59
59
  }
60
60
  const git = productGit(root);
61
- const branch = git('rev-parse', '--abbrev-ref', 'HEAD').stdout;
62
61
  const defaultBranch = resolveDefaultBranch(git, productConfig);
62
+ const branch = branchToCommitOn(root, git, defaultBranch); // an epic worktree's detached trunk counts (#115)
63
63
  if (branch !== defaultBranch) {
64
64
  fail(`on '${branch}', not the default branch '${defaultBranch}' — ${INDEX_FILE} is written on the default branch only, so a branch never carries it`);
65
65
  hand(`switch to '${defaultBranch}' and re-run (if '${defaultBranch}' is wrong, set default_branch in ${settingsEditHint(root)}); \`yad index --json\` prints it here without writing`);
package/cli/ledger.mjs CHANGED
@@ -241,6 +241,66 @@ export function writeRetroShip(epicDir, { story, repo, task = 'retro', mergeComm
241
241
  }, lockOpts);
242
242
  }
243
243
 
244
+ // Why a ship of (story, task, repo) cannot be written now — `{ reason: 'exists' | 'collision', repo?, file? }` —
245
+ // or null. `yad build merged` asks it too, so it never answers "merged" for a ship this would refuse.
246
+ export function shipBlocked(epicDir, { story, task, repo }) {
247
+ const ships = readShips(epicDir).filter((s) => s.story === story && s.task === task);
248
+ if (ships.some((s) => s.repo === repo)) return { reason: 'exists' };
249
+ const clash = ships.find((s) => safe(s.repo) === safe(repo));
250
+ if (clash) return { reason: 'collision', repo: clash.repo };
251
+ const file = path.join(epicFiles(epicDir).buildLogDir, buildShardName({ story, task, repo }));
252
+ if (fs.existsSync(file)) return { reason: 'collision', file };
253
+ return null;
254
+ }
255
+
256
+ // Record a ship (`yad build ship`, #346): one shard per (story, task, repo), refused when that ship is
257
+ // already recorded, or when another repo's ship shares its file name (`safe()` folds `api.v2` and `api_v2`
258
+ // into one name, and writing the second would overwrite the first). The guard, the collision check and the
259
+ // write are one critical section, as in `writeRetroShip`. Returns { written, reason?, file?, ship? }.
260
+ export function writeShip(epicDir, ship, lockOpts = {}) {
261
+ const { story, task, repo } = ship;
262
+ if (!story || !task || !repo) throw new Error('writeShip: story, task and repo are required');
263
+ return withLedgerLock(buildLogLock(epicDir), () => {
264
+ const blocked = shipBlocked(epicDir, ship);
265
+ if (blocked) return { written: false, ...blocked };
266
+ const file = path.join(epicFiles(epicDir).buildLogDir, buildShardName(ship));
267
+ writeJSON(file, ship);
268
+ return { written: true, file, ship };
269
+ }, lockOpts);
270
+ }
271
+
272
+ // Record one trust run (`yad build trust`, #346): a new shard under its own `uid`, never over another file.
273
+ export function writeTrustRun(epicDir, entry, lockOpts = {}) {
274
+ if (!entry?.story || !entry.repo || !entry.step || !entry.uid) throw new Error('writeTrustRun: story, repo, step and uid are required');
275
+ return withLedgerLock(trustLogLock(epicDir), () => {
276
+ const file = path.join(epicFiles(epicDir).trustLogDir, trustShardName(entry));
277
+ if (fs.existsSync(file)) return { written: false, reason: 'collision', file };
278
+ writeJSON(file, entry);
279
+ return { written: true, file };
280
+ }, lockOpts);
281
+ }
282
+
283
+ // Finalize a trust run's verdict where it lives: its own shard, or its entry in the folded trust-log.json
284
+ // once `yad tidy up` folded it — the human gate's word on a run the orchestrator recorded.
285
+ export function updateTrustRun(epicDir, match, update, lockOpts = {}) {
286
+ return withLedgerLock(trustLogLock(epicDir), () => {
287
+ const f = epicFiles(epicDir);
288
+ // Both copies when a half-applied tidy left the run in each: readers take the folded one then.
289
+ const foldedObj = readJSONStrict(f.trustLog, null);
290
+ const run = Array.isArray(foldedObj?.runs) ? foldedObj.runs.find(match) : null;
291
+ if (run) { update(run); writeJSON(f.trustLog, foldedObj); }
292
+ for (const { name, obj } of readShardDir(f.trustLogDir)) {
293
+ if (match(obj)) {
294
+ update(obj);
295
+ const file = path.join(f.trustLogDir, name);
296
+ writeJSON(file, obj);
297
+ return { found: true, where: 'shard', file, run: obj };
298
+ }
299
+ }
300
+ return run ? { found: true, where: 'folded', file: f.trustLog, run } : { found: false };
301
+ }, lockOpts);
302
+ }
303
+
244
304
  // Find the ship matching `match(ship)` across loose shards (authoritative until folded) then the
245
305
  // folded file, apply `update(ship)`, and write back ONLY the file that holds it. Returns
246
306
  // { found, where, file, ship }; found:false writes nothing (the caller warns). The find and the
package/cli/lib.mjs CHANGED
@@ -219,6 +219,52 @@ export function copyDir(src, dest) {
219
219
  fs.rmSync(dest, { recursive: true, force: true });
220
220
  fs.cpSync(src, dest, { recursive: true });
221
221
  }
222
+ // E161 — which Node line this is. Below 18 yadflow does not run (YAD-ENV-003). 18 and 20 are end of life:
223
+ // yadflow 4 still runs on them, with a warning (YAD-ENV-004), and yadflow 5 needs 22. 22 and later are ok.
224
+ export const NODE_FLOOR = 18;
225
+ export const NODE_SUPPORTED = 22;
226
+ export function nodeSupport(version = process.versions.node) {
227
+ const major = Number(String(version).replace(/^v/, '').split('.')[0]);
228
+ return !(major >= NODE_FLOOR) ? 'unsupported' : major < NODE_SUPPORTED ? 'end-of-life' : 'ok';
229
+ }
230
+ export const nodeEndOfLife = (version) => `Node ${version} is end of life and gets no security fixes. yadflow 4 still runs on it; yadflow 5 will need Node ${NODE_SUPPORTED} or newer. Upgrade: https://nodejs.org`;
231
+
232
+ // Remove a file or a folder tree, read-only folders too: each folder is opened (its owner may write) first,
233
+ // since a folder whose mode forbids writing keeps its files from `rmSync`. A path that is not there is fine.
234
+ export function rmTree(p) {
235
+ let st;
236
+ try { st = fs.lstatSync(p); } catch { return; }
237
+ if (st.isDirectory()) {
238
+ try { fs.chmodSync(p, (st.mode & 0o7777) | 0o700); } catch { /* not ours to open: rmSync says why */ }
239
+ for (const name of fs.readdirSync(p)) rmTree(path.join(p, name));
240
+ }
241
+ fs.rmSync(p, { recursive: true, force: true });
242
+ }
243
+
244
+ // Copy a folder into another, joining folders and never replacing a file: a file that is already there is
245
+ // an EEXIST error. `fs.cpSync(…, { errorOnExist: true, force: false })` did this up to Node 22; Node 24
246
+ // refuses a folder that exists too, even an empty one, so a move into a folder with the user's own files
247
+ // failed. A new folder keeps its source's permissions, and a file its mode (copyFileSync). A link is copied
248
+ // as the link it is (cpSync made a relative link absolute, into the source the move then deletes).
249
+ // Anything else (a named pipe, a device) is refused, as cpSync did. `created`, when given, collects every
250
+ // path this copy made, so a failed move removes those and nothing that was there before.
251
+ export function cpMerge(src, dest, created = null) {
252
+ const st = fs.lstatSync(src);
253
+ let there = true;
254
+ try { fs.lstatSync(dest); } catch { there = false; }
255
+ if (st.isDirectory()) {
256
+ // The source's mode is set after the folder is filled: a read-only folder must still take its files.
257
+ if (!there) { fs.mkdirSync(dest); created?.push(dest); }
258
+ for (const name of fs.readdirSync(src)) cpMerge(path.join(src, name), path.join(dest, name), created);
259
+ if (!there) fs.chmodSync(dest, st.mode & 0o7777);
260
+ return;
261
+ }
262
+ if (there) throw Object.assign(new Error(`EEXIST: ${dest} already exists, and a copy never replaces a file`), { code: 'EEXIST' });
263
+ if (st.isSymbolicLink()) fs.symlinkSync(fs.readlinkSync(src), dest);
264
+ else if (st.isFile()) fs.copyFileSync(src, dest, fs.constants.COPYFILE_EXCL);
265
+ else throw Object.assign(new Error(`${src} is not a file, a folder or a link, so it is not copied`), { code: 'EINVAL' });
266
+ created?.push(dest);
267
+ }
222
268
  // Recursive list of file paths relative to `dir`.
223
269
  export function listFiles(dir, base = dir) {
224
270
  if (!fs.existsSync(dir)) return [];
@@ -0,0 +1,124 @@
1
+ {
2
+ "schemaVersion": 10,
3
+ "extends": "yadflow-default@2",
4
+ "phases": [
5
+ { "id": "foundation", "name": "Foundation", "level": "product", "runs": "once", "built": true,
6
+ "description": "The Product level, written once: what the product is for and how it will be built. Optional, but every epic reads it when it exists." },
7
+ { "id": "discover", "name": "Discover", "part": "Shape", "level": "feature", "runs": "once", "built": true,
8
+ "description": "Say what the change is and why: the optional analysis, then the epic." },
9
+ { "id": "design", "name": "Design", "part": "Shape", "level": "feature", "runs": "once", "built": true,
10
+ "description": "Decide how it is built: the architecture and its locked contract, and the user interface when there is one." },
11
+ { "id": "plan", "name": "Plan", "part": "Shape", "level": "feature", "runs": "once", "built": true,
12
+ "description": "Split the work into stories, and write the test cases that prove them." },
13
+ { "id": "build", "name": "Build", "part": "Build", "level": "feature", "runs": "loop", "over": ["story", "repo"], "built": true,
14
+ "description": "Each story is built in each repo it names, one lane at a time: spec, tasks, implement and checks by the agent, then a person's engineer review and merge." },
15
+ { "id": "release", "name": "Release", "part": "Run", "level": "feature", "runs": "loop", "over": ["release"], "built": false,
16
+ "description": "Not built yet." },
17
+ { "id": "operate", "name": "Operate", "part": "Run", "level": "feature", "runs": "once", "built": false,
18
+ "description": "Not built yet." }
19
+ ],
20
+ "steps": [
21
+ { "id": "foundation", "name": "Foundation", "phase": "foundation", "kind": "author",
22
+ "description": "Write the Product's foundation once: its purpose, scope, first release (MVP), roadmap, stack and repos, plus its market and risks if wanted. Every epic builds on it.", "driver": "pair",
23
+ "artifact": { "type": "set", "path": "foundation/",
24
+ "files": ["purpose.md", "market.md", "scope.md", "mvp.md", "roadmap.md", "stack.md", "repos.md", "risks.md"],
25
+ "optional": ["market.md", "risks.md"] },
26
+ "optional": false, "gate": { "riskTags": [], "advance": "human",
27
+ "description": "A person reviews the foundation and approves it: on its review PR/MR, then merges it, when the Product has a platform; with `yad gate approve` and `yad gate advance` when it has none (in solo mode no approval is counted, so only `yad gate advance`). The step never moves on by itself." }, "skills": ["yad-discovery"], "behaviours": ["product-level"],
28
+ "extraPaths": [], "inputs": [], "replaces": "discovery",
29
+ "provider": { "id": "yadflow", "version": 1, "origin": "foundation" } },
30
+ { "id": "discovery", "name": "Discovery", "phase": "foundation", "kind": "author",
31
+ "description": "The old Product-level step, replaced by Foundation. Kept so a Product that still uses it can be read.", "driver": "pair",
32
+ "artifact": { "type": "set", "path": "discovery/",
33
+ "files": ["market-research.md", "competitor-analysis.md", "current-state.md", "feasibility.md", "requirements.md", "roadmap.md"],
34
+ "optional": [] },
35
+ "optional": false, "gate": { "riskTags": [], "advance": "human",
36
+ "description": "A person reviews the discovery and approves it: on its review PR/MR, then merges it, when the Product has a platform; with `yad gate approve` and `yad gate advance` when it has none (in solo mode no approval is counted, so only `yad gate advance`). The step never moves on by itself." }, "skills": ["yad-discovery"], "behaviours": ["product-level"],
37
+ "extraPaths": [], "inputs": [], "retired": true,
38
+ "provider": { "id": "yadflow", "version": 1, "origin": "discovery" } },
39
+ { "id": "analysis", "name": "Analysis", "phase": "discover", "kind": "author",
40
+ "description": "Study the problem before the epic: who it is for, the options, and the evidence. The analysis-first and spike routes start here.", "driver": "pair",
41
+ "artifact": { "type": "file", "path": "analysis.md" },
42
+ "optional": false, "gate": { "riskTags": [], "advance": "human",
43
+ "description": "A person reviews the analysis and approves it: on its review PR/MR, then merges it, when the Product has a platform; with `yad gate approve` and `yad gate advance` when it has none (in solo mode no approval is counted, so only `yad gate advance`). The step never moves on by itself." }, "skills": ["yad-analysis"], "behaviours": [],
44
+ "extraPaths": [], "inputs": [],
45
+ "provider": { "id": "yadflow", "version": 1, "origin": "analysis" } },
46
+ { "id": "epic", "name": "Epic", "phase": "discover", "kind": "author",
47
+ "description": "Describe the change: the problem, the goal, what is in and out of scope, and how success is measured. It sets the work-item type the rest of the chain follows.", "driver": "pair",
48
+ "artifact": { "type": "file", "path": "epic.md" },
49
+ "optional": false, "gate": { "riskTags": [], "advance": "human",
50
+ "description": "A person reviews the epic and approves it: on its review PR/MR, then merges it, when the Product has a platform; with `yad gate approve` and `yad gate advance` when it has none (in solo mode no approval is counted, so only `yad gate advance`). The step never moves on by itself." }, "skills": ["yad-epic"], "behaviours": ["work-item-source"],
51
+ "extraPaths": [], "inputs": ["analysis"],
52
+ "provider": { "id": "yadflow", "version": 1, "origin": "epic" } },
53
+ { "id": "architecture", "name": "Architecture", "phase": "design", "kind": "author",
54
+ "description": "Decide how the change is built across the repos, and lock the contract between them. A later change to the locked contract needs its own review.", "driver": "pair",
55
+ "artifact": { "type": "file", "path": "architecture.md" },
56
+ "optional": false, "gate": { "riskTags": ["contract"], "advance": "human",
57
+ "description": "A person reviews the architecture and approves it: on its review PR/MR, then merges it, when the Product has a platform; with `yad gate approve` and `yad gate advance` when it has none (in solo mode no approval is counted, so only `yad gate advance`). The step never moves on by itself." }, "skills": ["yad-architecture"], "behaviours": ["locks-contract"],
58
+ "extraPaths": ["contract.md", ".sdlc/contract-lock.json"], "inputs": ["epic"],
59
+ "provider": { "id": "yadflow", "version": 1, "origin": "architecture" } },
60
+ { "id": "ui-design", "name": "UI design", "phase": "design", "kind": "author",
61
+ "description": "Design the screens and flows, and link the design files. Optional on the routes that offer it: skip it when the change has no user interface.", "driver": "pair",
62
+ "artifact": { "type": "file", "path": "ui-design.md" },
63
+ "optional": false, "gate": { "riskTags": [], "advance": "human",
64
+ "description": "A person reviews the UI design and approves it: on its review PR/MR, then merges it, when the Product has a platform; with `yad gate approve` and `yad gate advance` when it has none (in solo mode no approval is counted, so only `yad gate advance`). The step never moves on by itself." }, "skills": ["yad-ui"], "behaviours": [],
65
+ "extraPaths": ["DESIGN.md", ".sdlc/design-links.json"], "inputs": ["epic", "architecture"],
66
+ "provider": { "id": "yadflow", "version": 1, "origin": "ui-design" } },
67
+ { "id": "stories", "name": "Stories", "phase": "plan", "kind": "author",
68
+ "description": "Split the epic into stories, each tagged with the repos it touches. Its approval ends Shape, so Build can start.", "driver": "pair",
69
+ "artifact": { "type": "folder", "path": "stories/", "unit": "story" },
70
+ "optional": false, "gate": { "riskTags": [], "advance": "human",
71
+ "description": "A person reviews the stories and approves them: on their review PR/MR, then merges it, when the Product has a platform; with `yad gate approve` and `yad gate advance` when it has none (in solo mode no approval is counted, so only `yad gate advance`). The step never moves on by itself." }, "skills": ["yad-stories"], "behaviours": ["ends-shape"],
72
+ "extraPaths": [], "inputs": ["epic", "architecture", "ui-design"],
73
+ "provider": { "id": "yadflow", "version": 1, "origin": "stories" } },
74
+ { "id": "test-cases", "name": "Test cases", "phase": "plan", "kind": "author",
75
+ "description": "Write the test cases that prove the stories work. It runs beside Build, not before it.", "driver": "pair",
76
+ "artifact": { "type": "file", "path": "test-cases.md" },
77
+ "optional": false, "gate": { "riskTags": [], "advance": "human",
78
+ "description": "A person reviews the test cases and approves them: on their review PR/MR, then merges it, when the Product has a platform; with `yad gate approve` and `yad gate advance` when it has none (in solo mode no approval is counted, so only `yad gate advance`). The step never moves on by itself." }, "skills": ["yad-test-cases"], "behaviours": ["parallel-with-build"],
79
+ "extraPaths": [".sdlc/test-links.json"], "inputs": ["stories"],
80
+ "provider": { "id": "yadflow", "version": 1, "origin": "test-cases" } },
81
+ { "id": "spec", "name": "Spec", "phase": "build", "kind": "author",
82
+ "description": "For one story in one repo, write the detailed spec the code is built from.", "driver": "agent",
83
+ "artifact": null,
84
+ "optional": false, "gate": null, "skills": ["yad-spec"], "behaviours": ["spec-source"],
85
+ "extraPaths": [], "inputs": ["stories"],
86
+ "provider": { "id": "yadflow", "version": 1, "origin": "spec" } },
87
+ { "id": "tasks", "name": "Tasks", "phase": "build", "kind": "author",
88
+ "description": "Break the spec into small, ordered tasks, each naming the files it may touch (aim for 3 or fewer).", "driver": "agent",
89
+ "artifact": null,
90
+ "optional": false, "gate": null, "skills": ["yad-spec"], "behaviours": [],
91
+ "extraPaths": [], "inputs": ["spec"],
92
+ "provider": { "id": "yadflow", "version": 1, "origin": "tasks" } },
93
+ { "id": "implement", "name": "Implement", "phase": "build", "kind": "author",
94
+ "description": "Write the code and its tests for one task, on the task's branch.", "driver": "agent",
95
+ "artifact": null,
96
+ "optional": false, "gate": null, "skills": ["yad-implement"], "behaviours": ["code-change"],
97
+ "extraPaths": [], "inputs": ["tasks"],
98
+ "provider": { "id": "yadflow", "version": 1, "origin": "implement" } },
99
+ { "id": "checks", "name": "Checks", "phase": "build", "kind": "author",
100
+ "description": "Run the CI gates on this machine (`yad run checks`). Then the task's PR/MR is opened, so CI runs them too; `yad dial open-pr` says whether the agent asks first.", "driver": "agent",
101
+ "artifact": null,
102
+ "optional": false, "gate": null, "skills": ["yad-checks"], "behaviours": ["ci-gates"],
103
+ "extraPaths": [], "inputs": ["implement"],
104
+ "provider": { "id": "yadflow", "version": 1, "origin": "checks" } },
105
+ { "id": "engineer-review", "name": "Engineer review", "phase": "build", "kind": "review",
106
+ "description": "A person reviews the PR/MR, approves it and merges it. An AI first pass may help, but the merge is always a person's.", "driver": "human",
107
+ "artifact": null,
108
+ "optional": false, "gate": null, "skills": ["yad-engineer-review"], "behaviours": ["merge-gate"],
109
+ "extraPaths": [], "inputs": ["checks"],
110
+ "provider": { "id": "yadflow", "version": 1, "origin": "engineer-review" } }
111
+ ],
112
+ "routes": [
113
+ { "id": "classic", "name": "the 10-step chain",
114
+ "steps": ["epic", "architecture", { "id": "ui-design", "optional": true }, "stories", "test-cases"] },
115
+ { "id": "analysis-first", "name": "the 12-step chain",
116
+ "steps": ["analysis", "epic", "architecture", { "id": "ui-design", "optional": true }, "stories", "test-cases"] },
117
+ { "id": "chore", "name": "the upkeep lane", "steps": ["epic", "stories"] },
118
+ { "id": "spike", "name": "the investigation lane", "steps": ["analysis", "epic", "stories"] },
119
+ { "id": "discovery", "name": "the product front-zero", "steps": ["discovery"], "retired": true },
120
+ { "id": "foundation", "name": "the Product Foundation", "steps": ["foundation"] },
121
+ { "id": "lane", "name": "the Build lane", "steps": ["spec", "tasks", "implement", "checks", "engineer-review"] }
122
+ ],
123
+ "plugins": []
124
+ }
@@ -54,7 +54,9 @@
54
54
  "type": "object",
55
55
  "properties": {
56
56
  "riskTags": { "type": "array", "items": { "type": "string" } },
57
- "skills": { "type": "array", "items": { "type": "string" } }
57
+ "skills": { "type": "array", "items": { "type": "string" } },
58
+ "description": { "type": "string", "description": "What the review is for, in a sentence an AI agent can show the person." },
59
+ "advance": { "const": "human", "description": "Who moves the gate on: always a person." }
58
60
  }
59
61
  }
60
62
  ]
@@ -88,7 +90,8 @@
88
90
  "inputs": { "type": "array", "items": { "type": "string", "minLength": 1 } },
89
91
  "retired": { "type": "boolean", "default": false },
90
92
  "replaces": { "type": "string" },
91
- "provider": { "$ref": "#/$defs/provider" }
93
+ "provider": { "$ref": "#/$defs/provider" },
94
+ "driver": { "enum": ["human", "pair", "agent"], "description": "Who does the step's work by default: only a person, the AI agent and the person together (the agent drafts, the person decides), or the agent. A review step's driver is \"human\"." }
92
95
  }
93
96
  },
94
97
  "route": {
package/cli/lifecycle.mjs CHANGED
@@ -25,7 +25,7 @@
25
25
  import fs from 'node:fs';
26
26
 
27
27
  // The newest shipped default — the one every reader uses until a team file exists (E135).
28
- export const DEFAULT_VERSION = 1;
28
+ export const DEFAULT_VERSION = 2;
29
29
 
30
30
  const DEFAULTS_DIR = new URL('./lifecycle/defaults/', import.meta.url);
31
31
 
@@ -92,6 +92,14 @@ export const ARTIFACT_TYPES = ['file', 'folder', 'set'];
92
92
  export const PHASE_RUNS = ['once', 'loop'];
93
93
  export const PHASE_LEVELS = ['feature', 'product'];
94
94
  export const PARTS = ['Shape', 'Build', 'Run'];
95
+ // Who does a step's work, by default (E157), in the words of the shape-4 `driver` dial (cli/manifest.mjs):
96
+ // `human` (only a person can), `pair` (the AI agent drafts, the person answers its questions and decides)
97
+ // or `agent` (the agent does it). An epic's own `driver` on a step, when it records one, says what that
98
+ // epic chose. An AI agent reads it through `yad guide --json` to know when to stop and hand the work over.
99
+ // A review step is a person's approval, so its driver is `human`. A gate is moved on only by a person (its
100
+ // `advance` is `human`, rule 1 of the spine: a gate is never automatic), so a file that says otherwise is
101
+ // refused.
102
+ export const DRIVERS = ['human', 'pair', 'agent'];
95
103
 
96
104
  // THE BEHAVIOUR REGISTRY. A behaviour is something the engine does because of a step, not because of a
97
105
  // step's name: the epic step is where the work-item type is read, the architecture step locks the
@@ -137,9 +145,9 @@ export const KNOWN_KEYS = {
137
145
  file: ['$schema', 'schemaVersion', 'extends', 'phases', 'steps', 'routes', 'plugins'],
138
146
  phase: ['id', 'name', 'description', 'part', 'level', 'runs', 'over', 'built'],
139
147
  step: ['id', 'name', 'description', 'phase', 'kind', 'artifact', 'optional', 'gate', 'skills', 'behaviours',
140
- 'extraPaths', 'inputs', 'retired', 'replaces', 'provider'],
148
+ 'extraPaths', 'inputs', 'retired', 'replaces', 'provider', 'driver'],
141
149
  route: ['id', 'name', 'description', 'steps', 'bindings', 'retired', 'provider'],
142
- gate: ['riskTags', 'skills'],
150
+ gate: ['riskTags', 'skills', 'description', 'advance'],
143
151
  artifact: ['type', 'path', 'unit', 'files', 'optional', 'in'],
144
152
  provider: ['id', 'version', 'origin'],
145
153
  routeStep: ['id', 'optional'],
@@ -335,6 +343,9 @@ export function lifecycleProblems(raw) {
335
343
  }
336
344
  if (s.replaces !== undefined && typeof s.replaces !== 'string') add('error', where, '"replaces" must be a step id');
337
345
  if (s.description !== undefined && typeof s.description !== 'string') add('error', where, '"description" must be text');
346
+ if (s.driver !== undefined && typeof s.driver !== 'string') add('error', where, `"driver" must be one word: ${DRIVERS.join(', ')}`);
347
+ else if (s.driver !== undefined && !DRIVERS.includes(s.driver)) add('unusable', where, `"driver" is "${s.driver}", which this yadflow does not know; the step cannot be used for new epics`);
348
+ if (s.kind === 'review' && s.driver !== undefined && s.driver !== 'human') add('error', where, 'a review step is a person\'s approval, so its "driver" is "human"');
338
349
  if (s.provider !== undefined && !providerOk(s.provider)) add('error', where, PROVIDER_SHAPE);
339
350
  if (!phaseIds.has(s.phase)) add('error', where, `its phase "${s.phase}" does not exist`);
340
351
  else if (unknownRuns.has(s.phase)) add('unusable', where, `its phase "${s.phase}" uses a "runs" value this yadflow does not know`);
@@ -351,6 +362,8 @@ export function lifecycleProblems(raw) {
351
362
  || (s.gate.skills !== undefined && !isStrings(s.gate.skills)))) {
352
363
  add('error', where, '"gate" must be null or { "riskTags": [ … ], "skills": [ … ] }');
353
364
  }
365
+ if (isObj(s.gate) && s.gate.description !== undefined && typeof s.gate.description !== 'string') add('error', where, 'the gate\'s "description" must be text');
366
+ if (isObj(s.gate) && s.gate.advance !== undefined && s.gate.advance !== 'human') add('error', where, 'a gate is moved on only by a person, so the gate\'s "advance" is "human"');
354
367
 
355
368
  if (n.artifact !== null) {
356
369
  const a = n.artifact;
package/cli/manifest.mjs CHANGED
@@ -56,6 +56,8 @@ export const SKILLS = [
56
56
  'yad-pair-review',
57
57
  'yad-status',
58
58
  'yad-report',
59
+ // E158: the rules and the step loop for an AI agent, loaded before any yadflow work.
60
+ 'yad-guide',
59
61
  'yad-change',
60
62
  'yad-timeline',
61
63
  'yad-defects',
@@ -568,6 +570,26 @@ export const PRODUCT_WIRING = {
568
570
  // The branch-protection setup guide (E48), linked from `yad doctor`'s `protection` section. A URL, not a
569
571
  // path: the reader is in their own repo, where `docs/` is not yadflow's.
570
572
  export const PROTECTION_GUIDE_URL = 'https://github.com/abdelrahmannasr/yadflow/blob/main/docs/branch-protection.md';
573
+ // E160b — the checks a team requires before a merge, by the name the platform gives each one: on GitHub a
574
+ // check is named after its job (the jobs set no `name:`), on GitLab a job is the job's key. `yad ci check`
575
+ // reads the GitHub list against the branch's required checks; on GitLab "Pipelines must succeed" covers
576
+ // every job, so the list there is for the docs only. `productVerified` is the Product's verified-commits
577
+ // workflow, required when that file is there. Tests hold this equal to the templates' jobs and to the table
578
+ // in docs/branch-protection.md.
579
+ export const REQUIRED_CHECKS = Object.freeze({
580
+ github: Object.freeze({
581
+ product: Object.freeze(['commit-message', 'pr-title', 'pr-template', 'ledger-guard', 'member-check']),
582
+ productVerified: Object.freeze(['verified-commits']),
583
+ code: Object.freeze(['spec-link', 'contract-check', 'risk-map', 'build-test-lint', 'lineage-check', 'epic-open', 'reconcile-debt',
584
+ 'commit-message', 'pr-title', 'pr-template', 'verified-commits']),
585
+ }),
586
+ gitlab: Object.freeze({
587
+ product: Object.freeze(['yad-product-commit-message', 'yad-product-pr-title', 'yad-product-pr-template', 'yad-product-ledger-guard', 'yad-product-member-check']),
588
+ productVerified: Object.freeze(['yad-product-verified-commits']),
589
+ code: Object.freeze(['yad-spec-link', 'yad-contract-check', 'yad-risk-map', 'yad-build-test-lint', 'yad-lineage-check', 'yad-epic-open',
590
+ 'yad-reconcile-debt', 'yad-commit-message', 'yad-pr-title', 'yad-pr-template', 'yad-verified-commits']),
591
+ }),
592
+ });
571
593
  // The hub -> Product hand-change guide (E124), linked from `yad migrate`'s last line while `.sdlc/hub.json` is on
572
594
  // disk. A URL for the same reason.
573
595
  export const PRODUCT_RENAME_GUIDE_URL = 'https://github.com/abdelrahmannasr/yadflow/blob/main/docs/migrations/hub-to-product.md';
@@ -748,6 +770,59 @@ export const CAPTURE_ADAPTERS = Object.freeze({
748
770
  }),
749
771
  });
750
772
 
773
+ // The agent guard (E158): BEFORE an agent's shell command runs, `hooks/agent-guard.mjs` asks
774
+ // `yad hook agent-guard` whether it is a yad command only the person may run (an approval, a gate comment,
775
+ // advance or reopen, `commit --manual`), a PR/MR approval or merge, skipping the git hooks, or a force push,
776
+ // and refuses it with what to do instead. Wired on every Product and every connected code repo cloned here
777
+ // (E158b), in both ledger modes: it is about the agent's rules, not about who owns the ledger. A speed bump,
778
+ // not proof (cli/agent-guard.mjs). Codex has no hooks: there, only the rules in AGENTS.md apply.
779
+ //
780
+ // ONE script for both harnesses. It reads the payload and answers in the protocol the payload names:
781
+ // Cursor's `beforeShellExecution` is a permission hook (a JSON verdict on stdout, always), Claude Code's
782
+ // `PreToolUse` reads the exit code. So both entries are a program and one path, the form Cursor documents.
783
+ export const AGENT_GUARD_WIRING = [
784
+ { src: 'skills/yad-checks/templates/hooks/agent-guard.mjs', dest: 'hooks/agent-guard.mjs' },
785
+ ];
786
+ // In a connected code repo the script goes in `checks/`, the folder yad already owns there (E158b): a root
787
+ // `hooks/` folder is often the app's own. The script finds yad from its grandparent, the repo's root, either way.
788
+ export const REPO_AGENT_GUARD_DEST = 'checks/agent-guard.mjs';
789
+ // The Claude and Cursor entries that run the script at `dest` (a path from the project's root).
790
+ export const agentGuardAdapters = (dest) => Object.freeze({
791
+ '.claude': Object.freeze({
792
+ target: '.claude',
793
+ label: 'agent guard',
794
+ settings: '.claude/settings.json',
795
+ event: 'PreToolUse',
796
+ nested: true,
797
+ preamble: null,
798
+ // The shell tool: the one way an agent runs a yad command or a git push.
799
+ matcher: 'Bash',
800
+ projectDirEnv: CLAUDE_PROJECT_DIR_ENV,
801
+ // Quoted and anchored on the project root, for the reason the ledger guard's entry is (see above).
802
+ command: `node "$${CLAUDE_PROJECT_DIR_ENV}/${dest}"`,
803
+ wiring: Object.freeze([]),
804
+ legacyCommands: Object.freeze([]),
805
+ }),
806
+ '.cursor': Object.freeze({
807
+ target: '.cursor',
808
+ label: 'agent guard',
809
+ settings: '.cursor/hooks.json',
810
+ // Fires before every shell command the agent runs, and takes no matcher.
811
+ event: 'beforeShellExecution',
812
+ nested: false,
813
+ preamble: Object.freeze({ version: 1 }),
814
+ matcher: null,
815
+ projectDirEnv: CURSOR_PROJECT_DIR_ENV,
816
+ // Relative and unquoted, for the reason the ledger guard's Cursor entry is (see above).
817
+ command: `node ${dest}`,
818
+ // A permission hook: an empty or off-schema answer BLOCKS, so the script always prints a verdict.
819
+ requiresJsonVerdict: true,
820
+ wiring: Object.freeze([]),
821
+ legacyCommands: Object.freeze([]),
822
+ }),
823
+ });
824
+ export const AGENT_GUARD_ADAPTERS = agentGuardAdapters(AGENT_GUARD_WIRING[0].dest);
825
+
751
826
  // The Claude adapter's fields under their original names. Kept because they are what the shipped
752
827
  // error text and the existing tests name, and renaming a constant buys nothing; new code should read
753
828
  // the adapter, since these three describe ONE harness and the engine now supports two.
@@ -0,0 +1,48 @@
1
+ // A block yad owns inside a file the team owns (E158): AGENTS.md and CLAUDE.md. Only the lines between the
2
+ // two markers are ever written; everything outside them is the team's and is kept byte for byte.
3
+ //
4
+ // The markers bound the block, so nothing has to guess where it ends (the lesson of E87: never infer the end
5
+ // of a generated block from headings). The rules follow `applyConfigRegions` (cli/lifecycle.mjs): exactly one
6
+ // begin marker followed by exactly one end marker, or the file is refused and left as it is; a file checked
7
+ // out with Windows line endings (CRLF) is compared without them and written back with them.
8
+ //
9
+ // Unlike a config region, a block that is not there yet is ADDED: the file is the team's, and yad's block is
10
+ // appended after their text, with one blank line between.
11
+
12
+ // The text of a file with yad's block in place, and what that changed.
13
+ // status 'new' the file had no block (or did not exist): it is appended
14
+ // 'outdated' the block is there with other lines
15
+ // 'ok' the block is there and right
16
+ // refused why the markers could not be trusted (a begin with no end, two of either, an end first). The
17
+ // text is then returned unchanged.
18
+ // `text` is null for a file that does not exist.
19
+ // `beginKey` is the start every begin line shares, so a later release can reword the note after it.
20
+ export function applyMarkedBlock(text, { begin, beginKey = begin, end, lines }) {
21
+ const source = text ?? '';
22
+ // Each line with its own ending, so the text outside the block is kept byte for byte, mixed endings too.
23
+ const rows = source.match(/[^\n]*\n|[^\n]+$/g) ?? [];
24
+ const bare = rows.map((r) => r.replace(/\r?\n$/, ''));
25
+ const begins = bare.flatMap((l, i) => (l.trim().startsWith(beginKey) ? [i] : []));
26
+ const ends = bare.flatMap((l, i) => (l.trim() === end ? [i] : []));
27
+ const want = [begin, ...lines, end];
28
+ if (!begins.length && !ends.length) {
29
+ // Appended after the team's text, in the file's own line ending: a newline is added only when it has none
30
+ // at the end, and a blank line only when it does not already end with one.
31
+ const eol = source.includes('\r\n') ? '\r\n' : '\n';
32
+ let head = source;
33
+ if (head && !/\n$/.test(head)) head += eol;
34
+ if (head && !/\n\r?\n$/.test(head)) head += eol;
35
+ return { text: `${head}${want.join(eol)}${eol}`, status: 'new', refused: null };
36
+ }
37
+ if (begins.length !== 1 || ends.length !== 1 || ends[0] < begins[0]) {
38
+ return { text: source, status: null, refused: `the yadflow block needs exactly one line starting "${beginKey}" followed by one line "${end}"` };
39
+ }
40
+ const [b, e] = [begins[0], ends[0]];
41
+ if (bare.slice(b, e + 1).join('\n') === want.join('\n')) return { text: source, status: 'ok', refused: null };
42
+ // The block is written in the ending its begin line had; the end line keeps whatever followed it (none at
43
+ // the very end of a file).
44
+ const eol = /\r\n$/.test(rows[b]) ? '\r\n' : '\n';
45
+ const tail = (rows[e].match(/\r?\n$/) ?? [''])[0];
46
+ const block = `${want.join(eol)}${tail}`;
47
+ return { text: rows.slice(0, b).join('') + block + rows.slice(e + 1).join(''), status: 'outdated', refused: null };
48
+ }