yadflow 4.9.0 → 4.11.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 (155) hide show
  1. package/CHANGELOG.md +184 -0
  2. package/README.md +15 -5
  3. package/bin/commands.mjs +11 -1
  4. package/bin/yad.mjs +203 -14
  5. package/cli/agent-guard-worker.mjs +13 -0
  6. package/cli/agent-guard.mjs +1797 -73
  7. package/cli/agent-rules.mjs +64 -5
  8. package/cli/argv-flags.mjs +2 -2
  9. package/cli/brain/vendor/LICENSE-graphology-library.txt +21 -0
  10. package/cli/brain/vendor/LICENSE-graphology.txt +21 -0
  11. package/cli/brain/vendor/LICENSE-sigma.txt +12 -0
  12. package/cli/brain/vendor/graphology-library.min.js +2 -0
  13. package/cli/brain/vendor/graphology.umd.min.js +2 -0
  14. package/cli/brain/vendor/sigma.min.js +1369 -0
  15. package/cli/brain/view/app.js +382 -0
  16. package/cli/brain/view/index.html +63 -0
  17. package/cli/brain/view/live.css +228 -0
  18. package/cli/brain/view/live.html +110 -0
  19. package/cli/brain/view/live.js +884 -0
  20. package/cli/brain/view/style.css +141 -0
  21. package/cli/brain-about.mjs +206 -0
  22. package/cli/brain-activity.mjs +285 -0
  23. package/cli/brain-skills.mjs +118 -0
  24. package/cli/brain-vendor.mjs +71 -0
  25. package/cli/brain-view.mjs +344 -0
  26. package/cli/brain.mjs +810 -0
  27. package/cli/ci-check.mjs +48 -4
  28. package/cli/codeowners-command.mjs +72 -6
  29. package/cli/commit.mjs +17 -3
  30. package/cli/docs.mjs +2 -0
  31. package/cli/doctor.mjs +151 -25
  32. package/cli/epic-state.mjs +186 -4
  33. package/cli/epic.mjs +26 -10
  34. package/cli/errors.mjs +2 -1
  35. package/cli/find-product.mjs +69 -15
  36. package/cli/fold.mjs +31 -6
  37. package/cli/foundation-publish.mjs +256 -0
  38. package/cli/gate.mjs +29 -3
  39. package/cli/git-read.mjs +38 -0
  40. package/cli/guard-stream.mjs +409 -0
  41. package/cli/guide.mjs +3 -1
  42. package/cli/hook.mjs +102 -9
  43. package/cli/issue-links.mjs +61 -0
  44. package/cli/issues-act.mjs +371 -0
  45. package/cli/issues-write.mjs +441 -0
  46. package/cli/issues.mjs +513 -0
  47. package/cli/lib.mjs +37 -2
  48. package/cli/lifecycle.mjs +7 -0
  49. package/cli/local-page.mjs +138 -0
  50. package/cli/machine.mjs +1 -1
  51. package/cli/manifest.mjs +59 -3
  52. package/cli/map/view/app.js +712 -0
  53. package/cli/map/view/index.html +50 -0
  54. package/cli/map/view/style.css +142 -0
  55. package/cli/map-view.mjs +186 -0
  56. package/cli/map.mjs +637 -0
  57. package/cli/members.mjs +9 -15
  58. package/cli/next.mjs +1 -1
  59. package/cli/openpr.mjs +26 -6
  60. package/cli/plan.mjs +127 -0
  61. package/cli/platform.mjs +159 -4
  62. package/cli/product-index.mjs +1 -1
  63. package/cli/protection.mjs +53 -3
  64. package/cli/reconcile.mjs +9 -3
  65. package/cli/report.mjs +9 -3
  66. package/cli/reports-dir.mjs +391 -0
  67. package/cli/reports.mjs +65 -0
  68. package/cli/run-checks.mjs +15 -4
  69. package/cli/scan.mjs +314 -0
  70. package/cli/setup.mjs +42 -8
  71. package/cli/standup.mjs +120 -78
  72. package/cli/status.mjs +6 -5
  73. package/cli/story-frames.mjs +17 -6
  74. package/cli/test-agents-file.mjs +985 -12
  75. package/cli/test-brain-activity.mjs +753 -0
  76. package/cli/test-brain-view.mjs +381 -0
  77. package/cli/test-brain.mjs +795 -0
  78. package/cli/test-build.mjs +25 -0
  79. package/cli/test-ci-check.mjs +469 -10
  80. package/cli/test-guide.mjs +218 -0
  81. package/cli/test-machine.mjs +59 -0
  82. package/cli/test-map.mjs +615 -0
  83. package/cli/test-node.mjs +15 -0
  84. package/cli/test-reports.mjs +382 -0
  85. package/cli/test-run-checks.mjs +21 -0
  86. package/cli/test-setup-agent.mjs +14 -0
  87. package/cli/test-story-frames.mjs +74 -4
  88. package/cli/test-worktree.mjs +24 -3
  89. package/cli/toolbox-connect.mjs +259 -0
  90. package/cli/toolbox.mjs +187 -12
  91. package/cli/update-commit.mjs +101 -9
  92. package/cli/usage.mjs +8 -4
  93. package/package.json +12 -4
  94. package/skills/sdlc/config.yaml +1 -1
  95. package/skills/sdlc/module-help.csv +3 -1
  96. package/skills/yad-analysis/SKILL.md +4 -0
  97. package/skills/yad-architecture/SKILL.md +22 -4
  98. package/skills/yad-backfill/SKILL.md +4 -0
  99. package/skills/yad-change/SKILL.md +7 -1
  100. package/skills/yad-change/references/triage.md +2 -0
  101. package/skills/yad-checks/SKILL.md +15 -7
  102. package/skills/yad-checks/references/check-gates.md +70 -35
  103. package/skills/yad-checks/templates/checks/build-test-lint.sh +7 -0
  104. package/skills/yad-checks/templates/checks/install-deps.sh +6 -0
  105. package/skills/yad-checks/templates/checks/member-check.mjs +3 -2
  106. package/skills/yad-checks/templates/checks/package-manager.sh +42 -0
  107. package/skills/yad-checks/templates/checks/risk-map-check.sh +2 -2
  108. package/skills/yad-checks/templates/checks/verified-commits.sh +3 -3
  109. package/skills/yad-checks/templates/github/yad-checks.yml +358 -69
  110. package/skills/yad-checks/templates/github/yad-pr-text.yml +118 -0
  111. package/skills/yad-checks/templates/github/yad-product-checks.yml +130 -54
  112. package/skills/yad-checks/templates/github/yad-product-pr-text.yml +131 -0
  113. package/skills/yad-checks/templates/github/yad-update-guard.yml +2 -1
  114. package/skills/yad-checks/templates/github/yad-verified-commits.yml +49 -3
  115. package/skills/yad-checks/templates/gitlab/yad-checks.gitlab-ci.yml +80 -20
  116. package/skills/yad-checks/templates/gitlab/yad-product-checks.gitlab-ci.yml +59 -9
  117. package/skills/yad-checks/templates/gitlab/yad-update-guard.gitlab-ci.yml +1 -0
  118. package/skills/yad-checks/templates/gitlab/yad-verified-commits.gitlab-ci.yml +49 -1
  119. package/skills/yad-checks/templates/hooks/agent-guard.mjs +44 -10
  120. package/skills/yad-checks/templates/hooks/ledger-guard-cursor.mjs +12 -6
  121. package/skills/yad-checks/templates/hooks/yad-activity.mjs +238 -0
  122. package/skills/yad-commit/SKILL.md +3 -1
  123. package/skills/yad-connect-design/SKILL.md +42 -10
  124. package/skills/yad-connect-design/references/design-context.md +35 -5
  125. package/skills/yad-connect-design/references/design-registry.md +3 -3
  126. package/skills/yad-connect-learning/SKILL.md +12 -2
  127. package/skills/yad-connect-repos/SKILL.md +18 -0
  128. package/skills/yad-connect-testing/SKILL.md +22 -5
  129. package/skills/yad-connect-testing/references/testing-context.md +1 -1
  130. package/skills/yad-discovery/SKILL.md +11 -0
  131. package/skills/yad-discovery/references/foundation-schema.md +11 -0
  132. package/skills/yad-docs/templates/app/package-lock.json +18 -10
  133. package/skills/yad-docs/templates/app/package.json +6 -1
  134. package/skills/yad-epic/SKILL.md +7 -0
  135. package/skills/yad-epic/references/state-schema.md +50 -1
  136. package/skills/yad-guide/SKILL.md +8 -4
  137. package/skills/yad-implement/SKILL.md +117 -4
  138. package/skills/yad-implement/references/implement-conventions.md +2 -1
  139. package/skills/yad-issues/SKILL.md +54 -0
  140. package/skills/yad-learn/SKILL.md +4 -0
  141. package/skills/yad-open-pr/SKILL.md +6 -0
  142. package/skills/yad-pr-template/SKILL.md +2 -1
  143. package/skills/yad-pr-template/templates/checks/pr-template.sh +8 -4
  144. package/skills/yad-pr-template/templates/checks/pr-title.sh +42 -6
  145. package/skills/yad-product-bridge/references/bridge.md +28 -0
  146. package/skills/yad-product-bridge/templates/github/yad-gate-sync.yml +25 -11
  147. package/skills/yad-product-bridge/templates/gitlab/yad-gate-sync.gitlab-ci.yml +38 -14
  148. package/skills/yad-run/SKILL.md +5 -0
  149. package/skills/yad-scan/SKILL.md +51 -0
  150. package/skills/yad-spec/SKILL.md +32 -2
  151. package/skills/yad-stories/SKILL.md +22 -4
  152. package/skills/yad-stories/references/story-schema.md +1 -1
  153. package/skills/yad-test-cases/SKILL.md +18 -2
  154. package/skills/yad-ui/SKILL.md +43 -8
  155. package/skills/yad-checks/templates/gitlab/.gitlab-ci.yml +0 -49
package/cli/doctor.mjs CHANGED
@@ -7,7 +7,7 @@ import os from 'node:os';
7
7
  import path from 'node:path';
8
8
  import fs from 'node:fs';
9
9
  import { c, log, ok, info, warn, fail, hand, run, has, exists, isPlainObject, readJSON, readJSONStrict, emitJSON, asArg, nodeSupport, nodeEndOfLife, NODE_FLOOR, NODE_SUPPORTED } from './lib.mjs';
10
- import { VERSION, BACKUP_SUFFIX, MIRRORED_FILES, mirrorDrift, PROJECT_FILES, MODULE_CONFIG, epicFiles, DESIGN_TOOLS, TESTING_TOOLS, LEARNING_TOOLS, HOOK_ADAPTERS, CAPTURE_ADAPTERS, HOOK_WIRING, CAPTURE_WIRING, PROTECTION_GUIDE_URL, isVerifiedLedger , productConfigPath, settingsEditHint, PRODUCT_LINK, ADVANCE_FROM_AUTOMATION, DRIVER_FROM_ASSISTANCE } from './manifest.mjs';
10
+ import { VERSION, BACKUP_SUFFIX, MIRRORED_FILES, mirrorDrift, PROJECT_FILES, MODULE_CONFIG, epicFiles, DESIGN_TOOLS, TESTING_TOOLS, LEARNING_TOOLS, HOOK_ADAPTERS, CAPTURE_ADAPTERS, HOOK_WIRING, CAPTURE_WIRING, ACTIVITY_WIRING, ACTIVITY_ADAPTERS, PROTECTION_GUIDE_URL, isVerifiedLedger , productConfigPath, settingsEditHint, PRODUCT_LINK, ADVANCE_FROM_AUTOMATION, DRIVER_FROM_ASSISTANCE } from './manifest.mjs';
11
11
  import { mergeHookSettings, hookMatcherFires, ideTargetsFor, agentFilesState, safeIdeTargetStateFor, hookScriptReady, miswiredGuardCommand, gitHookState, legacyModuleActions, legacyProductActions, renamedNameHits, PRODUCT_CHECK_WORKFLOWS, productProfileEffect, workflowsPassingProduct, productGateBlockers, oldProfileAdvice, gateProfileFix } from './plan.mjs';
12
12
  import { hasSiblingRepo, workspaceFileState, WORKSPACE_FILE } from './find-product.mjs';
13
13
  import { planMigration } from './migrate.mjs';
@@ -19,9 +19,10 @@ import { judgeRepo, runnable, shown as forTerminal } from './workspace.mjs';
19
19
  import { cliFor, hostFromGitUrl, ambiguousLegacyNames, plainHost, detectPlatform } from './platform.mjs';
20
20
  import { legacyLogins, stampLegacyLogins } from './gate.mjs';
21
21
  import { checkRepo } from './riskmap-command.mjs';
22
- import { checkCodeowners, codeownersFindings } from './codeowners-command.mjs';
22
+ import { checkCodeowners, codeownersFindings, unguardedHint, unguardedWords } from './codeowners-command.mjs';
23
23
  import { RISK_MAP_FILE } from './riskmap.mjs';
24
- import { readProtection, protectionLine, protectionJSON, hideAddresses, repoPathFromGitUrl, shown } from './protection.mjs';
24
+ import { readProtection, protectionLine, protectionJSON, hideAddresses, repoPathFromGitUrl, repoGitUrl, configuredGitUrl, shown } from './protection.mjs';
25
+ import { tracksHere } from './brain-activity.mjs';
25
26
  import { readTokenPlacement, tokenLine, readExpiringProductTokens, TOKEN_NAME } from './product-token.mjs';
26
27
  import { soloTeamHint, TEAM_CMD } from './people.mjs';
27
28
  import { pagesWorkflowPath, pagesWorkflowFailsOnBuild, wiredPagesPlatform } from './docs.mjs';
@@ -35,6 +36,15 @@ import { nodePins, satisfies, nodeFix, dockerReasons, dockerState, glabConfigs }
35
36
  import { allStoryFrames, FRAMES_KEY } from './story-frames.mjs';
36
37
  import { previewPattern, PREVIEW_KEY } from './preview.mjs';
37
38
 
39
+ // The design, testing and learning rows (E165 follow-up). The files are the team's, committed: `source` says
40
+ // what was found on the machine of whoever refreshed last, so a row says what was RECORDED, and the refresh
41
+ // checks this machine. A refresh with no `tool` checks the skill's default tool, not the team's, so every
42
+ // hint names it. The tool is one of DESIGN_TOOLS / TESTING_TOOLS / LEARNING_TOOLS by the time these run,
43
+ // each with a connect recipe; one that is installed but cannot be reached (signed out, its app closed)
44
+ // needs the person, not a connect step.
45
+ const connectThenRefresh = (skill, tool) => `if ${tool} is not on this machine, your agent can connect it: \`yad toolbox connect ${tool} --json\` (it asks you first); if it is, make sure it can be reached (signed in, its app open). Then run \`${skill}\` with \`action: refresh\` and \`tool: ${tool}\``;
46
+ const confirmByRefresh = (skill, tool) => `run \`${skill}\` with \`action: refresh\` and \`tool: ${tool}\` in your AI agent to check it on this machine`;
47
+
38
48
  // A registered path doctor may run git in (E81): a checkout the judgement accepts — never a refused
39
49
  // entry (git run in a folder the Product shaped as a repo reads its `config`, which can run a command),
40
50
  // and never one reached through a link inside a repo's tree (`yad repo sync` and `refresh` skip it too).
@@ -290,9 +300,20 @@ export function projectChecks(checks, root, { headCount = null } = {}) {
290
300
  // resolved host), so it fires even when an origin remote can substitute: the field itself
291
301
  // is required regardless.
292
302
  if (!hostFromGitUrl(productConfig.git_url)) {
303
+ // Set, but not an address yad can read a host from (`gitlab.example.com`, no scheme) — not "missing".
304
+ const set = typeof productConfig.git_url === 'string' && productConfig.git_url.trim();
305
+ check(checks, 'product-git-url', 'project', 'warn',
306
+ set ? `${settingsRel}'s git_url is not an address yad can read a host from (it needs a scheme, such as https://, or the user@host:path form) [YAD-CFG-005]`
307
+ : `${settingsRel} sets platform '${productConfig.platform}' but has no git_url [YAD-CFG-005]`,
308
+ set ? `fix git_url in ${settingsEditHint(root)} to the Product's full address, or re-run \`yad setup\` — it replaces it from origin when origin names a repo`
309
+ : `add git_url to ${settingsEditHint(root)} (or re-run \`yad setup\`) — auth/PR checks need the Product host`);
310
+ } else if (!repoGitUrl(productConfig.git_url)) {
311
+ // A host and no repo (#513): every platform read falls back to origin, but the record is still
312
+ // wrong — and code repos' product-link records copy it. Only the host is shown, never the value.
313
+ const where = plainHost(hostFromGitUrl(productConfig.git_url));
293
314
  check(checks, 'product-git-url', 'project', 'warn',
294
- `${settingsRel} sets platform '${productConfig.platform}' but has no git_url [YAD-CFG-005]`,
295
- `add git_url to ${settingsEditHint(root)} (or re-run \`yad setup\`) — auth/PR checks need the Product host`);
315
+ `${settingsRel}'s git_url names no repo, only a host${where ? ` (${where})` : ''} — yad takes the Product's repo path from its origin remote instead [YAD-CFG-005]`,
316
+ `edit git_url in ${settingsEditHint(root)} to the Product's full address, or re-run \`yad setup\` — it sets it from origin when origin is on the same host`);
296
317
  }
297
318
  // Scope the auth probe to the Product's own host (derived from git_url, falling back to the
298
319
  // origin remote). `${cli} auth status` without --hostname exits non-zero when ANY configured
@@ -449,6 +470,7 @@ export function projectChecks(checks, root, { headCount = null } = {}) {
449
470
  // Background capture (E43), on any Product in either ledger mode: is the post-edit hook wired, and will
450
471
  // a push to the `yad/wip/*` branches start the team's own CI?
451
472
  if (exists(productPath)) captureChecks(root, checks, readJSON(productPath, null));
473
+ if (exists(productPath)) activityChecks(root, checks, readJSON(productPath, null));
452
474
  docsWorkflowChecks(root, checks);
453
475
  if (exists(productPath)) lineEndingChecks(root, checks);
454
476
 
@@ -468,8 +490,8 @@ export function projectChecks(checks, root, { headCount = null } = {}) {
468
490
  else if (design.tool === 'none') check(checks, 'design', 'project', 'ok', 'design: markdown-only');
469
491
  else if (!DESIGN_TOOLS.includes(design.tool)) check(checks, 'design', 'project', 'fail', `${PROJECT_FILES.designConfig}: unknown or missing design tool '${design.tool}' [YAD-CFG-002]`, `expected one of ${DESIGN_TOOLS.join(', ')}, or none`);
470
492
  else if (design.source && design.source !== 'unavailable') check(checks, 'design', 'project', 'ok', `design: ${design.tool} (${design.source})`);
471
- else if (design.source === 'unavailable') check(checks, 'design', 'project', 'warn', `design: ${design.tool} MCP unavailable — yad-ui runs markdown-only`, 'connect the MCP, then run `yad-connect-design` (action: refresh)');
472
- else check(checks, 'design', 'project', 'warn', `design: ${design.tool} recorded but the MCP is not confirmed`, 'run `yad-connect-design` in your AI agent to detect the MCP');
493
+ else if (design.source === 'unavailable') check(checks, 'design', 'project', 'warn', `design: ${design.tool} recorded as not found when last checked — yad-ui runs markdown-only`, connectThenRefresh('yad-connect-design', design.tool));
494
+ else check(checks, 'design', 'project', 'warn', `design: ${design.tool} recorded but not confirmed`, confirmByRefresh('yad-connect-design', design.tool));
473
495
  }
474
496
 
475
497
  // testing.json: parse + shape + tool + MCP confirmation (absent is the normal artifacts-only default —
@@ -488,8 +510,8 @@ export function projectChecks(checks, root, { headCount = null } = {}) {
488
510
  else if (testing.tool === 'none') check(checks, 'testing', 'project', 'ok', 'testing: artifacts-only');
489
511
  else if (!TESTING_TOOLS.includes(testing.tool)) check(checks, 'testing', 'project', 'fail', `${PROJECT_FILES.testingConfig}: unknown or missing testing tool '${testing.tool}' [YAD-CFG-003]`, `expected one of ${TESTING_TOOLS.join(', ')}, or none`);
490
512
  else if (testing.source && testing.source !== 'unavailable') check(checks, 'testing', 'project', 'ok', `testing: ${testing.tool} (${testing.source})`);
491
- else if (testing.source === 'unavailable') check(checks, 'testing', 'project', 'warn', `testing: ${testing.tool} MCP unavailable — yad-test-cases runs artifacts-only`, 'connect the MCP, then run `yad-connect-testing` (action: refresh)');
492
- else check(checks, 'testing', 'project', 'warn', `testing: ${testing.tool} recorded but the MCP is not confirmed`, 'run `yad-connect-testing` in your AI agent to detect the MCP');
513
+ else if (testing.source === 'unavailable') check(checks, 'testing', 'project', 'warn', `testing: ${testing.tool} recorded as not found when last checked — yad-test-cases runs artifacts-only`, connectThenRefresh('yad-connect-testing', testing.tool));
514
+ else check(checks, 'testing', 'project', 'warn', `testing: ${testing.tool} recorded but not confirmed`, confirmByRefresh('yad-connect-testing', testing.tool));
493
515
  }
494
516
 
495
517
  // learning.json: parse + shape + tool + CLI confirmation (absent is the normal harness-native default —
@@ -509,8 +531,8 @@ export function projectChecks(checks, root, { headCount = null } = {}) {
509
531
  else if (learning.tool === 'none') check(checks, 'learning', 'project', 'ok', 'learning: harness-native');
510
532
  else if (!LEARNING_TOOLS.includes(learning.tool)) check(checks, 'learning', 'project', 'fail', `${PROJECT_FILES.learningConfig}: unknown or missing learning tool '${learning.tool}' [YAD-CFG-004]`, `expected one of ${LEARNING_TOOLS.join(', ')}, or none`);
511
533
  else if (learning.source === 'deeptutor-cli') check(checks, 'learning', 'project', 'ok', `learning: ${learning.tool} (${learning.source})`);
512
- else if (learning.source === 'harness-native') check(checks, 'learning', 'project', 'warn', `learning: ${learning.tool} CLI unavailable — yad-learn tutors harness-native`, 'install the deeptutor CLI, then run `yad-connect-learning` (action: refresh)');
513
- else if (learning.source == null) check(checks, 'learning', 'project', 'warn', `learning: ${learning.tool} recorded but the CLI is not confirmed`, 'run `yad-connect-learning` in your AI agent to detect the CLI');
534
+ else if (learning.source === 'harness-native') check(checks, 'learning', 'project', 'warn', `learning: ${learning.tool} recorded as not found when last checked — yad-learn tutors harness-native`, connectThenRefresh('yad-connect-learning', learning.tool));
535
+ else if (learning.source == null) check(checks, 'learning', 'project', 'warn', `learning: ${learning.tool} recorded but not confirmed`, confirmByRefresh('yad-connect-learning', learning.tool));
514
536
  else check(checks, 'learning', 'project', 'fail', `${PROJECT_FILES.learningConfig}: unknown source '${learning.source}' [YAD-STATE-002]`, 'expected deeptutor-cli, harness-native, or null');
515
537
  }
516
538
 
@@ -656,12 +678,13 @@ export function projectChecks(checks, root, { headCount = null } = {}) {
656
678
  const blindGates = gateRoots.flatMap((x) => PRODUCT_PATH_GATES.map((rel) => ({ ...x, rel })))
657
679
  .filter((x) => productRecordBlindGate(path.join(x.root, x.rel)))
658
680
  .map((x) => `${x.rel} in ${x.where}`);
659
- // A `#` line naming the script is prose, not a step that runs it (review 1).
681
+ // A `#` line naming the script is prose, not a step that runs it (review 1). Since #426 the shipped
682
+ // workflow runs the base branch's copy, `"$YAD_CHECKS/product-checkout.sh"`; an older one, `checks/…`.
660
683
  const blindFlows = gateRoots.filter((x) => x.where !== 'the Product').flatMap((x) => CHECK_WORKFLOWS.map((rel) => ({ ...x, rel })))
661
684
  .filter((x) => {
662
685
  let src;
663
686
  try { src = fs.readFileSync(path.join(x.root, x.rel), 'utf8'); } catch { return false; }
664
- return !src.split('\n').some((l) => !/^\s*#/.test(l) && /checks\/product-checkout\.sh/.test(l));
687
+ return !src.split('\n').some((l) => !/^\s*#/.test(l) && /(?:\bchecks|\$\{?YAD_CHECKS\}?)\/product-checkout\.sh/.test(l));
665
688
  })
666
689
  .map((x) => `${x.rel} in ${x.where}`);
667
690
  const said = [
@@ -672,6 +695,17 @@ export function projectChecks(checks, root, { headCount = null } = {}) {
672
695
  check(checks, 'checks:product-record-blind', 'project', 'warn', said.join('; '),
673
696
  'run `yad check --fix` (it refreshes wired files nobody changed by hand); otherwise copy the shipped gate or workflow over it from skills/yad-checks/templates/');
674
697
  }
698
+ // #425. A gate workflow that still starts on `edited`: its gate jobs skip that run, a skipped job counts as
699
+ // passed, and the newer run turns a failed gate green. The shipped copies no longer start on it; one the
700
+ // team changed by hand is kept by `yad update`, so name it.
701
+ const editRun = gateRoots.flatMap((x) => EDIT_RUN_WORKFLOWS.map((rel) => ({ ...x, rel })))
702
+ .filter((x) => editRunWorkflow(path.join(x.root, x.rel)))
703
+ .map((x) => `${x.rel} in ${x.where}`);
704
+ if (editRun.length) {
705
+ check(checks, 'checks:edit-run', 'project', 'warn',
706
+ `${editRun.join(', ')} ${editRun.length > 1 ? 'start' : 'starts'} on an edit of the PR text (\`edited\`) — the gate jobs skip that run, GitHub counts a skipped job as passed, so editing the title or description can turn a failed gate green`,
707
+ 'run `yad update --overwrite-local` — it replaces every hand-edited managed file, keeping a `.yad-orig` copy of each; the PR-text checks now run from yad-pr-text.yml / yad-product-pr-text.yml. Or, by hand, remove `edited` from that file\'s `types:` and delete its `pr-title` and `pr-template` jobs: the PR-text file runs them now, and two runs under one check name let either decide');
708
+ }
675
709
  // E120. A wired code repo (not the Product's own git repo) whose record is not COMMITTED: its gates
676
710
  // fall back to link.md, and CI has nothing to check the Product out from. Committed, not on disk
677
711
  // (review 1): the gates read it from the default branch, and one that setup wrote and nobody
@@ -2101,6 +2135,16 @@ export function productRecordBlindGate(file) {
2101
2135
  try { src = fs.readFileSync(file, 'utf8'); } catch { return false; }
2102
2136
  return productRecordBlindText(src);
2103
2137
  }
2138
+ // #425. The GitHub gate workflows that must never start on `edited` (the Product's under the old name too).
2139
+ export const EDIT_RUN_WORKFLOWS = Object.freeze(['.github/workflows/yad-checks.yml', '.github/workflows/yad-product-checks.yml', '.github/workflows/yad-hub-checks.yml']);
2140
+ // `edited` in a `types:` list, inline or as a block item; a `#` comment is prose, not a trigger.
2141
+ export const editRunText = (src) => src.split('\n').map((l) => l.replace(/(^|\s)#.*$/, '')).some((l) =>
2142
+ /^\s*types:.*(?:^|[\s[,'"])edited(?:$|[\s\],'"])/.test(l) || /^\s*-\s*(['"]?)edited\1\s*$/.test(l));
2143
+ export function editRunWorkflow(file) {
2144
+ let src;
2145
+ try { src = fs.readFileSync(file, 'utf8'); } catch { return false; }
2146
+ return editRunText(src);
2147
+ }
2104
2148
  // The checks workflows a connected repo may carry (one per platform).
2105
2149
  export const CHECK_WORKFLOWS = ['.github/workflows/yad-checks.yml', '.gitlab/ci/yad-checks.yml'];
2106
2150
  // E117: a Product-reading gate that does not read link.md from the base (`git show`) or a tracked Product
@@ -2118,7 +2162,8 @@ export function productPathBlindGate(file) {
2118
2162
  }
2119
2163
 
2120
2164
  // `owners:rename-blind` (E47). The wired `pr-title` / `pr-template` checks let a PR of step owner files alone
2121
- // through; that is safe only while the product-checks workflow lists renames by BOTH paths (`--no-renames`).
2165
+ // through, and of the issue-links and roadmap-items records (#512: one pattern, found by its owners half). Safe only
2166
+ // while the product-checks workflow lists renames by BOTH paths (`--no-renames`).
2122
2167
  // `yad update` keeps a workflow the team changed by hand, so a Product can hold the new checks and the old
2123
2168
  // workflow — and then `git mv epic.md .sdlc/owners/epic.json` on a non-review branch passes. Say so.
2124
2169
  // The old names too (E123): an edited `yad-hub-checks.yml` is kept by `yad update`, and still runs.
@@ -2130,8 +2175,13 @@ export function ownerGuardChecks(checks, root) {
2130
2175
  // Line by line: one fixed diff line must not hide its blind twin in the other job.
2131
2176
  const blind = PRODUCT_CHECK_WORKFLOWS.filter((rel) => renameBlindText(read(rel) || ''));
2132
2177
  if (!blind.length) return;
2178
+ // The records' half (#512) is named only when every exempting copy has it: an older copy the team edited
2179
+ // exempts owner files alone, and the message must not claim more than the copy on disk lets through.
2180
+ const records = exempting.every((rel) => read(rel)?.includes('issue-links\\.json$'));
2133
2181
  check(checks, 'owners:rename-blind', 'project', 'warn',
2134
- `${blind.join(', ')} lists a PR's changes without \`--no-renames\`, while ${exempting.join(' and ')} let a PR of step owner files alone through — so moving an artifact into .sdlc/owners/ on a non-review branch passes both`,
2182
+ records
2183
+ ? `${blind.join(', ')} lists a PR's changes without \`--no-renames\`, while ${exempting.join(' and ')} let a PR of step owner files, issue-links files or the roadmap-items file alone through — so moving an artifact into .sdlc/owners/, or onto .sdlc/issue-links.json or .sdlc/roadmap-items.json, on a non-review branch passes both`
2184
+ : `${blind.join(', ')} lists a PR's changes without \`--no-renames\`, while ${exempting.join(' and ')} let a PR of step owner files alone through — so moving an artifact into .sdlc/owners/ on a non-review branch passes both`,
2135
2185
  'add `--no-renames` (and `-c core.quotePath=false`) to that workflow\'s `git diff --name-only` lines, as the shipped one has — `yad update` did not replace it because it was changed by hand');
2136
2186
  }
2137
2187
 
@@ -2577,20 +2627,31 @@ export function riskMapChecks(checks, root) {
2577
2627
  // a guess, and it prints only in `yad codeowners check`, never here. Advisory — a warning, never a
2578
2628
  // failure: CODEOWNERS is a hint (Part 3). No file at all is a note; a repo with no review rules at all is
2579
2629
  // E70's to warn about. A repo not on disk, or not a git repo, is the repos check's to report.
2630
+ // #426: gate files (checks/, every CI file) with no owner whose review the platform can require are a warning
2631
+ // too, with or without a CODEOWNERS file — on each code repo and on the Product, which runs its own gates (once:
2632
+ // a Product registered as one of its own repos is not said twice). The hint gives the lines.
2580
2633
  export function codeownersChecks(checks, root) {
2581
2634
  const registry = readJSON(path.join(root, PROJECT_FILES.reposRegistry), { repos: [] });
2582
2635
  const repos = Array.isArray(registry?.repos) ? registry.repos : [];
2636
+ const real = (d) => { try { return fs.realpathSync.native(d); } catch { return d; } };
2637
+ const seen = new Set();
2638
+ const can = { github: 'GitHub', gitlab: 'GitLab' };
2583
2639
  for (const repo of repos) {
2584
2640
  if (!repo || typeof repo.name !== 'string' || typeof repo.path !== 'string' || !repo.path) continue;
2585
2641
  const repoRoot = path.resolve(root, repo.path);
2586
2642
  if (!isCheckout(root, repo) || !gitHead(repoRoot)) continue;
2643
+ seen.add(real(repoRoot));
2587
2644
  const r = checkCodeowners(repoRoot, { platform: repo.platform || null });
2588
2645
  if (!r.git) continue;
2589
2646
  const id = `codeowners:${repo.name}`;
2590
2647
  const nm = forTerminal(repo.name); // printed as in riskMapChecks (E81 review 11)
2591
2648
  const more = `\`yad codeowners check ${asArg(repo.name)}\``;
2592
2649
  if (r.unknown) { check(checks, id, 'codeowners', 'warn', `${nm}: CODEOWNERS could not be checked — ${forTerminal(r.unknown)}`, more); continue; }
2593
- if (r.none) { check(checks, id, 'codeowners', 'ok', `${nm}: no CODEOWNERS — nothing to check`); continue; }
2650
+ if (r.none && !r.unguarded) { check(checks, id, 'codeowners', 'ok', `${nm}: no CODEOWNERS — nothing to check`); continue; }
2651
+ if (r.none) {
2652
+ check(checks, id, 'codeowners', 'warn', `${nm}: no CODEOWNERS, so ${unguardedWords(r.unguarded)} have no code owner`, unguardedHint(r.platform, r.unguarded), { findings: codeownersFindings(r) });
2653
+ continue;
2654
+ }
2594
2655
  const findings = codeownersFindings(r);
2595
2656
  if (!findings.length) { check(checks, id, 'codeowners', 'ok', `${nm}: every ${r.path} line yad can read matches a file`); continue; }
2596
2657
  const lines = (code) => findings.filter((f) => f.code === code).map((f) => f.line);
@@ -2602,10 +2663,27 @@ export function codeownersChecks(checks, root) {
2602
2663
  if (dead.length) said.push(`in ${r.path}, ${dead.length === 1 ? '1 line matches' : `${dead.length} lines match`} no file (line${dead.length === 1 ? '' : 's'} ${listed(dead)})`);
2603
2664
  const unread = lines('not-read');
2604
2665
  if (unread.length) said.push(`in ${r.path}, ${unread.length === 1 ? '1 line' : `${unread.length} lines`} yad could not read (line${unread.length === 1 ? '' : 's'} ${listed(unread)})`);
2605
- check(checks, id, 'codeowners', 'warn', `${nm}: CODEOWNERS may be out of date — ${said.join('; ')}`,
2606
- `${more} lists each one; fix it in ${nm} through a PR (advisory — CODEOWNERS is a hint, and yad never enforces it)`,
2666
+ const stale = said.length ? [`${nm}: CODEOWNERS may be out of date — ${said.join('; ')}`] : [];
2667
+ const gates = r.unguarded ? [`${stale.length ? '' : `${nm}: `}no line in ${r.path} that yad can read gives ${unguardedWords(r.unguarded)} an owner whose review ${can[r.platform] || 'the platform'} can require`] : [];
2668
+ check(checks, id, 'codeowners', 'warn', [...stale, ...gates].join('; '),
2669
+ [...(stale.length ? [`${more} lists each one; fix it in ${nm} through a PR (advisory — CODEOWNERS is a hint, and yad never enforces it)`] : []),
2670
+ ...(r.unguarded ? [unguardedHint(r.platform, r.unguarded)] : [])].join('; '),
2607
2671
  { findings });
2608
2672
  }
2673
+ // The Product's own gates (#426). Only the gate-file finding: the stale-line facts above are for code repos.
2674
+ const productConfig = readJSON(productConfigPath(root), null);
2675
+ if (!isPlainObject(productConfig) || !gitHead(root) || seen.has(real(root))) return;
2676
+ const platform = ['github', 'gitlab'].includes(productConfig.platform) ? productConfig.platform : null;
2677
+ const p = checkCodeowners(root, { platform });
2678
+ if (!p.git || p.unknown || p.tooBig || !p.platform) return;
2679
+ if (!p.unguarded) {
2680
+ // No CODEOWNERS and nothing unguarded means no gate files at all: nothing to say.
2681
+ if (!p.none && fs.existsSync(path.join(root, 'checks'))) check(checks, 'codeowners:(the Product)', 'codeowners', 'ok', `the Product: checks/ and the CI files have a code owner in ${p.path}`);
2682
+ return;
2683
+ }
2684
+ check(checks, 'codeowners:(the Product)', 'codeowners', 'warn',
2685
+ `the Product: ${p.none ? 'no CODEOWNERS, so ' : `no line in ${p.path} that yad can read gives `}${unguardedWords(p.unguarded)}${p.none ? ' have no code owner' : ` an owner whose review ${can[p.platform] || 'the platform'} can require`}`,
2686
+ unguardedHint(p.platform, p.unguarded), { findings: codeownersFindings(p).filter((f) => f.code === 'unguarded') });
2609
2687
  }
2610
2688
 
2611
2689
  // E70 — what the platform holds on the Product's branch and on each connected repo's: branch
@@ -2631,7 +2709,7 @@ export function protectionChecks(checks, root, { runner, env } = {}) {
2631
2709
  // `protection` alone, never `protection:product`: a connected repo may be named `product`.
2632
2710
  emit('protection', 'Product', {
2633
2711
  platform: productConfig.platform || null,
2634
- gitUrl: productConfig.git_url || origin(root),
2712
+ gitUrl: configuredGitUrl(productConfig.git_url, () => origin(root)) || null,
2635
2713
  branch: typeof productConfig.default_branch === 'string' && productConfig.default_branch ? productConfig.default_branch : null,
2636
2714
  });
2637
2715
  }
@@ -2645,7 +2723,7 @@ export function protectionChecks(checks, root, { runner, env } = {}) {
2645
2723
  // validates a repo's name, so a repo literally named `#1` could take the same id — it only labels a line.
2646
2724
  emit(hideAddresses(repo.name) === repo.name ? `protection:${repo.name}` : `protection:#${i + 1}`, forTerminal(repo.name), {
2647
2725
  platform: repo.platform || null,
2648
- gitUrl: (typeof repo.git_url === 'string' && repo.git_url) || (onDisk ? origin(repoRoot) : null),
2726
+ gitUrl: configuredGitUrl(repo.git_url, () => (onDisk ? origin(repoRoot) : null)) || null,
2649
2727
  branch: typeof repo.default_branch === 'string' && repo.default_branch ? repo.default_branch : null,
2650
2728
  });
2651
2729
  }
@@ -2658,20 +2736,22 @@ export function protectionChecks(checks, root, { runner, env } = {}) {
2658
2736
  export function productTokenChecks(checks, root, { runner, env, today } = {}) {
2659
2737
  const productConfig = readJSON(productConfigPath(root), null);
2660
2738
  if (!isPlainObject(productConfig) || typeof productConfig.git_url !== 'string' || !productConfig.git_url.trim()) return;
2739
+ // The Product's address: its git_url when that names a repo, else the clone's origin (#513) — a git_url
2740
+ // that names only a host would leave every comparison below, and the expiry read, with no repo.
2741
+ const productUrl = configuredGitUrl(productConfig.git_url, () => run('git', ['remote', 'get-url', 'origin'], { cwd: root }).stdout) || productConfig.git_url;
2661
2742
  const opts = { ...(runner ? { runner } : {}), ...(env ? { env } : {}), authCache: new Map() };
2662
2743
  const where = (url) => {
2663
2744
  const host = plainHost(hostFromGitUrl(url || ''));
2664
2745
  const repo = repoPathFromGitUrl(url || '');
2665
2746
  return host && repo ? { host, repo: repo.toLowerCase() } : null;
2666
2747
  };
2667
- const product = where(productConfig.git_url);
2748
+ const product = where(productUrl);
2668
2749
  const registry = readJSON(path.join(root, PROJECT_FILES.reposRegistry), { repos: [] });
2669
2750
  const repos = (Array.isArray(registry?.repos) ? registry.repos : []).map((repo, i) => ({ repo, i }))
2670
2751
  .filter(({ repo }) => isPlainObject(repo) && typeof repo.name === 'string' && repo.name);
2671
2752
  const urlOf = (repo) => {
2672
- if (typeof repo.git_url === 'string' && repo.git_url) return repo.git_url;
2673
2753
  const repoRoot = typeof repo.path === 'string' && repo.path ? path.resolve(root, repo.path) : null;
2674
- return repoRoot && isCheckout(root, repo) && gitHead(repoRoot) ? (run('git', ['remote', 'get-url', 'origin'], { cwd: repoRoot }).stdout || null) : null;
2754
+ return configuredGitUrl(repo.git_url, () => (repoRoot && isCheckout(root, repo) && gitHead(repoRoot) ? run('git', ['remote', 'get-url', 'origin'], { cwd: repoRoot }).stdout : null)) || null;
2675
2755
  };
2676
2756
  const listed = repos.map(({ repo, i }) => ({ repo, i, url: urlOf(repo), at: where(urlOf(repo)) }));
2677
2757
  let checked = 0;
@@ -2706,10 +2786,10 @@ export function productTokenChecks(checks, root, { runner, env, today } = {}) {
2706
2786
  const id = hideAddresses(repo.name) === repo.name ? `product-token:${repo.name}` : `product-token:#${i + 1}`;
2707
2787
  check(checks, id, 'product-token', line.status, line.message, line.hint || '');
2708
2788
  }
2709
- const productPlatform = productConfig.platform || detectPlatform(productConfig.git_url) || null;
2789
+ const productPlatform = productConfig.platform || detectPlatform(productUrl) || null;
2710
2790
  // Whatever platform the code repos are on (review 2): a GitHub repo can hold a GitLab Product's token.
2711
2791
  if (checked && productPlatform === 'gitlab') {
2712
- const r = readExpiringProductTokens({ gitUrl: productConfig.git_url }, { ...opts, ...(today ? { today } : {}) });
2792
+ const r = readExpiringProductTokens({ gitUrl: productUrl }, { ...opts, ...(today ? { today } : {}) });
2713
2793
  if (!r.known) {
2714
2794
  check(checks, 'product-token-expiry', 'product-token', 'warn', `whether one of the Product's access tokens that can clone it expires soon is not known — ${r.why}`);
2715
2795
  } else {
@@ -2929,6 +3009,52 @@ export function captureChecks(root, checks, cfg) {
2929
3009
  }
2930
3010
  }
2931
3011
 
3012
+ // The activity half (E178): off says so; on says whether the Product's own script and entries are wired, and
3013
+ // where the record is and how big. The code repos' entries are `yad check`'s to report, as the agent guard's are.
3014
+ export function activityChecks(root, checks, cfg) {
3015
+ if (!(cfg && cfg.activity === true)) {
3016
+ check(checks, 'activity', 'project', 'ok', 'the live activity record is off — `"activity": true` in the Product config turns it on, for `yad brain view --live`');
3017
+ return;
3018
+ }
3019
+ const unwired = [];
3020
+ for (const w of ACTIVITY_WIRING) if (!hookScriptReady(root, w.dest)) unwired.push(w.dest);
3021
+ const safe = new Set(safeIdeTargetStateFor(root, ideTargetsFor(root)).targets);
3022
+ for (const adapter of ACTIVITY_ADAPTERS) {
3023
+ if (!safe.has(adapter.target)) continue;
3024
+ const settingsPath = path.join(root, adapter.settings);
3025
+ let settings = null;
3026
+ if (exists(settingsPath)) {
3027
+ try { settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8')); } catch { settings = null; }
3028
+ }
3029
+ if (!isPlainObject(settings) || mergeHookSettings(settings, adapter).changed || !hookMatcherFires(settings, adapter)) {
3030
+ const where = `${adapter.settings} (${adapter.event})`;
3031
+ if (!unwired.includes(where)) unwired.push(where);
3032
+ }
3033
+ }
3034
+ if (unwired.length) {
3035
+ check(checks, 'activity', 'project', 'warn', `the live activity record is on but not wired: ${unwired.join(', ')}`,
3036
+ 'run `yad check --fix` — until then `yad brain view --live` sees nothing the agent does');
3037
+ return;
3038
+ }
3039
+ if (!exists(path.join(root, '.git')) && !tracksHere(root)) {
3040
+ check(checks, 'activity', 'project', 'warn', 'the live activity record is wired, but the Product is not committed in a git repo of its own, so the record has nowhere to go',
3041
+ 'commit the Product (the hook writes into the git folder of the repo that tracks it), then start the agent again');
3042
+ return;
3043
+ }
3044
+ const log = activityLogState(root);
3045
+ check(checks, 'activity', 'project', 'ok', `the live activity record is wired${log ? ` — ${log}` : ''}`);
3046
+ }
3047
+
3048
+ // Where this clone's record is, and its size, in words; null when git cannot say.
3049
+ function activityLogState(root) {
3050
+ const r = run('git', ['-C', root, 'rev-parse', '--path-format=absolute', '--git-common-dir']);
3051
+ if (!r.ok || !r.stdout) return null;
3052
+ const file = path.join(r.stdout, 'yad-activity.jsonl');
3053
+ let size;
3054
+ try { size = fs.statSync(file).size; } catch { return 'nothing recorded yet in this clone'; }
3055
+ return `${file} holds ${size < 1024 ? `${size} bytes` : `${(size / 1024).toFixed(0)} KB`} (never committed: it is inside .git)`;
3056
+ }
3057
+
2932
3058
  // The Pages workflow `yad docs sync --wire` wrote. Nothing else rewrites it, so a Product wired by yadflow
2933
3059
  // 4.5.0 or older keeps a script that deploys a site with a page missing when a site fails to build. Only
2934
3060
  // that one behaviour is judged — not the whole file, which Dependabot bumps and a team may edit — and only
@@ -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
 
@@ -583,6 +589,49 @@ const LEGACY_FORMS = [
583
589
  }),
584
590
  ];
585
591
 
592
+ // ---- the genesis lineage header (#499) -----------------------------------------------------------
593
+ //
594
+ // Before a change threads off a feature epic written before Phase 6, yad-change adds three lines to that
595
+ // epic's frontmatter: `kind: feature`, `type: feature` and `thread: <its own id>`. They state what every
596
+ // reader already assumes for an epic with no lineage (`workItemType` defaults to `feature`, and an epic
597
+ // with no parent is its own thread root), so they change nothing the reviewers read. Yet they changed the
598
+ // file, so every approval of its review read as stale. So a reader also accepts the fingerprint of the
599
+ // file with those lines taken out. What an approval RECORDS is unchanged (`reviewedSha`), so no release
600
+ // reads a new record differently. Only those exact values are taken out, and only from an epic with no
601
+ // `parent:` (a change-epic's type and thread are part of what its review approved). Any other value
602
+ // (`type: defect`, a thread naming another epic) still counts as an edit. Like the `status:` line, it is read
603
+ // only in a frontmatter block that opens with `---\n`: a file with CRLF line ends throughout keeps its
604
+ // whole-text fingerprint, so there the header still revokes (stale, never wrongly live).
605
+ const escapeRe = (s) => String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
606
+ export function withoutGenesisLineage(text, epicId) {
607
+ const fm = String(text).match(FRONTMATTER_BLOCK);
608
+ if (!fm || !epicId) return null;
609
+ const lines = fm[1].split('\n');
610
+ if (lines.some((l) => /^parent:/.test(l))) return null;
611
+ const genesis = [/^kind: feature[ \t]*\r?$/, /^type: feature[ \t]*\r?$/, new RegExp(`^thread: ${escapeRe(epicId)}[ \\t]*\\r?$`)];
612
+ const kept = lines.filter((l) => !genesis.some((re) => re.test(l)));
613
+ // Only when they are the epic's ONLY lineage lines. Next to another `kind:`, `type:` or `thread:` they
614
+ // are not the default: the readers disagree on which copy of a key wins (Node the last, the bash gates
615
+ // the first) and read `kind` before `type`, so adding `kind: feature` to a `type: chore` epic changes
616
+ // what it is (review 1).
617
+ if (kept.length === lines.length || kept.some((l) => /^(?:kind|type|thread)\s*:/.test(l))) return null;
618
+ return `---\n${kept.join('\n')}${text.slice(4 + fm[1].length)}`;
619
+ }
620
+
621
+ // Today's form and every legacy form, over the file's text with the genesis lines taken out. Empty when
622
+ // the file has none of them, so nothing new is accepted for any other file.
623
+ function genesisForms(p, epicId) {
624
+ if (!fs.existsSync(p)) return [];
625
+ const text = withoutGenesisLineage(fs.readFileSync(p).toString('utf8'), epicId);
626
+ if (text === null) return [];
627
+ const status = (edit) => { const t = withStatusLine(text, edit); return shaOf(t === null ? text : t); };
628
+ return [
629
+ status(''),
630
+ shaOf(text),
631
+ ...LEGACY_STATUSES.map((value) => status((line) => `status: ${value}${line.match(/\r?\n?$/)[0]}`)),
632
+ ];
633
+ }
634
+
586
635
  // Deterministic fingerprint of the whole stories/ set: hash each story file, sort, combine. Lets an
587
636
  // edit to any story revoke prior stories-review approvals.
588
637
  // `sha` is how one file is fingerprinted — `reviewedSha` for the record, a legacy form for reading.
@@ -595,6 +644,85 @@ export function storiesHash(epicDir, sha = reviewedSha) {
595
644
  return 'sha256:' + createHash('sha256').update(parts.join('\n')).digest('hex');
596
645
  }
597
646
 
647
+ // E164: the UI design's fingerprint. With no file under `design/`, it is the fingerprint of ui-design.md
648
+ // alone — byte for byte what every release before E164 recorded, so no approval of a Figma or Pencil
649
+ // design moves. With design files, it covers them too: ui-design.md as reviewed (`sha`), then each design
650
+ // file (`designSha`, never with a status line left out), sorted by path.
651
+ //
652
+ // Which files count is decided here, and the copy `artifactHashAt` makes of a commit is read by the same
653
+ // walk, so the disk and the approved commit agree:
654
+ // - regular files only (a link is skipped; so is a `design` folder that is itself a link — a commit
655
+ // holds it as a link, not a folder);
656
+ // - never a file the system or an editor drops beside a design (`isDesignJunk`: `.DS_Store`, macOS's
657
+ // `._<name>` copies, a `.~lock.<name>#` lock file, a name ending in `~`, `Thumbs.db`, `desktop.ini`)
658
+ // — git often does not ignore those, and counting one would make every approval look changed on that
659
+ // machine only. Any other name, a dot-name included, is a design file;
660
+ // - never inside a folder holding `.git` (a submodule or a nested repository: a commit holds it as one
661
+ // entry, not its files).
662
+ const DESIGN_JUNK = /^(?:\.ds_store|\._.*|\.~lock\..*|.*~|thumbs\.db|desktop\.ini)$/i;
663
+ export const isDesignJunk = (rel) => rel.split('/').some((seg) => DESIGN_JUNK.test(seg));
664
+ function designFiles(dir, rel = '') {
665
+ if (rel === '') {
666
+ try { if (!fs.lstatSync(dir).isDirectory()) return []; } catch { return []; }
667
+ }
668
+ let entries;
669
+ try { entries = fs.readdirSync(path.join(dir, rel), { withFileTypes: true }); } catch { return []; }
670
+ if (entries.some((e) => e.name === '.git')) return [];
671
+ const out = [];
672
+ for (const e of entries) {
673
+ if (DESIGN_JUNK.test(e.name)) continue;
674
+ const r = rel ? `${rel}/${e.name}` : e.name;
675
+ if (e.isDirectory()) out.push(...designFiles(dir, r));
676
+ else if (e.isFile()) out.push(r);
677
+ }
678
+ return out;
679
+ }
680
+ // One design file's fingerprint: the SHA-256 of its content. A Git LFS pointer (the small text file a
681
+ // checkout without LFS leaves in place of a large file) names that same SHA-256 as its `oid`, so the
682
+ // pointer and the real file give one fingerprint — CI checks out pointers, `artifactHashAt` may read
683
+ // the real file through the LFS filter, and the two must agree.
684
+ // Only the exact pointer format git-lfs writes counts — its version line, any `ext-` lines, the oid, the
685
+ // size and nothing else — so no other text can ride in a file whose fingerprint is its oid alone.
686
+ 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?$/;
687
+ function designSha(p) {
688
+ const bytes = fs.readFileSync(p);
689
+ if (bytes.length < 1024) {
690
+ const oid = bytes.toString('utf8').match(LFS_POINTER);
691
+ if (oid) return `sha256:${oid[1]}`;
692
+ }
693
+ return shaOf(bytes);
694
+ }
695
+ // The files under `design/` that git ignores here (an exports folder in .gitignore, an editor's settings
696
+ // folder): no commit holds them, so counting them would make the approval look changed on this machine
697
+ // only. Never asked for the scratch copy `artifactHashAt` makes (`askGit: false`): it holds only committed
698
+ // files, and a temporary folder inside some checkout would be judged by that checkout's rules. A tracked
699
+ // file is never reported, even when a pattern matches it. The variables that point git at another
700
+ // repository (set inside a git hook, or by a script) are dropped, so git finds the Product's checkout from
701
+ // the folder itself — the same list hook.mjs drops. Names are compared in one Unicode form, because git
702
+ // on macOS may print a name precomposed that it was given decomposed.
703
+ const REPO_ENV = /^GIT_(DIR|WORK_TREE|PREFIX|INDEX_FILE|COMMON_DIR|OBJECT_DIRECTORY|ALTERNATE_OBJECT_DIRECTORIES)$/;
704
+ function ignoredByGit(dir, files) {
705
+ if (!files.length) return new Set();
706
+ const env = { ...Object.fromEntries(Object.entries(process.env).filter(([k]) => !REPO_ENV.test(k))), GIT_OPTIONAL_LOCKS: '0' };
707
+ const r = spawnSync('git', ['check-ignore', '-z', '--stdin'], { cwd: dir, input: files.map((f) => `${f}\0`).join(''), env, maxBuffer: 64 * 1024 * 1024 });
708
+ return r.status === 0 ? new Set(r.stdout.toString('utf8').split('\0').filter(Boolean).map((f) => f.normalize('NFC'))) : new Set();
709
+ }
710
+ // The design files' part of the fingerprint, read once: `acceptedHashes` combines it with each form of
711
+ // ui-design.md, so a large design file is not read again for every form.
712
+ function designParts(epicDir, { askGit = true } = {}) {
713
+ const dir = path.join(epicDir, UI_DESIGN_DIR);
714
+ const all = designFiles(dir);
715
+ const ignored = askGit ? ignoredByGit(dir, all) : new Set();
716
+ return all.filter((f) => !ignored.has(f.normalize('NFC'))).sort().map((f) => `${UI_DESIGN_DIR}/${f}:${designSha(path.join(dir, ...f.split('/')))}`);
717
+ }
718
+ export function uiDesignHash(epicDir, sha = reviewedSha, parts = null, { askGit = true } = {}) {
719
+ const doc = sha(path.join(epicDir, 'ui-design.md'));
720
+ if (doc === null) return null;
721
+ parts ??= designParts(epicDir, { askGit });
722
+ if (!parts.length) return doc;
723
+ return 'sha256:' + createHash('sha256').update([`ui-design.md:${doc}`, ...parts].join('\n')).digest('hex');
724
+ }
725
+
598
726
  // The reserved id of the Product level in its OLD spelling ("epic zero", `epics/EP-discovery/`), written
599
727
  // by every release before E75 and still read. yad-epic / yad-analysis must never pick this slug — or
600
728
  // `EP-foundation` — for a feature.
@@ -667,6 +795,9 @@ const TABLE_RULE = /^\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)*\|?$/;
667
795
  const isTableRule = (l) => l.includes('|') && TABLE_RULE.test(l);
668
796
  const DIVIDER = /^(-{3,}|\*{3,}|_{3,})$/;
669
797
  export function isUnwrittenSection(text) {
798
+ // Comments are stripped in ONE pass. This reads a section for words; it does not clean HTML. In
799
+ // `<!<!-- x -->-- y -->` Markdown hides only the inner comment, and the rest shows as text, so it must
800
+ // stay and make the section written. Code scanning flags the single pass (alert #45): a false positive.
670
801
  const lines = text.replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n').replace(FRONTMATTER_BLOCK, '')
671
802
  .replace(/<!--[\s\S]*?-->/g, '').split('\n').map((l) => l.trim());
672
803
  return lines.every((l, i) => !l
@@ -940,12 +1071,14 @@ export function discoveryHash(epicDir, sha = reviewedSha) {
940
1071
  // the whole discovery file set; for every other artifact it is the file. Every file is fingerprinted
941
1072
  // without its frontmatter `status:` line (see `reviewedSha`). `sha` swaps that for a legacy form —
942
1073
  // only `acceptedHashes` passes one.
943
- export function artifactHash(epicDir, artifact, sha = reviewedSha) {
1074
+ // `askGit: false` is for a scratch copy of a commit (`artifactHashAt`): see `ignoredByGit`.
1075
+ export function artifactHash(epicDir, artifact, sha = reviewedSha, { askGit = true } = {}) {
944
1076
  const b = artifactBase(artifact);
945
1077
  if (b === 'architecture') return contractSurfaceHash(epicDir);
946
1078
  if (b === 'stories') return storiesHash(epicDir, sha);
947
1079
  if (b === 'discovery') return discoveryHash(epicDir, sha);
948
1080
  if (b === 'foundation') return foundationHash(epicDir, FOUNDATION_SECTIONS, sha);
1081
+ if (b === 'ui-design') return uiDesignHash(epicDir, sha, null, { askGit });
949
1082
  return sha(path.join(epicDir, artifact.replace(/\/$/, '')));
950
1083
  }
951
1084
 
@@ -953,9 +1086,15 @@ export function artifactHash(epicDir, artifact, sha = reviewedSha) {
953
1086
  // legacy forms (see LEGACY_FORMS). Empty when there is nothing to fingerprint — the same "no claim"
954
1087
  // answer a null `artifactHash` gives. What is WRITTEN is always `artifactHash`; this is for reading.
955
1088
  export function acceptedHashes(epicDir, artifact) {
956
- const current = artifactHash(epicDir, artifact);
1089
+ // The UI design's files are read once and combined with each form of ui-design.md (E164).
1090
+ const parts = artifactBase(artifact) === 'ui-design' ? designParts(epicDir) : null;
1091
+ const hashWith = parts ? (sha) => uiDesignHash(epicDir, sha, parts) : (sha) => artifactHash(epicDir, artifact, sha);
1092
+ const current = hashWith(reviewedSha);
957
1093
  if (current === null) return [];
958
- return [...new Set([current, ...LEGACY_FORMS.map((sha) => artifactHash(epicDir, artifact, sha))].filter(Boolean))];
1094
+ // An epic's own file also matches with its genesis lineage lines taken out (#499).
1095
+ const genesis = artifactBase(artifact) === 'epic' && !/\//.test(artifact.replace(/\/$/, ''))
1096
+ ? genesisForms(path.join(epicDir, artifact), path.basename(epicDir)) : [];
1097
+ return [...new Set([current, ...LEGACY_FORMS.map(hashWith), ...genesis].filter(Boolean))];
959
1098
  }
960
1099
 
961
1100
  // Is a recorded fingerprint stale against the accepted ones? Never when nothing was recorded (a manual
@@ -974,6 +1113,9 @@ export function doneStepUnapproved(epicDir, step, approvals) {
974
1113
  let accepted;
975
1114
  try { accepted = acceptedHashes(epicDir, step.artifact); } catch { return null; }
976
1115
  if (!accepted.length) return null;
1116
+ // A solo re-review that merged this very content (the Foundation's `rereviews`) answers too, so `yad next`,
1117
+ // `yad status` and `yad doctor` agree with `yad foundation publish`.
1118
+ if (soloRereviewCovers(step, accepted)) return null;
977
1119
  return forStep.some((a) => !isStaleHash(a.artifactHash, accepted)) ? null : { count: forStep.length };
978
1120
  }
979
1121
 
@@ -1017,7 +1159,7 @@ export function artifactHashAt(root, epicDir, artifact, rev) {
1017
1159
  copied++;
1018
1160
  }
1019
1161
  } 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 };
1162
+ return { ok: true, hash: artifactHash(dir, artifact, reviewedSha, { askGit: false }), copied };
1021
1163
  } finally {
1022
1164
  fs.rmSync(tmp, { recursive: true, force: true });
1023
1165
  }
@@ -2514,6 +2656,46 @@ export function reopenStampDue(state, reviewStepId) {
2514
2656
  // approvals were given before the step they rest on was approved again, so each later step is reviewed afresh,
2515
2657
  // on a new PR/MR. Recorded per walked-back review (`passes[]`), so a reopen of `epic` closes its hold step by
2516
2658
  // step. Mutates `state`; true when it recorded one.
2659
+ // A solo Foundation reviewed again (E174 follow-up). Solo mode counts no approvals, so once the Foundation
2660
+ // changes after its review nothing could ever say the new text was reviewed: a sync of an already-done
2661
+ // step only re-syncs approvals, and the first close wins. In solo mode the merge IS the human decision, so
2662
+ // the merge of a FRESH review PR/MR is recorded beside the first close, never over it, in the review
2663
+ // step's `rereviews` list: the PR/MR, its platform, what it merged (`hash`, the content at its approved
2664
+ // head — never the default branch's, so an edit merged after it is not covered) and who and when. An entry
2665
+ // covers only the content it merged, so recording one never covers more than was reviewed; the order rule
2666
+ // only keeps the list from growing. The PR/MR that made the first close is not recorded again, and a PR/MR
2667
+ // is recorded only when it is newer than every earlier entry FROM THE SAME PLATFORM: a Product that moved
2668
+ // from GitHub to GitLab starts numbering again, and comparing across that move would refuse every new one.
2669
+ // So a re-sync of the same or an older merge writes nothing. Mutates `state`; true when it wrote.
2670
+ export function recordSoloRereview(state, reviewStepId, { pr, platform = null, hash, by = null, date = null, commit = null, mergedBy = null } = {}) {
2671
+ const step = state?.steps?.find((s) => s?.id === reviewStepId);
2672
+ if (!soloRereviewDue(step, { pr, platform, commit })) return false;
2673
+ if (typeof hash !== 'string' || !hash.startsWith('sha256:')) return false;
2674
+ const earlier = Array.isArray(step.rereviews) ? step.rereviews : [];
2675
+ step.rereviews = [...earlier, { pr, platform, hash, by, date, commit, mergedBy, via: 'merged', waived: 'solo' }];
2676
+ return true;
2677
+ }
2678
+
2679
+ // Whether a merged PR/MR is one `recordSoloRereview` would still add — the one rule, read by the gate too,
2680
+ // so a run fails for a merge it could not read only when that merge was still waiting to be recorded.
2681
+ // The first close's PR/MR is told apart by its merge commit when both are known: `closed` records no
2682
+ // platform, and after a move to another platform the same number is another PR/MR.
2683
+ export function soloRereviewDue(step, { pr, platform = null, commit = null } = {}) {
2684
+ if (!isPlainObject(step) || step.type !== 'review+approve' || stepStatus(step) !== 'done') return false;
2685
+ if (!Number.isInteger(pr) || pr <= 0) return false;
2686
+ const closed = isPlainObject(step.closed) ? step.closed : null;
2687
+ if (closed?.pr === pr && (closed.commit == null || commit == null || closed.commit === commit)) return false;
2688
+ const earlier = Array.isArray(step.rereviews) ? step.rereviews : [];
2689
+ return !earlier.some((r) => isPlainObject(r) && (r.platform ?? null) === (platform ?? null) && Number.isInteger(r.pr) && r.pr >= pr);
2690
+ }
2691
+
2692
+ // Whether a solo re-review covers the content as it stands (`accepted`, from `acceptedHashes`).
2693
+ export function soloRereviewCovers(step, accepted) {
2694
+ const list = Array.isArray(step?.rereviews) ? step.rereviews : [];
2695
+ // Strict: nothing to fingerprint now (`accepted` empty) is never covered.
2696
+ return Array.isArray(accepted) && accepted.length > 0 && list.some((r) => isPlainObject(r) && typeof r.hash === 'string' && accepted.includes(r.hash));
2697
+ }
2698
+
2517
2699
  export function stampPassed(state, reviewStepId, { platform = null, number } = {}) {
2518
2700
  if (!reopenStampDue(state, reviewStepId) || !Number.isInteger(number) || number <= 0) return false;
2519
2701
  const steps = state.steps;