yadflow 4.7.0 → 4.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/README.md +43 -4
  3. package/bin/commands.mjs +4 -1
  4. package/bin/yad.mjs +147 -20
  5. package/cli/agent-guard.mjs +511 -0
  6. package/cli/agent-guide.mjs +83 -0
  7. package/cli/agent-rules.mjs +381 -0
  8. package/cli/argv-flags.mjs +7 -0
  9. package/cli/ci-check.mjs +492 -0
  10. package/cli/docs.mjs +1 -1
  11. package/cli/doctor.mjs +43 -7
  12. package/cli/epic-state.mjs +3 -3
  13. package/cli/errors.mjs +1 -0
  14. package/cli/guide.mjs +549 -0
  15. package/cli/hook.mjs +32 -3
  16. package/cli/lib.mjs +46 -0
  17. package/cli/lifecycle/defaults/2.json +124 -0
  18. package/cli/lifecycle/lifecycle.schema.json +5 -2
  19. package/cli/lifecycle.mjs +16 -3
  20. package/cli/manifest.mjs +75 -0
  21. package/cli/marked-block.mjs +48 -0
  22. package/cli/members.mjs +19 -5
  23. package/cli/migrate.mjs +17 -19
  24. package/cli/next.mjs +1 -1
  25. package/cli/plan.mjs +326 -22
  26. package/cli/protection.mjs +50 -0
  27. package/cli/reconcile.mjs +187 -26
  28. package/cli/report.mjs +62 -14
  29. package/cli/setup.mjs +244 -25
  30. package/cli/signing.mjs +377 -0
  31. package/cli/test-agents-file.mjs +993 -0
  32. package/cli/test-ci-check.mjs +616 -0
  33. package/cli/test-guide.mjs +1267 -0
  34. package/cli/test-node.mjs +129 -0
  35. package/cli/test-setup-agent.mjs +352 -0
  36. package/cli/test-signing.mjs +524 -0
  37. package/cli/toolbox.mjs +1 -1
  38. package/cli/update-commit.mjs +313 -11
  39. package/cli/workspace.mjs +37 -12
  40. package/package.json +6 -4
  41. package/skills/sdlc/config.yaml +4 -4
  42. package/skills/sdlc/module-help.csv +1 -0
  43. package/skills/yad-change/SKILL.md +3 -2
  44. package/skills/yad-checks/SKILL.md +29 -9
  45. package/skills/yad-checks/references/check-gates.md +9 -4
  46. package/skills/yad-checks/templates/checks/package-manager.sh +1 -1
  47. package/skills/yad-checks/templates/github/yad-checks.yml +1 -1
  48. package/skills/yad-checks/templates/gitlab/.gitlab-ci.yml +1 -1
  49. package/skills/yad-checks/templates/gitlab/yad-checks.gitlab-ci.yml +1 -1
  50. package/skills/yad-checks/templates/gitlab/yad-product-checks.gitlab-ci.yml +1 -1
  51. package/skills/yad-checks/templates/gitlab/yad-update-guard.gitlab-ci.yml +1 -1
  52. package/skills/yad-checks/templates/gitlab/yad-verified-commits.gitlab-ci.yml +1 -1
  53. package/skills/yad-checks/templates/hooks/agent-guard.mjs +116 -0
  54. package/skills/yad-commit/SKILL.md +4 -3
  55. package/skills/yad-connect-repos/SKILL.md +5 -3
  56. package/skills/yad-connect-repos/references/code-context.md +2 -1
  57. package/skills/yad-connect-repos/references/repos-registry.md +2 -1
  58. package/skills/yad-docs-overview/references/pipeline-model.md +2 -2
  59. package/skills/yad-engineer-review/SKILL.md +12 -7
  60. package/skills/yad-engineer-review/references/ship-and-record.md +7 -4
  61. package/skills/yad-epic/SKILL.md +2 -1
  62. package/skills/yad-epic/references/state-schema.md +1 -1
  63. package/skills/yad-guide/SKILL.md +192 -0
  64. package/skills/yad-open-pr/SKILL.md +1 -1
  65. package/skills/yad-pair-review/SKILL.md +14 -5
  66. package/skills/yad-product-bridge/SKILL.md +32 -13
  67. package/skills/yad-product-bridge/references/bridge.md +6 -3
  68. package/skills/yad-product-bridge/templates/github/yad-gate-sync.yml +2 -2
  69. package/skills/yad-product-bridge/templates/gitlab/yad-gate-sync.gitlab-ci.yml +1 -1
  70. package/skills/yad-report/SKILL.md +15 -0
  71. package/skills/yad-review-companion/SKILL.md +5 -3
  72. package/skills/yad-review-gate/SKILL.md +13 -9
  73. package/skills/yad-review-gate/references/gating.md +1 -1
  74. package/skills/yad-run/SKILL.md +10 -6
  75. package/skills/yad-run/references/run-loop.md +2 -1
  76. package/skills/yad-sync-repos/SKILL.md +2 -1
  77. package/skills/yad-ui/SKILL.md +2 -2
package/cli/migrate.mjs CHANGED
@@ -17,7 +17,7 @@
17
17
  import fs from 'node:fs';
18
18
  import path from 'node:path';
19
19
 
20
- import { ask, c, exists, fail, hand, info, isPlainObject, log, ok, readJSON, warn, writeFileAtomic, writeJSON, writeProductConfig, emitJSON, collectWarning } from './lib.mjs';
20
+ import { ask, c, exists, fail, hand, info, isPlainObject, log, ok, readJSON, warn, writeFileAtomic, writeJSON, writeProductConfig, emitJSON, collectWarning, cpMerge, rmTree } from './lib.mjs';
21
21
  import { err } from './errors.mjs';
22
22
  import {
23
23
  ADVANCE_FROM_AUTOMATION, BACKUP_SUFFIX, DRIVER_FROM_ASSISTANCE, epicFiles, isVerifiedLedger,
@@ -468,23 +468,18 @@ export function planProductMove(root, { verified = false, ci = false, migrations
468
468
  // `copy` is a seam for the tests, which need a copy that fails or corrupts on demand.
469
469
  // `backup: false` is for the gate bot. In CI the old folder is in git history, a `.yad-orig` copy would be
470
470
  // an untracked directory on a throwaway runner, and `yad migrate` is not there to add it to .gitignore.
471
- export function applyProductMove(root, move, { migrations = MIGRATIONS, copy = fs.cpSync, backup: keepBackup = true } = {}) {
471
+ export function applyProductMove(root, move, { migrations = MIGRATIONS, copy = cpMerge, backup: keepBackup = true } = {}) {
472
472
  const from = path.join(root, move.from);
473
473
  const to = path.join(root, move.to);
474
474
  const backup = path.join(root, move.backup);
475
- // The folders under `foundation/` the copy will create, deepest first — computed BEFORE copying.
476
- const made = new Set();
477
- for (const m of move.moves) {
478
- for (let d = path.posix.dirname(m.to); d !== move.to && d !== '.'; d = path.posix.dirname(d)) {
479
- if (!exists(path.join(root, d))) made.add(d);
480
- }
481
- }
482
475
  const toExisted = exists(to);
476
+ const created = []; // every path the copy into `to` made: a failure removes these, and only these
483
477
  try {
484
478
  const before = artifactHash(from, 'discovery/');
485
- if (keepBackup) copy(from, backup, { recursive: true, errorOnExist: true, force: false });
486
- fs.mkdirSync(to, { recursive: true });
487
- copy(from, to, { recursive: true, errorOnExist: true, force: false });
479
+ // Folders are joined and a file that is already there is refused (cpMerge: Node 24's cpSync refuses
480
+ // a folder that exists, even with the user's own files in it).
481
+ if (keepBackup) copy(from, backup);
482
+ copy(from, to, created);
488
483
  if (artifactHash(to, 'discovery/') !== before) {
489
484
  throw new Error(`the copy in ${move.to}/ does not fingerprint like the original`);
490
485
  }
@@ -505,17 +500,20 @@ export function applyProductMove(root, move, { migrations = MIGRATIONS, copy = f
505
500
  writeJSON(file, stamped(obj, version));
506
501
  }
507
502
  } catch (e) {
503
+ // rmTree: a folder this copy made may carry a read-only mode copied from the source.
508
504
  if (!toExisted) {
509
- fs.rmSync(to, { recursive: true, force: true });
505
+ rmTree(to);
510
506
  } else {
511
- for (const m of move.moves) fs.rmSync(path.join(root, m.to), { force: true });
512
- for (const d of [...made].sort((a, b) => b.length - a.length)) fs.rmSync(path.join(root, d), { recursive: true, force: true });
507
+ // Only what this copy made: a file that came into foundation/ after the plan is the user's, and stays.
508
+ // Its folders are opened first: a file inside a read-only folder it made goes before that folder does.
509
+ for (const p of created) { try { if (fs.lstatSync(p).isDirectory()) fs.chmodSync(p, 0o700); } catch { /* gone */ } }
510
+ for (const p of [...created].reverse()) rmTree(p);
513
511
  }
514
512
  // Only a backup THIS run made. Without one, the path may still hold an earlier run's copy — the user's.
515
- if (keepBackup) fs.rmSync(backup, { recursive: true, force: true });
513
+ if (keepBackup) rmTree(backup);
516
514
  throw new Error(`nothing was moved — ${e.message}`, { cause: e });
517
515
  }
518
- fs.rmSync(from, { recursive: true, force: true });
516
+ rmTree(from);
519
517
  return productMoveFiles(move);
520
518
  }
521
519
 
@@ -1010,7 +1008,7 @@ function printNotRenamedHere(root) {
1010
1008
  // which means no backup, no row in the report, and a preview that under-reports what an apply does. It
1011
1009
  // would also be free to overwrite the one file the same run had just declared corrupt or newer than
1012
1010
  // this engine. What shape a file is in is recorded in that file, which is the whole point of rule 1.
1013
- export async function runMigrate(root, { apply = false, json = false, keep = null } = {}, { migrations = MIGRATIONS, copy = fs.cpSync, choose = null } = {}) {
1011
+ export async function runMigrate(root, { apply = false, json = false, keep = null } = {}, { migrations = MIGRATIONS, copy = cpMerge, choose = null } = {}) {
1014
1012
  if (keep != null && !KEEP_CHOICES.includes(keep)) {
1015
1013
  throw err('YAD-STATE-008', `--keep takes product or hub, not "${keep}"`, '`--keep product` keeps .sdlc/product.json (and each product-prs.json); `--keep hub` keeps the old names');
1016
1014
  }
@@ -1042,7 +1040,7 @@ export async function runMigrate(root, { apply = false, json = false, keep = nul
1042
1040
  // way to commit it is named: a drift there came from a hand edit that got past the guard already.
1043
1041
  const ciOwnedSettled = plan.verified ? settledFiles.filter((f) => !f.startsWith('.sdlc/')) : [];
1044
1042
  if (ciOwnedSettled.length) {
1045
- warn(`${ciOwnedSettled.join(', ')} ${ciOwnedSettled.length === 1 ? 'is' : 'are'} CI-owned on this verified Product: the ledger-guard check refuses a hand commit of ${ciOwnedSettled.length === 1 ? 'it' : 'them'} — commit the repair with \`yad commit --manual --reason "<why>" --type chore -m "<subject>"\`, which records the reason the check quotes`);
1043
+ warn(`${ciOwnedSettled.join(', ')} ${ciOwnedSettled.length === 1 ? 'is' : 'are'} CI-owned on this verified Product: the ledger-guard check refuses a hand commit of ${ciOwnedSettled.length === 1 ? 'it' : 'them'} — the person commits the repair with \`yad commit --manual --reason "<why>" --type chore -m "<subject>"\` (an AI agent hands it to them, \`!\` in front in Claude Code), which records the reason the check quotes`);
1046
1044
  }
1047
1045
  const move = plan.product?.action === 'move' ? plan.product : null;
1048
1046
  const pending = plan.rows.filter((r) => r.changes);
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 38 skills / gate commands comes next. "Guide, don't act" — the
3
+ // never has to remember which of the 39 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/plan.mjs CHANGED
@@ -5,14 +5,16 @@ import fs from 'node:fs';
5
5
  import path from 'node:path';
6
6
  import { err } from './errors.mjs';
7
7
  import {
8
- asset, exists, copyDir, copyFile, dirMatches, sameContent, readJSON, readJSONStrict, writeJSON, contentSha, warn, info, isPlainObject, run, samePath,
8
+ asset, exists, listFiles, copyDir, copyFile, dirMatches, sameContent, readJSON, readJSONStrict, writeJSON, contentSha, warn, info, isPlainObject, run, samePath,
9
9
  } from './lib.mjs';
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
- HOOK_WIRING, HOOK_ADAPTERS, CLAUDE_HOOK_ADAPTER, CAPTURE_WIRING, CAPTURE_ADAPTERS,
12
+ HOOK_WIRING, HOOK_ADAPTERS, CLAUDE_HOOK_ADAPTER, CAPTURE_WIRING, CAPTURE_ADAPTERS, AGENT_GUARD_WIRING, AGENT_GUARD_ADAPTERS, REPO_AGENT_GUARD_DEST, agentGuardAdapters,
13
13
  legacySkillPairs, REMOVED_SKILLS, LEGACY_REPO_FILES, LEGACY_PRODUCT_FILES, LEGACY_HOOK_SCRIPTS, MANAGED_LEDGER, BACKUP_SUFFIX,
14
14
  productConfigPath, PRODUCT_LINK, PRODUCT_LINK_DEFAULT_PATH,
15
15
  } from './manifest.mjs';
16
+ import { applyMarkedBlock } from './marked-block.mjs';
17
+ import { AGENTS_MARKERS, agentsBlock, pointerBlock, claudeBlock, readAllowList, RETIRED_ALLOW_ENTRIES, SHIPPED_ALLOW_LISTS } from './agent-rules.mjs';
16
18
 
17
19
  // A git pathspec (forward slashes, relative to a repo root) for `dest` under `root`. Actions carry
18
20
  // these so `yad update --push` can stage an EXPLICIT allowlist of exactly what it wrote per repo —
@@ -52,7 +54,41 @@ const dirAction = (scope, item, src, dest, { root } = {}) => ({
52
54
  status: !exists(dest) ? 'missing' : dirMatches(src, dest) ? 'ok' : 'outdated',
53
55
  root,
54
56
  paths: root ? [rel(root, dest)] : [],
57
+ // The template's own files, one path each — for staging a folder that is already right on disk without
58
+ // sweeping in a person's own files beside them (`yad update --open-pr` restages; E157 update review 6).
59
+ ownPaths: () => (root ? listFiles(src).map((f) => rel(root, path.join(dest, f))) : []),
55
60
  apply: () => copyDir(src, dest),
61
+ // Writes the template but keeps every file the template does not have (a person's notes, or a file an older
62
+ // yadflow shipped) — for `yad update --open-pr`, which an agent runs without asking (E157 update review 7).
63
+ // The kept files are moved aside and back, so their bytes, modes and links are untouched. Returns them,
64
+ // relative to `root`.
65
+ applyKeepingOwn: () => {
66
+ const shipped = listFiles(src);
67
+ const theirs = new Set(shipped);
68
+ // A path where the template now has a folder, or under a name the template now has as a file, is an older
69
+ // template's shape (a file swapped for a folder): it goes, as `yad update` always did, or it could never
70
+ // come back.
71
+ const clash = (f) => shipped.some((t) => t.startsWith(`${f}${path.sep}`) || f.startsWith(`${t}${path.sep}`));
72
+ const own = exists(dest) ? listFiles(dest).filter((f) => !theirs.has(f) && !clash(f)) : [];
73
+ if (!own.length) { copyDir(src, dest); return []; }
74
+ const aside = `${dest}.yad-keep-${process.pid}`;
75
+ const moved = [];
76
+ const stuck = [];
77
+ try {
78
+ for (const f of own) { fs.mkdirSync(path.dirname(path.join(aside, f)), { recursive: true }); fs.renameSync(path.join(dest, f), path.join(aside, f)); moved.push(f); }
79
+ copyDir(src, dest);
80
+ } finally {
81
+ // Back even when the copy failed. One that cannot go back stays in the side folder, which is named, never
82
+ // removed.
83
+ for (const f of moved) {
84
+ try { fs.mkdirSync(path.dirname(path.join(dest, f)), { recursive: true }); fs.renameSync(path.join(aside, f), path.join(dest, f)); } catch { stuck.push(f); }
85
+ }
86
+ if (stuck.length) warn(`${stuck.length} of your own file(s) could not go back into ${dest}; they are in ${aside}`);
87
+ else fs.rmSync(aside, { recursive: true, force: true });
88
+ }
89
+ // Only the files back in place: one left in the side folder is said by the warning above.
90
+ return own.filter((f) => !stuck.includes(f)).map((f) => (root ? rel(root, path.join(dest, f)) : f));
91
+ },
56
92
  });
57
93
 
58
94
  // ---- managed-file provenance (#164) --------------------------------------------------------
@@ -145,6 +181,7 @@ const displayTarget = (value) => {
145
181
  try { return JSON.stringify(value) ?? String(value); } catch { return String(value); }
146
182
  };
147
183
  const ideTargetError = (message) => Object.assign(new Error(message), { code: IDE_TARGET_ERROR_CODE });
184
+ const isDirectory = (full) => { try { return fs.statSync(full).isDirectory(); } catch { return false; } };
148
185
  const lstatIfPresent = (full) => {
149
186
  try {
150
187
  return fs.lstatSync(full);
@@ -282,7 +319,7 @@ export function safeIdeTargetStateFor(root, input) {
282
319
  // sight in a repo that uses Cursor for rules alone, and `.claude/` in one that only ever set
283
320
  // permissions. Detecting on the bare directory meant that adding `.cursor` to the supported list
284
321
  // silently enrolled every such project: no `ideTargets` in the stamp, so this fallback runs, `.cursor`
285
- // is "detected", and the next `yad check --fix` writes 38 skill folders into `.cursor/skills/`, adds
322
+ // is "detected", and the next `yad check --fix` writes 39 skill folders into `.cursor/skills/`, adds
286
323
  // `.cursor/hooks.json`, and stamps the target permanently — for a team that never asked. Requiring
287
324
  // `<ide>/skills/` (or `.opencode/commands/`) means detection finds only a directory yad already
288
325
  // installs into, which is the question this function was always trying to answer.
@@ -872,6 +909,14 @@ export function repoActions(root, repo) {
872
909
  || actions.some((a) => a.status !== 'missing' && a.item.startsWith('checks/'));
873
910
  const link = productLinkAction(root, repo, repoRoot);
874
911
  if (link) actions.push(link);
912
+ // E158: the short rules block, in a repo cloned here that is not the Product itself (a monorepo entry has
913
+ // the Product's full block in the same file). Not relabelled here: like the wiring, it is `new` for `yad
914
+ // update` only on a wired repo (below), so update never does a repo's one-time setup.
915
+ if (!samePath(repoRoot, path.resolve(root)) && isDirectory(repoRoot)) {
916
+ actions.push(...agentFileActions(repoRoot, ideTargetsFor(root), { scope: repo.name, lines: pointerBlock(), relabel: false }));
917
+ // E158b: the agent guard and the read-only allow list, so a session opened in the code repo has them too.
918
+ actions.push(...repoAgentGuardActions(repoRoot, ideTargetsFor(root), { scope: repo.name, ledger }));
919
+ }
875
920
  if (!wired) return actions;
876
921
  // The record is not a template: an absent one on a wired repo is always `new` (nothing to respect).
877
922
  const neverWritten = (a) => !a.managed || !ledger[rel(a.managed.root, a.managed.dest)];
@@ -1147,9 +1192,12 @@ export function hookMatcherFires(settings, adapter = CLAUDE_HOOK_ADAPTER) {
1147
1192
  // bytes against — the file belongs to the team and we own exactly one entry inside it. So it is also
1148
1193
  // deliberately NOT recorded in `.sdlc/managed.json` (recordManagedWrites only records a dest that
1149
1194
  // byte-matches its src); the marker above is its provenance instead.
1150
- function hookSettingsAction(root, adapter) {
1195
+ const unparsedSaid = new Set();
1196
+ // `where` names a connected code repo in the warnings (E158b); the Product's own files need no name.
1197
+ function hookSettingsAction(root, adapter, merge = (obj) => mergeHookSettings(obj, adapter), where = null) {
1151
1198
  const ide = adapter.target;
1152
1199
  const relDest = adapter.settings;
1200
+ const named = where ? `${where}/${relDest}` : relDest;
1153
1201
  const dest = path.join(root, relDest);
1154
1202
  const raw = exists(dest) ? fs.readFileSync(dest, 'utf8') : null;
1155
1203
  let parsed = null;
@@ -1165,7 +1213,10 @@ function hookSettingsAction(root, adapter) {
1165
1213
  // every other entry in that allowlist is a file yad wrote in full. This one the team co-owns, so
1166
1214
  // staging it wholesale would sweep their unrelated working-tree edits into a `chore(yad-update)`
1167
1215
  // commit pushed straight to the default branch, bypassing review. The entry is theirs to commit.
1168
- const base = { scope: ide, item: path.basename(relDest), root, paths: [] };
1216
+ // `shared` names the file for `yad update --open-pr`, which stages it only when the change is yad's alone
1217
+ // (reconcile; E157 update review 11): without it a merged update ships a hook script nothing runs.
1218
+ // `mergeShared` adds yad's entry to a settings object, so reconcile can tell a file that is yad's alone.
1219
+ const base = { scope: ide, item: path.basename(relDest), root, paths: [], shared: relDest, mergeShared: merge };
1169
1220
  // A settings file we cannot READ is never rewritten — not even by `--overwrite-local`.
1170
1221
  //
1171
1222
  // For a managed file, `--overwrite-local` restores the shipped template, which is coherent. Here
@@ -1179,15 +1230,19 @@ function hookSettingsAction(root, adapter) {
1179
1230
  // hand — "replace them with `yad update --overwrite-local`" — advice that can never clear this,
1180
1231
  // since this action deliberately writes nothing. The specific reason has to surface either way.
1181
1232
  if (unreadable) {
1182
- warn(`${relDest} does not parse — the ${adapter.label || 'ledger guard'} cannot be wired; fix the JSON, then re-run \`yad check --fix\``);
1183
- return { ...base, status: 'modified', apply: () => {} };
1233
+ // Said once per file, not once per action: up to four share `.claude/settings.json` (E158 review 1).
1234
+ if (!unparsedSaid.has(`${dest}\0${raw}`)) {
1235
+ unparsedSaid.add(`${dest}\0${raw}`);
1236
+ warn(`${named} does not parse — yad's entries in it (hooks, the read-only allow list) cannot be written; fix the JSON, then re-run \`yad check --fix\``);
1237
+ }
1238
+ return { ...base, status: 'modified', writesNothing: true, apply: () => {} };
1184
1239
  }
1185
- const { changed, unreadable: unmergeable } = mergeHookSettings(parsed, adapter);
1240
+ const { changed, unreadable: unmergeable } = merge(parsed);
1186
1241
  // Same treatment as a file that does not parse, and for the same reason: everything in it is the
1187
1242
  // team's, there is no shipped template to restore, and `--overwrite-local` must not invent one.
1188
1243
  if (unmergeable) {
1189
- warn(`${relDest}: ${unmergeable} — the ${adapter.label || 'ledger guard'} cannot be wired without discarding what is there; fix it by hand, then re-run \`yad check --fix\``);
1190
- return { ...base, status: 'modified', apply: () => {} };
1244
+ warn(`${named}: ${unmergeable} — the ${adapter.label || 'ledger guard'} cannot be wired without discarding what is there; fix it by hand, then re-run \`yad check --fix\``);
1245
+ return { ...base, status: 'modified', writesNothing: true, apply: () => {} };
1191
1246
  }
1192
1247
  return {
1193
1248
  ...base,
@@ -1209,23 +1264,91 @@ function hookSettingsAction(root, adapter) {
1209
1264
  let current;
1210
1265
  try { current = JSON.parse(fs.readFileSync(dest, 'utf8')); } catch { /* unreadable — refused below */ }
1211
1266
  if (!current || typeof current !== 'object' || Array.isArray(current)) {
1212
- warn(`${relDest} does not parse — left untouched; fix the JSON, then re-run \`yad check --fix\``);
1267
+ warn(`${named} does not parse — left untouched; fix the JSON, then re-run \`yad check --fix\``);
1213
1268
  return;
1214
1269
  }
1215
- const merged = mergeHookSettings(current, adapter);
1270
+ const merged = merge(current);
1216
1271
  if (merged.unreadable) {
1217
- warn(`${relDest}: ${merged.unreadable} — left untouched; fix it by hand, then re-run \`yad check --fix\``);
1272
+ warn(`${named}: ${merged.unreadable} — left untouched; fix it by hand, then re-run \`yad check --fix\``);
1218
1273
  return;
1219
1274
  }
1220
1275
  writeJSON(dest, merged.settings);
1221
1276
  return;
1222
1277
  }
1223
1278
  fs.mkdirSync(path.dirname(dest), { recursive: true });
1224
- writeJSON(dest, mergeHookSettings({}, adapter).settings);
1279
+ writeJSON(dest, merge({}).settings);
1225
1280
  },
1226
1281
  };
1227
1282
  }
1228
1283
 
1284
+ // A block yad owns inside a file the team owns (E158): AGENTS.md and CLAUDE.md. Like the agent settings file
1285
+ // above, the file is the team's, so `paths` is EMPTY (`yad update --push` never stages it) and `shared` names it
1286
+ // for `yad update --open-pr`, which stages it only when the change is yad's block alone (reconcile). It is
1287
+ // text, not JSON: `mergeShared` puts the block into a file's text.
1288
+ function blockState(dest, opts) {
1289
+ let raw = null;
1290
+ try {
1291
+ const st = lstatIfPresent(dest);
1292
+ if (st) raw = st.isFile() ? fs.readFileSync(dest, 'utf8') : undefined;
1293
+ } catch { raw = undefined; }
1294
+ // Not a plain file yad can read (a folder, a symbolic link that could point anywhere, no permission).
1295
+ if (raw === undefined) return { raw, state: 'unreadable', refused: 'it is not a file yad can read' };
1296
+ const now = applyMarkedBlock(raw, opts);
1297
+ if (now.refused) return { raw, state: 'refused', refused: now.refused };
1298
+ // A file with no block is `missing` too: the BLOCK is missing. So `yad update` adds it only where it adds
1299
+ // other missing files (the Product, a wired repo), never to the team's own AGENTS.md in a repo yad never set up.
1300
+ return { raw, state: now.status === 'ok' ? 'ok' : now.status === 'new' ? 'missing' : 'outdated', refused: null, exists: raw !== null };
1301
+ }
1302
+
1303
+ function markedBlockAction(root, relDest, lines, { scope = 'product' } = {}) {
1304
+ const dest = path.join(root, relDest);
1305
+ const opts = { ...AGENTS_MARKERS, lines };
1306
+ const base = { scope, item: relDest, root, paths: [], shared: relDest, kind: 'text', mergeShared: (text) => applyMarkedBlock(text, opts) };
1307
+ const { state, refused } = blockState(dest, opts);
1308
+ // Never written, said once at plan time. Markers yad cannot trust are never guessed around: the team's
1309
+ // text is left as it is (as a broken config.yaml region is, cli/lifecycle.mjs).
1310
+ if (refused) {
1311
+ warn(`${scope}/${relDest}: ${refused} — the yadflow rules block was left out; ${state === 'refused' ? 'fix the markers (or delete both to have the block added again)' : 'make it a plain file'}, then re-run \`yad check --fix\``);
1312
+ return { ...base, status: 'modified', writesNothing: true, apply: () => {} };
1313
+ }
1314
+ return {
1315
+ ...base,
1316
+ status: state,
1317
+ // Re-read at apply() time: the file may have been written since the plan was built.
1318
+ apply: () => {
1319
+ const now = blockState(dest, opts);
1320
+ if (now.refused) { warn(`${scope}/${relDest}: ${now.refused} — left untouched`); return; }
1321
+ if (now.state === 'ok') return;
1322
+ const next = applyMarkedBlock(now.raw, opts);
1323
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
1324
+ fs.writeFileSync(dest, next.text);
1325
+ },
1326
+ };
1327
+ }
1328
+
1329
+ // The always-read instruction files (E158): AGENTS.md with yad's rules block, which Codex, Cursor, Copilot and
1330
+ // Gemini read, and, for a project that installs for Claude Code, CLAUDE.md importing it. `lines` is the
1331
+ // Product's full block by default; a connected code repo gets the short pointer block (`repoActions`).
1332
+ // Relabelled `new`, so `yad update` brings them to an install that predates them.
1333
+ export function agentFileActions(root, ideTargets = ideTargetsFor(root), { scope = 'product', lines = agentsBlock(), relabel = true } = {}) {
1334
+ const actions = [markedBlockAction(root, 'AGENTS.md', lines, { scope })];
1335
+ // Only the target's name is read here: nothing is written under it.
1336
+ if (canonicalIdeTargets(ideTargets).includes('.claude')) actions.push(markedBlockAction(root, 'CLAUDE.md', claudeBlock(), { scope }));
1337
+ return relabel ? actions.map(asNew) : actions;
1338
+ }
1339
+
1340
+ // The same files, for `yad doctor`: each one's state, with nothing printed. `state` is ok | outdated | missing (no
1341
+ // block; `exists` says whether the file is there) | refused (markers yad cannot trust) | unreadable (not a plain
1342
+ // file).
1343
+ export function agentFilesState(root, ideTargets = ideTargetsFor(root), lines = agentsBlock()) {
1344
+ const files = [['AGENTS.md', lines]];
1345
+ if (canonicalIdeTargets(ideTargets).includes('.claude')) files.push(['CLAUDE.md', claudeBlock()]);
1346
+ return files.map(([file, l]) => {
1347
+ const { state, refused, exists = true } = blockState(path.join(root, file), { ...AGENTS_MARKERS, lines: l });
1348
+ return { file, state, refused, exists };
1349
+ });
1350
+ }
1351
+
1229
1352
  // Harness-hook wiring on the Product: the guard script plus, per IDE target that defines a hook protocol,
1230
1353
  // the entry that invokes it. Verified-only exactly like `productActions` — with a local ledger it is
1231
1354
  // locally owned, the hand-edit the authoring skills describe is CORRECT, and a guard would be wrong.
@@ -1340,14 +1463,25 @@ export function orphanHookActions(root, ideTargets = ideTargetsFor(root)) {
1340
1463
  // and `yad check` print it.
1341
1464
  export const GIT_HOOK_MARKER = '# yadflow ledger-guard (E48)';
1342
1465
  const shQuote = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
1343
- export function gitPreCommitScript(prefix = '') {
1466
+ // The last two comment lines of the script, today's first. The earlier ones are kept so a copy yad wrote
1467
+ // before is still known as yad's own (`orphanGitHookActions` removes only yad's bytes).
1468
+ const PRE_COMMIT_NOTES = [
1469
+ ['# node, or no guard script, it allows. A person can skip it once with YAD_HOOK_DISABLE=1 (never an AI',
1470
+ '# agent). Git runs it from the top of the repo. yad rewrites this file; to stop it, delete the file.'],
1471
+ // Up to E158.
1472
+ ['# node, or no guard script, it allows. Skip it once with YAD_HOOK_DISABLE=1. Git runs it from the top',
1473
+ '# of the repo. yad rewrites this file; to stop it, delete the file.'],
1474
+ ];
1475
+ export const gitPreCommitScript = (prefix = '') => preCommitScript(prefix, PRE_COMMIT_NOTES[0]);
1476
+ // Every text yad has written for this hook, today's first.
1477
+ export const gitPreCommitScripts = (prefix = '') => PRE_COMMIT_NOTES.map((notes) => preCommitScript(prefix, notes));
1478
+ function preCommitScript(prefix, notes) {
1344
1479
  return [
1345
1480
  '#!/bin/sh',
1346
1481
  `${GIT_HOOK_MARKER} — installed in this clone by \`yad check --fix\`.`,
1347
1482
  '# Refuses a commit that changes a file only CI may change on a verified Product (the gate ledger and',
1348
1483
  '# the Product index), the same files the `ledger-guard` check in CI refuses. It fails open: with no',
1349
- '# node, or no guard script, it allows. Skip it once with YAD_HOOK_DISABLE=1. Git runs it from the top',
1350
- '# of the repo. yad rewrites this file; to stop it, delete the file.',
1484
+ ...notes,
1351
1485
  `guard=${shQuote(`${prefix}hooks/ledger-guard.mjs`)}`,
1352
1486
  'command -v node >/dev/null 2>&1 || exit 0',
1353
1487
  '[ -f "$guard" ] || exit 0',
@@ -1405,7 +1539,9 @@ export function gitHookState(root) {
1405
1539
  let runnable = true;
1406
1540
  if (process.platform !== 'win32') { try { runnable = (fs.statSync(file).mode & 0o111) !== 0; } catch { runnable = false; } }
1407
1541
  if (text === expected && runnable) return { applies: true, file, expected, prefix, state: 'ok' };
1408
- return { applies: true, file, expected, prefix, state: 'outdated', why: text === expected ? 'not-executable' : 'changed' };
1542
+ // `earlier`: a text an earlier yad wrote, so nothing in it is anyone's edit.
1543
+ const why = text === expected ? 'not-executable' : gitPreCommitScripts(prefix).includes(text) ? 'earlier' : 'changed';
1544
+ return { applies: true, file, expected, prefix, state: 'outdated', why };
1409
1545
  }
1410
1546
 
1411
1547
  // The install action. 'foreign' and 'hooks-path' build no action — there is nothing yad may write —
@@ -1416,9 +1552,8 @@ export function gitHookActions(root) {
1416
1552
  const status = st.state === 'missing' ? 'new' : st.state;
1417
1553
  // An outdated copy may carry a person's edit below our marker, so it is saved beside itself first —
1418
1554
  // the same rule `wiredFileAction` keeps for content it cannot prove it wrote. Not when only the execute
1419
- // bit is missing: nothing of anyone's is being replaced then.
1420
- const sameBytes = st.state === 'outdated' && (() => { try { return fs.readFileSync(st.file, 'utf8') === st.expected; } catch { return false; } })();
1421
- const backup = st.state === 'outdated' && !sameBytes ? backupPathFor(st.file) : null;
1555
+ // bit is missing, nor when it is a text an earlier yad wrote: nothing of anyone's is being replaced then.
1556
+ const backup = st.state === 'outdated' && st.why === 'changed' ? backupPathFor(st.file) : null;
1422
1557
  return [{
1423
1558
  scope: 'product',
1424
1559
  item: 'pre-commit git hook (this clone)',
@@ -1445,7 +1580,7 @@ export function orphanGitHookActions(root) {
1445
1580
  const file = path.resolve(root, hookRel);
1446
1581
  let text;
1447
1582
  try { text = fs.readFileSync(file, 'utf8'); } catch { return []; }
1448
- if (text !== gitPreCommitScript(prefix)) return [];
1583
+ if (!gitPreCommitScripts(prefix).includes(text)) return [];
1449
1584
  return [{ scope: 'product', item: 'pre-commit git hook (this clone) (removed)', status: 'removed', root, paths: [], apply: () => fs.rmSync(file, { force: true }) }];
1450
1585
  }
1451
1586
 
@@ -1527,6 +1662,175 @@ export function orphanCaptureHookActions(root, ideTargets = ideTargetsFor(root))
1527
1662
  return actions;
1528
1663
  }
1529
1664
 
1665
+ // The read-only yad commands, pre-approved for Claude Code (E158, issue #353): `readAllowList` added to
1666
+ // `permissions.allow` in `.claude/settings.json`. Additive: the team's own entries are kept, and an entry of
1667
+ // ours already there is not added twice. A shape it cannot read is refused, as the hook merge refuses one.
1668
+ export function mergeAllowList(input) {
1669
+ if (isPlainObject(input)) {
1670
+ if (Object.hasOwn(input, 'permissions') && !isPlainObject(input.permissions)) return { settings: input, changed: false, unreadable: 'permissions is not an object' };
1671
+ if (isPlainObject(input.permissions) && Object.hasOwn(input.permissions, 'allow') && !Array.isArray(input.permissions.allow)) {
1672
+ return { settings: input, changed: false, unreadable: 'permissions.allow is not a list' };
1673
+ }
1674
+ }
1675
+ const settings = { ...(isPlainObject(input) ? input : {}) };
1676
+ const permissions = { ...(isPlainObject(settings.permissions) ? settings.permissions : {}) };
1677
+ const allow = Array.isArray(permissions.allow) ? [...permissions.allow] : [];
1678
+ const missing = readAllowList().filter((e) => !allow.includes(e));
1679
+ if (!missing.length) return { settings, changed: false };
1680
+ permissions.allow = [...allow, ...missing];
1681
+ settings.permissions = permissions;
1682
+ return { settings, changed: true };
1683
+ }
1684
+
1685
+ // The settings action that writes it, for a configured Product that installs for Claude Code.
1686
+ export const ALLOW_LIST_ADAPTER = Object.freeze({ target: '.claude', settings: '.claude/settings.json', label: 'read-only yad allow list' });
1687
+ export function allowListActions(root, ideTargets = ideTargetsFor(root)) {
1688
+ if (!exists(productConfigPath(root)) || !safeIdeTargetsFor(root, ideTargets).includes('.claude')) return [];
1689
+ return [asNew(allowListAction(root))];
1690
+ }
1691
+ // `allowList` marks it for setup, which shows the list before it is first written.
1692
+ const allowListAction = (at) => ({ ...hookSettingsAction(at, ALLOW_LIST_ADAPTER, mergeAllowList), item: `${path.basename(ALLOW_LIST_ADAPTER.settings)} (read-only yad commands)`, allowList: true });
1693
+
1694
+ // yad's allow-list entries that should no longer be there: all of them once `.claude` has left the IDE targets,
1695
+ // and, while it is a target, those a later yadflow stopped pre-approving (`RETIRED_ALLOW_ENTRIES`). Only these
1696
+ // exact strings come out; every other entry is the team's and stays. A file that does not parse is left alone.
1697
+ //
1698
+ // A team may type one of yad's strings by hand (`Bash(yad status:*)`), so with `.claude` gone the list comes out
1699
+ // only when ALL the entries of a list yad wrote are there (today's, or one an older release wrote and no
1700
+ // `check --fix` brought up to date, `SHIPPED_ALLOW_LISTS`): that is yad's list, not a hand-picked line.
1701
+ export function orphanAllowListActions(root, ideTargets = ideTargetsFor(root)) {
1702
+ if (!exists(productConfigPath(root))) return [];
1703
+ return allowListOrphans(root, safeIdeTargetsFor(root, ideTargets).includes('.claude'));
1704
+ }
1705
+ // `kept`: `.claude` is still a target. `scope`: the line's scope in the report (a code repo's name, E158b).
1706
+ function allowListOrphans(root, kept, scope = ALLOW_LIST_ADAPTER.target) {
1707
+ const file = path.join(root, ALLOW_LIST_ADAPTER.settings);
1708
+ if (!exists(file)) return [];
1709
+ let wholeList = false;
1710
+ if (!kept) {
1711
+ try {
1712
+ const allow = JSON.parse(fs.readFileSync(file, 'utf8'))?.permissions?.allow;
1713
+ wholeList = Array.isArray(allow) && [readAllowList(), ...SHIPPED_ALLOW_LISTS].some((list) => list.every((e) => allow.includes(e)));
1714
+ } catch { return []; }
1715
+ }
1716
+ const gone = new Set(wholeList ? [...readAllowList(), ...SHIPPED_ALLOW_LISTS.flat(), ...RETIRED_ALLOW_ENTRIES] : RETIRED_ALLOW_ENTRIES);
1717
+ if (!gone.size) return [];
1718
+ const without = (obj) => {
1719
+ if (!isPlainObject(obj) || !isPlainObject(obj.permissions) || !Array.isArray(obj.permissions.allow)) return null;
1720
+ const allow = obj.permissions.allow.filter((e) => !gone.has(e));
1721
+ return allow.length === obj.permissions.allow.length ? null : { ...obj, permissions: { ...obj.permissions, allow } };
1722
+ };
1723
+ let parsed;
1724
+ try { parsed = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return []; }
1725
+ if (!without(parsed)) return [];
1726
+ return [{
1727
+ scope,
1728
+ item: `${path.basename(file)} (read-only yad commands removed)`,
1729
+ status: 'removed',
1730
+ root,
1731
+ paths: [],
1732
+ apply: () => {
1733
+ let current;
1734
+ try { current = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return; }
1735
+ const next = without(current);
1736
+ if (next) writeJSON(file, next);
1737
+ },
1738
+ }];
1739
+ }
1740
+
1741
+ // The agent guard (E158): the script, and per IDE target with a hook protocol the entry that runs it before
1742
+ // every shell command the agent sends. On every configured Product, in both ledger modes (see the manifest).
1743
+ // The script and its entries land together, for the reason `hookActions` gives.
1744
+ export function agentGuardActions(root, ideTargets = ideTargetsFor(root)) {
1745
+ if (!exists(productConfigPath(root))) return [];
1746
+ const ledger = readManagedLedger(root);
1747
+ const actions = AGENT_GUARD_WIRING.map((w) =>
1748
+ wiredFileAction('product', w.dest, asset(w.src), path.join(root, w.dest), { root, exec: !!w.exec, ledger }),
1749
+ );
1750
+ for (const ide of safeIdeTargetsFor(root, ideTargets)) {
1751
+ const adapter = AGENT_GUARD_ADAPTERS[ide];
1752
+ if (adapter) actions.push(hookSettingsAction(root, adapter));
1753
+ }
1754
+ return actions.map(asNew);
1755
+ }
1756
+
1757
+ // An agent-guard entry for a target that left `ideTargets`: only OUR entry comes out, as
1758
+ // `orphanCaptureHookActions` does it. The script stays while the Product is configured (a remaining target
1759
+ // may still run it; with none, it is one file nothing runs, and `yad check` names nothing wrong with it).
1760
+ export function orphanAgentGuardActions(root, ideTargets = ideTargetsFor(root)) {
1761
+ if (!exists(productConfigPath(root))) return [];
1762
+ return agentGuardOrphans(root, new Set(safeIdeTargetsFor(root, ideTargets)), AGENT_GUARD_ADAPTERS);
1763
+ }
1764
+ function agentGuardOrphans(root, kept, adapters, scope = null) {
1765
+ const actions = [];
1766
+ for (const adapter of Object.values(adapters)) {
1767
+ if (kept.has(adapter.target)) continue;
1768
+ const settingsPath = path.join(root, adapter.settings);
1769
+ if (!exists(settingsPath)) continue;
1770
+ let parsed;
1771
+ try { parsed = JSON.parse(fs.readFileSync(settingsPath, 'utf8')); } catch { continue; }
1772
+ if (!isPlainObject(parsed) || !unmergeHookSettings(parsed, adapter).changed) continue;
1773
+ actions.push({
1774
+ scope: scope || adapter.target,
1775
+ item: `${path.basename(adapter.settings)} (agent guard entry removed)`,
1776
+ status: 'removed',
1777
+ root,
1778
+ paths: [],
1779
+ apply: () => {
1780
+ let current;
1781
+ try { current = JSON.parse(fs.readFileSync(settingsPath, 'utf8')); } catch { return; }
1782
+ if (!isPlainObject(current)) return;
1783
+ const { settings, changed } = unmergeHookSettings(current, adapter);
1784
+ if (changed) writeJSON(settingsPath, settings);
1785
+ },
1786
+ });
1787
+ }
1788
+ return actions;
1789
+ }
1790
+
1791
+ // E158b: the agent guard and the read-only allow list in a connected code repo, so a session opened there has
1792
+ // them too. The script goes in `checks/` (REPO_AGENT_GUARD_DEST); the entries go in the repo's own settings
1793
+ // files, which stay the team's: `paths` is empty, so `--push` never stages them, and `--open-pr` stages one only
1794
+ // when the change is yad's alone (reconcile). The tools are the Product's IDE targets, as CLAUDE.md's are. A
1795
+ // target folder in the repo that is a link or a file is named and skipped, never written through. Not
1796
+ // relabelled here: `repoActions` makes them `new` for `yad update` only on a wired repo.
1797
+ export function repoAgentGuardActions(repoRoot, ideTargets, { scope, ledger = readManagedLedger(repoRoot) }) {
1798
+ const targets = repoTargets(repoRoot, ideTargets, scope);
1799
+ const adapters = agentGuardAdapters(REPO_AGENT_GUARD_DEST);
1800
+ const settings = targets.filter((ide) => adapters[ide]).map((ide) => ({ ...hookSettingsAction(repoRoot, adapters[ide], undefined, scope), scope, item: `${adapters[ide].settings} (agent guard)` }));
1801
+ if (targets.includes('.claude')) settings.push({ ...hookSettingsAction(repoRoot, ALLOW_LIST_ADAPTER, mergeAllowList, scope), scope, item: `${ALLOW_LIST_ADAPTER.settings} (read-only yad commands)`, allowList: true });
1802
+ if (!settings.length) return [];
1803
+ const script = AGENT_GUARD_WIRING[0];
1804
+ return [wiredFileAction(scope, REPO_AGENT_GUARD_DEST, asset(script.src), path.join(repoRoot, REPO_AGENT_GUARD_DEST), { root: repoRoot, ledger }), ...settings];
1805
+ }
1806
+
1807
+ // The same entries for a target that left, in a connected code repo: only yad's come out. The script stays.
1808
+ // A tool folder that is a link or not a folder is never written through — a target or not: removing an entry
1809
+ // would change the file the link points at (the Product's own, when it points there).
1810
+ export function repoOrphanAgentGuardActions(repoRoot, ideTargets, { scope }) {
1811
+ if (!isDirectory(repoRoot)) return [];
1812
+ const kept = new Set(repoTargets(repoRoot, ideTargets, null));
1813
+ const linked = (ide) => { const st = lstatIfPresent(path.join(repoRoot, ide)); return !!st && (st.isSymbolicLink() || !st.isDirectory()); };
1814
+ const adapters = Object.fromEntries(Object.entries(agentGuardAdapters(REPO_AGENT_GUARD_DEST)).filter(([ide]) => !linked(ide)));
1815
+ return [
1816
+ ...agentGuardOrphans(repoRoot, kept, adapters, scope),
1817
+ ...(linked('.claude') ? [] : allowListOrphans(repoRoot, kept.has('.claude'), scope)),
1818
+ ];
1819
+ }
1820
+
1821
+ // The Product's IDE targets that are safe to write through in a code repo. An unsafe one is named once (when
1822
+ // `scope` is given) and left out.
1823
+ const unsafeRepoSaid = new Set();
1824
+ function repoTargets(repoRoot, ideTargets, scope) {
1825
+ const { targets, unsafe } = safeIdeTargetStateFor(repoRoot, ideTargets);
1826
+ for (const u of unsafe) {
1827
+ if (!scope || unsafeRepoSaid.has(`${repoRoot}\0${u.target}`)) continue;
1828
+ unsafeRepoSaid.add(`${repoRoot}\0${u.target}`);
1829
+ warn(`${scope}: ${u.message} — the agent guard and the read-only allow list are not written there`);
1830
+ }
1831
+ return targets;
1832
+ }
1833
+
1530
1834
  // ---- the shell-script hooks, retired (E113) -----------------------------------------------------------
1531
1835
  //
1532
1836
  // Every hook was a bash script until E113; each is now a Node script, and the adapters list the old
@@ -714,3 +714,53 @@ function unknownHint(r) {
714
714
  default: return 'fix what the message names, then run `yad doctor` again; nothing about this repo\'s protection is assumed meanwhile';
715
715
  }
716
716
  }
717
+
718
+ // 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
720
+ // never "none". `readProtection` runs first, so a repo that cannot be read (no platform, reads turned off,
721
+ // no login…) comes back with only `protection`, and every platform row is "not known" with its reason.
722
+ // GitHub — `rules`: the active rules on the branch (null when not read; `full` when a whole page came
723
+ // back, which proves nothing about what is past it). `classic`: classic branch protection, the
724
+ // string 'none' when PROVEN absent (the branch reads `protected: false`, or GitHub answers 404 with
725
+ // exactly "Branch not protected"), or null — GitHub answers a bare 404 to anyone who is not an
726
+ // admin, even on a protected branch.
727
+ // GitLab — the project's merge settings, the protected-branch entries that match the branch (null when not
728
+ // read), the approval settings (Premium) and the push rule (Premium; a 404 is "no push rule").
729
+ export function readCiSettings(target, { runner: ask = run, env = process.env, authCache = new Map() } = {}) {
730
+ // One answer per call for this repo: `readProtection` and the reads below ask some of the same paths, and
731
+ // two answers to one question could disagree.
732
+ const answers = new Map();
733
+ const runner = (cmd, args, opts) => {
734
+ if (args[0] !== 'api') return ask(cmd, args, opts);
735
+ const key = [cmd, ...args].join('\0');
736
+ if (!answers.has(key)) answers.set(key, ask(cmd, args, opts));
737
+ return answers.get(key);
738
+ };
739
+ const protection = readProtection(target, { runner, env, authCache });
740
+ if (!protection.known) return { protection };
741
+ const { platform, host, repo, branch } = protection;
742
+ if (platform === 'github') {
743
+ const at = `repos/${repo.split('/').map(encodeURIComponent).join('/')}`;
744
+ const r = api(runner, 'gh', host, `${at}/rules/branches/${segment(branch)}?per_page=${PAGE}`);
745
+ const rules = r.ok && Array.isArray(r.body) ? r.body : null;
746
+ let classic = null;
747
+ if (protection.protected === false) classic = 'none';
748
+ else {
749
+ const c = api(runner, 'gh', host, `${at}/branches/${segment(branch)}/protection`);
750
+ if (c.ok && c.body && typeof c.body === 'object' && !Array.isArray(c.body)) classic = c.body;
751
+ else if (c.status === 404 && c.body?.message === 'Branch not protected') classic = 'none';
752
+ }
753
+ return { protection, rules, rulesFull: !!rules && rules.length >= PAGE, classic };
754
+ }
755
+ const at = `projects/${encodeURIComponent(repo)}`;
756
+ const obj = (res) => (res.ok && res.body && typeof res.body === 'object' && !Array.isArray(res.body) ? res.body : null);
757
+ const project = obj(api(runner, 'glab', host, at));
758
+ const pb = api(runner, 'glab', host, `${at}/protected_branches?per_page=${PAGE}`);
759
+ const list = pb.ok && Array.isArray(pb.body) ? pb.body : null;
760
+ const matched = list ? list.filter((p) => branchMatches(p?.name, branch)) : null;
761
+ const approvals = obj(api(runner, 'glab', host, `${at}/approvals`));
762
+ const pr = api(runner, 'glab', host, `${at}/push_rule`);
763
+ // No push rule is set: GitLab answers 404, or (on some versions) 200 with an empty body.
764
+ const pushRule = obj(pr) ?? (pr.ok || pr.status === 404 ? 'none' : null);
765
+ return { protection, project, matched, matchedFull: !!list && list.length >= PAGE, approvals, pushRule };
766
+ }