yadflow 4.9.0 → 4.10.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 (93) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/README.md +4 -3
  3. package/bin/commands.mjs +6 -0
  4. package/bin/yad.mjs +101 -6
  5. package/cli/agent-guard.mjs +793 -65
  6. package/cli/agent-rules.mjs +33 -5
  7. package/cli/argv-flags.mjs +1 -1
  8. package/cli/ci-check.mjs +45 -1
  9. package/cli/codeowners-command.mjs +72 -6
  10. package/cli/commit.mjs +17 -3
  11. package/cli/docs.mjs +2 -0
  12. package/cli/doctor.mjs +71 -12
  13. package/cli/epic-state.mjs +94 -4
  14. package/cli/epic.mjs +11 -7
  15. package/cli/fold.mjs +31 -6
  16. package/cli/guide.mjs +3 -1
  17. package/cli/hook.mjs +50 -7
  18. package/cli/issue-links.mjs +61 -0
  19. package/cli/issues-act.mjs +327 -0
  20. package/cli/issues-write.mjs +428 -0
  21. package/cli/issues.mjs +474 -0
  22. package/cli/lifecycle.mjs +7 -0
  23. package/cli/manifest.mjs +9 -3
  24. package/cli/openpr.mjs +24 -4
  25. package/cli/plan.mjs +2 -0
  26. package/cli/platform.mjs +157 -2
  27. package/cli/protection.mjs +21 -3
  28. package/cli/reconcile.mjs +1 -1
  29. package/cli/run-checks.mjs +10 -2
  30. package/cli/scan.mjs +314 -0
  31. package/cli/setup.mjs +12 -3
  32. package/cli/standup.mjs +33 -7
  33. package/cli/story-frames.mjs +17 -6
  34. package/cli/test-agents-file.mjs +378 -11
  35. package/cli/test-build.mjs +25 -0
  36. package/cli/test-ci-check.mjs +469 -10
  37. package/cli/test-guide.mjs +7 -0
  38. package/cli/test-node.mjs +15 -0
  39. package/cli/test-run-checks.mjs +17 -0
  40. package/cli/test-setup-agent.mjs +14 -0
  41. package/cli/test-story-frames.mjs +74 -4
  42. package/cli/toolbox-connect.mjs +244 -0
  43. package/cli/toolbox.mjs +129 -9
  44. package/package.json +7 -3
  45. package/skills/sdlc/config.yaml +1 -1
  46. package/skills/sdlc/module-help.csv +3 -1
  47. package/skills/yad-analysis/SKILL.md +4 -0
  48. package/skills/yad-backfill/SKILL.md +4 -0
  49. package/skills/yad-change/SKILL.md +4 -0
  50. package/skills/yad-checks/SKILL.md +13 -7
  51. package/skills/yad-checks/references/check-gates.md +62 -30
  52. package/skills/yad-checks/templates/checks/member-check.mjs +3 -2
  53. package/skills/yad-checks/templates/checks/risk-map-check.sh +2 -2
  54. package/skills/yad-checks/templates/checks/verified-commits.sh +3 -3
  55. package/skills/yad-checks/templates/github/yad-checks.yml +357 -69
  56. package/skills/yad-checks/templates/github/yad-pr-text.yml +118 -0
  57. package/skills/yad-checks/templates/github/yad-product-checks.yml +130 -54
  58. package/skills/yad-checks/templates/github/yad-product-pr-text.yml +131 -0
  59. package/skills/yad-checks/templates/github/yad-update-guard.yml +2 -1
  60. package/skills/yad-checks/templates/github/yad-verified-commits.yml +49 -3
  61. package/skills/yad-checks/templates/gitlab/yad-checks.gitlab-ci.yml +79 -20
  62. package/skills/yad-checks/templates/gitlab/yad-product-checks.gitlab-ci.yml +59 -9
  63. package/skills/yad-checks/templates/gitlab/yad-update-guard.gitlab-ci.yml +1 -0
  64. package/skills/yad-checks/templates/gitlab/yad-verified-commits.gitlab-ci.yml +49 -1
  65. package/skills/yad-checks/templates/hooks/agent-guard.mjs +44 -10
  66. package/skills/yad-checks/templates/hooks/ledger-guard-cursor.mjs +12 -6
  67. package/skills/yad-commit/SKILL.md +3 -1
  68. package/skills/yad-connect-design/SKILL.md +42 -10
  69. package/skills/yad-connect-design/references/design-context.md +35 -5
  70. package/skills/yad-connect-design/references/design-registry.md +3 -3
  71. package/skills/yad-connect-learning/SKILL.md +12 -2
  72. package/skills/yad-connect-repos/SKILL.md +4 -0
  73. package/skills/yad-connect-testing/SKILL.md +22 -5
  74. package/skills/yad-connect-testing/references/testing-context.md +1 -1
  75. package/skills/yad-epic/SKILL.md +4 -0
  76. package/skills/yad-epic/references/state-schema.md +15 -0
  77. package/skills/yad-guide/SKILL.md +8 -4
  78. package/skills/yad-implement/SKILL.md +56 -4
  79. package/skills/yad-implement/references/implement-conventions.md +2 -1
  80. package/skills/yad-issues/SKILL.md +53 -0
  81. package/skills/yad-learn/SKILL.md +4 -0
  82. package/skills/yad-open-pr/SKILL.md +6 -0
  83. package/skills/yad-pr-template/SKILL.md +2 -1
  84. package/skills/yad-pr-template/templates/checks/pr-title.sh +34 -2
  85. package/skills/yad-product-bridge/references/bridge.md +28 -0
  86. package/skills/yad-product-bridge/templates/github/yad-gate-sync.yml +25 -11
  87. package/skills/yad-product-bridge/templates/gitlab/yad-gate-sync.gitlab-ci.yml +38 -14
  88. package/skills/yad-run/SKILL.md +5 -0
  89. package/skills/yad-scan/SKILL.md +51 -0
  90. package/skills/yad-spec/SKILL.md +13 -2
  91. package/skills/yad-test-cases/SKILL.md +18 -2
  92. package/skills/yad-ui/SKILL.md +43 -8
  93. package/skills/yad-checks/templates/gitlab/.gitlab-ci.yml +0 -49
@@ -440,6 +440,8 @@ export function artifactFromBase(base) {
440
440
  // The files (relative to the epic dir) a review of this artifact covers — what `gate open` commits
441
441
  // on the review branch (the owner's artifact), and what CI re-reads to bind the approval at merge.
442
442
  // Architecture mirrors artifactHash(): the approval is bound to the locked contract surface too.
443
+ // E164: the folder beside ui-design.md that holds the epic's design file.
444
+ export const UI_DESIGN_DIR = 'design';
443
445
  export function artifactPaths(base) {
444
446
  if (base === 'architecture') return ['architecture.md', 'contract.md', '.sdlc/contract-lock.json'];
445
447
  if (base === 'stories') return ['stories'];
@@ -447,6 +449,10 @@ export function artifactPaths(base) {
447
449
  // Every section, optional ones included: this names what a Foundation review COVERS, and a section
448
450
  // that is absent today is still one a reviewer may be asked to look at tomorrow.
449
451
  if (base === 'foundation') return [...FOUNDATION_FILES];
452
+ // E164: the UI step's design file lives in the epic's `design/` folder (an OpenPencil file in the repo),
453
+ // so the UI review covers it: `yad fold` commits it, and a change to it after approval needs a fresh
454
+ // review. A folder, so `fold` and `artifactHashAt` take everything under it.
455
+ if (base === 'ui-design') return ['ui-design.md', UI_DESIGN_DIR];
450
456
  return [`${base}.md`];
451
457
  }
452
458
 
@@ -595,6 +601,85 @@ export function storiesHash(epicDir, sha = reviewedSha) {
595
601
  return 'sha256:' + createHash('sha256').update(parts.join('\n')).digest('hex');
596
602
  }
597
603
 
604
+ // E164: the UI design's fingerprint. With no file under `design/`, it is the fingerprint of ui-design.md
605
+ // alone — byte for byte what every release before E164 recorded, so no approval of a Figma or Pencil
606
+ // design moves. With design files, it covers them too: ui-design.md as reviewed (`sha`), then each design
607
+ // file (`designSha`, never with a status line left out), sorted by path.
608
+ //
609
+ // Which files count is decided here, and the copy `artifactHashAt` makes of a commit is read by the same
610
+ // walk, so the disk and the approved commit agree:
611
+ // - regular files only (a link is skipped; so is a `design` folder that is itself a link — a commit
612
+ // holds it as a link, not a folder);
613
+ // - never a file the system or an editor drops beside a design (`isDesignJunk`: `.DS_Store`, macOS's
614
+ // `._<name>` copies, a `.~lock.<name>#` lock file, a name ending in `~`, `Thumbs.db`, `desktop.ini`)
615
+ // — git often does not ignore those, and counting one would make every approval look changed on that
616
+ // machine only. Any other name, a dot-name included, is a design file;
617
+ // - never inside a folder holding `.git` (a submodule or a nested repository: a commit holds it as one
618
+ // entry, not its files).
619
+ const DESIGN_JUNK = /^(?:\.ds_store|\._.*|\.~lock\..*|.*~|thumbs\.db|desktop\.ini)$/i;
620
+ export const isDesignJunk = (rel) => rel.split('/').some((seg) => DESIGN_JUNK.test(seg));
621
+ function designFiles(dir, rel = '') {
622
+ if (rel === '') {
623
+ try { if (!fs.lstatSync(dir).isDirectory()) return []; } catch { return []; }
624
+ }
625
+ let entries;
626
+ try { entries = fs.readdirSync(path.join(dir, rel), { withFileTypes: true }); } catch { return []; }
627
+ if (entries.some((e) => e.name === '.git')) return [];
628
+ const out = [];
629
+ for (const e of entries) {
630
+ if (DESIGN_JUNK.test(e.name)) continue;
631
+ const r = rel ? `${rel}/${e.name}` : e.name;
632
+ if (e.isDirectory()) out.push(...designFiles(dir, r));
633
+ else if (e.isFile()) out.push(r);
634
+ }
635
+ return out;
636
+ }
637
+ // One design file's fingerprint: the SHA-256 of its content. A Git LFS pointer (the small text file a
638
+ // checkout without LFS leaves in place of a large file) names that same SHA-256 as its `oid`, so the
639
+ // pointer and the real file give one fingerprint — CI checks out pointers, `artifactHashAt` may read
640
+ // the real file through the LFS filter, and the two must agree.
641
+ // Only the exact pointer format git-lfs writes counts — its version line, any `ext-` lines, the oid, the
642
+ // size and nothing else — so no other text can ride in a file whose fingerprint is its oid alone.
643
+ const LFS_POINTER = /^version https:\/\/git-lfs\.github\.com\/spec\/v1\r?\n(?:ext-[^\r\n]*\r?\n)*oid sha256:([0-9a-f]{64})\r?\nsize \d+\r?\n?$/;
644
+ function designSha(p) {
645
+ const bytes = fs.readFileSync(p);
646
+ if (bytes.length < 1024) {
647
+ const oid = bytes.toString('utf8').match(LFS_POINTER);
648
+ if (oid) return `sha256:${oid[1]}`;
649
+ }
650
+ return shaOf(bytes);
651
+ }
652
+ // The files under `design/` that git ignores here (an exports folder in .gitignore, an editor's settings
653
+ // folder): no commit holds them, so counting them would make the approval look changed on this machine
654
+ // only. Never asked for the scratch copy `artifactHashAt` makes (`askGit: false`): it holds only committed
655
+ // files, and a temporary folder inside some checkout would be judged by that checkout's rules. A tracked
656
+ // file is never reported, even when a pattern matches it. The variables that point git at another
657
+ // repository (set inside a git hook, or by a script) are dropped, so git finds the Product's checkout from
658
+ // the folder itself — the same list hook.mjs drops. Names are compared in one Unicode form, because git
659
+ // on macOS may print a name precomposed that it was given decomposed.
660
+ const REPO_ENV = /^GIT_(DIR|WORK_TREE|PREFIX|INDEX_FILE|COMMON_DIR|OBJECT_DIRECTORY|ALTERNATE_OBJECT_DIRECTORIES)$/;
661
+ function ignoredByGit(dir, files) {
662
+ if (!files.length) return new Set();
663
+ const env = { ...Object.fromEntries(Object.entries(process.env).filter(([k]) => !REPO_ENV.test(k))), GIT_OPTIONAL_LOCKS: '0' };
664
+ const r = spawnSync('git', ['check-ignore', '-z', '--stdin'], { cwd: dir, input: files.map((f) => `${f}\0`).join(''), env, maxBuffer: 64 * 1024 * 1024 });
665
+ return r.status === 0 ? new Set(r.stdout.toString('utf8').split('\0').filter(Boolean).map((f) => f.normalize('NFC'))) : new Set();
666
+ }
667
+ // The design files' part of the fingerprint, read once: `acceptedHashes` combines it with each form of
668
+ // ui-design.md, so a large design file is not read again for every form.
669
+ function designParts(epicDir, { askGit = true } = {}) {
670
+ const dir = path.join(epicDir, UI_DESIGN_DIR);
671
+ const all = designFiles(dir);
672
+ const ignored = askGit ? ignoredByGit(dir, all) : new Set();
673
+ return all.filter((f) => !ignored.has(f.normalize('NFC'))).sort().map((f) => `${UI_DESIGN_DIR}/${f}:${designSha(path.join(dir, ...f.split('/')))}`);
674
+ }
675
+ export function uiDesignHash(epicDir, sha = reviewedSha, parts = null, { askGit = true } = {}) {
676
+ const doc = sha(path.join(epicDir, 'ui-design.md'));
677
+ if (doc === null) return null;
678
+ parts ??= designParts(epicDir, { askGit });
679
+ if (!parts.length) return doc;
680
+ return 'sha256:' + createHash('sha256').update([`ui-design.md:${doc}`, ...parts].join('\n')).digest('hex');
681
+ }
682
+
598
683
  // The reserved id of the Product level in its OLD spelling ("epic zero", `epics/EP-discovery/`), written
599
684
  // by every release before E75 and still read. yad-epic / yad-analysis must never pick this slug — or
600
685
  // `EP-foundation` — for a feature.
@@ -940,12 +1025,14 @@ export function discoveryHash(epicDir, sha = reviewedSha) {
940
1025
  // the whole discovery file set; for every other artifact it is the file. Every file is fingerprinted
941
1026
  // without its frontmatter `status:` line (see `reviewedSha`). `sha` swaps that for a legacy form —
942
1027
  // only `acceptedHashes` passes one.
943
- export function artifactHash(epicDir, artifact, sha = reviewedSha) {
1028
+ // `askGit: false` is for a scratch copy of a commit (`artifactHashAt`): see `ignoredByGit`.
1029
+ export function artifactHash(epicDir, artifact, sha = reviewedSha, { askGit = true } = {}) {
944
1030
  const b = artifactBase(artifact);
945
1031
  if (b === 'architecture') return contractSurfaceHash(epicDir);
946
1032
  if (b === 'stories') return storiesHash(epicDir, sha);
947
1033
  if (b === 'discovery') return discoveryHash(epicDir, sha);
948
1034
  if (b === 'foundation') return foundationHash(epicDir, FOUNDATION_SECTIONS, sha);
1035
+ if (b === 'ui-design') return uiDesignHash(epicDir, sha, null, { askGit });
949
1036
  return sha(path.join(epicDir, artifact.replace(/\/$/, '')));
950
1037
  }
951
1038
 
@@ -953,9 +1040,12 @@ export function artifactHash(epicDir, artifact, sha = reviewedSha) {
953
1040
  // legacy forms (see LEGACY_FORMS). Empty when there is nothing to fingerprint — the same "no claim"
954
1041
  // answer a null `artifactHash` gives. What is WRITTEN is always `artifactHash`; this is for reading.
955
1042
  export function acceptedHashes(epicDir, artifact) {
956
- const current = artifactHash(epicDir, artifact);
1043
+ // The UI design's files are read once and combined with each form of ui-design.md (E164).
1044
+ const parts = artifactBase(artifact) === 'ui-design' ? designParts(epicDir) : null;
1045
+ const hashWith = parts ? (sha) => uiDesignHash(epicDir, sha, parts) : (sha) => artifactHash(epicDir, artifact, sha);
1046
+ const current = hashWith(reviewedSha);
957
1047
  if (current === null) return [];
958
- return [...new Set([current, ...LEGACY_FORMS.map((sha) => artifactHash(epicDir, artifact, sha))].filter(Boolean))];
1048
+ return [...new Set([current, ...LEGACY_FORMS.map(hashWith)].filter(Boolean))];
959
1049
  }
960
1050
 
961
1051
  // Is a recorded fingerprint stale against the accepted ones? Never when nothing was recorded (a manual
@@ -1017,7 +1107,7 @@ export function artifactHashAt(root, epicDir, artifact, rev) {
1017
1107
  copied++;
1018
1108
  }
1019
1109
  } catch (e) { return { ok: false, reason: `the files at ${rev.slice(0, 12)} could not be copied (${e.code || e.message})` }; }
1020
- return { ok: true, hash: artifactHash(dir, artifact), copied };
1110
+ return { ok: true, hash: artifactHash(dir, artifact, reviewedSha, { askGit: false }), copied };
1021
1111
  } finally {
1022
1112
  fs.rmSync(tmp, { recursive: true, force: true });
1023
1113
  }
package/cli/epic.mjs CHANGED
@@ -51,11 +51,15 @@ export function epicIdFrom(slug) {
51
51
 
52
52
  // `type` defaults to null rather than `feature` so an explicit `--type` is distinguishable from no
53
53
  // flag at all — which is what lets an existing `epic.md` supply the answer without overriding the user.
54
- export async function runEpicNew(root, { slug, type = null, profile = null, stub = false, parent = null, inherits = null, today, json = false } = {}) {
54
+ export async function runEpicNew(root, { slug, type = null, profile = null, stub = false, parent = null, inherits = null, today, json = false, returnResult = false } = {}) {
55
+ // `returnResult` (E170, with json): a caller that seeds as one part of its work gets the answer back, and
56
+ // it alone speaks, so stdout stays one JSON document.
57
+ const answer = returnResult ? (payload) => payload : emitJSON;
55
58
  const bail = (message, hint) => {
56
- if (json) emitJSON({ ok: false, error: message, hint });
57
- else { fail(message); if (hint) hand(hint); }
58
59
  process.exitCode = 1;
60
+ if (json) return answer({ ok: false, error: message, hint });
61
+ fail(message); if (hint) hand(hint);
62
+ return undefined;
59
63
  };
60
64
 
61
65
  const epic = epicIdFrom(slug);
@@ -169,7 +173,7 @@ export async function runEpicNew(root, { slug, type = null, profile = null, stub
169
173
  if (parent) {
170
174
  return seedThreaded(root, {
171
175
  epic, dir, files, mdPath, fm, type, parent, profile,
172
- inherits: flagInherits ?? declaredInherits ?? [], headerLists: declaredInherits !== null, today, json, bail,
176
+ inherits: flagInherits ?? declaredInherits ?? [], headerLists: declaredInherits !== null, today, json, bail, answer,
173
177
  });
174
178
  }
175
179
  profile = profile || 'classic';
@@ -230,7 +234,7 @@ export async function runEpicNew(root, { slug, type = null, profile = null, stub
230
234
  // `nextSkills` appears only for a bound chain, the same rule `yad next --json` follows — a key that
231
235
  // showed up on every seed would be one more always-null field for every reader to ignore.
232
236
  if (json) {
233
- return emitJSON({
237
+ return answer({
234
238
  ok: true, epic, type, profile, stub, currentStep: state.currentStep,
235
239
  steps: state.steps.map((s) => s.id), next: skill,
236
240
  ...(skills.length > 1 ? { nextSkills: skills } : {}),
@@ -266,7 +270,7 @@ const listOf = (v) => (Array.isArray(v) ? v : String(v ?? '').replace(/^\s*\[|\]
266
270
  // The threaded half of `yad epic new` (E42): a change, defect or hotfix off an epic that exists. The
267
271
  // engine plans the chain from the parent (`planThreadedSeed`) and this writes it — the ledger, one
268
272
  // provenance record per inherited gate, and the pointer-lock when the contract is carried.
269
- function seedThreaded(root, { epic, dir, files, mdPath, fm, type, parent, profile, inherits, headerLists, today, json, bail }) {
273
+ function seedThreaded(root, { epic, dir, files, mdPath, fm, type, parent, profile, inherits, headerLists, today, json, bail, answer }) {
270
274
  const plan = planThreadedSeed(root, { epic, parent, inherits, type, today });
271
275
  if (!plan.ok) return bail(plan.message, plan.hint);
272
276
  // The route is the parent's. A flag naming the same one is harmless; a different one is refused
@@ -319,7 +323,7 @@ function seedThreaded(root, { epic, dir, files, mdPath, fm, type, parent, profil
319
323
  const skills = stepSkills(first.id, bindingsForEpic(loadSkillBindings(root), state));
320
324
  const carried = state.steps.filter((s) => s.inherited);
321
325
  if (json) {
322
- return emitJSON({
326
+ return answer({
323
327
  ok: true, epic, type, profile: plan.profile, stub: false, parent, thread: plan.thread,
324
328
  inherits, inheritedFrom: plan.owners, pointerLock: plan.lock ? plan.lock.ref : null, anchor: plan.anchor,
325
329
  currentStep: state.currentStep, steps: state.steps.map((s) => s.id), next: skills[0] || null,
package/cli/fold.mjs CHANGED
@@ -30,7 +30,7 @@ import os from 'node:os';
30
30
  import path from 'node:path';
31
31
  import { ok, info, warn, fail, hand, readJSON } from './lib.mjs';
32
32
  import { productConfigPath, isVerifiedLedger } from './manifest.mjs';
33
- import { STEPS, FOUNDATION_EPIC, FOUNDATION_DIR, DISCOVERY_EPIC, artifactBase, artifactPaths, epicRoot, isValidEpicId } from './epic-state.mjs';
33
+ import { STEPS, FOUNDATION_EPIC, FOUNDATION_DIR, DISCOVERY_EPIC, artifactBase, artifactPaths, epicRoot, isValidEpicId, isDesignJunk, UI_DESIGN_DIR } from './epic-state.mjs';
34
34
  import { capturedEpic, gitIn, isOwnerPath, statusEntries, wipName, wipBranch, runCapture } from './capture.mjs';
35
35
  import { resolveDefaultBranch, preflightGuardReadiness } from './productcommit.mjs';
36
36
 
@@ -53,7 +53,32 @@ export function stepPaths(epic, stepId) {
53
53
  if (!step) return null;
54
54
  return [...artifactPaths(artifactBase(step.artifact)), ...(STEP_EXTRAS[stepId] || [])].map((p) => `${epicRel(epic)}/${p}`);
55
55
  }
56
- const covers = (paths, p) => paths.some((s) => p === s || p.startsWith(`${s}/`));
56
+ // A file the system or an editor drops in the UI design's `design/` folder (`.DS_Store`, `x.fig~`) is not
57
+ // the step's: the fingerprint leaves it out (`isDesignJunk`), so a fold that committed it would put a file
58
+ // in the review that no approval covers. It is left on disk like any other file. So is a nested repository
59
+ // there — git lists an untracked one as a folder (`design/kit/`) and a committed submodule by its folder
60
+ // name (`design/kit`), and `isRepo` (a folder holding `.git`) tells the second: `git add` would record a
61
+ // link to another repository, and the fingerprint skips it.
62
+ const covers = (paths, p, isRepo = null) => paths.some((s) => p === s
63
+ || (p.startsWith(`${s}/`) && !(s.endsWith(`/${UI_DESIGN_DIR}`) && (isDesignJunk(p.slice(s.length + 1)) || p.endsWith('/') || !!isRepo?.(p)))));
64
+ // Is this Product-relative path a nested repository or a submodule — a folder holding `.git`, or a gitlink
65
+ // in the index (a submodule never initialised here has no `.git`)? The index's gitlinks are read once, on
66
+ // the first path that needs them, so many changed design files cost one git call. `GIT_LITERAL_PATHSPECS`
67
+ // is cleared so git reads the `:(glob)` pattern as a pattern.
68
+ export const repoAt = (root, env = process.env) => {
69
+ let gitlinks = null;
70
+ const links = () => {
71
+ if (gitlinks) return gitlinks;
72
+ const rest = Object.fromEntries(Object.entries(env).filter(([k]) => k !== 'GIT_LITERAL_PATHSPECS'));
73
+ const r = gitIn(root, rest, { GIT_OPTIONAL_LOCKS: '0' })(['ls-files', '-s', '-z', '--', `:(glob)**/${UI_DESIGN_DIR}/**`]);
74
+ gitlinks = new Set(r.ok ? r.out.split('\0').filter((e) => e.startsWith('160000 ')).map((e) => e.slice(e.indexOf('\t') + 1)) : []);
75
+ return gitlinks;
76
+ };
77
+ return (p) => {
78
+ const bare = p.replace(/\/$/, '');
79
+ return fs.existsSync(path.join(root, ...bare.split('/'), '.git')) || links().has(bare);
80
+ };
81
+ };
57
82
 
58
83
  // The scope is the epic ID in lowercase (#413): the commit-message gate takes a lowercase scope
59
84
  // (`[a-z0-9._-]`), so `docs(EP-x)` failed every review PR. The exact ID stays in the Yad-Epic trailer.
@@ -73,7 +98,7 @@ export const foldMessage = ({ epic, step, folded }) =>
73
98
  // only while its state.json is off the base ref (#162))
74
99
  // ci — ledger changes left for CI (verified mode, every other case)
75
100
  // other — the epic's other changed artifacts, left on disk
76
- export function sortChanges(entries, { epic, step, verified, seeding = false }) {
101
+ export function sortChanges(entries, { epic, step, verified, seeding = false, isRepo = null }) {
77
102
  const own = stepPaths(epic, step) || [];
78
103
  const dir = `${epicRel(epic)}/`;
79
104
  const out = { step: [], seed: [], ledger: [], ci: [], other: [] };
@@ -83,7 +108,7 @@ export function sortChanges(entries, { epic, step, verified, seeding = false })
83
108
  // `??` is untracked, `A` in the first column is added to the index: both are a file being created.
84
109
  // ` A` is a file marked with `git add -N` (intent to add): new too.
85
110
  const creating = xy === '??' || xy[0] === 'A' || xy === ' A';
86
- if (covers(own, p)) out.step.push(p);
111
+ if (covers(own, p, isRepo)) out.step.push(p);
87
112
  // A step owner file (E47) is never folded: an assignment is not authoring, and a fold that carried one
88
113
  // alone would be a "docs: author <step>" commit with nothing authored. It is committed on its own.
89
114
  else if (isOwnerPath(p)) out.other.push(p);
@@ -108,7 +133,7 @@ export function unfoldedPaths(root, epic, base, env = process.env) {
108
133
  const own = stepPaths(epic, authorStepOf(base)) || [];
109
134
  // A per-story branch (`stories-S01`) reviews that one story: another story's edit is not its business.
110
135
  const story = /^stories-S\d+$/i.test(base) ? base.toLowerCase() : null;
111
- return entries.map((e) => e.path).filter((p) => covers(own, p) && (!story || artifactBase(p).toLowerCase() === story));
136
+ return entries.map((e) => e.path).filter((p) => covers(own, p, repoAt(root, env)) && (!story || artifactBase(p).toLowerCase() === story));
112
137
  }
113
138
 
114
139
  // `yad fold <epic> <step>`. Returns a plain object (E1 turns it into the `--json` answer); a refusal
@@ -170,7 +195,7 @@ export async function runFold(root, { epic, step, env = process.env, capture = r
170
195
  const seededAt = (e) => git(['cat-file', '-e', `HEAD:./${epicRel(e)}/.sdlc/state.json`]).ok;
171
196
  const productLevel = epic === FOUNDATION_EPIC || epic === DISCOVERY_EPIC;
172
197
  const seeding = productLevel ? !seededAt(FOUNDATION_EPIC) && !seededAt(DISCOVERY_EPIC) : !seededAt(epic);
173
- const sorted = sortChanges(entries, { epic, step, verified, seeding });
198
+ const sorted = sortChanges(entries, { epic, step, verified, seeding, isRepo: repoAt(root, env) });
174
199
  // What `git add` can take: a path on disk or in the index. A deletion already staged (`D `, from `git rm`
175
200
  // or the old half of a `git mv`) is in neither, and `git add` would refuse it — but it is in HEAD, so
176
201
  // `commit --only` commits the deletion. A path added and then deleted (`AD`) is in none of the three and
package/cli/guide.mjs CHANGED
@@ -32,6 +32,7 @@ import { RULES, HUMAN_ONLY_ACTS, NEVER, classify, askFor, reaches } from './agen
32
32
  import { seededSlugs } from './hook.mjs';
33
33
  import { setupQuestions } from './setup.mjs';
34
34
  import { reposBeside, insideGitRepo, PRODUCT_DIR } from './workspace.mjs';
35
+ import { PREAPPROVED } from './agent-guard.mjs';
35
36
 
36
37
  export const GUIDE_VERSION = 1;
37
38
 
@@ -422,7 +423,8 @@ const thenFor = (person, epic) => (person.some((p) => p.verify)
422
423
  // Build the guide. `root` is the Product, or null when there is none here. `cwd` is where the agent is.
423
424
  // `productElsewhere`: no Product here, but one is a `cd` away (bin/yad.mjs finds it).
424
425
  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
+ // `preapproved` (E167): what the agent guard lets run with no permission prompt, and what it never does.
427
+ const base = { guideVersion: GUIDE_VERSION, rules: RULES, humanOnly: HUMAN_ONLY_ACTS, never: NEVER, preapproved: PREAPPROVED };
426
428
  if (!root && productElsewhere) {
427
429
  const where = clean(productElsewhere);
428
430
  const q = shellPath(where);
package/cli/hook.mjs CHANGED
@@ -29,7 +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
+ import { agentGuardDecision, agentGuardPreapproval, payloadCommand, isCursorPayload } from './agent-guard.mjs';
33
33
 
34
34
  // The CI-owned files, exactly as `templates/checks/ledger-guard.sh` lists them. NOT `contract-lock.json`
35
35
  // (artifact-side: the architect commits it with the architecture) and NOT `change.json` — both are a
@@ -511,12 +511,38 @@ export function runStagedLedgerGuard({ env = process.env, cwd = process.cwd(), g
511
511
  return 2;
512
512
  }
513
513
 
514
+ // Read all of stdin. Asking `process.stdin.isTTY` makes Node open stdin as a stream, and on a pipe that
515
+ // switches fd 0 to non-blocking: a read then throws EAGAIN ("no data yet") whenever the payload arrives a
516
+ // moment after the hook starts. `fs.readFileSync(0)` gave up there, the hook read no payload, and it
517
+ // allowed — the macOS CI failures on #459 (a deny allowed) and #460 (no Cursor verdict: with no payload
518
+ // the hook could not tell it was Cursor). So this reads in a loop and, on EAGAIN, waits 5 ms and tries
519
+ // again, for up to `limitMs`; after that the error goes to the caller, which fails open. Keep the loop:
520
+ // the non-blocking mode is also what gives the limit — a blocking read would hang for ever on a parent
521
+ // that never closes stdin. A read of 0 bytes (or Windows' EOF error) is the end.
522
+ export function readStdin({ fd = 0, readSync = fs.readSync, limitMs = 5000 } = {}) {
523
+ const chunks = [];
524
+ const buf = Buffer.alloc(64 * 1024);
525
+ const nap = new Int32Array(new SharedArrayBuffer(4));
526
+ const until = Date.now() + limitMs;
527
+ for (;;) {
528
+ let n;
529
+ try { n = readSync(fd, buf, 0, buf.length, null); } catch (e) {
530
+ if (e?.code === 'EAGAIN' && Date.now() < until) { Atomics.wait(nap, 0, 0, 5); continue; }
531
+ if (e?.code === 'EOF') break;
532
+ throw e;
533
+ }
534
+ if (n === 0) break;
535
+ chunks.push(Buffer.from(buf.subarray(0, n)));
536
+ }
537
+ return Buffer.concat(chunks).toString('utf8');
538
+ }
539
+
514
540
  // Read the harness payload off stdin. Absent, empty, or unparseable all mean "nothing to inspect" —
515
541
  // never an error, and never a block.
516
542
  function readPayload() {
517
543
  try {
518
544
  if (process.stdin.isTTY) return null;
519
- const raw = fs.readFileSync(0, 'utf8').trim();
545
+ const raw = readStdin().trim();
520
546
  if (!raw) return null;
521
547
  return JSON.parse(raw);
522
548
  } catch {
@@ -581,10 +607,10 @@ const isReadOnlyCall = (payload) => {
581
607
  };
582
608
 
583
609
  export function runLedgerGuardHook({ paths = [], format = 'exit' } = {}) {
584
- // Only read stdin when there is nothing else to go on. `readFileSync(0)` blocks until EOF, and a
585
- // caller that passes `--path` (the documented stdin-free alternative) may well have inherited an
586
- // open pipe from a long-lived parent — `isTTY` is false there, so the TTY guard does not trip and
587
- // the hook would hang forever. A hang is strictly worse for an agent than a block.
610
+ // Only read stdin when there is nothing else to go on. A caller that passes `--path` (the documented
611
+ // stdin-free alternative) may well have inherited an open pipe from a long-lived parent — `isTTY` is
612
+ // false there, so the TTY guard does not trip, and `readStdin` would wait out its whole limit before
613
+ // going on. Every agent tool call would pay that wait.
588
614
  const payload = paths.length ? null : readPayload();
589
615
  const all = isReadOnlyCall(payload) ? [...paths] : [...new Set([...payloadPaths(payload), ...paths])];
590
616
  const verdict = ledgerGuardDecision(all, {
@@ -618,6 +644,11 @@ export function runLedgerGuardHook({ paths = [], format = 'exit' } = {}) {
618
644
  // `agentGuardDecision`, answered in the protocol the payload names (Cursor's `beforeShellExecution` wants a
619
645
  // JSON verdict; Claude Code reads the exit code) unless `--format` says which. `YAD_HOOK_DISABLE` turns it
620
646
  // off, as it does the ledger guard. Fail-open: no payload, or no command in it, is allowed.
647
+ //
648
+ // Pre-approval (E167, #353): under Claude Code, a line `agentGuardPreapproval` sees only reads is answered with
649
+ // a PreToolUse "allow" on stdout, so it runs with no permission prompt; any other allowed line gets no answer
650
+ // (exit 0, nothing printed), which leaves the prompt to Claude Code as before. `YAD_NO_PREAPPROVE=1` keeps the
651
+ // refusals and drops this half. Cursor's answer is unchanged.
621
652
  export function runAgentGuardHook({ format = null } = {}) {
622
653
  const payload = readPayload();
623
654
  const cursor = format ? format === 'cursor' : isCursorPayload(payload);
@@ -630,8 +661,20 @@ export function runAgentGuardHook({ format = null } = {}) {
630
661
  if (!verdict.allow) console.error(verdict.message);
631
662
  return 0;
632
663
  }
633
- if (verdict.allow) return 0;
664
+ if (verdict.allow) {
665
+ if (!process.env.YAD_HOOK_DISABLE && !process.env.YAD_NO_PREAPPROVE) {
666
+ // Claude Code names the project in CLAUDE_PROJECT_DIR and where the command runs in the payload's `cwd`.
667
+ const root = process.env.CLAUDE_PROJECT_DIR || process.cwd();
668
+ const pre = agentGuardPreapproval(payloadCommand(payload), { root, cwd: typeof payload?.cwd === 'string' && payload.cwd ? payload.cwd : root });
669
+ if (pre.preapproved) process.stdout.write(`${claudePreapproval(pre.reason)}\n`);
670
+ }
671
+ return 0;
672
+ }
634
673
  console.error(verdict.message);
635
674
  process.exitCode = 2;
636
675
  return 2;
637
676
  }
677
+
678
+ // Claude Code's PreToolUse answer that skips the permission prompt. A team's own `deny` or `ask` rule still wins.
679
+ export const claudePreapproval = (reason) => JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'allow',
680
+ permissionDecisionReason: `yad agent guard: a read-only command (${reason}), pre-approved (E167; YAD_NO_PREAPPROVE=1 turns this off)` } });
@@ -0,0 +1,61 @@
1
+ // E170 — which tracker items (GitHub issues, GitLab work items) belong to an epic. One sidecar per epic,
2
+ // `.sdlc/issue-links.json`, holding only where the item is: its text stays on the platform, so private text
3
+ // does not spread into the repo. It is a separate file so `state.json` and `epic.md` keep their bytes, and
4
+ // the approvals bound to them stay valid.
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { readJSONStrict, writeJSON } from './lib.mjs';
8
+ import { err } from './errors.mjs';
9
+ import { epicIds, epicRoot, epicStories, featureStatus, loadLedger, PRODUCT_EPICS } from './epic-state.mjs';
10
+
11
+ export const ISSUE_LINKS_FILE = path.join('.sdlc', 'issue-links.json');
12
+ export const linksPath = (root, epic) => path.join(epicRoot(root, epic), ISSUE_LINKS_FILE);
13
+ export const itemKey = ({ host, repo, number }) => `${String(host).toLowerCase()}/${String(repo).toLowerCase()}#${number}`;
14
+
15
+ // The one rule for what a record is: an entry that fails it makes the whole file unreadable, never "not linked".
16
+ const validLink = (l) => !!l && typeof l === 'object' && !Array.isArray(l) && !!l.host && !!l.repo && Number.isInteger(l.number);
17
+
18
+ // Strict: this is read before a write, and a file that cannot be understood is refused, never replaced.
19
+ export function readLinks(root, epic) {
20
+ const p = linksPath(root, epic);
21
+ const doc = readJSONStrict(p, { items: [] });
22
+ if (!doc || typeof doc !== 'object' || !Array.isArray(doc.items) || !doc.items.every(validLink)) throw err('YAD-STATE-001', `${p} is not an issue-links file (it needs an "items" list of records)`, 'fix the file or restore it from git');
23
+ return doc.items;
24
+ }
25
+ export function writeLinks(root, epic, items) {
26
+ const p = linksPath(root, epic);
27
+ fs.mkdirSync(path.dirname(p), { recursive: true });
28
+ writeJSON(p, { items });
29
+ }
30
+
31
+ const featureEpics = (root) => epicIds(root).filter((e) => !PRODUCT_EPICS.includes(e));
32
+
33
+ // Every link in the Product, as Map(itemKey → [epic id]). An epic whose sidecar cannot be read is named in
34
+ // `unreadable`: its items would otherwise look unlinked, and "unknown" must never read as "none".
35
+ export function allLinks(root) {
36
+ const byItem = new Map();
37
+ const unreadable = [];
38
+ for (const epic of featureEpics(root)) {
39
+ let items;
40
+ try { items = readLinks(root, epic); } catch { unreadable.push(epic); continue; }
41
+ for (const l of items) {
42
+ const k = itemKey(l);
43
+ byItem.set(k, [...(byItem.get(k) || []), epic]);
44
+ }
45
+ }
46
+ return { byItem, unreadable };
47
+ }
48
+
49
+ // An epic's stage (`featureStatus`), or null when its ledger cannot be read.
50
+ export function epicStage(root, epic) {
51
+ try {
52
+ const dir = epicRoot(root, epic);
53
+ return featureStatus(loadLedger(dir), { stories: epicStories(dir) });
54
+ } catch { return null; }
55
+ }
56
+
57
+ // One stage for an item with several epics: the first that has not shipped, else shipped. Null if any is unread.
58
+ export function combinedStage(stages) {
59
+ if (!stages.length || stages.some((s) => s === null)) return null;
60
+ return stages.find((s) => s !== 'shipped') ?? 'shipped';
61
+ }