mandrel 2.90.0 → 2.91.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 (169) hide show
  1. package/.agents/README.md +47 -7
  2. package/.agents/agents/story-worker.md +20 -0
  3. package/.agents/audit-checklists/lean.md +26 -0
  4. package/.agents/docs/agentrc-reference.json +5 -6
  5. package/.agents/docs/configuration.md +31 -30
  6. package/.agents/docs/workflows.md +7 -1
  7. package/.agents/instructions.md +3 -1
  8. package/.agents/runtime-deps.json +0 -2
  9. package/.agents/schemas/agentrc.schema.json +46 -45
  10. package/.agents/schemas/audit-rules.json +19 -0
  11. package/.agents/scripts/acceptance-eval.js +2 -6
  12. package/.agents/scripts/audit-exceptions.js +2 -4
  13. package/.agents/scripts/check-arch-cycles.js +1 -5
  14. package/.agents/scripts/check-context-budget.js +1 -5
  15. package/.agents/scripts/check-cyclomatic.js +1 -5
  16. package/.agents/scripts/check-dead-exports.js +23 -14
  17. package/.agents/scripts/check-doc-links.js +4 -4
  18. package/.agents/scripts/check-test-temp-hygiene.js +29 -33
  19. package/.agents/scripts/coverage-capture.js +14 -6
  20. package/.agents/scripts/diagnose-friction.js +8 -10
  21. package/.agents/scripts/generate-workflows-doc.js +5 -0
  22. package/.agents/scripts/lib/audit-exceptions/adapters/index.js +2 -0
  23. package/.agents/scripts/lib/audit-exceptions/adapters/inline-suppressions.js +36 -27
  24. package/.agents/scripts/lib/audit-exceptions/adapters/shortcut-markers.js +70 -0
  25. package/.agents/scripts/lib/audit-exceptions/adapters/source-scan.js +26 -0
  26. package/.agents/scripts/lib/audit-to-stories/audit-lenses.js +1 -0
  27. package/.agents/scripts/lib/baseline-schema-registry.js +3 -5
  28. package/.agents/scripts/lib/baselines/bundle-size-scorer.js +11 -28
  29. package/.agents/scripts/lib/baselines/components.js +5 -5
  30. package/.agents/scripts/lib/baselines/crap-preview-scan.js +4 -1
  31. package/.agents/scripts/lib/baselines/crap-updater-cli.js +6 -4
  32. package/.agents/scripts/lib/baselines/duplication-scanner.js +4 -10
  33. package/.agents/scripts/lib/baselines/kinds/crap.js +4 -2
  34. package/.agents/scripts/lib/baselines/kinds/duplication.js +4 -2
  35. package/.agents/scripts/lib/baselines/kinds/kind-factory.js +13 -6
  36. package/.agents/scripts/lib/baselines/refresh-service.js +10 -13
  37. package/.agents/scripts/lib/baselines/writer.js +4 -4
  38. package/.agents/scripts/lib/bdd-scenario-scanner.js +26 -31
  39. package/.agents/scripts/lib/bootstrap/gh-list.js +4 -5
  40. package/.agents/scripts/lib/bootstrap/gh-preflight.js +13 -8
  41. package/.agents/scripts/lib/child-exec.js +4 -4
  42. package/.agents/scripts/lib/claude/agents-projection.js +170 -0
  43. package/.agents/scripts/lib/claude/commands-projection.js +184 -0
  44. package/.agents/scripts/lib/close-validation/commands.js +28 -117
  45. package/.agents/scripts/lib/close-validation/gates.js +54 -48
  46. package/.agents/scripts/lib/close-validation/projections/crap.js +2 -1
  47. package/.agents/scripts/lib/close-validation/projections/maintainability.js +50 -15
  48. package/.agents/scripts/lib/config/agentrc-overlay.js +4 -7
  49. package/.agents/scripts/lib/config/commands.js +82 -7
  50. package/.agents/scripts/lib/config/explain.js +2 -1
  51. package/.agents/scripts/lib/config/gates/coverage.schema.js +39 -3
  52. package/.agents/scripts/lib/config/gates/crap-incremental-coverage.schema.js +1 -1
  53. package/.agents/scripts/lib/config/gates/crap.schema.js +5 -3
  54. package/.agents/scripts/lib/config/gates/duplication.schema.js +6 -11
  55. package/.agents/scripts/lib/config/gates/shared.js +2 -2
  56. package/.agents/scripts/lib/config/git-roots.js +120 -0
  57. package/.agents/scripts/lib/config/quality.js +46 -50
  58. package/.agents/scripts/lib/config/review-chain-default.js +4 -3
  59. package/.agents/scripts/lib/config/review-provider-clis.js +11 -0
  60. package/.agents/scripts/lib/config/temp-paths.js +3 -37
  61. package/.agents/scripts/lib/config-resolver.js +5 -9
  62. package/.agents/scripts/lib/config-settings-schema-delivery.js +2 -2
  63. package/.agents/scripts/lib/config-settings-schema-quality.js +3 -2
  64. package/.agents/scripts/lib/config-settings-schema.js +6 -7
  65. package/.agents/scripts/lib/coverage-baseline.js +2 -1
  66. package/.agents/scripts/lib/coverage-capture-affected.js +4 -3
  67. package/.agents/scripts/lib/coverage-capture-fullscope.js +3 -1
  68. package/.agents/scripts/lib/coverage-capture-passes.js +119 -34
  69. package/.agents/scripts/lib/coverage-capture-usage.js +1 -1
  70. package/.agents/scripts/lib/coverage-capture.js +31 -20
  71. package/.agents/scripts/lib/coverage-utils.js +34 -16
  72. package/.agents/scripts/lib/cpu-pool.js +2 -4
  73. package/.agents/scripts/lib/crap-engine.js +19 -1
  74. package/.agents/scripts/lib/crap-utils.js +2 -1
  75. package/.agents/scripts/lib/dead-exports-knip.js +29 -11
  76. package/.agents/scripts/lib/detect-package-manager.js +13 -0
  77. package/.agents/scripts/lib/feedback-loop/graduator-gh.js +4 -2
  78. package/.agents/scripts/lib/full-suite-lock.js +25 -9
  79. package/.agents/scripts/lib/gates/baseline-store.js +2 -10
  80. package/.agents/scripts/lib/generated/agentrc-validator.js +4 -1
  81. package/.agents/scripts/lib/gh-env.js +72 -0
  82. package/.agents/scripts/lib/gh-exec.js +26 -1
  83. package/.agents/scripts/lib/maintainability-utils.js +8 -8
  84. package/.agents/scripts/lib/npm-scripts.js +1 -1
  85. package/.agents/scripts/lib/observability/signal-validator.js +2 -6
  86. package/.agents/scripts/lib/observability/terse-result.js +2 -6
  87. package/.agents/scripts/lib/orchestration/board-access-latch.js +19 -8
  88. package/.agents/scripts/lib/orchestration/ci-rerun-guard.js +10 -13
  89. package/.agents/scripts/lib/orchestration/deliver-recover.js +2 -1
  90. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes.js +3 -3
  91. package/.agents/scripts/lib/orchestration/lifecycle/emit-ledger-event.js +2 -6
  92. package/.agents/scripts/lib/orchestration/light-suitability.js +5 -7
  93. package/.agents/scripts/lib/orchestration/pr-watch.js +7 -7
  94. package/.agents/scripts/lib/orchestration/project-meta-cache.js +2 -11
  95. package/.agents/scripts/lib/orchestration/review-deposit.js +2 -9
  96. package/.agents/scripts/lib/orchestration/review-providers/callers-context.js +219 -0
  97. package/.agents/scripts/lib/orchestration/review-providers/code-review.js +53 -5
  98. package/.agents/scripts/lib/orchestration/review-providers/codex-cli.js +2 -2
  99. package/.agents/scripts/lib/orchestration/review-providers/llm-review.js +96 -0
  100. package/.agents/scripts/lib/orchestration/review-providers/mi-exemptions.js +2 -2
  101. package/.agents/scripts/lib/orchestration/review-providers/native.js +13 -19
  102. package/.agents/scripts/lib/orchestration/review-providers/review-depth.js +3 -2
  103. package/.agents/scripts/lib/orchestration/review-providers/review-provider-factory.js +2 -0
  104. package/.agents/scripts/lib/orchestration/review-providers/security-review.js +11 -3
  105. package/.agents/scripts/lib/orchestration/story-close/baseline-upward-writeback.js +2 -3
  106. package/.agents/scripts/lib/orchestration/story-close/format-autofix.js +41 -15
  107. package/.agents/scripts/lib/orchestration/story-deliver-terminal-schema.js +2 -4
  108. package/.agents/scripts/lib/orchestration/story-deliver-terminal.js +2 -13
  109. package/.agents/scripts/lib/orchestration/story-handoff.js +13 -5
  110. package/.agents/scripts/lib/orchestration/story-progress.js +3 -11
  111. package/.agents/scripts/lib/orchestration/ticketing/bulk.js +3 -5
  112. package/.agents/scripts/lib/orchestration/verify-credit.js +52 -28
  113. package/.agents/scripts/lib/single-story-sweep/protection-ctx.js +11 -11
  114. package/.agents/scripts/lib/single-story-sweep/protection.js +1 -9
  115. package/.agents/scripts/lib/single-story-sweep/sweep-lock.js +1 -5
  116. package/.agents/scripts/lib/source-extensions.js +30 -15
  117. package/.agents/scripts/lib/test-run-credit.js +1 -9
  118. package/.agents/scripts/lib/test-temp.js +22 -21
  119. package/.agents/scripts/lib/util/ajv.js +111 -0
  120. package/.agents/scripts/lib/util/atomic-write.js +30 -0
  121. package/.agents/scripts/lib/util/paths.js +51 -0
  122. package/.agents/scripts/lib/util/sleep.js +6 -0
  123. package/.agents/scripts/lib/util/slug.js +12 -0
  124. package/.agents/scripts/lib/validation-evidence.js +19 -40
  125. package/.agents/scripts/lib/worktree/lifecycle/force-drain.js +2 -1
  126. package/.agents/scripts/lib/worktree/lifecycle/pending-cleanup.js +10 -28
  127. package/.agents/scripts/lib/worktree/lifecycle/reap.js +2 -2
  128. package/.agents/scripts/lib/worktree/node-modules-strategy.js +21 -14
  129. package/.agents/scripts/lint-issue-body.js +2 -2
  130. package/.agents/scripts/plan-context.js +2 -7
  131. package/.agents/scripts/providers/github/auth.js +3 -3
  132. package/.agents/scripts/providers/github/errors.js +3 -1
  133. package/.agents/scripts/providers/github/gh-token-diagnostics.js +10 -7
  134. package/.agents/scripts/providers/github/issues.js +6 -2
  135. package/.agents/scripts/providers/github/mappers.js +1 -5
  136. package/.agents/scripts/providers/github/projects-v2-graphql.js +11 -3
  137. package/.agents/scripts/providers/github/search-budget.js +3 -1
  138. package/.agents/scripts/resolve-doc-tiers.js +7 -20
  139. package/.agents/scripts/sync-agentrc.js +5 -14
  140. package/.agents/scripts/sync-claude-agents.js +38 -150
  141. package/.agents/scripts/sync-claude-commands.js +35 -218
  142. package/.agents/scripts/update-coverage-baseline.js +1 -1
  143. package/.agents/scripts/update-crap-baseline.js +1 -1
  144. package/.agents/scripts/update-duplication-baseline.js +2 -16
  145. package/.agents/scripts/validate-skills.js +6 -10
  146. package/.agents/skills/core/code-review-and-quality/SKILL.md +3 -18
  147. package/.agents/skills/core/documentation-and-adrs/SKILL.md +4 -14
  148. package/.agents/workflows/audit-exceptions.md +9 -0
  149. package/.agents/workflows/audit-lean.md +129 -0
  150. package/.agents/workflows/helpers/audit-lens-core.md +7 -0
  151. package/.agents/workflows/helpers/code-quality-guardrails.md +21 -0
  152. package/.agents/workflows/helpers/code-review.md +15 -1
  153. package/.agents/workflows/helpers/deliver-digest.md +1 -1
  154. package/.agents/workflows/helpers/deliver-reference.md +2 -2
  155. package/.agents/workflows/mandrel-plan.md +2 -2
  156. package/docs/CHANGELOG.md +35 -0
  157. package/lib/cli/doctor-checks/codex.js +6 -5
  158. package/lib/cli/doctor-checks/llm-review.js +102 -0
  159. package/lib/cli/doctor-checks/project-access.js +20 -10
  160. package/lib/cli/doctor-checks/sync-parity.js +65 -140
  161. package/lib/cli/doctor-checks/test-credit-path.js +69 -28
  162. package/lib/cli/doctor-checks/toolchain.js +5 -3
  163. package/lib/cli/registry.js +5 -0
  164. package/lib/migrations/helpers/retire-agentrc-key.js +3 -3
  165. package/lib/migrations/index.js +6 -0
  166. package/lib/migrations/steps/2.91.0-move-shared-crap-capture-script.js +84 -0
  167. package/lib/migrations/steps/2.91.0-retire-duplication-formats.js +23 -0
  168. package/lib/migrations/steps/2.91.0-unset-null-lint-command.js +54 -0
  169. package/package.json +1 -3
@@ -0,0 +1,111 @@
1
+ /**
2
+ * The one Ajv factory for validators that need string formats. Mandrel's
3
+ * schemas declare only `date-time` and `date`, so those two are registered by
4
+ * hand (a port of the Ajv formats plugin's full-mode RFC 3339 checks) instead
5
+ * of loading that whole plugin.
6
+ */
7
+
8
+ import AjvDraft07 from 'ajv';
9
+ import AjvDraft2020 from 'ajv/dist/2020.js';
10
+
11
+ const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
12
+ const TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;
13
+ const DATE_TIME_SEPARATOR = /t|\s/i;
14
+ const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
15
+
16
+ /**
17
+ * @param {number} year
18
+ * @returns {boolean}
19
+ */
20
+ function isLeapYear(year) {
21
+ return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
22
+ }
23
+
24
+ /**
25
+ * RFC 3339 full-date on a real calendar day.
26
+ *
27
+ * @param {string} str
28
+ * @returns {boolean}
29
+ */
30
+ function isDate(str) {
31
+ const m = DATE.exec(str);
32
+ if (!m) return false;
33
+ const year = +m[1];
34
+ const month = +m[2];
35
+ const day = +m[3];
36
+ if (month < 1 || month > 12 || day < 1) return false;
37
+ return day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]);
38
+ }
39
+
40
+ /**
41
+ * A `:60` second is valid only at 23:59 UTC once the offset is applied.
42
+ *
43
+ * @param {RegExpExecArray} m
44
+ * @returns {boolean}
45
+ */
46
+ function isLeapSecond(m) {
47
+ const sign = m[5] === '-' ? -1 : 1;
48
+ const utcMin = +m[2] - +(m[7] || 0) * sign;
49
+ const utcHr = +m[1] - +(m[6] || 0) * sign - (utcMin < 0 ? 1 : 0);
50
+ const atLastHour = utcHr === 23 || utcHr === -1;
51
+ return atLastHour && (utcMin === 59 || utcMin === -1) && +m[3] < 61;
52
+ }
53
+
54
+ /**
55
+ * RFC 3339 full-time with a required `Z` or `±hh:mm` offset.
56
+ *
57
+ * @param {string} str
58
+ * @returns {boolean}
59
+ */
60
+ function isTime(str) {
61
+ const m = TIME.exec(str);
62
+ if (!m || !m[4]) return false;
63
+ if (+(m[6] || 0) > 23 || +(m[7] || 0) > 59) return false;
64
+ if (+m[1] <= 23 && +m[2] <= 59 && +m[3] < 60) return true;
65
+ return isLeapSecond(m);
66
+ }
67
+
68
+ /**
69
+ * RFC 3339 date-time: full-date, a `T`/`t`/space separator, full-time.
70
+ *
71
+ * @param {string} str
72
+ * @returns {boolean}
73
+ */
74
+ function isDateTime(str) {
75
+ const parts = str.split(DATE_TIME_SEPARATOR);
76
+ return parts.length === 2 && isDate(parts[0]) && isTime(parts[1]);
77
+ }
78
+
79
+ /**
80
+ * @template {import('ajv').default} T
81
+ * @param {T} ajv
82
+ * @returns {T}
83
+ */
84
+ function withFormats(ajv) {
85
+ ajv.addFormat('date-time', isDateTime);
86
+ ajv.addFormat('date', isDate);
87
+ return ajv;
88
+ }
89
+
90
+ const Draft07 = AjvDraft07.default ?? AjvDraft07;
91
+ const Draft2020 = AjvDraft2020.default ?? AjvDraft2020;
92
+
93
+ /**
94
+ * Draft-07 Ajv with the `date-time` and `date` formats registered.
95
+ *
96
+ * @param {import('ajv').Options} [options]
97
+ * @returns {import('ajv').default}
98
+ */
99
+ export function createAjv(options = {}) {
100
+ return withFormats(new Draft07(options));
101
+ }
102
+
103
+ /**
104
+ * Draft 2020-12 Ajv with the `date-time` and `date` formats registered.
105
+ *
106
+ * @param {import('ajv').Options} [options]
107
+ * @returns {import('ajv/dist/2020.js').default}
108
+ */
109
+ export function createAjv2020(options = {}) {
110
+ return withFormats(new Draft2020(options));
111
+ }
@@ -0,0 +1,30 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ /**
5
+ * Tmp-then-rename via a pid-scoped sibling; reaps the tmp and rethrows on
6
+ * failure.
7
+ *
8
+ * @param {string} target
9
+ * @param {string} contents
10
+ * @param {{ fsImpl?: typeof fs }} [opts]
11
+ */
12
+ export function writeFileAtomic(target, contents, { fsImpl = fs } = {}) {
13
+ const tmp = `${target}.${process.pid}.tmp`;
14
+ try {
15
+ fsImpl.mkdirSync(path.dirname(target), { recursive: true });
16
+ fsImpl.writeFileSync(tmp, contents, 'utf8');
17
+ fsImpl.renameSync(tmp, target);
18
+ } catch (err) {
19
+ reapTmp(fsImpl, tmp);
20
+ throw err;
21
+ }
22
+ }
23
+
24
+ function reapTmp(fsImpl, tmp) {
25
+ try {
26
+ if (typeof fsImpl.rmSync === 'function')
27
+ fsImpl.rmSync(tmp, { force: true });
28
+ else fsImpl.unlinkSync(tmp);
29
+ } catch {}
30
+ }
@@ -29,3 +29,54 @@ export function dirExists(dir) {
29
29
  return false;
30
30
  }
31
31
  }
32
+
33
+ /**
34
+ * Non-directory entries under `dir` passing `filter`, pruning `skipDirs`
35
+ * before descent. A missing root is `[]`; any other readdir error throws,
36
+ * or, given `onError(err, dir)`, is reported and that directory skipped.
37
+ *
38
+ * @param {string} dir
39
+ * @param {{ skipDirs?: Iterable<string> | ((name: string) => boolean), filter?: (absPath: string, dirent: fs.Dirent) => boolean, onError?: (err: Error, dir: string) => void, fsImpl?: typeof fs }} [opts]
40
+ * @returns {string[]}
41
+ */
42
+ export function walkFiles(
43
+ dir,
44
+ { skipDirs = [], filter, onError, fsImpl = fs } = {},
45
+ ) {
46
+ const skip = toSkipPredicate(skipDirs);
47
+ const out = [];
48
+ const visit = (current) => {
49
+ for (const dirent of readEntries(
50
+ fsImpl,
51
+ current,
52
+ current === dir,
53
+ onError,
54
+ )) {
55
+ const abs = path.join(current, dirent.name);
56
+ if (dirent.isDirectory()) {
57
+ if (!skip(dirent.name)) visit(abs);
58
+ } else if (!filter || filter(abs, dirent)) {
59
+ out.push(abs);
60
+ }
61
+ }
62
+ };
63
+ visit(dir);
64
+ return out;
65
+ }
66
+
67
+ function toSkipPredicate(skipDirs) {
68
+ if (typeof skipDirs === 'function') return skipDirs;
69
+ const names = new Set(skipDirs);
70
+ return (name) => names.has(name);
71
+ }
72
+
73
+ function readEntries(fsImpl, dir, isRoot, onError) {
74
+ try {
75
+ return fsImpl.readdirSync(dir, { withFileTypes: true });
76
+ } catch (err) {
77
+ if (isRoot && err?.code === 'ENOENT') return [];
78
+ if (!onError) throw err;
79
+ onError(err, dir);
80
+ return [];
81
+ }
82
+ }
@@ -13,3 +13,9 @@ export function defaultSleep(ms) {
13
13
  setTimeout(resolve, ms);
14
14
  });
15
15
  }
16
+
17
+ /** Blocks without spinning; a no-op for a non-finite or non-positive `ms`. */
18
+ export function sleepSync(ms) {
19
+ if (!Number.isFinite(ms) || ms <= 0) return;
20
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
21
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * `[a-z0-9]` dash slug, capped at `max`; `fallback` when nothing survives.
3
+ * `git-utils.js` `slugify` keeps a wider charset.
4
+ */
5
+ export function slugifyLabel(text, { max, fallback }) {
6
+ let slug = String(text ?? '')
7
+ .toLowerCase()
8
+ .replace(/[^a-z0-9]+/g, '-')
9
+ .replace(/^-+|-+$/g, '');
10
+ if (max !== undefined) slug = slug.slice(0, max).replace(/-+$/, '');
11
+ return slug === '' ? fallback : slug;
12
+ }
@@ -17,9 +17,9 @@ import {
17
17
  } from 'node:fs';
18
18
  import path from 'node:path';
19
19
  import { fileURLToPath } from 'node:url';
20
- import Ajv from 'ajv/dist/2020.js';
21
- import addFormats from 'ajv-formats';
22
20
  import { storyTempDir } from './config/temp-paths.js';
21
+ import { createAjv2020 } from './util/ajv.js';
22
+ import { writeFileAtomic } from './util/atomic-write.js';
23
23
 
24
24
  export const SCHEMA_VERSION = 1;
25
25
  const DEFAULT_TEMP_DIR = 'temp';
@@ -44,8 +44,7 @@ let cachedValidator = null;
44
44
  */
45
45
  function getEvidenceValidator() {
46
46
  if (cachedValidator) return cachedValidator;
47
- const ajv = new Ajv({ allErrors: true, strict: false });
48
- addFormats(ajv);
47
+ const ajv = createAjv2020({ allErrors: true, strict: false });
49
48
  const schema = JSON.parse(defaultReadFileSync(SCHEMA_PATH, 'utf8'));
50
49
  cachedValidator = ajv.compile(schema);
51
50
  return cachedValidator;
@@ -199,50 +198,33 @@ export function recordPass(
199
198
  commandConfigHash: configHash,
200
199
  exitCode,
201
200
  durationMs,
202
- inputFingerprint:
203
- typeof inputFingerprint === 'string' && inputFingerprint.length > 0
204
- ? inputFingerprint
205
- : null,
201
+ inputFingerprint: isNonEmptyString(inputFingerprint)
202
+ ? inputFingerprint
203
+ : null,
206
204
  timestamp: resolved.now().toISOString(),
207
205
  };
208
206
  doc.records = [...doc.records.filter((r) => r.gateName !== gateName), record];
209
207
 
210
- const validator = getEvidenceValidator();
211
- if (!validator(doc)) {
212
- const detail = (validator.errors || [])
213
- .map((e) => `${e.instancePath || '(root)'} ${e.message}`)
214
- .join('; ');
215
- throw new Error(`Evidence document failed schema validation: ${detail}`);
216
- }
217
-
218
- writeEvidenceAtomically(
219
- resolved.fs,
208
+ assertValidEvidence(doc);
209
+ writeFileAtomic(
220
210
  evidencePath(storyId, evidenceOpts),
221
211
  JSON.stringify(doc, null, 2),
212
+ { fsImpl: resolved.fs },
222
213
  );
223
214
  return record;
224
215
  }
225
216
 
226
- /** Atomic write (pid-scoped tmp + rename): a torn file drops all credit. */
227
- function writeEvidenceAtomically(fsImpl, file, body) {
228
- fsImpl.mkdirSync(path.dirname(file), { recursive: true });
229
- const tmpPath = `${file}.${process.pid}.tmp`;
230
- try {
231
- fsImpl.writeFileSync(tmpPath, body, 'utf8');
232
- fsImpl.renameSync(tmpPath, file);
233
- } catch (err) {
234
- reapTmp(fsImpl, tmpPath);
235
- throw err;
236
- }
217
+ function assertValidEvidence(doc) {
218
+ const validator = getEvidenceValidator();
219
+ if (validator(doc)) return;
220
+ const detail = (validator.errors || [])
221
+ .map((e) => `${e.instancePath || '(root)'} ${e.message}`)
222
+ .join('; ');
223
+ throw new Error(`Evidence document failed schema validation: ${detail}`);
237
224
  }
238
225
 
239
- /** Best-effort removal of a tmp sibling. */
240
- function reapTmp(fsImpl, tmpPath) {
241
- try {
242
- if (fsImpl.existsSync(tmpPath)) fsImpl.unlinkSync(tmpPath);
243
- } catch {
244
- // A leftover tmp is never read as evidence.
245
- }
226
+ function isNonEmptyString(value) {
227
+ return typeof value === 'string' && value.length > 0;
246
228
  }
247
229
 
248
230
  /**
@@ -291,10 +273,7 @@ export function shouldSkip(
291
273
  return { skip: true, reason: 'evidence-match', record: match };
292
274
  }
293
275
  if (
294
- typeof inputFingerprint === 'string' &&
295
- inputFingerprint.length > 0 &&
296
- typeof match.inputFingerprint === 'string' &&
297
- match.inputFingerprint.length > 0 &&
276
+ isNonEmptyString(inputFingerprint) &&
298
277
  match.inputFingerprint === inputFingerprint
299
278
  ) {
300
279
  return { skip: true, reason: 'fingerprint-match', record: match };
@@ -8,6 +8,7 @@
8
8
  import { spawnSync } from 'node:child_process';
9
9
  import path from 'node:path';
10
10
  import { NOOP_LOGGER } from '../../Logger.js';
11
+ import { defaultSleep } from '../../util/sleep.js';
11
12
  import { drainPendingCleanup, readManifest } from './pending-cleanup.js';
12
13
 
13
14
  const SETTLE_MS = 1500;
@@ -233,7 +234,7 @@ export async function forceDrainPendingCleanup({
233
234
  logger = NOOP_LOGGER,
234
235
  findHolders = findHoldersInPath,
235
236
  killHolders = terminateHolders,
236
- sleep = (ms) => new Promise((r) => setTimeout(r, ms)),
237
+ sleep = defaultSleep,
237
238
  escalate = true,
238
239
  } = {}) {
239
240
  const first = await drainPendingCleanup({
@@ -13,6 +13,7 @@ import { rm as fsPromisesRm } from 'node:fs/promises';
13
13
  import path from 'node:path';
14
14
  import { NOOP_LOGGER } from '../../Logger.js';
15
15
  import { acquireSweepLock } from '../../single-story-sweep/sweep-lock.js';
16
+ import { writeFileAtomic } from '../../util/atomic-write.js';
16
17
 
17
18
  const MANIFEST_FILENAME = '.pending-cleanup.json';
18
19
  const MANIFEST_LOCK_FILENAME = '.pending-cleanup.lock';
@@ -87,34 +88,18 @@ function writeManifest(worktreeRoot, entries) {
87
88
  }
88
89
  return;
89
90
  }
90
- fs.mkdirSync(worktreeRoot, { recursive: true });
91
91
  writeFileAtomic(p, `${JSON.stringify(entries, null, 2)}\n`);
92
92
  }
93
93
 
94
- /**
95
- * Pid-scoped temp file in the same directory (so rename is atomic), renamed
96
- * into place; on failure the temp is reaped and the error propagates.
97
- *
98
- * @param {string} targetPath
99
- * @param {string} contents
100
- */
101
- function writeFileAtomic(targetPath, contents) {
102
- const tmp = `${targetPath}.${process.pid}.tmp`;
103
- try {
104
- fs.writeFileSync(tmp, contents, 'utf8');
105
- fs.renameSync(tmp, targetPath);
106
- } catch (err) {
107
- reapTempFile(tmp);
108
- throw err;
94
+ function gitWorktreeRemove(wtPath, { git, repoRoot }) {
95
+ const rm = git.gitSpawn(repoRoot, 'worktree', 'remove', wtPath);
96
+ if (rm.status !== 0) {
97
+ git.gitSpawn(repoRoot, 'worktree', 'remove', '--force', wtPath);
109
98
  }
110
99
  }
111
100
 
112
- function reapTempFile(tmp) {
113
- try {
114
- fs.unlinkSync(tmp);
115
- } catch {
116
- // Already gone.
117
- }
101
+ function spawnOutput(result) {
102
+ return (result.stderr || result.stdout || '').trim();
118
103
  }
119
104
 
120
105
  /**
@@ -164,10 +149,7 @@ export function removePendingCleanup(worktreeRoot, storyId) {
164
149
 
165
150
  async function removeStuckWorktreePath(wtPath, { git, repoRoot, fsRm }) {
166
151
  if (!fs.existsSync(wtPath)) return { ok: true };
167
- let rm = git.gitSpawn(repoRoot, 'worktree', 'remove', wtPath);
168
- if (rm.status !== 0) {
169
- rm = git.gitSpawn(repoRoot, 'worktree', 'remove', '--force', wtPath);
170
- }
152
+ gitWorktreeRemove(wtPath, { git, repoRoot });
171
153
  if (fs.existsSync(wtPath)) {
172
154
  try {
173
155
  await fsRm(wtPath, { recursive: true, force: true });
@@ -189,7 +171,7 @@ async function removeStuckWorktreePath(wtPath, { git, repoRoot, fsRm }) {
189
171
  function sweepBranchLocal(branch, { git, repoRoot, logger }) {
190
172
  const localDel = git.gitSpawn(repoRoot, 'branch', '-D', branch);
191
173
  if (localDel.status === 0) return true;
192
- const stderr = (localDel.stderr || localDel.stdout || '').trim();
174
+ const stderr = spawnOutput(localDel);
193
175
  if (/not found|no such|not match/i.test(stderr)) return true;
194
176
  logger.warn(
195
177
  `worktree-sweep: branch -D ${branch} failed: ${stderr || 'unknown'} (continuing)`,
@@ -207,7 +189,7 @@ function sweepBranchRemote(branch, { git, repoRoot, logger }) {
207
189
  branch,
208
190
  );
209
191
  if (remoteDel.status === 0) return true;
210
- const stderr = (remoteDel.stderr || remoteDel.stdout || '').trim();
192
+ const stderr = spawnOutput(remoteDel);
211
193
  if (/remote ref does not exist|not found/i.test(stderr)) return true;
212
194
  logger.warn(
213
195
  `worktree-sweep: push --delete ${branch} failed: ${stderr || 'unknown'} (continuing)`,
@@ -7,9 +7,9 @@
7
7
  import fs from 'node:fs';
8
8
  import { rm as fsPromisesRm } from 'node:fs/promises';
9
9
  import { fileURLToPath } from 'node:url';
10
+ import { defaultSleep, sleepSync } from '../../util/sleep.js';
10
11
  import { canonicalPath } from '../canonical-path.js';
11
12
  import { isInsideWorktree, samePath } from '../inspector.js';
12
- import { sleepSync } from '../node-modules-strategy.js';
13
13
  import { checkMergeReachability } from './merge-reachability.js';
14
14
  import { recordPendingCleanup } from './pending-cleanup.js';
15
15
  import { checkLocalSafety } from './precheck.js';
@@ -108,7 +108,7 @@ async function fsRmWithRetry(
108
108
  } catch (err) {
109
109
  lastErr = err;
110
110
  if (attempt < maxRetries && retryDelay > 0) {
111
- await new Promise((r) => setTimeout(r, retryDelay));
111
+ await defaultSleep(retryDelay);
112
112
  }
113
113
  }
114
114
  }
@@ -6,16 +6,26 @@
6
6
  * install), `symlink` (to a donor; opt-in on Windows) and `pnpm-store`.
7
7
  */
8
8
 
9
- import { spawnSync } from 'node:child_process';
10
9
  import crypto from 'node:crypto';
11
10
  import fs from 'node:fs';
12
11
  import path from 'node:path';
12
+ import { spawnChild } from '../child-exec.js';
13
13
  import { detectPackageManager } from '../detect-package-manager.js';
14
+ import { sleepSync } from '../util/sleep.js';
14
15
 
15
- function sleepSync(ms) {
16
- if (!Number.isFinite(ms) || ms <= 0) return;
17
- const signal = new Int32Array(new SharedArrayBuffer(4));
18
- Atomics.wait(signal, 0, 0, ms);
16
+ /**
17
+ * Every spawn here goes through `spawnChild` so the wrapper's stdout ceiling
18
+ * applies: a chatty install overflowing Node's 1 MiB default would be killed
19
+ * mid-write and leave a half-populated `node_modules`. An injected `spawnFn`
20
+ * becomes the wrapper's `run` seam, so tests still see every call.
21
+ *
22
+ * @param {Function|undefined} spawnFn - `spawnSync`-shaped seam; omitted → real.
23
+ * @param {string} cmd
24
+ * @param {string[]} args
25
+ * @param {object} opts
26
+ */
27
+ function runChild(spawnFn, cmd, args, opts) {
28
+ return spawnChild(cmd, args, spawnFn ? { ...opts, run: spawnFn } : opts);
19
29
  }
20
30
 
21
31
  /**
@@ -106,11 +116,11 @@ export function applyNodeModulesStrategy(ctx, wtPath) {
106
116
  *
107
117
  * @param {{ config: object, platform: NodeJS.Platform, logger: object, repoRoot: string }} ctx
108
118
  * @param {string} wtPath
109
- * @param {{ spawnFn?: typeof spawnSync, fsLike?: typeof fs }} [io]
119
+ * @param {{ spawnFn?: Function, fsLike?: typeof fs }} [io]
110
120
  * @returns {{ cloned: boolean, reason?: string }}
111
121
  */
112
122
  export function cloneNodeModules(ctx, wtPath, io = {}) {
113
- const spawnFn = io.spawnFn ?? spawnSync;
123
+ const spawnFn = io.spawnFn;
114
124
  const fsLike = io.fsLike ?? fs;
115
125
  // Real host OS, not `ctx.platform`: Windows has no clone `cp` here.
116
126
  if (process.platform === 'win32') {
@@ -144,7 +154,7 @@ export function cloneNodeModules(ctx, wtPath, io = {}) {
144
154
  process.platform === 'darwin'
145
155
  ? ['-c', '-R', donorNodeModules, target]
146
156
  : ['--reflink=always', '-R', donorNodeModules, target];
147
- const result = spawnFn('cp', cloneArgs, {
157
+ const result = runChild(spawnFn, 'cp', cloneArgs, {
148
158
  cwd: wtPath,
149
159
  stdio: 'pipe',
150
160
  encoding: 'utf-8',
@@ -319,7 +329,7 @@ function primePnpmStore({
319
329
  strategy,
320
330
  repoRoot,
321
331
  logger,
322
- spawnFn = spawnSync,
332
+ spawnFn,
323
333
  fsLike = fs,
324
334
  shell = process.platform === 'win32',
325
335
  }) {
@@ -334,7 +344,7 @@ function primePnpmStore({
334
344
  logger.info(
335
345
  `worktree.install priming pnpm content-addressable store at ${repoRoot} (sentinel missing)`,
336
346
  );
337
- const result = spawnFn('pnpm', ['install', '--frozen-lockfile'], {
347
+ const result = runChild(spawnFn, 'pnpm', ['install', '--frozen-lockfile'], {
338
348
  cwd: repoRoot,
339
349
  stdio: 'pipe',
340
350
  encoding: 'utf-8',
@@ -391,7 +401,7 @@ export function runInstallWithRetry({
391
401
  logger.info(
392
402
  `worktree.install strategy=${strategy} cmd=${cmd} attempt=${attempt}/${policy.maxAttempts} path=${cwd}`,
393
403
  );
394
- lastResult = spawnFn(cmd, args, {
404
+ lastResult = runChild(spawnFn, cmd, args, {
395
405
  cwd,
396
406
  stdio: 'pipe',
397
407
  encoding: 'utf-8',
@@ -480,7 +490,6 @@ export function installDependencies(ctx, wtPath) {
480
490
  cwd: wtPath,
481
491
  shell: ctx.platform === 'win32',
482
492
  policy,
483
- spawnFn: spawnSync,
484
493
  sleepFn: sleepSync,
485
494
  logger: ctx.logger,
486
495
  strategy,
@@ -493,5 +502,3 @@ export function installDependencies(ctx, wtPath) {
493
502
  }
494
503
  return { status: 'installed' };
495
504
  }
496
-
497
- export { sleepSync };
@@ -8,8 +8,8 @@
8
8
  * @module lint-issue-body
9
9
  */
10
10
 
11
- import { spawnSync } from 'node:child_process';
12
11
  import { runAsCli } from './lib/cli-utils.js';
12
+ import { runGh } from './lib/gh-exec.js';
13
13
  import { parse, StoryBodyParseError } from './lib/story-body/story-body.js';
14
14
 
15
15
  export const LINT_COMMENT_MARKER = '<!-- mandrel:issue-body-conformance -->';
@@ -142,7 +142,7 @@ export function renderConformanceComment(verdict) {
142
142
  * @returns {string}
143
143
  */
144
144
  function gh(args) {
145
- const res = spawnSync('gh', args, { encoding: 'utf8' });
145
+ const res = runGh(args, { encoding: 'utf8' });
146
146
  if (res.status !== 0) {
147
147
  throw new Error(
148
148
  `gh ${args.join(' ')} failed (exit ${res.status}): ${res.stderr?.trim() ?? ''}`,
@@ -31,6 +31,7 @@ import {
31
31
  } from './lib/orchestration/plan-context.js';
32
32
  import { recordPlanInvocation } from './lib/orchestration/plan-metrics.js';
33
33
  import { createProvider } from './lib/provider-factory.js';
34
+ import { slugifyLabel } from './lib/util/slug.js';
34
35
 
35
36
  const PLAN_SLUG_MAX_LENGTH = 48;
36
37
 
@@ -42,13 +43,7 @@ const PLAN_SLUG_MAX_LENGTH = 48;
42
43
  * @returns {string} `plan` when nothing survives.
43
44
  */
44
45
  export function slugifyPlanLabel(raw) {
45
- const slug = String(raw ?? '')
46
- .toLowerCase()
47
- .replace(/[^a-z0-9]+/g, '-')
48
- .replace(/^-+|-+$/g, '')
49
- .slice(0, PLAN_SLUG_MAX_LENGTH)
50
- .replace(/-+$/, '');
51
- return slug === '' ? 'plan' : slug;
46
+ return slugifyLabel(raw, { max: PLAN_SLUG_MAX_LENGTH, fallback: 'plan' });
52
47
  }
53
48
 
54
49
  /**
@@ -1,10 +1,10 @@
1
1
  /**
2
2
  * GitHub Provider — token resolution: GITHUB_TOKEN / GH_TOKEN env →
3
- * `gh auth token` → classified throw (`gh-token-diagnostics.js`). `execSync`
4
- * sits behind a holder so tests can swap it.
3
+ * `gh auth token` → classified throw (`gh-token-diagnostics.js`). The
4
+ * `execFileSync`-shaped runner sits behind a holder so tests can swap it.
5
5
  */
6
6
 
7
- import { execSync as defaultExecSync } from 'node:child_process';
7
+ import { execFileSync as defaultExecSync } from 'node:child_process';
8
8
  import {
9
9
  describeTokenFailure,
10
10
  runGhAuthToken,
@@ -7,6 +7,8 @@
7
7
  * permission rule because a secondary rate limit arrives as HTTP 403.
8
8
  */
9
9
 
10
+ import { defaultSleep } from '../../lib/util/sleep.js';
11
+
10
12
  /**
11
13
  * Schema facts (absent field, disabled feature) no retry can change. Never
12
14
  * add a bare `sub-issues` needle: it matches the endpoint name, so a rate
@@ -186,7 +188,7 @@ export async function withTransientRetry(fn, opts = {}) {
186
188
  classify = classifyGithubError,
187
189
  label = 'gh-api',
188
190
  onRetry,
189
- sleep = (ms) => new Promise((r) => setTimeout(r, ms)),
191
+ sleep = defaultSleep,
190
192
  random = Math.random,
191
193
  } = opts;
192
194
 
@@ -1,5 +1,6 @@
1
1
  /** Classified `gh auth token` results; only a confirmed not-logged-in result says `gh auth login`. */
2
2
 
3
+ import { runGhOrThrow } from '../../lib/gh-exec.js';
3
4
  import {
4
5
  isTransportFailure,
5
6
  sandboxDenialCode,
@@ -60,15 +61,17 @@ function classifyGhTokenFailure(err) {
60
61
  * detail: string|null }} GhTokenResult
61
62
  */
62
63
 
63
- /** @returns {GhTokenResult} */
64
+ /**
65
+ * @param {Function} execImpl - an `execFileSync`-shaped `(file, args, opts)` runner.
66
+ * @returns {GhTokenResult}
67
+ */
64
68
  export function runGhAuthToken(execImpl) {
65
69
  try {
66
- const out = execImpl('gh auth token', {
67
- encoding: 'utf8',
68
- timeout: 5000,
69
- stdio: ['pipe', 'pipe', 'pipe'],
70
- env: process.env,
71
- });
70
+ const out = runGhOrThrow(
71
+ ['auth', 'token'],
72
+ { encoding: 'utf8', timeout: 5000, stdio: ['pipe', 'pipe', 'pipe'] },
73
+ execImpl,
74
+ );
72
75
  const token = String(out ?? '').trim();
73
76
  if (token) return { token, verdict: 'ok', detail: null };
74
77
  return {
@@ -8,7 +8,11 @@ import { Logger } from '../../lib/Logger.js';
8
8
  import { concurrentMap } from '../../lib/util/concurrent-map.js';
9
9
  import { isNotFoundError } from './branch-protection.js';
10
10
  import { classifyGithubError, withTransientRetry } from './errors.js';
11
- import { issueToEpic, issueToTicket, subIssueNodeToTicket } from './mappers.js';
11
+ import {
12
+ baseIssueFields,
13
+ issueToTicket,
14
+ subIssueNodeToTicket,
15
+ } from './mappers.js';
12
16
  import {
13
17
  defaultRetryWarn,
14
18
  paginateRest,
@@ -229,7 +233,7 @@ export class IssuesGateway {
229
233
  }),
230
234
  { label: `getEpic #${epicId}`, onRetry: defaultRetryWarn },
231
235
  );
232
- return issueToEpic(parseApiJson(result));
236
+ return baseIssueFields(parseApiJson(result));
233
237
  }
234
238
 
235
239
  /**