mandrel 2.94.0 → 2.96.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 (119) hide show
  1. package/.agents/audit-checklists/red-team.md +20 -0
  2. package/.agents/docs/workflows.md +3 -1
  3. package/.agents/runtime-deps.json +6 -6
  4. package/.agents/schemas/audit-rules.json +16 -0
  5. package/.agents/scripts/agents-bootstrap-github.js +1 -1
  6. package/.agents/scripts/board-backfill.js +1 -1
  7. package/.agents/scripts/boot-sweep.js +1 -1
  8. package/.agents/scripts/check-arch-cycles.js +69 -41
  9. package/.agents/scripts/check-doc-links.js +5 -7
  10. package/.agents/scripts/check-gherkin-corpus.js +2 -11
  11. package/.agents/scripts/clean-temp.js +1 -1
  12. package/.agents/scripts/cleanup-repo-test-temp.js +1 -1
  13. package/.agents/scripts/diagnose-friction.js +1 -1
  14. package/.agents/scripts/generate-lens-checklists.js +4 -4
  15. package/.agents/scripts/generate-skills-index.js +3 -2
  16. package/.agents/scripts/generate-workflows-doc.js +2 -1
  17. package/.agents/scripts/lib/audit-baselines/read.js +2 -1
  18. package/.agents/scripts/lib/audit-exceptions/adapters/tool-config.js +13 -3
  19. package/.agents/scripts/lib/audit-exceptions/globs.js +12 -1
  20. package/.agents/scripts/lib/audit-exceptions/probe.js +24 -2
  21. package/.agents/scripts/lib/audit-exceptions/read.js +2 -2
  22. package/.agents/scripts/lib/audit-to-stories/audit-lenses.js +1 -0
  23. package/.agents/scripts/lib/audit-to-stories/group-findings.js +77 -67
  24. package/.agents/scripts/lib/baselines/components.js +21 -19
  25. package/.agents/scripts/lib/baselines/duplication-scanner.js +4 -8
  26. package/.agents/scripts/lib/baselines/kinds/maintainability.js +2 -3
  27. package/.agents/scripts/lib/baselines/preview-gates.js +2 -2
  28. package/.agents/scripts/lib/baselines/refresh-service.js +4 -7
  29. package/.agents/scripts/lib/baselines/writer.js +2 -7
  30. package/.agents/scripts/lib/bdd-runner-detect.js +2 -2
  31. package/.agents/scripts/lib/bdd-step-index.js +3 -7
  32. package/.agents/scripts/lib/bootstrap/baseline-merge-driver.js +11 -7
  33. package/.agents/scripts/lib/bootstrap/install-ledger.js +19 -4
  34. package/.agents/scripts/lib/bootstrap/json-io.js +14 -0
  35. package/.agents/scripts/lib/bootstrap/project-bootstrap.js +20 -44
  36. package/.agents/scripts/lib/bootstrap/quality-bootstrap.js +38 -54
  37. package/.agents/scripts/lib/branch-name-guard.js +2 -3
  38. package/.agents/scripts/lib/claude/agents-projection.js +1 -12
  39. package/.agents/scripts/lib/codex/agents-projection.js +2 -5
  40. package/.agents/scripts/lib/codex/skills-projection.js +4 -12
  41. package/.agents/scripts/lib/config/defaults.js +2 -1
  42. package/.agents/scripts/lib/config/qa.js +4 -5
  43. package/.agents/scripts/lib/config-schema.js +1 -8
  44. package/.agents/scripts/lib/config-settings-schema.js +0 -3
  45. package/.agents/scripts/lib/coverage-baseline.js +2 -3
  46. package/.agents/scripts/lib/coverage-utils.js +2 -1
  47. package/.agents/scripts/lib/cpu-pool.js +0 -1
  48. package/.agents/scripts/lib/cyclomatic-scope.js +2 -1
  49. package/.agents/scripts/lib/doc-tiers.js +2 -1
  50. package/.agents/scripts/lib/gh-exec.js +21 -1
  51. package/.agents/scripts/lib/git/sync-from-base.js +1 -1
  52. package/.agents/scripts/lib/import-graph.js +13 -28
  53. package/.agents/scripts/lib/json-utils.js +11 -0
  54. package/.agents/scripts/lib/label-constants.js +7 -1
  55. package/.agents/scripts/lib/maintainability-utils.js +14 -22
  56. package/.agents/scripts/lib/observability/runtime-friction.js +37 -1
  57. package/.agents/scripts/lib/orchestration/check-baselines/phases/parse-args.js +25 -1
  58. package/.agents/scripts/lib/orchestration/ci-rerun-guard.js +9 -12
  59. package/.agents/scripts/lib/orchestration/code-review.js +1 -6
  60. package/.agents/scripts/lib/orchestration/deliver-recover.js +2 -1
  61. package/.agents/scripts/lib/orchestration/git-cleanup/phases/fast-forward.js +7 -14
  62. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes-ff.js +2 -21
  63. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes.js +11 -20
  64. package/.agents/scripts/lib/orchestration/git-cleanup/phases/phase-drivers.js +65 -86
  65. package/.agents/scripts/lib/orchestration/git-cleanup/phases/prompts.js +2 -2
  66. package/.agents/scripts/lib/orchestration/git-cleanup/phases/stashes.js +15 -6
  67. package/.agents/scripts/lib/orchestration/lifecycle/emit-merge-unlanded.js +5 -2
  68. package/.agents/scripts/lib/orchestration/merge-block-class.js +47 -48
  69. package/.agents/scripts/lib/orchestration/plan-persist/run-plan-persist.js +20 -1
  70. package/.agents/scripts/lib/orchestration/review-providers/claude-verdict.js +2 -3
  71. package/.agents/scripts/lib/orchestration/review-providers/parse-findings.js +4 -2
  72. package/.agents/scripts/lib/orchestration/story-close/baseline-upward-writeback.js +2 -2
  73. package/.agents/scripts/lib/orchestration/story-close/ratchet-shrink-writeback.js +3 -3
  74. package/.agents/scripts/lib/orchestration/story-handoff.js +18 -5
  75. package/.agents/scripts/lib/orchestration/ticketing/transition.js +17 -21
  76. package/.agents/scripts/lib/runtime-deps/dep-resolution.js +19 -5
  77. package/.agents/scripts/lib/runtime-deps/scan-imports.js +4 -10
  78. package/.agents/scripts/lib/skills/parse-skill.js +2 -2
  79. package/.agents/scripts/lib/skills/walk-skill-files.js +7 -23
  80. package/.agents/scripts/lib/story-body/story-body.js +4 -14
  81. package/.agents/scripts/lib/util/atomic-write.js +14 -3
  82. package/.agents/scripts/lib/util/regex.js +4 -0
  83. package/.agents/scripts/lint-issue-body.js +65 -10
  84. package/.agents/scripts/notify.js +1 -1
  85. package/.agents/scripts/plan-context.js +1 -1
  86. package/.agents/scripts/plan-critics.js +3 -11
  87. package/.agents/scripts/providers/github/auth.js +0 -4
  88. package/.agents/scripts/providers/github/project-board.js +0 -1
  89. package/.agents/scripts/providers/github/tickets.js +0 -2
  90. package/.agents/scripts/resync-status-column.js +1 -1
  91. package/.agents/scripts/run-tests.js +1 -1
  92. package/.agents/scripts/test-wrapper.js +1 -1
  93. package/.agents/scripts/update-ticket-state.js +4 -3
  94. package/.agents/scripts/validate-skills.js +2 -1
  95. package/.agents/skills/core/gates-and-baselines/reference.md +1 -0
  96. package/.agents/workflows/audit-baselines.md +21 -9
  97. package/.agents/workflows/audit-red-team.md +191 -0
  98. package/.agents/workflows/audit-security.md +4 -1
  99. package/.agents/workflows/clean-git.md +1 -1
  100. package/.agents/workflows/helpers/audit-lens-core.md +1 -1
  101. package/.agents/workflows/helpers/code-quality-guardrails.md +3 -3
  102. package/.agents/workflows/mandrel-leverage.md +199 -0
  103. package/.agents/workflows/mandrel-plan.md +3 -1
  104. package/README.md +1 -1
  105. package/docs/CHANGELOG.md +48 -0
  106. package/lib/cli/claude-code-version.js +13 -7
  107. package/lib/cli/doctor-checks/llm-review.js +12 -5
  108. package/lib/cli/doctor-checks/merge-driver.js +10 -6
  109. package/lib/cli/doctor-checks/project-access.js +21 -8
  110. package/lib/cli/doctor-checks/read-json.js +2 -15
  111. package/lib/cli/doctor-checks/spawn.js +29 -9
  112. package/lib/cli/doctor-checks/test-credit-path.js +2 -1
  113. package/lib/cli/doctor-checks/toolchain.js +16 -12
  114. package/lib/cli/doctor.js +31 -8
  115. package/lib/cli/registry.js +7 -10
  116. package/lib/cli/sync.js +46 -10
  117. package/lib/cli/uninstall.js +259 -175
  118. package/lib/cli/update.js +3 -3
  119. 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
+ }
@@ -21,6 +21,30 @@ const REQUIRED_SECTIONS = [
21
21
  { field: 'verify', label: 'Verify' },
22
22
  ];
23
23
 
24
+ /** The closed set of section names a comment may print. */
25
+ const SECTION_LABELS = new Map([
26
+ ['goal', 'Goal'],
27
+ ['acceptance', 'Acceptance'],
28
+ ['verify', 'Verify'],
29
+ ['changes', 'Changes'],
30
+ ['references', 'References'],
31
+ ['spec', 'Spec'],
32
+ ['context', 'Context'],
33
+ ['slicing', 'Slicing'],
34
+ ['non_goals', 'Non-Goals'],
35
+ ]);
36
+
37
+ /**
38
+ * Fixed-vocabulary problem line for a parse failure. `err.message` and
39
+ * `err.raw` echo issue text, so they go to the run log, never the comment.
40
+ */
41
+ function parseFailureProblem(err) {
42
+ const label = SECTION_LABELS.get(err.field);
43
+ return label
44
+ ? `The \`## ${label}\` section could not be parsed into the canonical schema.`
45
+ : 'An unrecognised section could not be parsed into the canonical schema.';
46
+ }
47
+
24
48
  /**
25
49
  * Issue Forms render a skipped field as `_No response_`; treat it as absent.
26
50
  * @param {string} body
@@ -39,6 +63,7 @@ function stripNoResponseSentinel(body) {
39
63
  * @property {string[]} problems
40
64
  * @property {string[]} warnings
41
65
  * @property {boolean} parseFailed
66
+ * @property {string|null} parseError - Full parser message; run log only.
42
67
  */
43
68
 
44
69
  /**
@@ -54,6 +79,7 @@ export function evaluateIssueBody(body) {
54
79
  problems: ['The issue body is empty.'],
55
80
  warnings: [],
56
81
  parseFailed: true,
82
+ parseError: null,
57
83
  };
58
84
  }
59
85
 
@@ -66,11 +92,10 @@ export function evaluateIssueBody(body) {
66
92
  if (err instanceof StoryBodyParseError) {
67
93
  return {
68
94
  conformant: false,
69
- problems: [
70
- `The body could not be parsed into the canonical schema: ${err.message}`,
71
- ],
95
+ problems: [parseFailureProblem(err)],
72
96
  warnings: [],
73
97
  parseFailed: true,
98
+ parseError: err.message,
74
99
  };
75
100
  }
76
101
  throw err;
@@ -103,10 +128,13 @@ export function evaluateIssueBody(body) {
103
128
  problems,
104
129
  warnings: result.warnings,
105
130
  parseFailed: false,
131
+ parseError: null,
106
132
  };
107
133
  }
108
134
 
109
135
  /**
136
+ * Built only from fixed strings and the fixed-vocabulary `problems`; warning
137
+ * text echoes issue content, so only the count is shown.
110
138
  * @param {ConformanceVerdict} verdict
111
139
  * @returns {string}
112
140
  */
@@ -127,11 +155,8 @@ export function renderConformanceComment(verdict) {
127
155
  if (verdict.warnings.length > 0) {
128
156
  lines.push(
129
157
  '',
130
- '<details><summary>Parser warnings (non-blocking)</summary>',
131
- '',
132
- ...verdict.warnings.map((w) => `- ${w}`),
133
- '',
134
- '</details>',
158
+ `The parser also raised ${verdict.warnings.length} non-blocking ` +
159
+ 'warning(s); see the workflow run log for the details.',
135
160
  );
136
161
  }
137
162
  return lines.join('\n');
@@ -159,6 +184,34 @@ export function isStoryTicket(labelNames) {
159
184
  return Array.isArray(labelNames) && labelNames.includes('type::story');
160
185
  }
161
186
 
187
+ /**
188
+ * The bot-authored marker comment to update, or `null`. A human-authored
189
+ * marker is ignored so an issue author cannot hijack or suppress the lint.
190
+ */
191
+ function findMarkerCommentId(ghFn, repoPath, issue) {
192
+ const out = ghFn([
193
+ 'api',
194
+ `repos/${repoPath}/issues/${issue}/comments`,
195
+ '--paginate',
196
+ '--jq',
197
+ '.[] | {id, login: .user.login, body}',
198
+ ]);
199
+ const comments = out.split('\n').filter((line) => line.trim() !== '');
200
+ return comments.map((line) => JSON.parse(line)).find(isBotMarker)?.id ?? null;
201
+ }
202
+
203
+ const isBotMarker = (c) =>
204
+ c.body?.startsWith(LINT_COMMENT_MARKER) && c.login?.endsWith('[bot]');
205
+
206
+ function upsertArgs(id, issue, repo, comment) {
207
+ if (id === null) {
208
+ const repoArgs = repo ? ['--repo', repo] : [];
209
+ return ['issue', 'comment', String(issue), ...repoArgs, '--body', comment];
210
+ }
211
+ const path = `repos/${repo ?? '{owner}/{repo}'}/issues/comments/${id}`;
212
+ return ['api', '-X', 'PATCH', path, '-f', `body=${comment}`];
213
+ }
214
+
162
215
  /**
163
216
  * @param {{
164
217
  * issue: string|number,
@@ -201,6 +254,8 @@ export function runLintIssueBody({
201
254
  issue: Number(issue),
202
255
  conformant: verdict.conformant,
203
256
  problems: verdict.problems,
257
+ warnings: verdict.warnings,
258
+ parseError: verdict.parseError,
204
259
  })}\n`,
205
260
  );
206
261
 
@@ -211,8 +266,8 @@ export function runLintIssueBody({
211
266
  };
212
267
  }
213
268
 
214
- const comment = renderConformanceComment(verdict);
215
- ghFn(['issue', 'comment', String(issue), ...repoArgs, '--body', comment]);
269
+ const id = findMarkerCommentId(ghFn, repo ?? '{owner}/{repo}', issue);
270
+ ghFn(upsertArgs(id, issue, repo, renderConformanceComment(verdict)));
216
271
  return { conformant: false, problems: verdict.problems };
217
272
  }
218
273
 
@@ -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).