mandrel 2.94.0 → 2.95.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 (110) hide show
  1. package/.agents/runtime-deps.json +6 -6
  2. package/.agents/scripts/agents-bootstrap-github.js +1 -1
  3. package/.agents/scripts/board-backfill.js +1 -1
  4. package/.agents/scripts/boot-sweep.js +1 -1
  5. package/.agents/scripts/check-arch-cycles.js +69 -41
  6. package/.agents/scripts/check-doc-links.js +5 -7
  7. package/.agents/scripts/check-gherkin-corpus.js +2 -11
  8. package/.agents/scripts/clean-temp.js +1 -1
  9. package/.agents/scripts/cleanup-repo-test-temp.js +1 -1
  10. package/.agents/scripts/diagnose-friction.js +1 -1
  11. package/.agents/scripts/generate-lens-checklists.js +4 -4
  12. package/.agents/scripts/generate-skills-index.js +3 -2
  13. package/.agents/scripts/generate-workflows-doc.js +2 -1
  14. package/.agents/scripts/lib/audit-baselines/read.js +2 -1
  15. package/.agents/scripts/lib/audit-exceptions/adapters/tool-config.js +13 -3
  16. package/.agents/scripts/lib/audit-exceptions/globs.js +12 -1
  17. package/.agents/scripts/lib/audit-exceptions/probe.js +24 -2
  18. package/.agents/scripts/lib/audit-exceptions/read.js +2 -2
  19. package/.agents/scripts/lib/audit-to-stories/group-findings.js +77 -67
  20. package/.agents/scripts/lib/baselines/components.js +21 -19
  21. package/.agents/scripts/lib/baselines/duplication-scanner.js +4 -8
  22. package/.agents/scripts/lib/baselines/kinds/maintainability.js +2 -3
  23. package/.agents/scripts/lib/baselines/preview-gates.js +2 -2
  24. package/.agents/scripts/lib/baselines/refresh-service.js +4 -7
  25. package/.agents/scripts/lib/baselines/writer.js +2 -7
  26. package/.agents/scripts/lib/bdd-runner-detect.js +2 -2
  27. package/.agents/scripts/lib/bdd-step-index.js +3 -7
  28. package/.agents/scripts/lib/bootstrap/baseline-merge-driver.js +11 -7
  29. package/.agents/scripts/lib/bootstrap/install-ledger.js +19 -4
  30. package/.agents/scripts/lib/bootstrap/json-io.js +14 -0
  31. package/.agents/scripts/lib/bootstrap/project-bootstrap.js +20 -44
  32. package/.agents/scripts/lib/bootstrap/quality-bootstrap.js +38 -54
  33. package/.agents/scripts/lib/branch-name-guard.js +2 -3
  34. package/.agents/scripts/lib/claude/agents-projection.js +1 -12
  35. package/.agents/scripts/lib/codex/agents-projection.js +2 -5
  36. package/.agents/scripts/lib/codex/skills-projection.js +4 -12
  37. package/.agents/scripts/lib/config/defaults.js +2 -1
  38. package/.agents/scripts/lib/config/qa.js +4 -5
  39. package/.agents/scripts/lib/config-schema.js +1 -8
  40. package/.agents/scripts/lib/config-settings-schema.js +0 -3
  41. package/.agents/scripts/lib/coverage-baseline.js +2 -3
  42. package/.agents/scripts/lib/coverage-utils.js +2 -1
  43. package/.agents/scripts/lib/cpu-pool.js +0 -1
  44. package/.agents/scripts/lib/cyclomatic-scope.js +2 -1
  45. package/.agents/scripts/lib/doc-tiers.js +2 -1
  46. package/.agents/scripts/lib/gh-exec.js +21 -1
  47. package/.agents/scripts/lib/git/sync-from-base.js +1 -1
  48. package/.agents/scripts/lib/import-graph.js +13 -28
  49. package/.agents/scripts/lib/json-utils.js +11 -0
  50. package/.agents/scripts/lib/label-constants.js +7 -1
  51. package/.agents/scripts/lib/maintainability-utils.js +14 -22
  52. package/.agents/scripts/lib/observability/runtime-friction.js +37 -1
  53. package/.agents/scripts/lib/orchestration/check-baselines/phases/parse-args.js +25 -1
  54. package/.agents/scripts/lib/orchestration/ci-rerun-guard.js +9 -12
  55. package/.agents/scripts/lib/orchestration/code-review.js +1 -6
  56. package/.agents/scripts/lib/orchestration/deliver-recover.js +2 -1
  57. package/.agents/scripts/lib/orchestration/git-cleanup/phases/fast-forward.js +7 -14
  58. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes-ff.js +2 -21
  59. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes.js +11 -20
  60. package/.agents/scripts/lib/orchestration/git-cleanup/phases/phase-drivers.js +65 -86
  61. package/.agents/scripts/lib/orchestration/git-cleanup/phases/prompts.js +2 -2
  62. package/.agents/scripts/lib/orchestration/git-cleanup/phases/stashes.js +15 -6
  63. package/.agents/scripts/lib/orchestration/lifecycle/emit-merge-unlanded.js +5 -2
  64. package/.agents/scripts/lib/orchestration/merge-block-class.js +47 -48
  65. package/.agents/scripts/lib/orchestration/plan-persist/run-plan-persist.js +20 -1
  66. package/.agents/scripts/lib/orchestration/review-providers/claude-verdict.js +2 -3
  67. package/.agents/scripts/lib/orchestration/review-providers/parse-findings.js +4 -2
  68. package/.agents/scripts/lib/orchestration/story-close/baseline-upward-writeback.js +2 -2
  69. package/.agents/scripts/lib/orchestration/story-close/ratchet-shrink-writeback.js +3 -3
  70. package/.agents/scripts/lib/orchestration/story-handoff.js +18 -5
  71. package/.agents/scripts/lib/orchestration/ticketing/transition.js +17 -21
  72. package/.agents/scripts/lib/runtime-deps/dep-resolution.js +19 -5
  73. package/.agents/scripts/lib/runtime-deps/scan-imports.js +4 -10
  74. package/.agents/scripts/lib/skills/parse-skill.js +2 -2
  75. package/.agents/scripts/lib/skills/walk-skill-files.js +7 -23
  76. package/.agents/scripts/lib/story-body/story-body.js +4 -14
  77. package/.agents/scripts/lib/util/atomic-write.js +14 -3
  78. package/.agents/scripts/lib/util/regex.js +4 -0
  79. package/.agents/scripts/notify.js +1 -1
  80. package/.agents/scripts/plan-context.js +1 -1
  81. package/.agents/scripts/plan-critics.js +3 -11
  82. package/.agents/scripts/providers/github/auth.js +0 -4
  83. package/.agents/scripts/providers/github/project-board.js +0 -1
  84. package/.agents/scripts/providers/github/tickets.js +0 -2
  85. package/.agents/scripts/resync-status-column.js +1 -1
  86. package/.agents/scripts/run-tests.js +1 -1
  87. package/.agents/scripts/test-wrapper.js +1 -1
  88. package/.agents/scripts/update-ticket-state.js +4 -3
  89. package/.agents/scripts/validate-skills.js +2 -1
  90. package/.agents/skills/core/gates-and-baselines/reference.md +1 -0
  91. package/.agents/workflows/audit-baselines.md +21 -9
  92. package/.agents/workflows/clean-git.md +1 -1
  93. package/.agents/workflows/helpers/audit-lens-core.md +1 -1
  94. package/.agents/workflows/helpers/code-quality-guardrails.md +3 -3
  95. package/README.md +1 -1
  96. package/docs/CHANGELOG.md +34 -0
  97. package/lib/cli/claude-code-version.js +13 -7
  98. package/lib/cli/doctor-checks/llm-review.js +12 -5
  99. package/lib/cli/doctor-checks/merge-driver.js +10 -6
  100. package/lib/cli/doctor-checks/project-access.js +21 -8
  101. package/lib/cli/doctor-checks/read-json.js +2 -15
  102. package/lib/cli/doctor-checks/spawn.js +29 -9
  103. package/lib/cli/doctor-checks/test-credit-path.js +2 -1
  104. package/lib/cli/doctor-checks/toolchain.js +16 -12
  105. package/lib/cli/doctor.js +31 -8
  106. package/lib/cli/registry.js +7 -10
  107. package/lib/cli/sync.js +46 -10
  108. package/lib/cli/uninstall.js +259 -175
  109. package/lib/cli/update.js +3 -3
  110. package/package.json +23 -20
@@ -45,6 +45,7 @@ import { getStoryBranch, gitSpawn } from '../git-utils.js';
45
45
  import { readPackageScripts } from '../npm-scripts.js';
46
46
  import { TIMEOUT_EXIT_CODE } from '../process-group.js';
47
47
  import { describeBlocking } from '../suite-admission.js';
48
+ import { writeFileAtomic } from '../util/atomic-write.js';
48
49
  import { defaultSleep } from '../util/sleep.js';
49
50
  import { runStreamed } from './evidence-stream.js';
50
51
  import { probeHeldReviewDiff } from './review-deposit.js';
@@ -817,15 +818,28 @@ function precheck(ctx) {
817
818
  }
818
819
 
819
820
  /**
821
+ * `{}` when absent or corrupt; a corrupt file is reported.
822
+ *
820
823
  * @param {string} statePath
824
+ * @param {(tag: string, msg: string) => void} progress
821
825
  * @returns {{ preflightHead?: string, creditHead?: string, seatHead?: string }}
822
826
  */
823
- function readState(statePath) {
827
+ function readState(statePath, progress) {
828
+ let raw;
824
829
  try {
825
- return JSON.parse(fs.readFileSync(statePath, 'utf8'))?.state ?? {};
830
+ raw = fs.readFileSync(statePath, 'utf8');
826
831
  } catch {
827
832
  return {};
828
833
  }
834
+ try {
835
+ return JSON.parse(raw)?.state ?? {};
836
+ } catch (err) {
837
+ progress(
838
+ 'STATE',
839
+ `⚠️ ignoring corrupt ${statePath} (${err.message}) — every step re-runs`,
840
+ );
841
+ return {};
842
+ }
829
843
  }
830
844
 
831
845
  /**
@@ -945,7 +959,7 @@ export async function runStoryHandoff({ storyId, cwd, config }, deps) {
945
959
  sleep,
946
960
  lockPollMs,
947
961
  env,
948
- state: readState(statePath),
962
+ state: readState(statePath, progress),
949
963
  review: null,
950
964
  reviewPath: storyReviewDepositPath(storyId, config),
951
965
  depositor: selectCreditedDepositor({
@@ -1008,10 +1022,9 @@ export async function runStoryHandoff({ storyId, cwd, config }, deps) {
1008
1022
  }
1009
1023
  : {}),
1010
1024
  };
1011
- fs.writeFileSync(
1025
+ writeFileAtomic(
1012
1026
  statePath,
1013
1027
  `${JSON.stringify({ state: ctx.state, envelope }, null, 2)}\n`,
1014
- 'utf8',
1015
1028
  );
1016
1029
  return { envelope, exitCode: EXIT_CODES[status] };
1017
1030
  }
@@ -9,12 +9,14 @@
9
9
 
10
10
  import { extractEpicIdFromBody } from '../../dependency-parser.js';
11
11
  import { Logger } from '../../Logger.js';
12
+ import { AGENT_LABELS } from '../../label-constants.js';
12
13
  import {
13
14
  eventSeverity,
14
15
  renderTransitionMessage,
15
16
  } from '../../notifications/notifier.js';
16
17
  import {
17
18
  emitBlockRecoveredFriction,
19
+ emitInvalidTransitionFriction,
18
20
  emitRuntimeFriction,
19
21
  RUNTIME_FRICTION_CATEGORIES,
20
22
  } from '../../observability/runtime-friction.js';
@@ -76,26 +78,22 @@ function validateTransitionInputs(newState) {
76
78
  */
77
79
  const BLOCK_RECOVERY_TARGETS = [STATE_LABELS.EXECUTING, STATE_LABELS.READY];
78
80
 
81
+ /** The observer also reads a `review-spec` origin; a lifecycle state wins. */
82
+ const OBSERVED_STATES = Object.values(AGENT_LABELS);
83
+
79
84
  /**
80
- * Resolve the pre-transition snapshot, honoring `opts.ticketSnapshot`. Loaded
81
- * only when `notify` needs `fromState` or `needFromState` is set (recovery
82
- * detection must read the prior label before `updateTicket` overwrites it).
83
- * Returns `null` on transient failure.
85
+ * Resolve the pre-transition snapshot, honoring `opts.ticketSnapshot`; the
86
+ * provider's label merge reuses it instead of its own read. Returns `null`
87
+ * on transient failure.
84
88
  *
85
89
  * @param {object} provider
86
- * @param {{ notify?: Function, ticketSnapshot?: object|null }} opts
90
+ * @param {{ ticketSnapshot?: object|null }} opts
87
91
  * @param {number} ticketId
88
- * @param {boolean} [needFromState]
89
92
  * @returns {Promise<object|null>}
90
93
  */
91
- async function loadTicketSnapshot(provider, opts, ticketId, needFromState) {
94
+ async function loadTicketSnapshot(provider, opts, ticketId) {
92
95
  if (opts.ticketSnapshot) return opts.ticketSnapshot;
93
- if (
94
- (!opts.notify && !needFromState) ||
95
- typeof provider.getTicket !== 'function'
96
- ) {
97
- return null;
98
- }
96
+ if (typeof provider.getTicket !== 'function') return null;
99
97
  try {
100
98
  return await provider.getTicket(ticketId);
101
99
  } catch (err) {
@@ -285,14 +283,11 @@ export async function transitionTicketState(
285
283
 
286
284
  const toRemove = ALL_STATES.filter((state) => state !== newState);
287
285
 
288
- const ticketSnapshot = await loadTicketSnapshot(
289
- provider,
290
- opts,
291
- ticketId,
292
- BLOCK_RECOVERY_TARGETS.includes(newState),
293
- );
294
- const fromState =
295
- ticketSnapshot?.labels?.find((l) => ALL_STATES.includes(l)) ?? null;
286
+ const ticketSnapshot = await loadTicketSnapshot(provider, opts, ticketId);
287
+ const priorLabels = ticketSnapshot?.labels ?? [];
288
+ const fromState = priorLabels.find((l) => ALL_STATES.includes(l)) ?? null;
289
+ const observedFrom =
290
+ fromState ?? priorLabels.find((l) => OBSERVED_STATES.includes(l)) ?? null;
296
291
 
297
292
  const isDone = newState === STATE_LABELS.DONE;
298
293
 
@@ -307,6 +302,7 @@ export async function transitionTicketState(
307
302
  _ticketSnapshot: ticketSnapshot,
308
303
  });
309
304
 
305
+ await emitInvalidTransitionFriction(ticketId, observedFrom, newState, opts);
310
306
  await emitBlockedFriction(ticketId, fromState, newState, opts);
311
307
 
312
308
  const boardSync = await syncProjectStatusColumn(
@@ -2,8 +2,8 @@
2
2
  * runtime-deps/dep-resolution — is a declared runtime dependency present and
3
3
  * the right major. Deps resolve from the consumer's `node_modules`, so a
4
4
  * declared range is only enforced by comparing it to what resolved.
5
- * Major-only and semver-free on purpose: every range is `^`, and a semver
6
- * dependency would grow the very closure this guards.
5
+ * Major-only and semver-free on purpose: every range is `^` or a `||` union
6
+ * of them, and a semver dependency would grow the very closure this guards.
7
7
  *
8
8
  * @module lib/runtime-deps/dep-resolution
9
9
  */
@@ -21,6 +21,20 @@ function majorOf(spec) {
21
21
  return match ? Number(match[1]) : null;
22
22
  }
23
23
 
24
+ /**
25
+ * The majors a range admits, one per `||` alternative — or none (not
26
+ * range-checked) when any alternative is unreadable, the same conservative
27
+ * miss as a single unreadable range.
28
+ *
29
+ * @param {string|null|undefined} range
30
+ * @returns {number[]}
31
+ */
32
+ function wantedMajors(range) {
33
+ if (typeof range !== 'string') return [];
34
+ const majors = range.split('||').map(majorOf);
35
+ return majors.includes(null) ? [] : majors;
36
+ }
37
+
24
38
  /**
25
39
  * `false` when either side is unreadable. `0.x` minors are not separated —
26
40
  * accepted, since the range this enforces is `@babel/parser`'s `^7`.
@@ -30,11 +44,11 @@ function majorOf(spec) {
30
44
  * @returns {boolean}
31
45
  */
32
46
  function majorMismatch(range, resolved) {
33
- const want = majorOf(range);
34
- if (want === null) return false;
47
+ const wanted = wantedMajors(range);
48
+ if (wanted.length === 0) return false;
35
49
  const got = majorOf(resolved);
36
50
  if (got === null) return false;
37
- return want !== got;
51
+ return !wanted.includes(got);
38
52
  }
39
53
 
40
54
  /**
@@ -10,6 +10,7 @@ import fs from 'node:fs';
10
10
  import { builtinModules } from 'node:module';
11
11
  import path from 'node:path';
12
12
  import { stripJsComments } from '../source-text/strip-js-comments.js';
13
+ import { walkFiles } from '../util/paths.js';
13
14
 
14
15
  const BUILTIN_MODULES = new Set([
15
16
  ...builtinModules,
@@ -117,16 +118,9 @@ export function extractThirdPartyImports(source) {
117
118
  * @returns {string[]}
118
119
  */
119
120
  export function listJsFiles(dir) {
120
- const out = [];
121
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
122
- const full = path.join(dir, entry.name);
123
- if (entry.isDirectory()) {
124
- out.push(...listJsFiles(full));
125
- } else if (entry.isFile() && entry.name.endsWith('.js')) {
126
- out.push(full);
127
- }
128
- }
129
- return out;
121
+ return walkFiles(dir, {
122
+ filter: (abs, dirent) => dirent.isFile() && abs.endsWith('.js'),
123
+ });
130
124
  }
131
125
 
132
126
  /**
@@ -6,7 +6,7 @@
6
6
 
7
7
  import fs from 'node:fs';
8
8
  import path from 'node:path';
9
- import yaml from 'js-yaml';
9
+ import { load } from 'js-yaml';
10
10
  import { toPosix } from '../util/paths.js';
11
11
 
12
12
  const FRONTMATTER_DELIMITER = '---';
@@ -116,7 +116,7 @@ export function parseSkill(absolutePath, options = {}) {
116
116
 
117
117
  let frontmatter;
118
118
  try {
119
- frontmatter = yaml.load(yamlText);
119
+ frontmatter = load(yamlText);
120
120
  } catch (err) {
121
121
  throw new Error(
122
122
  `SKILL.md frontmatter is not valid YAML at ${absolutePath}: ${err.message}`,
@@ -8,6 +8,7 @@
8
8
 
9
9
  import fs from 'node:fs';
10
10
  import path from 'node:path';
11
+ import { toPosix, walkFiles } from '../util/paths.js';
11
12
 
12
13
  const TIERS = Object.freeze(['core', 'stack']);
13
14
 
@@ -35,27 +36,10 @@ export const SKILL_ID_RE = /^[a-z0-9][a-z0-9._-]*(?:\/[a-z0-9][a-z0-9._-]*)+$/;
35
36
  * @returns {string[]} absolute paths
36
37
  */
37
38
  function walkSkillFiles(rootDir) {
38
- const out = [];
39
- if (!fs.existsSync(rootDir)) return out;
40
- const stack = [rootDir];
41
- while (stack.length > 0) {
42
- const dir = stack.pop();
43
- let entries;
44
- try {
45
- entries = fs.readdirSync(dir, { withFileTypes: true });
46
- } catch {
47
- continue;
48
- }
49
- for (const entry of entries) {
50
- const full = path.join(dir, entry.name);
51
- if (entry.isDirectory()) {
52
- stack.push(full);
53
- } else if (entry.isFile() && entry.name === 'SKILL.md') {
54
- out.push(full);
55
- }
56
- }
57
- }
58
- return out;
39
+ return walkFiles(rootDir, {
40
+ filter: (_abs, dirent) => dirent.isFile() && dirent.name === 'SKILL.md',
41
+ onError: () => {},
42
+ });
59
43
  }
60
44
 
61
45
  /**
@@ -65,8 +49,8 @@ function walkSkillFiles(rootDir) {
65
49
  */
66
50
  function sortByRepoRelative(files, repoRoot) {
67
51
  return [...files].sort((a, b) => {
68
- const ra = path.relative(repoRoot, a).split(path.sep).join('/');
69
- const rb = path.relative(repoRoot, b).split(path.sep).join('/');
52
+ const ra = toPosix(path.relative(repoRoot, a));
53
+ const rb = toPosix(path.relative(repoRoot, b));
70
54
  return ra < rb ? -1 : ra > rb ? 1 : 0;
71
55
  });
72
56
  }
@@ -8,6 +8,7 @@
8
8
  * @module story-body
9
9
  */
10
10
 
11
+ import { isObject } from '../json-utils.js';
11
12
  import { FILE_ASSUMPTION_VALUES } from '../orchestration/file-assumption-enum.js';
12
13
  import {
13
14
  isProseBullet,
@@ -258,17 +259,6 @@ function pathEntryFixIt(raw) {
258
259
  return ` — Suggested fix: ${suggestion} (adjust the assumption to creates|deletes if this is a new file or a removal).`;
259
260
  }
260
261
 
261
- /**
262
- * Delegates to footer-block.js so the body and dispatch-edge parsers cannot
263
- * disagree about what declares an edge.
264
- *
265
- * @param {string} footerBlock
266
- * @returns {string[]}
267
- */
268
- function extractBlockedBy(footerBlock) {
269
- return parseFooterBlockedByRefs(footerBlock);
270
- }
271
-
272
262
  /**
273
263
  * Split markdown into named sections plus the footer block; content after
274
264
  * the footer separator is not parsed as sections.
@@ -391,7 +381,7 @@ function parseUnstructuredBody(input, preamble, footer) {
391
381
  verify: [],
392
382
  references: [],
393
383
  non_goals: [],
394
- depends_on: extractBlockedBy(footer),
384
+ depends_on: parseFooterBlockedByRefs(footer),
395
385
  };
396
386
  return {
397
387
  body,
@@ -492,7 +482,7 @@ export function parse(input) {
492
482
  });
493
483
  }
494
484
 
495
- if (typeof input === 'object' && !Array.isArray(input)) {
485
+ if (isObject(input)) {
496
486
  return parseStructuredObject(input);
497
487
  }
498
488
 
@@ -543,7 +533,7 @@ export function parse(input) {
543
533
  warnings,
544
534
  );
545
535
  const non_goals = parseTextListSection(sections.get('non_goals') ?? []);
546
- const dependsOn = extractBlockedBy(footer);
536
+ const dependsOn = parseFooterBlockedByRefs(footer);
547
537
 
548
538
  const body = {
549
539
  goal,
@@ -3,17 +3,28 @@ import path from 'node:path';
3
3
 
4
4
  /**
5
5
  * Tmp-then-rename via a pid-scoped sibling; reaps the tmp and rethrows on
6
- * failure.
6
+ * failure. A string is written as UTF-8; a Buffer is written byte-for-byte.
7
7
  *
8
8
  * @param {string} target
9
- * @param {string} contents
9
+ * @param {string | Buffer} contents
10
10
  * @param {{ fsImpl?: typeof fs }} [opts]
11
11
  */
12
12
  export function writeFileAtomic(target, contents, { fsImpl = fs } = {}) {
13
+ replaceAtomic(target, fsImpl, (tmp) =>
14
+ fsImpl.writeFileSync(tmp, contents, 'utf8'),
15
+ );
16
+ }
17
+
18
+ /** {@link writeFileAtomic} for a copy; keeps `source`'s mode bits. */
19
+ export function copyFileAtomic(source, target, { fsImpl = fs } = {}) {
20
+ replaceAtomic(target, fsImpl, (tmp) => fsImpl.copyFileSync(source, tmp));
21
+ }
22
+
23
+ function replaceAtomic(target, fsImpl, fill) {
13
24
  const tmp = `${target}.${process.pid}.tmp`;
14
25
  try {
15
26
  fsImpl.mkdirSync(path.dirname(target), { recursive: true });
16
- fsImpl.writeFileSync(tmp, contents, 'utf8');
27
+ fill(tmp);
17
28
  fsImpl.renameSync(tmp, target);
18
29
  } catch (err) {
19
30
  reapTmp(fsImpl, tmp);
@@ -0,0 +1,4 @@
1
+ /** Escape every RegExp metacharacter in `text` so it matches literally. */
2
+ export function escapeRegExp(text) {
3
+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
4
+ }
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- /* node:coverage ignore file */
2
+ /* node:coverage ignore file -- live comment/webhook CLI */
3
3
 
4
4
  /**
5
5
  * notify.js — dispatch a notification to two independently gated channels:
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- /* node:coverage ignore file */
2
+ /* node:coverage ignore file -- CLI shell over tested libs */
3
3
 
4
4
  /**
5
5
  * plan-context.js — build the `/mandrel-plan` authoring-context envelope from
@@ -16,6 +16,7 @@ import { parseArgs } from 'node:util';
16
16
 
17
17
  import { runAsCli } from './lib/cli-utils.js';
18
18
  import { resolveConfig } from './lib/config-resolver.js';
19
+ import { readJsonOrNull } from './lib/json-utils.js';
19
20
  import { Logger, routeAllOutputToStderr } from './lib/Logger.js';
20
21
  import { evaluatePlanCritics } from './lib/orchestration/plan-critics-evaluate.js';
21
22
  import { appendCriticSkip } from './lib/orchestration/plan-metrics.js';
@@ -46,15 +47,6 @@ function collectPackageIdentity(names, pkg) {
46
47
  }
47
48
  }
48
49
 
49
- /** Best-effort JSON read: a missing or malformed file yields `null`. */
50
- async function readJsonIfPresent(filePath) {
51
- try {
52
- return JSON.parse(await readFile(filePath, 'utf8'));
53
- } catch {
54
- return null;
55
- }
56
- }
57
-
58
50
  function workspacePatterns(pkg) {
59
51
  const ws = pkg?.workspaces;
60
52
  if (Array.isArray(ws)) return ws;
@@ -102,7 +94,7 @@ async function resolveWorkspaceManifestPaths(rootDir, patterns) {
102
94
  * @returns {Promise<string[]>}
103
95
  */
104
96
  export async function collectRepoPackages({ rootDir = process.cwd() } = {}) {
105
- const root = await readJsonIfPresent(path.join(rootDir, 'package.json'));
97
+ const root = readJsonOrNull(path.join(rootDir, 'package.json'));
106
98
  if (!root) return [];
107
99
  const names = new Set();
108
100
  collectPackageIdentity(names, root);
@@ -111,7 +103,7 @@ export async function collectRepoPackages({ rootDir = process.cwd() } = {}) {
111
103
  workspacePatterns(root),
112
104
  );
113
105
  for (const wsPath of wsPaths) {
114
- const pkg = await readJsonIfPresent(wsPath);
106
+ const pkg = readJsonOrNull(wsPath);
115
107
  if (pkg) collectPackageIdentity(names, pkg);
116
108
  }
117
109
  return [...names];
@@ -17,23 +17,19 @@ export function __setExecSyncForTests(fn) {
17
17
  execSyncHolder.impl = fn ?? defaultExecSync;
18
18
  }
19
19
 
20
- /* node:coverage ignore next */
21
20
  export function readGhCliToken() {
22
21
  return runGhAuthToken(execSyncHolder.impl);
23
22
  }
24
23
 
25
- /* node:coverage ignore next */
26
24
  function readEnvToken() {
27
25
  return process.env.GITHUB_TOKEN || process.env.GH_TOKEN || null;
28
26
  }
29
27
 
30
- /* node:coverage ignore next */
31
28
  function memoizeEnvToken(token) {
32
29
  process.env.GITHUB_TOKEN = token;
33
30
  process.env[TOKEN_SOURCE_ENV] = 'gh-cli';
34
31
  }
35
32
 
36
- /* node:coverage ignore next */
37
33
  export function resolveToken() {
38
34
  const envToken = readEnvToken();
39
35
  if (envToken) return envToken;
@@ -21,7 +21,6 @@ export class ProjectBoardGateway {
21
21
  return projects.ensureStatusField(this._ctx, optionNames);
22
22
  }
23
23
 
24
- /* node:coverage ignore next */
25
24
  async ensureProjectFields(fieldDefs) {
26
25
  return projects.ensureProjectFields(this._ctx, fieldDefs);
27
26
  }
@@ -180,7 +180,6 @@ export class TicketGateway {
180
180
  return tickets;
181
181
  }
182
182
 
183
- /* node:coverage ignore next */
184
183
  async getTicketDependencies(ticketId) {
185
184
  const ticket = await this.getTicket(ticketId);
186
185
  return {
@@ -363,7 +362,6 @@ export class TicketGateway {
363
362
  * @field-manifest PATCH /repos/{owner}/{repo}/issues/{n}:
364
363
  * title, body, assignees, state, state_reason, labels
365
364
  */
366
- /* node:coverage ignore next */
367
365
  async updateTicket(ticketId, mutations) {
368
366
  await this._addAssignees(ticketId, mutations.addAssignees);
369
367
  const patch = {};
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- /* node:coverage ignore file */
2
+ /* node:coverage ignore file -- CLI entrypoint convention, see docs/decisions.md */
3
3
 
4
4
  /**
5
5
  * resync-status-column.js — re-assert a ticket's Projects v2 Status after
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- /* node:coverage ignore file */
2
+ /* node:coverage ignore file -- the suite driver itself */
3
3
 
4
4
  /**
5
5
  * Cross-platform driver for `npm test`. Cleanup runs in-process so reserved
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- /* node:coverage ignore file */
2
+ /* node:coverage ignore file -- pretest shell over tested runPreflight */
3
3
 
4
4
  /**
5
5
  * `pretest` preflight: runs the self-healing checks (scope `npm-test`) so the
@@ -56,15 +56,16 @@ function parseTicketStateArgs(argv) {
56
56
  }
57
57
 
58
58
  /**
59
- * @param {{ argv?: string[], provider?: object, transition?: typeof transitionTicketState }} [opts]
59
+ * @param {{ argv?: string[], provider?: object, transition?: typeof transitionTicketState, config?: object }} [opts]
60
60
  */
61
61
  export async function runUpdateTicketState({
62
62
  argv = process.argv.slice(2),
63
63
  provider,
64
64
  transition = transitionTicketState,
65
+ config = resolveConfig(),
65
66
  } = {}) {
66
67
  const { ticketId, state, removeLabel } = parseTicketStateArgs(argv);
67
- const ticketing = provider ?? createProvider(resolveConfig());
68
+ const ticketing = provider ?? createProvider(config);
68
69
 
69
70
  // Label-only mutation path — no state transition. Callers that just
70
71
  // need to drop a single label without flipping the agent::* state.
@@ -81,7 +82,7 @@ export async function runUpdateTicketState({
81
82
 
82
83
  Logger.info(`[State-Sync] Transitioning ticket #${ticketId} to ${state}...`);
83
84
  // No explicit cascade: `transitionTicketState` already runs it.
84
- await transition(ticketing, ticketId, state);
85
+ await transition(ticketing, ticketId, state, { config });
85
86
 
86
87
  // Optional secondary label removal alongside the state transition
87
88
  // (e.g. clear `status::blocked` when transitioning back to ready).
@@ -27,6 +27,7 @@ import {
27
27
  PAYLOAD_SKILLS_SEGMENTS,
28
28
  } from './lib/skills/walk-skill-files.js';
29
29
  import { createAjv } from './lib/util/ajv.js';
30
+ import { toPosix } from './lib/util/paths.js';
30
31
 
31
32
  const MIN_CAPSULE_BULLETS = 5;
32
33
  const MAX_CAPSULE_BULLETS = 12;
@@ -156,7 +157,7 @@ function validateOne(absPath, repoRoot, validateFrontmatter, indexPaths) {
156
157
  }
157
158
 
158
159
  function rel(absPath, repoRoot) {
159
- return path.relative(repoRoot, absPath).split(path.sep).join('/');
160
+ return toPosix(path.relative(repoRoot, absPath));
160
161
  }
161
162
 
162
163
  /**
@@ -42,6 +42,7 @@ flagged a signed-off API-surface change. If the underlying change is an
42
42
  | Duplication | `npm run duplication:update` | `npm run duplication:reanchor` |
43
43
  | Dead-exports | `npm run dead-exports:update` (regenerates both passes; never hand-edit the JSON) | same — no scope flag applies |
44
44
  | Cyclomatic | `npm run cyclomatic:update` | same — no scope flag applies |
45
+ | Arch cycles | `npm run arch:update` | same — no scope flag applies |
45
46
  | Context budget | `node .agents/scripts/check-context-budget.js --update` | same — no scope flag applies |
46
47
 
47
48
  ## Procedure
@@ -219,19 +219,31 @@ runs and the ratchet never moves. So **every Hotspot Cluster and Tightening
219
219
  Headroom finding's Recommendation MUST** end the remediation with the ratchet
220
220
  tightened and gate-enforced:
221
221
 
222
- 1. Lower the floor under `delivery.quality.gates` in `.agentrc.json` to the
223
- newly measured level, **or** delete the burnt-down rows from that kind's
224
- file under `baselines/`.
225
- 2. Carry `node .agents/scripts/check-baselines.js --gate <kind>` in the
226
- remediation Story's `verify[]`, so the tightened floor is enforced by the
227
- gate that already exists at that Story's delivery time rather than by prose
228
- nobody runs.
222
+ 1. For a `gate` kind (its `surface` in `gateSurface[]`), lower the floor
223
+ under `delivery.quality.gates` in `.agentrc.json` to the newly measured
224
+ level, **or** delete the burnt-down rows from that kind's file under
225
+ `baselines/`. A `ratchet` kind has no floor: its shrunken baseline is the
226
+ tightening, banked at close (`arch-cycles` alone needs its checker's
227
+ `--update`).
228
+ 2. Carry each kind's checker in the remediation Story's `verify[]`, so the
229
+ tightened ratchet is enforced by the gate that already exists at that
230
+ Story's delivery time rather than by prose nobody runs. A `gate` kind uses
231
+ `node .agents/scripts/check-baselines.js --gate <kind>`; that command
232
+ rejects a `ratchet` kind with exit 3, so a ratchet uses its own checker:
233
+
234
+ | Ratchet kind | Checker |
235
+ | --- | --- |
236
+ | `arch-cycles` | `node .agents/scripts/check-arch-cycles.js` |
237
+ | `context-budget` | `node .agents/scripts/check-context-budget.js` |
238
+ | `cyclomatic` | `node .agents/scripts/check-cyclomatic.js` |
239
+ | `dead-exports` | `node .agents/scripts/check-dead-exports.js` |
240
+ | `dead-exports-production` | `node .agents/scripts/check-dead-exports.js --production` |
229
241
 
230
242
  Use these two Recommendation templates verbatim, substituting the envelope's own
231
- values for the angle-bracketed slots:
243
+ values for the angle-bracketed slots (`<checker>` is item 2's command per kind):
232
244
 
233
245
  - **Hotspot Cluster template:**
234
- `Burn down the measured debt in <hotspots.path>, an outlier across <gateKinds>. Refactor and add tests until its rows leave that kind's file under baselines/, then regenerate that baseline with the matching update-*-baseline script in a commit whose subject carries the baseline-refresh: tag. Finish by TIGHTENING the ratchet in the same Story — lower the kind's floor under delivery.quality.gates in .agentrc.json to the new measured level, or delete the burnt-down rows — and carry node .agents/scripts/check-baselines.js --gate <kind> in this Story's verify[] so the tightened floor is enforced at delivery.`
246
+ `Burn down the measured debt in <hotspots.path>, an outlier across <gateKinds>. Refactor and add tests until its rows leave each kind's file under baselines/, then regenerate a gate kind's baseline with the matching update-*-baseline script in a commit whose subject carries the baseline-refresh: tag. Finish by TIGHTENING the ratchet in the same Story — lower each gate kind's floor under delivery.quality.gates in .agentrc.json to the new measured level, or delete the burnt-down rows — and carry each kind's <checker> in this Story's verify[] so the tightened ratchet is enforced at delivery.`
235
247
  - **Tightening Headroom template:**
236
248
  `The <kind> gate's <axis> floor sits at <floor> while the measured rollup is <measured> (headroom <headroom>, direction <direction>), and that kind's trend is flat or improving. Tighten it: set that axis under delivery.quality.gates in .agentrc.json to the measured level so no slack remains for the next change to re-spend, and carry node .agents/scripts/check-baselines.js --gate <kind> in this Story's verify[] so the new floor is enforced. Regenerate no baseline in this Story — the floor edit is the whole change.`
237
249
 
@@ -34,7 +34,7 @@ flags: `node .agents/scripts/clean-git.js --help`.
34
34
 
35
35
  | Phase | What it does | Safety contract |
36
36
  | --- | --- | --- |
37
- | **fast-forward-main** | `git fetch origin <base>` then `git merge --ff-only origin/<base>`. | Skipped silently on a dirty tree or a non-fast-forward; otherwise prompts `Fast-forward main by N commit(s)?`. Checks out `<base>` first when HEAD is elsewhere and does **not** restore the prior branch. |
37
+ | **fast-forward-main** | `git fetch origin <base>` then `git merge --ff-only origin/<base>`. | Skipped silently on a dirty tree or a non-fast-forward; otherwise prompts `Fast-forward main by N commit(s)?`. Checks out `<base>` first when HEAD is elsewhere, then restores the prior branch after the merge, even a failed one (best-effort: a failed restore warns and leaves HEAD on `<base>`). |
38
38
  | **prune-remotes** | `git fetch --prune origin` to drop `refs/remotes/origin/*` GitHub already deleted. | Prompts before pruning. Runs as its own phase regardless of `--remote`. |
39
39
  | **branches** | Reaps merged local branches (squash-aware: merged-PR, git-ancestry, and content-equivalence signals), removing an attached worktree first. Also enumerates **remote-only** merged branches. | Prints the candidate list, then prompts `Reap N merged branch(es)?`. `--remote` is required **on top of** `--execute` to delete any `origin/<branch>`. `content-merged` candidates carry a weaker-signal warning, and under `--yes` their **remote** ref is withheld unless `--include-content-merged` is passed (their local ref still goes — it is recoverable from the remote). |
40
40
  | **stashes** | Lists every stash and triages it. | Interactive: `drop / keep / quit` per entry (default `keep`). Under `--yes` / `--json`, drops require an explicit `--drop-stashes <ref>` allowlist (repeatable) — there is no "drop all". |
@@ -27,7 +27,7 @@ refines this shared constraint for that lens only.
27
27
 
28
28
  **Deliberate shortcuts are decisions.** In every lens, a `shortcut:` comment
29
29
  that names a ceiling and a trigger
30
- ([convention](code-quality-guardrails.md#deliberate-shortcuts)) is a decision,
30
+ (convention: `code-quality-guardrails.md` § Deliberate shortcuts) is a decision,
31
31
  not a finding, unless the lens can show the ceiling is already crossed at the
32
32
  expected load. A marker with no trigger, or one whose trigger has fired, is
33
33
  `/audit-exceptions`' finding, not the reading lens's.
@@ -13,7 +13,7 @@ read the same numbers from here so a "high cyclomatic complexity" finding in
13
13
 
14
14
  ## At-keyboard verification
15
15
 
16
- Run [`npm run quality:preview`](../../../package.json) before committing
16
+ Run `npm run quality:preview` before committing
17
17
  on any Story that touches production source. The preview runs
18
18
  `quality-preview.js`, which scopes the diff to `HEAD` by default (the
19
19
  alias passes no `--changed-since`; the script defaults to `HEAD`) and
@@ -63,7 +63,7 @@ No structural check enforces the pairing — it is a review-time rule
63
63
  ## Maintainability-Index drop refactor rule
64
64
 
65
65
  Per-file Maintainability Index (MI) is tracked in
66
- [`baselines/maintainability.json`](../../../baselines/maintainability.json).
66
+ `baselines/maintainability.json`.
67
67
  A commit that drops a file's MI by more than the configured
68
68
  `delivery.quality.gates.maintainability.tolerance` (default `0.5` points)
69
69
  requires a refactor in the same Story — not a baseline bump. `tolerance` is
@@ -108,7 +108,7 @@ Every judging surface reads the marker the same way:
108
108
  - **Rot**: a ceiling with no trigger. Nothing will ever say when to fix it.
109
109
  - **Fired**: the date has passed or the issue has closed. Fix it now.
110
110
 
111
- [`/audit-exceptions`](../audit-exceptions.md) lists every marker with its
111
+ `/audit-exceptions` lists every marker with its
112
112
  verdict.
113
113
 
114
114
  ## When a number changes