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/members.mjs CHANGED
@@ -42,11 +42,12 @@ import os from 'node:os';
42
42
  import path from 'node:path';
43
43
  import { createHash } from 'node:crypto';
44
44
  import { spawnSync } from 'node:child_process';
45
+ import { readBlobsAt } from './git-read.mjs';
45
46
 
46
47
  import { c, log, ok, info, warn, fail, hand, run, readJSON, forTerminal, isPlainObject, asset, inJSON, refuse as refuseJSON } from './lib.mjs';
47
48
  import { productConfigPath, isVerifiedLedger, SCHEMA_VERSION } from './manifest.mjs';
48
49
  import { LOGIN_RE, hostFromGitUrl, plainHost } from './platform.mjs';
49
- import { repoPathFromGitUrl, httpStatus } from './protection.mjs';
50
+ import { repoPathFromGitUrl, configuredGitUrl, httpStatus } from './protection.mjs';
50
51
  import { readRegistry, judgeRepo, runnable } from './workspace.mjs';
51
52
  import { resolveDefaultBranch } from './productcommit.mjs';
52
53
 
@@ -83,8 +84,10 @@ export const accountLabel = (a) => `${a.platform === 'github' ? 'GitHub' : 'GitL
83
84
  // clone's `origin`. `platform` is null on a Product with no platform: then nothing can be proven.
84
85
  export function productIdentity(root, { runner = run, productConfig = readJSON(productConfigPath(root), null) } = {}) {
85
86
  const platform = PLATFORMS.includes(productConfig?.platform) ? productConfig.platform : null;
86
- let url = typeof productConfig?.git_url === 'string' ? productConfig.git_url : '';
87
- if (!url) url = runner('git', ['remote', 'get-url', 'origin'], { cwd: root }).stdout || '';
87
+ // A git_url that names only a host is no repo: its repo path comes from origin then, and the host stays
88
+ // the settings' — the order the CI member check reads it in (#513, review 1).
89
+ const set = typeof productConfig?.git_url === 'string' ? productConfig.git_url : '';
90
+ const url = configuredGitUrl(set, () => runner('git', ['remote', 'get-url', 'origin'], { cwd: root }).stdout) || set;
88
91
  const host = plainHost(hostFromGitUrl(url)) || (platform ? DEFAULT_HOST[platform] : null);
89
92
  return { platform, host, repo: repoPathFromGitUrl(url), defaultBranch: typeof productConfig?.default_branch === 'string' ? productConfig.default_branch : null, verified: isVerifiedLedger(productConfig) };
90
93
  }
@@ -265,20 +268,11 @@ export function judgedMemberFiles(root, identity) {
265
268
  // Each candidate must be on disk byte for byte as origin holds it (review 5): an untracked copy, or an edit
266
269
  // git was told to ignore (`--assume-unchanged`), is not what the gate judged. One git run for them all.
267
270
  const cands = [...new Set(changed.out.split('\n').filter(Boolean))];
268
- const batch = spawnSync('git', ['cat-file', '--batch'], { cwd: root, input: cands.map((f) => `${base}:./${f}\n`).join(''), maxBuffer: 1 << 28 });
269
- const out = batch.status === 0 ? batch.stdout : Buffer.alloc(0);
271
+ const blobs = readBlobsAt(root, cands.map((f) => `${base}:./${f}`));
270
272
  const files = new Set();
271
- let at = 0;
272
273
  for (const f of cands) {
273
- const nl = out.indexOf(10, at);
274
- if (nl < 0) break;
275
- const header = out.subarray(at, nl).toString();
276
- at = nl + 1;
277
- const m = header.match(/^[0-9a-f]+ (\w+) (\d+)$/);
278
- if (!m) continue; // `<name> missing`: deleted at origin, and no body follows
279
- const blob = out.subarray(at, at + Number(m[2]));
280
- at += Number(m[2]) + 1; // every body is skipped, whatever its type (review 6)
281
- if (m[1] !== 'blob') continue;
274
+ const blob = blobs.get(`${base}:./${f}`);
275
+ if (!blob) continue; // deleted at origin, or not a file there
282
276
  let disk;
283
277
  try { if (fs.lstatSync(path.join(root, f)).isSymbolicLink()) continue; disk = fs.readFileSync(path.join(root, f)); } catch { continue; }
284
278
  if (sameText(disk.toString('utf8'), blob.toString('utf8'))) files.add(f);
package/cli/next.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  // `yad next` — the unified next-step driver. Read-only: it never writes state or acts. It reads the
2
2
  // file ledger and prints the ONE concrete, copy-pasteable next action (and a one-line why), so a user
3
- // never has to remember which of the 39 skills / gate commands comes next. "Guide, don't act" — the
3
+ // never has to remember which of the 41 skills / gate commands comes next. "Guide, don't act" — the
4
4
  // Shape still never auto-advances. Once an epic is `ready-for-build`, it reads each story's
5
5
  // build-state and prints the next BUILD sub-step per repo (spec → tasks → implement → checks → engineer-review)
6
6
  // plus the remaining chain — so Build is guided too, not just hinted at.
package/cli/openpr.mjs CHANGED
@@ -7,7 +7,7 @@ import fs from 'node:fs';
7
7
  import { c, log, ok, info, warn, hand, fail, run, exists, readJSON } from './lib.mjs';
8
8
  import { PROJECT_FILES , productConfigPath, settingsEditHint } from './manifest.mjs';
9
9
  import {
10
- detectPlatform, createPr, platformLogin, resolveBaseBranch, prNumberFromUrl, editPrBody,
10
+ detectPlatform, createPr, platformLogin, resolveBaseBranch, prNumberFromUrl, editPrBody, forkBranch, forkBranchWords, branchTaskId,
11
11
  } from './platform.mjs';
12
12
  import { taskFromBranch } from './commit.mjs';
13
13
  import { parseReviewBranch, artifactFromBase, gateCapFor, capLimit, peopleWord, gateRuleSum, gateRuleEnforced, legacyLogins } from './epic-state.mjs';
@@ -35,8 +35,8 @@ function resolveRepo(root, { repo, dir, product }) {
35
35
  if (found) return { repoRoot: path.resolve(productRoot, found.path), meta: found };
36
36
  }
37
37
  const here = path.resolve(root, dir || '.');
38
- // The checkout it runs in, when that checkout is a registered repo: worked at its top, from any
39
- // folder inside it. Anything else (a worktree, a nested repo) stays exactly where it is.
38
+ // The checkout it runs in, when that checkout is a registered repo or a git worktree of one (#515): worked
39
+ // at its own top, from any folder inside it. A nested repo stays exactly where it is, with no entry.
40
40
  const hit = registryEntryFor(product, here);
41
41
  return { repoRoot: hit ? hit.top : here, meta: hit ? hit.meta : null };
42
42
  }
@@ -164,8 +164,8 @@ export function routeCount(repoRoot, baseBranch, opts = {}) {
164
164
  if (high.length && opts.risk !== 'high') lines.push([warn, `the body says Risk level: ${opts.risk || 'low'}, but the risk map on ${map.base} marks ${high.join(', ')} high — the larger counts`]);
165
165
  // E72 — the cap, SHOWN and never enforced here. The Build count never holds a merge: the platform's
166
166
  // branch protection does (Part 9), and the user decided (2026-09-21) that the Build half stays
167
- // reported even after E108 turns the Shape cap on. That is also E66's answer: the CI half of this count runs from the PR's own checkout of
168
- // `checks/`, so a PR can edit the script that counts it — harmless only because nothing blocks on it.
167
+ // reported even after E108 turns the Shape cap on. That is also E66's answer: CI runs the base branch's copy of the script
168
+ // that counts (#426), but the workflow calling it comes from the PR — harmless only because nothing blocks on it.
169
169
  // `gateRuleEnforced` is called WITHOUT the cap on purpose, so the line keeps saying "advisory".
170
170
  const cap = gateCapFor(rule, opts.active);
171
171
  const capped = cap?.capped ? `, capped to ${cap.to} for ${cap.active} active ${peopleWord(cap.active)}` : '';
@@ -368,6 +368,21 @@ export async function runOpenPr(root, opts = {}) {
368
368
  if (!fetched && auto) throw err('YAD-STATE-009', `could not fetch ${baseBranch} from origin, so the tasks ${branch} carries are not known`, 'check the network and your login, then run this again');
369
369
  if (!fetched) warn(`could not fetch ${baseBranch} from origin — the tasks this PR carries are read against the last fetched ${baseRef}`);
370
370
  const haveBase = run('git', ['rev-parse', '--verify', '--quiet', `${baseRef}^{commit}`], { cwd: repoRoot }).ok;
371
+ // A base nobody chose (the platform's default, origin/HEAD, or 'main') may not be where this branch was
372
+ // cut from (#450): then the range below holds another branch's commits. Stop before anything is pushed.
373
+ // A --base, or a default_branch someone set in repos.json or the Product settings, is trusted as it is.
374
+ if (haveBase && !['flag', 'registry', 'product'].includes(baseSource)) {
375
+ const fork = forkBranch(repoRoot, { base: baseBranch, head: branch });
376
+ if (fork?.skipped) info(`origin has ${fork.skipped} branches, so yad did not check which one ${branch} was cut from — pass --base if it is not ${baseBranch}`);
377
+ else if (fork) {
378
+ const why = forkBranchWords(fork, baseBranch);
379
+ if (auto) throw err('YAD-STATE-009', why, 'a person picks the base and opens it with --base <branch>');
380
+ fail(why);
381
+ if (meta?.name) hand(`if tasks in ${meta.name} always go to one branch, set its default_branch in .sdlc/repos.json`);
382
+ process.exitCode = 1;
383
+ return;
384
+ }
385
+ }
371
386
  const commitIds = haveBase ? rangeTasks(repoRoot, `${baseRef}..HEAD`) : null;
372
387
  let groupIds = null;
373
388
  if (auto) {
@@ -381,7 +396,12 @@ export async function runOpenPr(root, opts = {}) {
381
396
  Object.assign(auto, { tasks, ...autoOpenCheck(auto.productRoot, { story: auto.story, tasks, repo: auto.repo }) });
382
397
  if (ids.length > 1) groupIds = ids;
383
398
  info(`opened on the standing approval: the checks of ${ids.join(', ')} passed, and the open-pr dial is auto`);
384
- } else if (commitIds && commitIds.length > 1) groupIds = commitIds;
399
+ } else if (commitIds && commitIds.length > 1) {
400
+ // The branch's own task first, so the body's Spec path is its story, not the newest commit's (#450).
401
+ const own = (branchTaskId(branch) || '').toLowerCase();
402
+ const at = commitIds.findIndex((t) => t.toLowerCase() === own);
403
+ groupIds = at > 0 ? [commitIds[at], ...commitIds.filter((_t, i) => i !== at)] : commitIds;
404
+ }
385
405
  if (groupIds) {
386
406
  info(`a grouped PR/MR: ${groupIds.join(', ')}`);
387
407
  const settings = readJSON(productConfigPath(opts.product || root), {}) || {};
package/cli/plan.mjs CHANGED
@@ -10,6 +10,7 @@ import {
10
10
  import {
11
11
  VERSION, SKILLS, IDE_TARGETS, IDE_OPENCODE_DIR, IDE_OPENCODE_TARGET, IDE_RECOVERY_TARGET, MODULE_CONFIG, wiringFor, PRODUCT_WIRING, PROJECT_FILES, isVerifiedLedger,
12
12
  HOOK_WIRING, HOOK_ADAPTERS, CLAUDE_HOOK_ADAPTER, CAPTURE_WIRING, CAPTURE_ADAPTERS, AGENT_GUARD_WIRING, AGENT_GUARD_ADAPTERS, REPO_AGENT_GUARD_DEST, agentGuardAdapters,
13
+ ACTIVITY_WIRING, ACTIVITY_ADAPTERS, REPO_ACTIVITY_DEST, activityAdapters,
13
14
  legacySkillPairs, REMOVED_SKILLS, LEGACY_REPO_FILES, LEGACY_PRODUCT_FILES, LEGACY_HOOK_SCRIPTS, MANAGED_LEDGER, BACKUP_SUFFIX,
14
15
  productConfigPath, PRODUCT_LINK, PRODUCT_LINK_DEFAULT_PATH,
15
16
  } from './manifest.mjs';
@@ -762,6 +763,8 @@ export const PRODUCT_PROFILE_FIX = 'add `product` to its `case "$PROFILE" in` li
762
763
  // The Product's checks workflows, under the new name and the old (E123): an edited old one is kept, and runs.
763
764
  export const PRODUCT_CHECK_WORKFLOWS = Object.freeze([
764
765
  '.github/workflows/yad-product-checks.yml', '.gitlab/ci/yad-product-checks.yml',
766
+ // pr-title + pr-template moved here on GitHub (#425), with their `--no-renames` diff lines.
767
+ '.github/workflows/yad-product-pr-text.yml',
765
768
  '.github/workflows/yad-hub-checks.yml', '.gitlab/ci/yad-hub-checks.yml',
766
769
  ]);
767
770
  // Those of them on disk that pass `--profile product` to the gates.
@@ -916,6 +919,8 @@ export function repoActions(root, repo) {
916
919
  actions.push(...agentFileActions(repoRoot, ideTargetsFor(root), { scope: repo.name, lines: pointerBlock(), relabel: false }));
917
920
  // E158b: the agent guard and the read-only allow list, so a session opened in the code repo has them too.
918
921
  actions.push(...repoAgentGuardActions(repoRoot, ideTargetsFor(root), { scope: repo.name, ledger }));
922
+ // E178: the live activity record, while the Product says `"activity": true`.
923
+ actions.push(...repoActivityActions(root, repoRoot, ideTargetsFor(root), { scope: repo.name, ledger }));
919
924
  }
920
925
  if (!wired) return actions;
921
926
  // The record is not a template: an absent one on a wired repo is always `new` (nothing to respect).
@@ -1662,6 +1667,128 @@ export function orphanCaptureHookActions(root, ideTargets = ideTargetsFor(root))
1662
1667
  return actions;
1663
1668
  }
1664
1669
 
1670
+ // ---- the live activity record (E178) -------------------------------------------------------------
1671
+ //
1672
+ // OFF by default: wired only while the Product config says `"activity": true` (`yad brain view --live` draws
1673
+ // it). The opposite polarity of capture's switch, read the same way: only the committed CONFIG decides, so two
1674
+ // people's `yad check` never disagree.
1675
+ export function activityWanted(root) {
1676
+ const cfgPath = productConfigPath(root);
1677
+ if (!exists(cfgPath)) return false;
1678
+ const cfg = readJSON(cfgPath, null);
1679
+ return !!(cfg && cfg.activity === true);
1680
+ }
1681
+
1682
+ // Is any folder on the way to `rel` under `root` a link (or not a folder)? Then nothing is written or removed
1683
+ // there: it would land wherever the link points (E178 review 1).
1684
+ function linkOnTheWay(root, rel) {
1685
+ let cur = root;
1686
+ const parts = rel.split('/');
1687
+ for (const part of parts.slice(0, -1)) {
1688
+ cur = path.join(cur, part);
1689
+ const st = lstatIfPresent(cur);
1690
+ if (st && (st.isSymbolicLink() || !st.isDirectory())) return true;
1691
+ }
1692
+ const last = lstatIfPresent(path.join(root, rel));
1693
+ return !!last && last.isSymbolicLink();
1694
+ }
1695
+ const keptSaid = new Set();
1696
+ function sayKept(where, rel) {
1697
+ if (keptSaid.has(`${where}\0${rel}`)) return;
1698
+ keptSaid.add(`${where}\0${rel}`);
1699
+ info(`${where}: ${rel} is not yad's copy (edited, or from before yad recorded it), so it is left in place; nothing runs it now — delete it if it is not yours`);
1700
+ }
1701
+ const linkSaid = new Set();
1702
+ function sayLinked(where, rel) {
1703
+ if (linkSaid.has(`${where}\0${rel}`)) return;
1704
+ linkSaid.add(`${where}\0${rel}`);
1705
+ warn(`${where}: a folder on the way to ${rel} is a link (or not a folder) — the live activity record is not wired there; make it a plain folder, then re-run \`yad check --fix\``);
1706
+ }
1707
+
1708
+ // The script and one entry per adapter whose target this Product uses. Landed together, as capture's are.
1709
+ export function activityHookActions(root, ideTargets = ideTargetsFor(root)) {
1710
+ if (!activityWanted(root)) return [];
1711
+ if (linkOnTheWay(root, ACTIVITY_WIRING[0].dest)) { sayLinked('the Product', ACTIVITY_WIRING[0].dest); return []; }
1712
+ const ledger = readManagedLedger(root);
1713
+ const actions = ACTIVITY_WIRING.map((w) =>
1714
+ wiredFileAction('product', w.dest, asset(w.src), path.join(root, w.dest), { root, exec: !!w.exec, ledger }),
1715
+ );
1716
+ const targets = new Set(safeIdeTargetsFor(root, ideTargets));
1717
+ for (const adapter of ACTIVITY_ADAPTERS) if (targets.has(adapter.target)) actions.push({ ...hookSettingsAction(root, adapter), item: `${path.basename(adapter.settings)} (activity: ${adapter.event})` });
1718
+ return actions.map(asNew);
1719
+ }
1720
+
1721
+ // Our entries for a target that left, or every entry and the script once `activity` is off.
1722
+ export function orphanActivityHookActions(root, ideTargets = ideTargetsFor(root)) {
1723
+ if (!exists(productConfigPath(root))) return [];
1724
+ const on = activityWanted(root);
1725
+ const kept = on ? new Set(safeIdeTargetsFor(root, ideTargets)) : new Set();
1726
+ return activityOrphans(root, kept, ACTIVITY_ADAPTERS, ACTIVITY_WIRING[0].dest, { removeScript: !on, scope: null });
1727
+ }
1728
+
1729
+ // The entries to unmerge (every adapter whose target is not kept), and the script when asked.
1730
+ function activityOrphans(root, kept, adapters, dest, { removeScript, scope }) {
1731
+ const actions = [];
1732
+ for (const adapter of adapters) {
1733
+ if (kept.has(adapter.target)) continue;
1734
+ const settingsPath = path.join(root, adapter.settings);
1735
+ if (!exists(settingsPath)) continue;
1736
+ let parsed;
1737
+ try { parsed = JSON.parse(fs.readFileSync(settingsPath, 'utf8')); } catch { continue; }
1738
+ if (!isPlainObject(parsed) || !unmergeHookSettings(parsed, adapter).changed) continue;
1739
+ actions.push({
1740
+ scope: scope || adapter.target,
1741
+ item: `${path.basename(adapter.settings)} (activity entry removed: ${adapter.event})`,
1742
+ status: 'removed',
1743
+ root,
1744
+ paths: [],
1745
+ apply: () => {
1746
+ let current;
1747
+ try { current = JSON.parse(fs.readFileSync(settingsPath, 'utf8')); } catch { return; }
1748
+ if (!isPlainObject(current)) return;
1749
+ const { settings, changed } = unmergeHookSettings(current, adapter);
1750
+ if (changed) writeJSON(settingsPath, settings);
1751
+ },
1752
+ });
1753
+ }
1754
+ // ONLY A COPY YAD PROVABLY WROTE, reached with no link on the way (E178 review 1, the E113 rule): its sha is
1755
+ // the one `.sdlc/managed.json` recorded, or it is byte for byte the script this release ships. A team's own
1756
+ // edited copy is theirs — their hook may run it — and a `checks/` or `hooks/` that is a link would take the
1757
+ // removal to wherever it points.
1758
+ if (removeScript && !linkOnTheWay(root, dest)) {
1759
+ const file = path.join(root, dest);
1760
+ const st = lstatIfPresent(file);
1761
+ const sha = st && st.isFile() ? contentSha(file) : null;
1762
+ const ours = sha && (readManagedLedger(root)[dest] === sha || sha === contentSha(asset(ACTIVITY_WIRING[0].src)));
1763
+ if (ours) actions.push({ scope: scope || 'product', item: `${dest} (removed)`, status: 'removed', root, paths: scope ? [] : [dest], apply: () => fs.rmSync(file, { force: true }) });
1764
+ else if (sha) sayKept(scope || 'the Product', dest);
1765
+ }
1766
+ return actions;
1767
+ }
1768
+
1769
+ // In a connected code repo cloned here: the script in `checks/` and the entries in the repo's own settings
1770
+ // files, for the Product's targets, as the agent guard's are (`repoAgentGuardActions`).
1771
+ export function repoActivityActions(productRoot, repoRoot, ideTargets, { scope, ledger = readManagedLedger(repoRoot) }) {
1772
+ if (!activityWanted(productRoot)) return [];
1773
+ if (linkOnTheWay(repoRoot, REPO_ACTIVITY_DEST)) { sayLinked(scope, REPO_ACTIVITY_DEST); return []; }
1774
+ const targets = new Set(repoTargets(repoRoot, ideTargets, scope));
1775
+ const settings = activityAdapters(REPO_ACTIVITY_DEST).filter((a) => targets.has(a.target))
1776
+ .map((a) => ({ ...hookSettingsAction(repoRoot, a, undefined, scope), scope, item: `${a.settings} (activity: ${a.event})` }));
1777
+ if (!settings.length) return [];
1778
+ return [wiredFileAction(scope, REPO_ACTIVITY_DEST, asset(ACTIVITY_WIRING[0].src), path.join(repoRoot, REPO_ACTIVITY_DEST), { root: repoRoot, ledger }), ...settings];
1779
+ }
1780
+
1781
+ // The same, taken out of a code repo: a target that left, or everything once `activity` is off. A tool folder
1782
+ // that is a link or not a folder is never written through.
1783
+ export function repoOrphanActivityActions(productRoot, repoRoot, ideTargets, { scope }) {
1784
+ if (!isDirectory(repoRoot)) return [];
1785
+ const on = activityWanted(productRoot);
1786
+ const kept = on ? new Set(repoTargets(repoRoot, ideTargets, null)) : new Set();
1787
+ const linked = (ide) => { const st = lstatIfPresent(path.join(repoRoot, ide)); return !!st && (st.isSymbolicLink() || !st.isDirectory()); };
1788
+ const adapters = activityAdapters(REPO_ACTIVITY_DEST).filter((a) => !linked(a.target));
1789
+ return activityOrphans(repoRoot, kept, adapters, REPO_ACTIVITY_DEST, { removeScript: !on, scope });
1790
+ }
1791
+
1665
1792
  // The read-only yad commands, pre-approved for Claude Code (E158, issue #353): `readAllowList` added to
1666
1793
  // `permissions.allow` in `.claude/settings.json`. Additive: the team's own entries are kept, and an entry of
1667
1794
  // ours already there is not added twice. A shape it cannot read is refused, as the hook merge refuses one.
package/cli/platform.mjs CHANGED
@@ -76,14 +76,14 @@ export function platformLogin(cwd, platform, { runner = run, env = process.env,
76
76
  const ghHost = platform === 'github'
77
77
  ? (host || hostFromGitUrl(runner('git', ['remote', 'get-url', 'origin'], { cwd }).stdout) || null)
78
78
  : null;
79
- const key = `${platform}\0${cwd}\0${ghHost || ''}`;
79
+ const key = `${platform}\0${cwd}\0${ghHost || host || ''}`;
80
80
  if (runner === run && loginCache.has(key)) return loginCache.get(key);
81
81
  let login = null;
82
82
  if (platform === 'github') {
83
83
  const r = runner('gh', ['api', ...(ghHost ? ['--hostname', ghHost] : []), 'user', '--jq', '.login'], { cwd, timeout: 10000 });
84
84
  if (r.ok) login = r.stdout.trim();
85
85
  } else {
86
- const r = runner('glab', ['api', 'user'], { cwd, timeout: 10000 });
86
+ const r = runner('glab', ['api', ...(host ? ['--hostname', host] : []), 'user'], { cwd, timeout: 10000 });
87
87
  if (r.ok) { try { login = String(JSON.parse(r.stdout).username || ''); } catch { /* not JSON — no login */ } }
88
88
  }
89
89
  if (!login || !LOGIN_RE.test(login)) login = null;
@@ -472,6 +472,72 @@ export function resolveBaseBranch(platform, {
472
472
  return { base: 'main', source: 'fallback', platformDefault };
473
473
  }
474
474
 
475
+ // The branch a task branch was really cut from, when it is not the base (#450). A branch cut from an
476
+ // integration branch (`develop`) and opened with no --base gets the platform default (`main`), and then
477
+ // `origin/main..HEAD` holds commits `develop` has that `main` lacks: other tasks' commits, read as this PR's
478
+ // tasks, its Spec path, its size. So, for each remote branch: the commits of `origin/<base>..<fork point>`
479
+ // (the fork point = merge-base of that branch and HEAD) are in the PR's range and came from that branch; the
480
+ // ones whose `Task:` line names ANOTHER task are the ones that matter. A commit with no `Task:` line, or with
481
+ // this task's own id, is not counted (a teammate's copy cut from this branch, when it was cut from the base,
482
+ // holds only those, and is never named).
483
+ // Git cannot always tell the integration branch from a teammate's copy of this branch, or from a release
484
+ // branch cut from develop earlier (reviews 2 and 3): every branch with any such commit is returned, newest
485
+ // fork point first (fewest commits from it to HEAD), ties by name, and the person picks — never one guess.
486
+ // Returns { branch, foreign, others }, { skipped: n } past FORK_REF_CAP remote branches, or null — none, or
487
+ // git could not tell. Left out up front: origin/HEAD, the base, the task branch's own pushed copy,
488
+ // task-shaped names (a branch cut FROM this one), and every branch that already holds HEAD.
489
+ export const FORK_REF_CAP = 200;
490
+ const TASK_SHAPED = /-S\d+-T\d+(?:-|$)/i;
491
+ const TASK_ID = /^EP-[a-z0-9-]+-S\d+-T\d+$/i;
492
+ // The task a branch carries, wherever its id sits in the name (`feat/team/EP-x-S01-T02-word`).
493
+ export function branchTaskId(branch = '') {
494
+ const m = String(branch).match(/(?:^|[/_-])(EP-[a-z0-9-]+?-S\d+-T\d+)(?=-|$)/i);
495
+ return m ? m[1] : null;
496
+ }
497
+ export function forkBranch(cwd, { base, head, runner = run } = {}) {
498
+ const g = (args) => runner('git', args, { cwd });
499
+ const baseRef = `origin/${base}`;
500
+ if (!g(['rev-parse', '--verify', '--quiet', `${baseRef}^{commit}`]).ok) return null;
501
+ // The full name, never `refname:short`: a short name can come out as `remotes/origin/x` when ambiguous.
502
+ const refs = g(['for-each-ref', '--format=%(refname)', '--no-contains', 'HEAD', 'refs/remotes/origin/']);
503
+ if (!refs.ok) return null;
504
+ const skip = new Set(['origin/HEAD', baseRef, `origin/${head}`]);
505
+ const cands = refs.stdout.split('\n').map((r) => r.replace(/^refs\/remotes\//, ''))
506
+ .filter((r) => r.startsWith('origin/') && !skip.has(r) && !TASK_SHAPED.test(r)).sort();
507
+ if (cands.length > FORK_REF_CAP) return { skipped: cands.length };
508
+ const own = (branchTaskId(head) || '').toLowerCase();
509
+ const found = [];
510
+ for (const cand of cands) {
511
+ const mb = g(['merge-base', cand, 'HEAD']);
512
+ if (!mb.ok || !mb.stdout) continue;
513
+ const log = g(['log', '--no-merges', '--format=%(trailers:key=Task,valueonly,separator=%x1e)%x00', `${baseRef}..${mb.stdout}`]);
514
+ if (!log.ok) return null;
515
+ const foreign = log.stdout.split('\0').map((x) => x.split('\x1e')[0].trim())
516
+ .filter((t) => TASK_ID.test(t) && t.toLowerCase() !== own).length;
517
+ if (!foreign) continue;
518
+ const toHead = g(['rev-list', '--count', `${mb.stdout}..HEAD`]);
519
+ if (!toHead.ok) return null;
520
+ found.push({ branch: cand.slice('origin/'.length), foreign, n: Number(toHead.stdout) });
521
+ }
522
+ if (!found.length) return null;
523
+ found.sort((x, y) => x.n - y.n || x.branch.localeCompare(y.branch));
524
+ return { branch: found[0].branch, foreign: found[0].foreign, others: found.slice(1).map((f) => f.branch) };
525
+ }
526
+
527
+ // The words both commands print for a forkBranch answer (#450): one sentence, and the two ways out.
528
+ // `yad open-pr --base` takes a branch name; `yad run checks --base` takes a ref, so it asks for origin/<name>.
529
+ export function forkBranchWords(fork, base, { ref = '', verb = 'open the PR/MR against' } = {}) {
530
+ const n = fork.foreign === 1 ? '1 commit' : `${fork.foreign} commits`;
531
+ const others = fork.others || [];
532
+ if (!others.length) {
533
+ return `this branch holds ${n} of other tasks from origin/${fork.branch} that origin/${base} does not have, so it was likely cut from origin/${fork.branch} — pass --base ${ref}${fork.branch}, or --base ${ref}${base} to ${verb} ${base} anyway`;
534
+ }
535
+ // Each name in the form this command's --base takes, so one can be copied as it is (review 4).
536
+ const all = [fork.branch, ...others].slice(0, 5).map((b) => `${ref}${b}`);
537
+ const more = others.length + 1 > 5 ? ` (and ${others.length + 1 - 5} more)` : '';
538
+ return `this branch holds commits of other tasks that origin/${base} does not have (${n} from origin/${fork.branch}), so it was cut from another branch — pass the one it was cut from as --base: ${all.join(', ')}${more}; or --base ${ref}${base} to ${verb} ${base} anyway`;
539
+ }
540
+
475
541
  // ---- create a PR/MR -----------------------------------------------------------------------------
476
542
  // `assignees` = the committer/PR-opener on GitLab (empty when `glab` cannot say who is logged in);
477
543
  // GitHub callers pass none and get `@me`, so the PR is owned by whoever pushed it;
@@ -573,7 +639,7 @@ export function createPr(platform, opts = {}) {
573
639
  if (platform === 'github') {
574
640
  const r = run('gh', buildPrArgs('github', { ...opts, reviewers: [] }), { cwd: opts.cwd });
575
641
  if (!r.ok) return { ok: false, reason: r.stderr };
576
- const url = r.stdout.split('\n').pop();
642
+ const url = urlFromStdout(r.stdout);
577
643
  const number = prNumberFromUrl(url);
578
644
  const added = []; const dropped = [];
579
645
  if (number) {
@@ -586,7 +652,7 @@ export function createPr(platform, opts = {}) {
586
652
  // gitlab
587
653
  const r = run('glab', buildPrArgs('gitlab', opts), { cwd: opts.cwd });
588
654
  if (!r.ok) return { ok: false, reason: r.stderr };
589
- const url = r.stdout.split('\n').pop();
655
+ const url = urlFromStdout(r.stdout);
590
656
  const iid = prNumberFromUrl(url);
591
657
  const rest = reviewers.slice(1);
592
658
  // Only report a reviewer as `mentioned` if the @-mention note actually posted; otherwise they were
@@ -669,3 +735,92 @@ export function issueUrl(platform, repo, { title = '', body = '', labels = [] }
669
735
  if (labels.length) q.set('labels', labels.join(','));
670
736
  return `https://github.com/${repo}/issues/new?${q.toString()}`;
671
737
  }
738
+
739
+ // ---- writes to a tracker item (E170) -----------------------------------------------------------------
740
+ // `t` is a `prTarget`: { platform, cli, host, repo }. Each returns the runner's result. `-f` sends the value as
741
+ // plain text, so a body starting with `@` is never read as a file name.
742
+ const itemAt = (t, number) => (t.platform === 'github' ? `repos/${t.repo}/issues/${number}` : `projects/${encodeURIComponent(t.repo)}/issues/${number}`);
743
+ const itemWrite = (t, method, at, fields, runner) => runner(t.cli, ['api', '--hostname', t.host, '-X', method, at, ...fields.flatMap((f) => ['-f', f])], { timeout: 30000 });
744
+
745
+ export function addItemLabels(t, number, labels, { runner = run } = {}) {
746
+ if (t.platform === 'github') return itemWrite(t, 'POST', `${itemAt(t, number)}/labels`, labels.map((l) => `labels[]=${l}`), runner);
747
+ if (labels.some((l) => l.includes(','))) return { ok: false, stderr: 'a GitLab label name with a comma cannot be sent' };
748
+ return itemWrite(t, 'PUT', itemAt(t, number), [`add_labels=${labels.join(',')}`], runner);
749
+ }
750
+
751
+ export function removeItemLabels(t, number, labels, { runner = run } = {}) {
752
+ if (t.platform === 'github') {
753
+ let last = { ok: true };
754
+ for (const l of labels) { const r = itemWrite(t, 'DELETE', `${itemAt(t, number)}/labels/${encodeURIComponent(l)}`, [], runner); if (!r.ok) last = r; }
755
+ return last;
756
+ }
757
+ if (labels.some((l) => l.includes(','))) return { ok: false, stderr: 'a GitLab label name with a comma cannot be sent' };
758
+ return itemWrite(t, 'PUT', itemAt(t, number), [`remove_labels=${labels.join(',')}`], runner);
759
+ }
760
+
761
+ export function commentOnItem(t, number, body, { runner = run } = {}) {
762
+ return itemWrite(t, 'POST', `${itemAt(t, number)}/${t.platform === 'github' ? 'comments' : 'notes'}`, [`body=${body}`], runner);
763
+ }
764
+
765
+ export function closeItem(t, number, { runner = run } = {}) {
766
+ return itemWrite(t, t.platform === 'github' ? 'PATCH' : 'PUT', itemAt(t, number), [t.platform === 'github' ? 'state=closed' : 'state_event=close'], runner);
767
+ }
768
+
769
+ // ---- filing findings (E172) --------------------------------------------------------------------------
770
+ // A number goes with `-F` so it is sent as a number. `confidential` exists on GitLab only.
771
+ export function createFinding(t, { title, body, labels, milestone = null, confidential = false }, { runner = run } = {}) {
772
+ if (t.platform === 'github') {
773
+ const fields = ['-f', `title=${title}`, '-f', `body=${body}`, ...labels.flatMap((l) => ['-f', `labels[]=${l}`]), ...(milestone !== null ? ['-F', `milestone=${milestone}`] : [])];
774
+ return runner('gh', ['api', '--hostname', t.host, '-X', 'POST', `repos/${t.repo}/issues`, ...fields], { timeout: 30000 });
775
+ }
776
+ const fields = ['-f', `title=${title}`, '-f', `description=${body}`, '-f', `labels=${labels.join(',')}`, ...(milestone !== null ? ['-F', `milestone_id=${milestone}`] : []), ...(confidential ? ['-F', 'confidential=true'] : [])];
777
+ return runner('glab', ['api', '--hostname', t.host, '-X', 'POST', `projects/${encodeURIComponent(t.repo)}/issues`, ...fields], { timeout: 30000 });
778
+ }
779
+
780
+ export function createMilestone(t, title, { runner = run } = {}) {
781
+ const at = t.platform === 'github' ? `repos/${t.repo}/milestones` : `projects/${encodeURIComponent(t.repo)}/milestones`;
782
+ return runner(t.cli, ['api', '--hostname', t.host, '-X', 'POST', at, '-f', `title=${title}`], { timeout: 30000 });
783
+ }
784
+
785
+ // A draft a person publishes or discards. GitHub needs an affected package; `other` fits an application.
786
+ export function createDraftAdvisory(t, { summary, description, severity, cwe }, { runner = run } = {}) {
787
+ return runner('gh', ['api', '--hostname', t.host, '-X', 'POST', `repos/${t.repo}/security-advisories`, '-f', `summary=${summary}`, '-f', `description=${description}`, '-f', `severity=${severity}`, '-f', `cwe_ids[]=${cwe}`, '-f', 'vulnerabilities[][package][ecosystem]=other'], { timeout: 30000 });
788
+ }
789
+
790
+ // ---- acting on an item when a person asks (E173) -------------------------------------------------------
791
+ // Each returns the runner's result. A GitLab list field cannot be sent through `glab api` (it refuses a
792
+ // bracketed field name), so GitLab takes one assignee by id.
793
+ export function newItem(t, { title, body, labels, assignee = null, confidential = false, milestone = null }, { runner = run } = {}) {
794
+ if (t.platform === 'github') {
795
+ const fields = ['-f', `title=${title}`, '-f', `body=${body}`, ...labels.flatMap((l) => ['-f', `labels[]=${l}`]), ...(assignee ? ['-f', `assignees[]=${assignee}`] : []), ...(milestone !== null ? ['-F', `milestone=${milestone}`] : [])];
796
+ return runner('gh', ['api', '--hostname', t.host, '-X', 'POST', `repos/${t.repo}/issues`, ...fields], { timeout: 30000 });
797
+ }
798
+ const fields = ['-f', `title=${title}`, '-f', `description=${body}`, '-f', `labels=${labels.join(',')}`, ...(assignee ? ['-F', `assignee_id=${assignee}`] : []), ...(confidential ? ['-F', 'confidential=true'] : []), ...(milestone !== null ? ['-F', `milestone_id=${milestone}`] : [])];
799
+ return runner('glab', ['api', '--hostname', t.host, '-X', 'POST', `projects/${encodeURIComponent(t.repo)}/issues`, ...fields], { timeout: 30000 });
800
+ }
801
+
802
+ // `fields` is a map of plain-text fields. GitHub's body is `body`, GitLab's `description`.
803
+ export function editItem(t, number, fields, { runner = run } = {}) {
804
+ const gh = t.platform === 'github';
805
+ return itemWrite(t, gh ? 'PATCH' : 'PUT', itemAt(t, number), Object.entries(fields).map(([k, v]) => `${k === 'body' && !gh ? 'description' : k}=${v}`), runner);
806
+ }
807
+
808
+ export function reopenItem(t, number, { runner = run } = {}) {
809
+ return itemWrite(t, t.platform === 'github' ? 'PATCH' : 'PUT', itemAt(t, number), [t.platform === 'github' ? 'state=open' : 'state_event=reopen'], runner);
810
+ }
811
+
812
+ // GitHub: PATCH with one login replaces every assignee; clearing removes the current ones by name.
813
+ // GitLab: one user id, or 0 to clear.
814
+ export function setAssignee(t, number, who, { current = [], runner = run } = {}) {
815
+ if (t.platform === 'github') {
816
+ if (who !== null) return itemWrite(t, 'PATCH', itemAt(t, number), [`assignees[]=${who}`], runner);
817
+ if (!current.length) return { ok: true, code: 0, stdout: '{}', stderr: '' };
818
+ return itemWrite(t, 'DELETE', `${itemAt(t, number)}/assignees`, current.map((l) => `assignees[]=${l}`), runner);
819
+ }
820
+ return runner('glab', ['api', '--hostname', t.host, '-X', 'PUT', itemAt(t, number), '-F', `assignee_id=${who ?? 0}`], { timeout: 30000 });
821
+ }
822
+
823
+ // GitLab only: make an item confidential before it is marked as a vulnerability.
824
+ export function makeConfidential(t, number, { runner = run } = {}) {
825
+ return runner('glab', ['api', '--hostname', t.host, '-X', 'PUT', itemAt(t, number), '-F', 'confidential=true'], { timeout: 30000 });
826
+ }
@@ -43,7 +43,7 @@ export const INDEX_FORMAT = 'e111-1';
43
43
  // Line endings are made `\n` before anything else: a checkout with `core.autocrlf` (the Windows default)
44
44
  // holds CRLF where git stores LF, and the same Product must hash the same on every machine — and parse
45
45
  // the same, since the frontmatter reader expects `\n`. Nothing else in the bytes is touched.
46
- function readInput(file) {
46
+ export function readInput(file) {
47
47
  try {
48
48
  const raw = fs.readFileSync(file);
49
49
  return { bytes: raw.includes(13) ? Buffer.from(raw.toString('latin1').replace(/\r\n/g, '\n'), 'latin1') : raw };
@@ -54,6 +54,38 @@ export function repoPathFromGitUrl(url = '') {
54
54
  return parts.length >= 2 ? parts.join('/') : null;
55
55
  }
56
56
 
57
+ // A git_url that names a repo, as written (trimmed), else ''. A url that names only a host
58
+ // (`https://gitlab.example.com`, `git@host:`) says where the platform is but not which repo, so a reader
59
+ // that falls back to the clone's origin remote must fall back for it too (#513) — through `configuredGitUrl`.
60
+ export const repoGitUrl = (u) => (typeof u === 'string' && repoPathFromGitUrl(u) ? u.trim() : '');
61
+
62
+ // The address to ask the platform about, from a settings `git_url` and the clone's origin remote (#513):
63
+ // - the settings' url when it names a repo;
64
+ // - else origin — but the HOST stays the settings' when they name one: origin can be a person's own SSH
65
+ // alias (`git@gitlab-work:acme/product.git`), and the CI member check reads the host from the settings
66
+ // first. So a host-only url and origin on another host give the settings' host with origin's repo path.
67
+ // - else '' when neither names anything.
68
+ // `origin` is the url, or a function that reads it — asked only when the settings name no repo. A rebuilt url
69
+ // is for asking the platform (host + repo path) only, never for git to clone: the login name is dropped, and
70
+ // a GitLab installed under a sub-path (`https://example.com/gitlab`) is not kept. An origin with no plain host
71
+ // (`file://`, a local path) is never rebuilt onto the platform's host: it names no repo there.
72
+ export function configuredGitUrl(set, origin) {
73
+ const own = repoGitUrl(set);
74
+ if (own) return own;
75
+ const read = typeof origin === 'function' ? origin() : origin;
76
+ const o = typeof read === 'string' ? read.trim() : '';
77
+ const repo = repoPathFromGitUrl(o);
78
+ const host = plainHost(hostFromGitUrl(typeof set === 'string' ? set : ''));
79
+ const originHost = plainHost(hostFromGitUrl(o));
80
+ if (!repo || !host || !originHost || originHost === host) return o;
81
+ const s = set.trim();
82
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(s)) {
83
+ try { const u = new URL(s); u.username = ''; u.password = ''; u.search = ''; u.hash = ''; u.pathname = `/${repo}.git`; return u.toString(); } catch { /* below */ }
84
+ }
85
+ const scp = s.match(/^((?:[^@/]+@)?[^/:]+):/);
86
+ return scp ? `${scp[1]}:${repo}.git` : `https://${host}/${repo}.git`;
87
+ }
88
+
57
89
  // The HTTP status of a failed `gh api` / `glab api` call, or null when there was none (offline, a timeout,
58
90
  // the host is down). gh ends with `gh: Not Found (HTTP 404)`; glab with `glab: 404 Not Found (HTTP 404)`
59
91
  // and prints the body `{"message":"401 Unauthorized"}` on stdout.
@@ -716,14 +748,15 @@ function unknownHint(r) {
716
748
  }
717
749
 
718
750
  // E160b — what `yad ci check` reads beyond protection and approvals: the rules that make yad's checks hold a
719
- // merge. Read-only, the same calls `readProtection` makes plus a few GETs, and the same trap: a failed call is
751
+ // merge. Read-only, the same calls `readProtection` makes plus a few GETs and one GraphQL query, and the same trap: a failed call is
720
752
  // never "none". `readProtection` runs first, so a repo that cannot be read (no platform, reads turned off,
721
753
  // no login…) comes back with only `protection`, and every platform row is "not known" with its reason.
722
754
  // GitHub — `rules`: the active rules on the branch (null when not read; `full` when a whole page came
723
755
  // back, which proves nothing about what is past it). `classic`: classic branch protection, the
724
756
  // string 'none' when PROVEN absent (the branch reads `protected: false`, or GitHub answers 404 with
725
757
  // exactly "Branch not protected"), or null — GitHub answers a bare 404 to anyone who is not an
726
- // admin, even on a protected branch.
758
+ // admin, even on a protected branch. `mergeQueue` (#433): 'on' / 'off' from one GraphQL query (a read),
759
+ // null when it was not answered.
727
760
  // GitLab — the project's merge settings, the protected-branch entries that match the branch (null when not
728
761
  // read), the approval settings (Premium) and the push rule (Premium; a 404 is "no push rule").
729
762
  export function readCiSettings(target, { runner: ask = run, env = process.env, authCache = new Map() } = {}) {
@@ -750,7 +783,24 @@ export function readCiSettings(target, { runner: ask = run, env = process.env, a
750
783
  if (c.ok && c.body && typeof c.body === 'object' && !Array.isArray(c.body)) classic = c.body;
751
784
  else if (c.status === 404 && c.body?.message === 'Branch not protected') classic = 'none';
752
785
  }
753
- return { protection, rules, rulesFull: !!rules && rules.length >= PAGE, classic };
786
+ // #433: a merge queue can be turned on by a ruleset or by classic branch protection, and the classic answer
787
+ // does not show it. GraphQL names the queue whatever turned it on: an object when on, null when off.
788
+ // The names go in as variables, never into the query text, and with -f, as plain strings: -F would turn
789
+ // `123` or `true` into a number or a boolean, and read a file for a value that starts with `@`.
790
+ // Anything else is not known (null).
791
+ const [owner, name] = repo.split('/');
792
+ const q = runner('gh', ['api', '--hostname', host, 'graphql',
793
+ '-f', 'query=query($owner: String!, $name: String!, $branch: String!) { repository(owner: $owner, name: $name) { mergeQueue(branch: $branch) { id } } }',
794
+ '-f', `owner=${owner}`, '-f', `branch=${branch}`, '-f', `name=${name}`], { timeout: TIMEOUT });
795
+ let mergeQueue = null;
796
+ if (q.ok) {
797
+ try {
798
+ const body = JSON.parse(q.stdout);
799
+ const repoNode = body?.data?.repository;
800
+ if (!body?.errors && repoNode && typeof repoNode === 'object' && 'mergeQueue' in repoNode) mergeQueue = repoNode.mergeQueue ? 'on' : 'off';
801
+ } catch { /* not JSON: not known */ }
802
+ }
803
+ return { protection, rules, rulesFull: !!rules && rules.length >= PAGE, classic, mergeQueue };
754
804
  }
755
805
  const at = `projects/${encodeURIComponent(repo)}`;
756
806
  const obj = (res) => (res.ok && res.body && typeof res.body === 'object' && !Array.isArray(res.body) ? res.body : null);
package/cli/reconcile.mjs CHANGED
@@ -14,7 +14,7 @@ import { preflightGuardReadiness } from './productcommit.mjs';
14
14
  import { VERSION, PROJECT_FILES, MANAGED_LEDGER, BACKUP_SUFFIX , productConfigPath, PRODUCT_LINK } from './manifest.mjs';
15
15
  import {
16
16
  moduleActions, repoActions, productActions, hookActions, agentFileActions, agentGuardActions, orphanAgentGuardActions, allowListActions, orphanAllowListActions, repoOrphanAgentGuardActions,
17
- legacyModuleActions, removedModuleActions, orphanHookActions, captureHookActions, orphanCaptureHookActions, legacyHookScriptActions, legacyRepoActions, legacyProductActions,
17
+ legacyModuleActions, removedModuleActions, orphanHookActions, captureHookActions, orphanCaptureHookActions, activityHookActions, orphanActivityHookActions, repoOrphanActivityActions, legacyHookScriptActions, legacyRepoActions, legacyProductActions,
18
18
  ideTargetStateFor, recordManagedWrites, gitHookActions, orphanGitHookActions, gitHookState, gitHookAdvice, renamedNameHits, withoutKeptRenames, PRODUCT_PROFILE_GATES, productProfileGap, productProfileEffect, PRODUCT_PROFILE_FIX, workflowsPassingProduct, productGateBlockers, oldProfileAdvice,
19
19
  } from './plan.mjs';
20
20
  import { gitHead, packRepo } from './setup.mjs';
@@ -73,6 +73,8 @@ export async function reconcile(root, { fix = false, scope = 'all', force = fals
73
73
  ...gitHookActions(root), ...orphanGitHookActions(root),
74
74
  // E43: the post-edit capture hook, in both ledger modes.
75
75
  ...captureHookActions(root, ideTargets), ...orphanCaptureHookActions(root, ideTargets),
76
+ // E178: the live activity record, only while the config says `"activity": true`.
77
+ ...activityHookActions(root, ideTargets), ...orphanActivityHookActions(root, ideTargets),
76
78
  // E113: the old shell-script hooks. LAST, so the entries above that named them are rewritten first.
77
79
  ...legacyHookScriptActions(root, ideTargets),
78
80
  ];
@@ -90,7 +92,11 @@ export async function reconcile(root, { fix = false, scope = 'all', force = fals
90
92
  for (const repo of registry.repos) {
91
93
  const repoRoot = path.resolve(root, repo.path);
92
94
  // E158b: a target that left takes yad's guard and allow-list entries out of the repo's own settings too.
93
- const orphans = samePath(repoRoot, path.resolve(root)) ? [] : repoOrphanAgentGuardActions(repoRoot, ideTargets, { scope: repo.name });
95
+ // E178: and the activity record's, when the Product turned `activity` off.
96
+ const orphans = samePath(repoRoot, path.resolve(root)) ? [] : [
97
+ ...repoOrphanAgentGuardActions(repoRoot, ideTargets, { scope: repo.name }),
98
+ ...repoOrphanActivityActions(root, repoRoot, ideTargets, { scope: repo.name }),
99
+ ];
94
100
  const own = withoutKeptRenames([...repoActions(root, repo), ...legacyRepoActions(root, repo)]).concat(orphans);
95
101
  // Set on the action itself: later steps compare actions by identity. `true`, not the name, which may be empty.
96
102
  for (const a of own) { a.fromRepo = true; if (repo.name === 'product') a.shownScope = repoShown(repo); }
@@ -218,7 +224,7 @@ export async function reconcile(root, { fix = false, scope = 'all', force = fals
218
224
  // `product` is on disk or this run installs one — the same test `yad doctor` makes (review 2).
219
225
  const productRel = (p) => path.relative(root, p).split(path.sep).join('/');
220
226
  const installsProduct = actions.filter((a) => a.managed && a.managed.root === root
221
- && /(^|\/)yad-product-checks\.yml$/.test(productRel(a.managed.dest))
227
+ && /(^|\/)yad-product-(checks|pr-text)\.yml$/.test(productRel(a.managed.dest))
222
228
  && a.status !== 'ok' && a.status !== 'modified' && (scope === 'all' || a.status !== 'missing'))
223
229
  .map((a) => productRel(a.managed.dest));
224
230
  const passing = [...new Set([...workflowsPassingProduct(root), ...installsProduct])];