yadflow 4.10.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 (106) hide show
  1. package/CHANGELOG.md +97 -0
  2. package/README.md +12 -3
  3. package/bin/commands.mjs +5 -1
  4. package/bin/yad.mjs +109 -15
  5. package/cli/agent-guard-worker.mjs +13 -0
  6. package/cli/agent-guard.mjs +1053 -57
  7. package/cli/agent-rules.mjs +34 -3
  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 +3 -3
  28. package/cli/doctor.mjs +80 -13
  29. package/cli/epic-state.mjs +93 -1
  30. package/cli/epic.mjs +15 -3
  31. package/cli/errors.mjs +2 -1
  32. package/cli/find-product.mjs +69 -15
  33. package/cli/foundation-publish.mjs +256 -0
  34. package/cli/gate.mjs +29 -3
  35. package/cli/git-read.mjs +38 -0
  36. package/cli/guard-stream.mjs +409 -0
  37. package/cli/hook.mjs +59 -9
  38. package/cli/issues-act.mjs +57 -13
  39. package/cli/issues-write.mjs +19 -6
  40. package/cli/issues.mjs +62 -23
  41. package/cli/lib.mjs +37 -2
  42. package/cli/local-page.mjs +138 -0
  43. package/cli/machine.mjs +1 -1
  44. package/cli/manifest.mjs +50 -0
  45. package/cli/map/view/app.js +712 -0
  46. package/cli/map/view/index.html +50 -0
  47. package/cli/map/view/style.css +142 -0
  48. package/cli/map-view.mjs +186 -0
  49. package/cli/map.mjs +637 -0
  50. package/cli/members.mjs +9 -15
  51. package/cli/next.mjs +1 -1
  52. package/cli/openpr.mjs +2 -2
  53. package/cli/plan.mjs +125 -0
  54. package/cli/platform.mjs +5 -5
  55. package/cli/product-index.mjs +1 -1
  56. package/cli/protection.mjs +32 -0
  57. package/cli/reconcile.mjs +8 -2
  58. package/cli/report.mjs +9 -3
  59. package/cli/reports-dir.mjs +391 -0
  60. package/cli/reports.mjs +65 -0
  61. package/cli/run-checks.mjs +5 -2
  62. package/cli/scan.mjs +1 -1
  63. package/cli/setup.mjs +30 -5
  64. package/cli/standup.mjs +87 -71
  65. package/cli/status.mjs +6 -5
  66. package/cli/test-agents-file.mjs +614 -8
  67. package/cli/test-brain-activity.mjs +753 -0
  68. package/cli/test-brain-view.mjs +381 -0
  69. package/cli/test-brain.mjs +795 -0
  70. package/cli/test-guide.mjs +211 -0
  71. package/cli/test-machine.mjs +59 -0
  72. package/cli/test-map.mjs +615 -0
  73. package/cli/test-reports.mjs +382 -0
  74. package/cli/test-run-checks.mjs +4 -0
  75. package/cli/test-worktree.mjs +24 -3
  76. package/cli/toolbox-connect.mjs +21 -6
  77. package/cli/toolbox.mjs +59 -4
  78. package/cli/update-commit.mjs +101 -9
  79. package/cli/usage.mjs +8 -4
  80. package/package.json +8 -4
  81. package/skills/yad-architecture/SKILL.md +22 -4
  82. package/skills/yad-change/SKILL.md +3 -1
  83. package/skills/yad-change/references/triage.md +2 -0
  84. package/skills/yad-checks/SKILL.md +2 -0
  85. package/skills/yad-checks/references/check-gates.md +8 -5
  86. package/skills/yad-checks/templates/checks/build-test-lint.sh +7 -0
  87. package/skills/yad-checks/templates/checks/install-deps.sh +6 -0
  88. package/skills/yad-checks/templates/checks/package-manager.sh +42 -0
  89. package/skills/yad-checks/templates/github/yad-checks.yml +3 -2
  90. package/skills/yad-checks/templates/gitlab/yad-checks.gitlab-ci.yml +3 -2
  91. package/skills/yad-checks/templates/hooks/yad-activity.mjs +238 -0
  92. package/skills/yad-connect-repos/SKILL.md +14 -0
  93. package/skills/yad-discovery/SKILL.md +11 -0
  94. package/skills/yad-discovery/references/foundation-schema.md +11 -0
  95. package/skills/yad-docs/templates/app/package-lock.json +18 -10
  96. package/skills/yad-docs/templates/app/package.json +6 -1
  97. package/skills/yad-epic/SKILL.md +3 -0
  98. package/skills/yad-epic/references/state-schema.md +35 -1
  99. package/skills/yad-guide/SKILL.md +4 -4
  100. package/skills/yad-implement/SKILL.md +76 -15
  101. package/skills/yad-issues/SKILL.md +2 -1
  102. package/skills/yad-pr-template/templates/checks/pr-template.sh +8 -4
  103. package/skills/yad-pr-template/templates/checks/pr-title.sh +8 -4
  104. package/skills/yad-spec/SKILL.md +19 -0
  105. package/skills/yad-stories/SKILL.md +22 -4
  106. package/skills/yad-stories/references/story-schema.md +1 -1
package/cli/ci-check.mjs CHANGED
@@ -22,7 +22,7 @@ import fs from 'node:fs';
22
22
  import path from 'node:path';
23
23
  import { c, log, ok, warn, fail, info, hand, run, exists, readJSON, isPlainObject, forTerminal, asArg } from './lib.mjs';
24
24
  import { REQUIRED_CHECKS, REPO_WIRING, PRODUCT_WIRING, PROJECT_FILES, PRODUCT_LINK, productConfigPath, isVerifiedLedger } from './manifest.mjs';
25
- import { readCiSettings, protectionLine } from './protection.mjs';
25
+ import { readCiSettings, protectionLine, configuredGitUrl } from './protection.mjs';
26
26
  import { repoActions, productActions } from './plan.mjs';
27
27
  import { judgeRepo, runnable } from './workspace.mjs';
28
28
  import { isSolo } from './gate.mjs';
@@ -474,7 +474,7 @@ export function ciTargets(root, { repo = null } = {}) {
474
474
  const onDisk = typeof entry.path === 'string' && entry.path && runnable(judgeRepo(root, entry));
475
475
  return {
476
476
  name: entry.name, kind: 'code', entry, ciRuns: true,
477
- target: { platform: entry.platform || null, gitUrl: (typeof entry.git_url === 'string' && entry.git_url) || (onDisk ? origin(path.resolve(root, entry.path)) : null), branch: branchOf(entry) },
477
+ target: { platform: entry.platform || null, gitUrl: configuredGitUrl(entry.git_url, () => (onDisk ? origin(path.resolve(root, entry.path)) : null)) || null, branch: branchOf(entry) },
478
478
  };
479
479
  };
480
480
  if (repo !== null) {
@@ -486,7 +486,7 @@ export function ciTargets(root, { repo = null } = {}) {
486
486
  name: 'Product', kind: 'product', wired, ciRuns: wired,
487
487
  // The verified ledger asked for, by its name or its older spellings, whether or not a platform is set.
488
488
  wantsVerified: config.ledger === 'verified' || (typeof config.ledger !== 'string' && (config.bridge_enabled === true || config.bridge === true)),
489
- target: { platform: config.platform || null, gitUrl: config.git_url || origin(root), branch: branchOf(config) },
489
+ target: { platform: config.platform || null, gitUrl: configuredGitUrl(config.git_url, () => origin(root)) || null, branch: branchOf(config) },
490
490
  };
491
491
  return { targets: [product, ...entries.map(code)] };
492
492
  }
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';
@@ -21,7 +21,8 @@ import { legacyLogins, stampLegacyLogins } from './gate.mjs';
21
21
  import { checkRepo } from './riskmap-command.mjs';
22
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';
@@ -299,9 +300,20 @@ export function projectChecks(checks, root, { headCount = null } = {}) {
299
300
  // resolved host), so it fires even when an origin remote can substitute: the field itself
300
301
  // is required regardless.
301
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();
302
305
  check(checks, 'product-git-url', 'project', 'warn',
303
- `${settingsRel} sets platform '${productConfig.platform}' but has no git_url [YAD-CFG-005]`,
304
- `add git_url to ${settingsEditHint(root)} (or re-run \`yad setup\`) — auth/PR checks need the Product host`);
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));
314
+ check(checks, 'product-git-url', 'project', 'warn',
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`);
305
317
  }
306
318
  // Scope the auth probe to the Product's own host (derived from git_url, falling back to the
307
319
  // origin remote). `${cli} auth status` without --hostname exits non-zero when ANY configured
@@ -458,6 +470,7 @@ export function projectChecks(checks, root, { headCount = null } = {}) {
458
470
  // Background capture (E43), on any Product in either ledger mode: is the post-edit hook wired, and will
459
471
  // a push to the `yad/wip/*` branches start the team's own CI?
460
472
  if (exists(productPath)) captureChecks(root, checks, readJSON(productPath, null));
473
+ if (exists(productPath)) activityChecks(root, checks, readJSON(productPath, null));
461
474
  docsWorkflowChecks(root, checks);
462
475
  if (exists(productPath)) lineEndingChecks(root, checks);
463
476
 
@@ -2149,7 +2162,8 @@ export function productPathBlindGate(file) {
2149
2162
  }
2150
2163
 
2151
2164
  // `owners:rename-blind` (E47). The wired `pr-title` / `pr-template` checks let a PR of step owner files alone
2152
- // 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`).
2153
2167
  // `yad update` keeps a workflow the team changed by hand, so a Product can hold the new checks and the old
2154
2168
  // workflow — and then `git mv epic.md .sdlc/owners/epic.json` on a non-review branch passes. Say so.
2155
2169
  // The old names too (E123): an edited `yad-hub-checks.yml` is kept by `yad update`, and still runs.
@@ -2161,8 +2175,13 @@ export function ownerGuardChecks(checks, root) {
2161
2175
  // Line by line: one fixed diff line must not hide its blind twin in the other job.
2162
2176
  const blind = PRODUCT_CHECK_WORKFLOWS.filter((rel) => renameBlindText(read(rel) || ''));
2163
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$'));
2164
2181
  check(checks, 'owners:rename-blind', 'project', 'warn',
2165
- `${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`,
2166
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');
2167
2186
  }
2168
2187
 
@@ -2690,7 +2709,7 @@ export function protectionChecks(checks, root, { runner, env } = {}) {
2690
2709
  // `protection` alone, never `protection:product`: a connected repo may be named `product`.
2691
2710
  emit('protection', 'Product', {
2692
2711
  platform: productConfig.platform || null,
2693
- gitUrl: productConfig.git_url || origin(root),
2712
+ gitUrl: configuredGitUrl(productConfig.git_url, () => origin(root)) || null,
2694
2713
  branch: typeof productConfig.default_branch === 'string' && productConfig.default_branch ? productConfig.default_branch : null,
2695
2714
  });
2696
2715
  }
@@ -2704,7 +2723,7 @@ export function protectionChecks(checks, root, { runner, env } = {}) {
2704
2723
  // validates a repo's name, so a repo literally named `#1` could take the same id — it only labels a line.
2705
2724
  emit(hideAddresses(repo.name) === repo.name ? `protection:${repo.name}` : `protection:#${i + 1}`, forTerminal(repo.name), {
2706
2725
  platform: repo.platform || null,
2707
- gitUrl: (typeof repo.git_url === 'string' && repo.git_url) || (onDisk ? origin(repoRoot) : null),
2726
+ gitUrl: configuredGitUrl(repo.git_url, () => (onDisk ? origin(repoRoot) : null)) || null,
2708
2727
  branch: typeof repo.default_branch === 'string' && repo.default_branch ? repo.default_branch : null,
2709
2728
  });
2710
2729
  }
@@ -2717,20 +2736,22 @@ export function protectionChecks(checks, root, { runner, env } = {}) {
2717
2736
  export function productTokenChecks(checks, root, { runner, env, today } = {}) {
2718
2737
  const productConfig = readJSON(productConfigPath(root), null);
2719
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;
2720
2742
  const opts = { ...(runner ? { runner } : {}), ...(env ? { env } : {}), authCache: new Map() };
2721
2743
  const where = (url) => {
2722
2744
  const host = plainHost(hostFromGitUrl(url || ''));
2723
2745
  const repo = repoPathFromGitUrl(url || '');
2724
2746
  return host && repo ? { host, repo: repo.toLowerCase() } : null;
2725
2747
  };
2726
- const product = where(productConfig.git_url);
2748
+ const product = where(productUrl);
2727
2749
  const registry = readJSON(path.join(root, PROJECT_FILES.reposRegistry), { repos: [] });
2728
2750
  const repos = (Array.isArray(registry?.repos) ? registry.repos : []).map((repo, i) => ({ repo, i }))
2729
2751
  .filter(({ repo }) => isPlainObject(repo) && typeof repo.name === 'string' && repo.name);
2730
2752
  const urlOf = (repo) => {
2731
- if (typeof repo.git_url === 'string' && repo.git_url) return repo.git_url;
2732
2753
  const repoRoot = typeof repo.path === 'string' && repo.path ? path.resolve(root, repo.path) : null;
2733
- 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;
2734
2755
  };
2735
2756
  const listed = repos.map(({ repo, i }) => ({ repo, i, url: urlOf(repo), at: where(urlOf(repo)) }));
2736
2757
  let checked = 0;
@@ -2765,10 +2786,10 @@ export function productTokenChecks(checks, root, { runner, env, today } = {}) {
2765
2786
  const id = hideAddresses(repo.name) === repo.name ? `product-token:${repo.name}` : `product-token:#${i + 1}`;
2766
2787
  check(checks, id, 'product-token', line.status, line.message, line.hint || '');
2767
2788
  }
2768
- const productPlatform = productConfig.platform || detectPlatform(productConfig.git_url) || null;
2789
+ const productPlatform = productConfig.platform || detectPlatform(productUrl) || null;
2769
2790
  // Whatever platform the code repos are on (review 2): a GitHub repo can hold a GitLab Product's token.
2770
2791
  if (checked && productPlatform === 'gitlab') {
2771
- const r = readExpiringProductTokens({ gitUrl: productConfig.git_url }, { ...opts, ...(today ? { today } : {}) });
2792
+ const r = readExpiringProductTokens({ gitUrl: productUrl }, { ...opts, ...(today ? { today } : {}) });
2772
2793
  if (!r.known) {
2773
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}`);
2774
2795
  } else {
@@ -2988,6 +3009,52 @@ export function captureChecks(root, checks, cfg) {
2988
3009
  }
2989
3010
  }
2990
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
+
2991
3058
  // The Pages workflow `yad docs sync --wire` wrote. Nothing else rewrites it, so a Product wired by yadflow
2992
3059
  // 4.5.0 or older keeps a script that deploys a site with a page missing when a site fails to build. Only
2993
3060
  // that one behaviour is judged — not the whole file, which Dependabot bumps and a team may edit — and only
@@ -589,6 +589,49 @@ const LEGACY_FORMS = [
589
589
  }),
590
590
  ];
591
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
+
592
635
  // Deterministic fingerprint of the whole stories/ set: hash each story file, sort, combine. Lets an
593
636
  // edit to any story revoke prior stories-review approvals.
594
637
  // `sha` is how one file is fingerprinted — `reviewedSha` for the record, a legacy form for reading.
@@ -752,6 +795,9 @@ const TABLE_RULE = /^\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)*\|?$/;
752
795
  const isTableRule = (l) => l.includes('|') && TABLE_RULE.test(l);
753
796
  const DIVIDER = /^(-{3,}|\*{3,}|_{3,})$/;
754
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.
755
801
  const lines = text.replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n').replace(FRONTMATTER_BLOCK, '')
756
802
  .replace(/<!--[\s\S]*?-->/g, '').split('\n').map((l) => l.trim());
757
803
  return lines.every((l, i) => !l
@@ -1045,7 +1091,10 @@ export function acceptedHashes(epicDir, artifact) {
1045
1091
  const hashWith = parts ? (sha) => uiDesignHash(epicDir, sha, parts) : (sha) => artifactHash(epicDir, artifact, sha);
1046
1092
  const current = hashWith(reviewedSha);
1047
1093
  if (current === null) return [];
1048
- return [...new Set([current, ...LEGACY_FORMS.map(hashWith)].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))];
1049
1098
  }
1050
1099
 
1051
1100
  // Is a recorded fingerprint stale against the accepted ones? Never when nothing was recorded (a manual
@@ -1064,6 +1113,9 @@ export function doneStepUnapproved(epicDir, step, approvals) {
1064
1113
  let accepted;
1065
1114
  try { accepted = acceptedHashes(epicDir, step.artifact); } catch { return null; }
1066
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;
1067
1119
  return forStep.some((a) => !isStaleHash(a.artifactHash, accepted)) ? null : { count: forStep.length };
1068
1120
  }
1069
1121
 
@@ -2604,6 +2656,46 @@ export function reopenStampDue(state, reviewStepId) {
2604
2656
  // approvals were given before the step they rest on was approved again, so each later step is reviewed afresh,
2605
2657
  // on a new PR/MR. Recorded per walked-back review (`passes[]`), so a reopen of `epic` closes its hold step by
2606
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
+
2607
2699
  export function stampPassed(state, reviewStepId, { platform = null, number } = {}) {
2608
2700
  if (!reopenStampDue(state, reviewStepId) || !Number.isInteger(number) || number <= 0) return false;
2609
2701
  const steps = state.steps;
package/cli/epic.mjs CHANGED
@@ -40,6 +40,7 @@ import {
40
40
  } from './epic-state.mjs';
41
41
  import { epicFiles, isVerifiedLedger, productConfigPath } from './manifest.mjs';
42
42
  import { refreshIndexAfterWrite } from './product-index.mjs';
43
+ import { foundationChanged, foundationReviewAgain, publishedItems } from './foundation-publish.mjs';
43
44
 
44
45
  // `foo`, `EP-foo` and `epics/EP-foo` all name the same epic. Accepting only one spelling would make the
45
46
  // command reject the id the user just read out of `yad next`.
@@ -488,8 +489,18 @@ export async function runFoundationStatus(root, { json = false } = {}) {
488
489
  } catch { return false; }
489
490
  });
490
491
 
492
+ // E174: whether the Foundation changed after its review, so a reader is told before `publish` refuses.
493
+ let checkFailed = false;
494
+ let foundationLedger = null;
495
+ const changed = productId === FOUNDATION_EPIC && approved ? (() => { try { foundationLedger = loadLedger(dir); return foundationChanged(dir, foundationLedger); } catch { checkFailed = true; return true; } })() : false;
496
+ if (checkFailed) warnings.push('whether the Foundation changed after its review could not be checked — run `yad doctor`');
497
+ else if (changed) warnings.push(`the Foundation changed after its review, so \`yad foundation publish\` refuses until it is reviewed again — ${foundationReviewAgain(root, foundationLedger)}`);
498
+ // E174: the item each row was published as, from the record only. Null when the record cannot be read.
499
+ const items = productId === FOUNDATION_EPIC ? publishedItems(root) : new Map();
500
+ for (const f of features) f.item = items ? (items.get(f.epicId) ?? null) : null;
501
+ if (items === null) warnings.push('foundation/.sdlc/roadmap-items.json cannot be read, so no row shows its item');
491
502
  if (json) {
492
- return emitJSON({ ok: true, epic: productId, roadmap: rel, approved, features, unlisted, ...(warnings.length ? { warnings } : {}) });
503
+ return emitJSON({ ok: true, epic: productId, roadmap: rel, approved, changed, features, unlisted, ...(warnings.length ? { warnings } : {}) });
493
504
  }
494
505
  for (const w of warnings) warn(w);
495
506
  log(`\n ${c.bold(`${productId} roadmap`)} ${c.dim(`${rel} — each status is read from the epic ledgers`)}`);
@@ -501,12 +512,13 @@ export async function runFoundationStatus(root, { json = false } = {}) {
501
512
  const name = `${f.feature || '(no name)'} ${c.dim(f.epicId || '(no id)')}`;
502
513
  if (f.problem) { log(` ${c.yellow('!')} ${name} ${c.yellow(f.problem)}`); continue; }
503
514
  const mark = f.status === 'shipped' ? c.green('✓') : f.status === 'planned' ? c.dim('·') : c.cyan('•');
504
- log(` ${mark} ${name} ${f.status}`);
515
+ log(` ${mark} ${name} ${f.status}${f.item ? c.dim(` #${f.item.number}`) : ''}`);
505
516
  if (f.disagrees) log(` ${c.dim(`the row says "${f.written}" — that column is no longer kept by hand; the ledger's answer is shown`)}`);
506
517
  }
507
518
  if (unlisted.length) {
508
519
  info(`not on the roadmap: ${unlisted.join(', ')} ${c.dim('(feature epics no row proposes — an epic may have been given a different id)')}`);
509
520
  }
510
521
  const next = features.find((f) => f.status === 'planned');
511
- if (next) hand(`next planned feature: ${next.feature || next.epicId} — seed it with the yad-epic skill (proposed id ${next.epicId})`);
522
+ if (next) hand(`next planned feature: ${next.feature || next.epicId} — seed it with the yad-epic skill (proposed id ${next.epicId}${next.item ? `, from item #${next.item.number}` : ''})`);
523
+ if (productId === FOUNDATION_EPIC && approved && !items?.size && features.length && !changed) info('the roadmap is approved: `yad foundation publish` opens one issue / work item per feature in the Product repo');
512
524
  }
package/cli/errors.mjs CHANGED
@@ -27,11 +27,12 @@ export const CODES = {
27
27
  'YAD-STATE-008': 'a file kept under two names (product.json + hub.json, or product-prs.json + hub-prs.json) says different things under each',
28
28
  'YAD-STATE-009': 'a Build record cannot be written in its current state (no lane yet, a step out of order, a PR not merged, a task not shipped)',
29
29
  'YAD-STATE-010': 'an epic worktree cannot be added or removed in its current state (a path taken, no origin, uncommitted or unpushed work, a lock)',
30
+ 'YAD-STATE-011': 'the project brain (.sdlc/brain/graph.json) or a Graphify graph cannot be read, or names a format this yadflow does not read',
30
31
  'YAD-CFG-001': 'the Product settings (product.json, or hub.json on a Product that has only that name) name an unknown platform (expected github, gitlab, or null)',
31
32
  'YAD-CFG-002': 'design.json names an unknown design tool (expected one of config.yaml design.tools, or none)',
32
33
  'YAD-CFG-003': 'testing.json names an unknown testing tool (expected one of config.yaml testing.tools, or none)',
33
34
  'YAD-CFG-004': 'learning.json names an unknown learning tool (expected one of config.yaml learning.tools, or none)',
34
- 'YAD-CFG-005': 'the Product settings (product.json, or hub.json on a Product that has only that name) set a platform but are missing git_url (required to scope auth + open PRs)',
35
+ 'YAD-CFG-005': 'the Product settings (product.json, or hub.json on a Product that has only that name) set a platform but are missing git_url, or name only a host in it with no repo path (required to scope auth + open PRs)',
35
36
  'YAD-CFG-006': 'skills.json binds a step to something that is not a skill name (expected a string, or a non-empty list of strings)',
36
37
  'YAD-CFG-007': 'toolbox.json has a line that does nothing — a tool this yadflow does not ship, a choice other than use or skip, or a custom tool that is incomplete, malformed, listed twice or uses a shipped tool\'s id',
37
38
  'YAD-CLI-001': 'a --json run needed an answer that only a prompt could give',
@@ -11,7 +11,8 @@
11
11
  // - a folder that is a Product (it has `.sdlc/hub.json` or `.sdlc/product.json`) — so any subfolder of
12
12
  // the Product finds it;
13
13
  // - a folder holding `.yad-workspace.json` — its `product` names the Product folder beside the repos.
14
- // It is used ONLY when `start` is inside a repo that Product registers in its `repos.json`. A
14
+ // It is used ONLY when `start` is inside a repo that Product registers in its `repos.json`, or in a git
15
+ // worktree of one (yad's own, #115, or a plain one, #515). A
15
16
  // workspace can be a shared folder (`~/Projects`, holding many teams' repos — setup always allowed
16
17
  // that), and a file there must not send an unrelated repo's `yad epic new` or `yad kill` to this
17
18
  // Product (E80 review 1). Anywhere else in the workspace there is no Product.
@@ -26,7 +27,7 @@ import os from 'node:os';
26
27
  import path from 'node:path';
27
28
  import { exists, readJSON, writeJSON } from './lib.mjs';
28
29
  import { productConfigPath, PROJECT_FILES } from './manifest.mjs';
29
- import { worktreeAt, sameDir } from './worktree-record.mjs';
30
+ import { worktreeAt, sameDir, linkedGitDir, commonDirOf } from './worktree-record.mjs';
30
31
 
31
32
  export const WORKSPACE_FILE = '.yad-workspace.json';
32
33
  export const WORKSPACE_VERSION = 1;
@@ -83,7 +84,11 @@ export function findProduct(start) {
83
84
  for (let d = from; ; d = path.dirname(d)) {
84
85
  if (exists(productConfigPath(d))) {
85
86
  if (d === from) return { root: d, via: 'here' };
86
- const repo = registeredRepoHolding(d, from);
87
+ // A worktree of a registered repo is that repo (#115, #515 review 1), wherever it sits: a repo inside
88
+ // the Product's folder can have one beside it (`product/backend-wt`), past which the walk crossed.
89
+ // No epic routing here, unlike the workspace branch below: `yad worktree add` refuses a repo kept
90
+ // inside the Product's folder, so no epic worktree of one exists to route to.
91
+ const repo = registeredRepoHolding(d, from) ?? (codeWorktreeOf(d, from) || linkedRepoWorktreeOf(d, from))?.meta ?? null;
87
92
  if (crossedRepo && !repo) return null;
88
93
  return { root: d, via: 'above', ...(repo ? { repo } : {}) };
89
94
  }
@@ -103,6 +108,9 @@ export function findProduct(start) {
103
108
  const epicTree = epicProductWorktree(ws.product, wt.epic);
104
109
  return { root: epicTree ?? ws.product, via: 'workspace', workspace: d, repo: wt.meta, ...(epicTree ? { worktree: wt.epic } : {}) };
105
110
  }
111
+ // A plain git worktree of a registered repo (#515): that repo. It has no epic, so the main Product.
112
+ const plain = linkedRepoWorktreeOf(ws.product, from);
113
+ if (plain) return { root: ws.product, via: 'workspace', workspace: d, repo: plain.meta };
106
114
  return { elsewhere: ws.product };
107
115
  }
108
116
  if (fs.existsSync(path.join(d, '.git'))) crossedRepo = true;
@@ -130,19 +138,49 @@ export function registeredRepoHolding(productRoot, dir) {
130
138
  return best;
131
139
  }
132
140
 
141
+ // Is `top` the worktree git knows by `gitDir`? Git keeps a back-link (`<gitDir>/gitdir`, absolute, or
142
+ // relative under `worktree.useRelativePaths`) to the worktree's `.git` file. A `.git` file written by hand
143
+ // that points at another worktree's git folder fails it, and so borrows nothing (#515).
144
+ function backLinked(top, gitDir) {
145
+ let back;
146
+ try { back = fs.readFileSync(path.join(gitDir, 'gitdir'), 'utf8').trim(); } catch { return false; }
147
+ return !!back && sameDir(path.resolve(gitDir, back), path.join(top, '.git'));
148
+ }
149
+
133
150
  // The registered repo whose epic worktree (#115) holds `dir`: yad made it (its record names the repo), and
134
- // its common git folder IS that repo's — a record copied into some other clone maps nothing.
151
+ // its common git folder IS that repo's — a record copied into some other clone maps nothing, and a `.git`
152
+ // file pointing at the worktree from another folder is not it (`backLinked`, #515 review 2).
135
153
  // → { meta, epic, top } or null.
136
154
  export function codeWorktreeOf(productRoot, dir) {
137
155
  const top = gitTopOf(dir);
138
156
  const rec = worktreeAt(top);
139
- if (!rec || typeof rec.repo !== 'string') return null;
157
+ if (!rec || typeof rec.repo !== 'string' || !backLinked(top, rec.gitDir)) return null;
140
158
  const reg = readJSON(path.join(productRoot, PROJECT_FILES.reposRegistry), null);
141
159
  const meta = (Array.isArray(reg?.repos) ? reg.repos : []).find((r) => r?.name === rec.repo && typeof r.path === 'string');
142
160
  if (!meta || !sameDir(rec.main, path.resolve(productRoot, meta.path))) return null;
143
161
  return { meta, epic: rec.epic, top };
144
162
  }
145
163
 
164
+ // The registered repo a plain git worktree belongs to (#515): one made by `git worktree add` or by an agent
165
+ // tool (Claude Code's `.claude/worktrees/<name>`), with no yad record. Its main checkout — the folder holding
166
+ // the common `.git` — must BE the registered repo, not a folder inside it or another clone. And git's own
167
+ // back-link (`<common>/.git/worktrees/<id>/gitdir`) must name this worktree's `.git` file: a `.git` file
168
+ // written by hand could otherwise point at a registered repo's worktree folder and borrow its entry.
169
+ // → { meta, top } with `top` the worktree's own top (worked there, never swapped for the repo's), or null.
170
+ // Never the Product's own entry (`registeredRepoHolding` refuses it).
171
+ export function linkedRepoWorktreeOf(productRoot, dir) {
172
+ if (!productRoot) return null;
173
+ const top = gitTopOf(dir);
174
+ const gitDir = top && linkedGitDir(top);
175
+ if (!gitDir) return null;
176
+ if (!backLinked(top, gitDir)) return null;
177
+ const common = commonDirOf(gitDir);
178
+ if (!common || path.basename(common) !== '.git') return null;
179
+ const main = path.dirname(common);
180
+ const meta = registeredRepoHolding(productRoot, main);
181
+ return meta && sameDir(main, path.resolve(productRoot, meta.path)) ? { meta, top } : null;
182
+ }
183
+
146
184
  // The epic's Product worktree beside the Product, when yad made one; else null.
147
185
  export function epicProductWorktree(productRoot, epic) {
148
186
  const root = path.resolve(productRoot);
@@ -235,21 +273,37 @@ export function toolsFolder(found, from) {
235
273
  return best ?? from;
236
274
  }
237
275
 
238
- // The registry entry for the code repo a code-repo command runs in (E80), with the folder to work in.
239
- // It is the CHECKOUT that must be the registered repo — not merely a folder inside it: a worktree or a
240
- // repo nested in `backend/` is another checkout, on another branch, and must never be swapped for
241
- // backend's own (E80 review 3). → { meta, top } or null. Never the Product's own entry.
242
- export function registryEntryFor(productRoot, dir) {
276
+ // The registered repo whose OWN checkout `dir` is in — never a worktree of it, never a nested repo. For the
277
+ // commands that work on the repo's files from its registered folder (`risk-map`, `codeowners`, `ci check`,
278
+ // which resolve `<Product>/<path>`): from a worktree they would act on the main checkout, on another
279
+ // branch, so they keep covering every repo there (E80 review 3, #515 review 1). → { meta, top } or null.
280
+ export function registeredCheckoutFor(productRoot, dir) {
243
281
  if (!productRoot) return null;
244
282
  const top = gitTopOf(dir);
245
283
  if (!top) return null;
246
284
  const meta = registeredRepoHolding(productRoot, top);
247
- if (!meta) {
248
- // The one worktree that IS the registered repo's: an epic worktree yad made of it (#115).
249
- const wt = codeWorktreeOf(productRoot, dir);
250
- return wt && sameDir(wt.top, top) ? { meta: wt.meta, top } : null;
251
- }
285
+ if (!meta) return null;
252
286
  const at = real(path.resolve(productRoot, meta.path));
253
287
  const topAt = real(top);
254
288
  return at && topAt && fold(at) === fold(topAt) ? { meta, top } : null;
255
289
  }
290
+
291
+ // The registry entry for the code repo a code-repo command runs in (E80), with the folder to work in.
292
+ // It is the CHECKOUT that must be the registered repo — not merely a folder inside it: a repo nested in
293
+ // `backend/` is another repo, and gets nothing. A git worktree of backend is backend on another branch: it
294
+ // gets backend's entry (its name, platform and default branch, #515), and `top` stays the worktree's own,
295
+ // so a command works where it runs and is never swapped for backend's checkout (E80 review 3).
296
+ // → { meta, top } or null. Never the Product's own entry.
297
+ export function registryEntryFor(productRoot, dir) {
298
+ if (!productRoot) return null;
299
+ const top = gitTopOf(dir);
300
+ if (!top) return null;
301
+ const own = registeredCheckoutFor(productRoot, dir);
302
+ if (own) return own;
303
+ // Not the registered checkout itself — a folder inside one, or beside it. Only a worktree of it counts: an
304
+ // epic worktree yad made (#115), or a plain git worktree, wherever it sits (#515), inside the repo
305
+ // (`.claude/worktrees/x`) or beside it. A repo nested inside one is neither, and gets nothing.
306
+ const wt = codeWorktreeOf(productRoot, dir);
307
+ if (wt && sameDir(wt.top, top)) return { meta: wt.meta, top };
308
+ return linkedRepoWorktreeOf(productRoot, dir);
309
+ }