mandrel 2.87.0 → 2.89.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 (170) hide show
  1. package/.agents/README.md +29 -0
  2. package/.agents/agents/auditor.md +4 -3
  3. package/.agents/docs/agentrc-reference.json +5 -2
  4. package/.agents/docs/configuration.md +14 -8
  5. package/.agents/docs/workflows.md +1 -1
  6. package/.agents/schemas/agentrc.schema.json +24 -5
  7. package/.agents/schemas/story-deliver-terminal.schema.json +1 -1
  8. package/.agents/schemas/story-progress.schema.json +5 -0
  9. package/.agents/scripts/audit-to-stories.js +3 -2
  10. package/.agents/scripts/boot-sweep.js +3 -2
  11. package/.agents/scripts/check-arch-cycles.js +19 -41
  12. package/.agents/scripts/check-context-budget.js +16 -44
  13. package/.agents/scripts/check-cyclomatic.js +13 -37
  14. package/.agents/scripts/check-dead-exports.js +16 -46
  15. package/.agents/scripts/clean-worktrees.js +1 -6
  16. package/.agents/scripts/coverage-capture.js +32 -49
  17. package/.agents/scripts/deliver-run.js +11 -0
  18. package/.agents/scripts/diagnose-friction.js +3 -3
  19. package/.agents/scripts/lib/audit-baselines/gate-surface.js +24 -11
  20. package/.agents/scripts/lib/audit-baselines/read.js +4 -2
  21. package/.agents/scripts/lib/audit-baselines/surface-entry.js +95 -11
  22. package/.agents/scripts/lib/baselines/coverage-updater-cli.js +6 -14
  23. package/.agents/scripts/lib/baselines/crap-preview-scan.js +3 -1
  24. package/.agents/scripts/lib/baselines/crap-updater-cli.js +38 -26
  25. package/.agents/scripts/lib/baselines/duplication-scanner.js +20 -1
  26. package/.agents/scripts/lib/baselines/env-overrides.js +39 -34
  27. package/.agents/scripts/lib/baselines/kernel.js +3 -2
  28. package/.agents/scripts/lib/baselines/kinds/crap.js +50 -53
  29. package/.agents/scripts/lib/baselines/preview-gates.js +5 -1
  30. package/.agents/scripts/lib/baselines/refresh-service.js +65 -22
  31. package/.agents/scripts/lib/baselines/writer.js +5 -1
  32. package/.agents/scripts/lib/bdd-runner-detect.js +7 -10
  33. package/.agents/scripts/lib/child-exec.js +14 -1
  34. package/.agents/scripts/lib/child-stream.js +122 -0
  35. package/.agents/scripts/lib/clean-temp.js +19 -13
  36. package/.agents/scripts/lib/cli-args.js +49 -0
  37. package/.agents/scripts/lib/close-validation/gates.js +40 -9
  38. package/.agents/scripts/lib/codex/skills-projection.js +1 -12
  39. package/.agents/scripts/lib/config/gates/crap.schema.js +15 -0
  40. package/.agents/scripts/lib/config/gates/mutation.schema.js +2 -2
  41. package/.agents/scripts/lib/config/gh-config-dir.js +63 -0
  42. package/.agents/scripts/lib/config/github.js +2 -0
  43. package/.agents/scripts/lib/config/paths.js +14 -3
  44. package/.agents/scripts/lib/config/quality.js +49 -1
  45. package/.agents/scripts/lib/config-resolver.js +78 -64
  46. package/.agents/scripts/lib/config-settings-schema-delivery.js +4 -3
  47. package/.agents/scripts/lib/config-settings-schema.js +7 -0
  48. package/.agents/scripts/lib/coverage-baseline.js +2 -2
  49. package/.agents/scripts/lib/coverage-capture-affected.js +2 -1
  50. package/.agents/scripts/lib/coverage-capture-fullscope.js +2 -2
  51. package/.agents/scripts/lib/coverage-capture-incremental.js +1 -1
  52. package/.agents/scripts/lib/coverage-capture-passes.js +143 -0
  53. package/.agents/scripts/lib/coverage-capture-usage.js +1 -1
  54. package/.agents/scripts/lib/coverage-capture.js +45 -15
  55. package/.agents/scripts/lib/crap-utils.js +65 -49
  56. package/.agents/scripts/lib/full-suite-lock.js +1 -10
  57. package/.agents/scripts/lib/gates/baseline-store.js +10 -0
  58. package/.agents/scripts/lib/generated/agentrc-validator.js +1 -1
  59. package/.agents/scripts/lib/gh-exec.js +45 -2
  60. package/.agents/scripts/lib/gh-transport.js +27 -0
  61. package/.agents/scripts/lib/git-utils.js +16 -9
  62. package/.agents/scripts/lib/maintainability-engine.js +27 -6
  63. package/.agents/scripts/lib/maintainability-utils.js +20 -2
  64. package/.agents/scripts/lib/orchestration/check-baselines/phases/evaluate.js +4 -1
  65. package/.agents/scripts/lib/orchestration/evidence-stream.js +186 -0
  66. package/.agents/scripts/lib/orchestration/file-assumptions.js +2 -19
  67. package/.agents/scripts/lib/orchestration/git-cleanup/phases/branches-reap.js +3 -7
  68. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes-ff.js +34 -40
  69. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes.js +4 -3
  70. package/.agents/scripts/lib/orchestration/plan-persist/persist-helpers.js +2 -19
  71. package/.agents/scripts/lib/orchestration/pr-watch.js +1 -5
  72. package/.agents/scripts/lib/orchestration/project-meta-cache.js +17 -4
  73. package/.agents/scripts/lib/orchestration/reassert-status-column.js +1 -8
  74. package/.agents/scripts/lib/orchestration/resolve-stories.js +1 -0
  75. package/.agents/scripts/lib/orchestration/review-providers/native.js +2 -2
  76. package/.agents/scripts/lib/orchestration/single-story-close/phase-timer.js +43 -0
  77. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +37 -13
  78. package/.agents/scripts/lib/orchestration/single-story-close/phases/finish.js +264 -0
  79. package/.agents/scripts/lib/orchestration/single-story-close/phases/open-pr.js +68 -0
  80. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-push.js +106 -0
  81. package/.agents/scripts/lib/orchestration/single-story-close/phases/reconcile-done.js +43 -35
  82. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-halt.js +52 -0
  83. package/.agents/scripts/lib/orchestration/single-story-close/result.js +273 -0
  84. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +68 -776
  85. package/.agents/scripts/lib/orchestration/story-close/context-budget-writeback.js +20 -9
  86. package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +2 -2
  87. package/.agents/scripts/lib/orchestration/story-close/ratchet-shrink-writeback.js +20 -12
  88. package/.agents/scripts/lib/orchestration/story-handoff.js +50 -21
  89. package/.agents/scripts/lib/orchestration/story-progress.js +32 -12
  90. package/.agents/scripts/lib/orchestration/ticket-validator.js +3 -13
  91. package/.agents/scripts/lib/orchestration/verify-credit.js +4 -1
  92. package/.agents/scripts/lib/qa/resolve-selection.js +1 -8
  93. package/.agents/scripts/lib/single-story/confirm-and-land.js +33 -0
  94. package/.agents/scripts/lib/single-story-sweep/reconcile-closing.js +43 -11
  95. package/.agents/scripts/lib/single-story-sweep/sweep-lock.js +130 -30
  96. package/.agents/scripts/lib/skills/parse-skill.js +1 -4
  97. package/.agents/scripts/lib/story-body/story-body.js +12 -1
  98. package/.agents/scripts/lib/suite-admission.js +3 -11
  99. package/.agents/scripts/lib/temp-retention.js +25 -11
  100. package/.agents/scripts/lib/test-run-credit.js +2 -5
  101. package/.agents/scripts/lib/transpile.js +193 -31
  102. package/.agents/scripts/lib/util/paths.js +31 -0
  103. package/.agents/scripts/lib/util/sleep.js +15 -0
  104. package/.agents/scripts/lib/validation-evidence.js +29 -3
  105. package/.agents/scripts/lib/wave-runner/live-probe.js +24 -0
  106. package/.agents/scripts/lib/workers/crap-worker.js +23 -12
  107. package/.agents/scripts/lib/workers/maintainability-report-worker.js +18 -12
  108. package/.agents/scripts/lib/workflow-closure.js +1 -8
  109. package/.agents/scripts/notify.js +83 -90
  110. package/.agents/scripts/plan-context.js +8 -4
  111. package/.agents/scripts/providers/github/auth.js +14 -30
  112. package/.agents/scripts/providers/github/blocked-by-add.js +11 -27
  113. package/.agents/scripts/providers/github/compose.js +1 -0
  114. package/.agents/scripts/providers/github/gh-token-diagnostics.js +130 -0
  115. package/.agents/scripts/providers/github/identity.js +158 -0
  116. package/.agents/scripts/providers/github/issues.js +2 -2
  117. package/.agents/scripts/providers/github/mappers.js +16 -19
  118. package/.agents/scripts/providers/github/projects-v2-graphql.js +4 -36
  119. package/.agents/scripts/providers/github/request-helpers.js +44 -0
  120. package/.agents/scripts/providers/github/sub-issue-add.js +11 -28
  121. package/.agents/scripts/providers/github.js +10 -2
  122. package/.agents/scripts/quality-preview.js +6 -19
  123. package/.agents/scripts/single-story-confirm-merge.js +8 -20
  124. package/.agents/scripts/single-story-init.js +0 -1
  125. package/.agents/scripts/stories-wave-tick.js +60 -46
  126. package/.agents/scripts/story-handoff.js +2 -23
  127. package/.agents/scripts/story-review-compute.js +3 -22
  128. package/.agents/scripts/sync-claude-agents.js +1 -12
  129. package/.agents/scripts/sync-claude-commands.js +1 -12
  130. package/.agents/scripts/update-crap-baseline.js +11 -20
  131. package/.agents/scripts/update-ticket-state.js +44 -45
  132. package/.agents/templates/docs/audit-sweep-runbook.md +1 -1
  133. package/.agents/workflows/audit-accessibility.md +1 -1
  134. package/.agents/workflows/audit-adrs.md +1 -1
  135. package/.agents/workflows/audit-architecture.md +1 -1
  136. package/.agents/workflows/audit-baselines.md +9 -4
  137. package/.agents/workflows/audit-clean-code.md +1 -1
  138. package/.agents/workflows/audit-data-model.md +1 -1
  139. package/.agents/workflows/audit-dependencies.md +1 -1
  140. package/.agents/workflows/audit-devops.md +1 -1
  141. package/.agents/workflows/audit-documentation.md +1 -1
  142. package/.agents/workflows/audit-exceptions.md +2 -2
  143. package/.agents/workflows/audit-mobile.md +1 -1
  144. package/.agents/workflows/audit-navigability.md +1 -1
  145. package/.agents/workflows/audit-performance.md +1 -1
  146. package/.agents/workflows/audit-privacy.md +1 -1
  147. package/.agents/workflows/audit-quality.md +1 -1
  148. package/.agents/workflows/audit-security.md +1 -1
  149. package/.agents/workflows/audit-seo.md +1 -1
  150. package/.agents/workflows/audit-sre.md +1 -1
  151. package/.agents/workflows/audit-to-stories.md +9 -7
  152. package/.agents/workflows/audit-ux-ui.md +1 -1
  153. package/.agents/workflows/helpers/audit-lens-core.md +8 -5
  154. package/.agents/workflows/helpers/deliver-digest.md +4 -5
  155. package/.agents/workflows/helpers/deliver-story-reference.md +4 -4
  156. package/.agents/workflows/mandrel-deliver.md +3 -1
  157. package/README.md +6 -3
  158. package/docs/CHANGELOG.md +42 -0
  159. package/lib/cli/doctor-checks/codex.js +240 -0
  160. package/lib/cli/doctor-checks/merge-driver.js +79 -0
  161. package/lib/cli/doctor-checks/payload.js +201 -0
  162. package/lib/cli/doctor-checks/read-json.js +16 -0
  163. package/lib/cli/doctor-checks/runtime-deps.js +146 -0
  164. package/lib/cli/doctor-checks/spawn.js +18 -0
  165. package/lib/cli/doctor-checks/sync-parity.js +205 -0
  166. package/lib/cli/doctor-checks/test-credit-path.js +270 -0
  167. package/lib/cli/doctor-checks/toolchain.js +137 -0
  168. package/lib/cli/doctor-checks/version-current.js +82 -0
  169. package/lib/cli/registry.js +40 -1330
  170. package/package.json +1 -1
@@ -17,7 +17,7 @@ import {
17
17
  buildScopePredicate,
18
18
  scoreCoverageFinal,
19
19
  } from '../coverage-baseline.js';
20
- import { missingCoverageArtifactMessage } from '../coverage-capture.js';
20
+ import { MissingCoverageArtifactError } from '../coverage-capture.js';
21
21
  import { loadCoverage } from '../coverage-utils.js';
22
22
  import {
23
23
  resolveEscomplexVersion,
@@ -78,20 +78,9 @@ function resolveQualityBlock({ quality, config } = {}) {
78
78
  return {};
79
79
  }
80
80
 
81
- /**
82
- * No coverage artifact: a full-scope refresh over zero rows would read as
83
- * "nothing to score", so it throws naming the capture contract; a scoped one
84
- * yields no rows and `refreshBaseline` refuses the missing in-scope files.
85
- *
86
- * @param {string} absPath
87
- * @param {{ fullScope?: boolean } | undefined} opts
88
- * @returns {object[]}
89
- */
90
- function noArtifactRows(absPath, opts) {
91
- if (opts?.fullScope) {
92
- throw new Error(missingCoverageArtifactMessage(absPath));
93
- }
94
- return [];
81
+ /** @param {string} absPath */
82
+ function refuseMissingArtifact(absPath) {
83
+ throw new MissingCoverageArtifactError(absPath);
95
84
  }
96
85
 
97
86
  /**
@@ -115,7 +104,7 @@ function buildDefaultCrapScorer({ cwd, config, quality } = {}) {
115
104
  ? coverageRelPath
116
105
  : path.resolve(effectiveCwd, coverageRelPath);
117
106
  const coverage = loadCoverage(coverageAbs);
118
- if (!coverage && requireCoverage) return noArtifactRows(coverageAbs, opts);
107
+ if (!coverage && requireCoverage) refuseMissingArtifact(coverageAbs);
119
108
  const scopeFiles = opts?.fullScope ? null : (files ?? null);
120
109
  const { rows } = await scanAndScore({
121
110
  targetDirs,
@@ -126,7 +115,7 @@ function buildDefaultCrapScorer({ cwd, config, quality } = {}) {
126
115
  scopeFiles,
127
116
  });
128
117
  resolveEscomplexVersion(effectiveCwd);
129
- resolveTsTranspilerVersion();
118
+ resolveTsTranspilerVersion({ cwd: effectiveCwd, targetDirs });
130
119
  return (rows ?? []).filter(
131
120
  (r) => typeof r?.crap === 'number' && Number.isFinite(r.crap),
132
121
  );
@@ -135,8 +124,7 @@ function buildDefaultCrapScorer({ cwd, config, quality } = {}) {
135
124
 
136
125
  /**
137
126
  * Coverage rows from the configured `coverage.coveragePath` artifact, scoped by
138
- * the optional `.c8rc.cjs`. A missing artifact throws on a full-scope refresh:
139
- * an empty row set would otherwise read as "nothing measured".
127
+ * the optional `.c8rc.cjs`. A missing artifact throws on every scope.
140
128
  *
141
129
  * @param {{ cwd: string, config?: object, quality?: object }} opts
142
130
  * @returns {(files: string[], opts: object) => object[]}
@@ -149,7 +137,7 @@ function buildDefaultCoverageScorer({ cwd, config, quality } = {}) {
149
137
  const effectiveCwd = opts?.cwd ?? cwd ?? process.cwd();
150
138
  const coverageFinalPath = path.resolve(effectiveCwd, coverageRelPath);
151
139
  if (!nodeFs.existsSync(coverageFinalPath)) {
152
- return noArtifactRows(coverageFinalPath, opts);
140
+ refuseMissingArtifact(coverageFinalPath);
153
141
  }
154
142
  const raw = JSON.parse(nodeFs.readFileSync(coverageFinalPath, 'utf-8'));
155
143
  let c8Scope;
@@ -266,6 +254,18 @@ export function resolveDefaultScorer(kind, { cwd } = {}) {
266
254
  return builder({ cwd: effectiveCwd, quality });
267
255
  }
268
256
 
257
+ /** The CRAP stamp anchors where check-baselines does: target dirs + root. */
258
+ function defaultExtrasContext(kind, cwd) {
259
+ if (kind !== 'crap') return { cwd };
260
+ let targetDirs;
261
+ try {
262
+ targetDirs = getQuality(resolveConfig({ cwd }))?.crap?.targetDirs;
263
+ } catch {
264
+ targetDirs = undefined;
265
+ }
266
+ return { cwd, targetDirs };
267
+ }
268
+
269
269
  /**
270
270
  * Refresh the on-disk baseline for `kind`. `scopeFiles: null` without
271
271
  * `fullScope` derives scope from `git diff baseRef..headRef`; `fullScope`
@@ -286,6 +286,7 @@ export function resolveDefaultScorer(kind, { cwd } = {}) {
286
286
  * cwd?: string,
287
287
  * requireRowsForScopeFiles?: boolean,
288
288
  * requiredScopeFilePredicate?: (file: string) => boolean,
289
+ * extrasContext?: { cwd?: string, targetDirs?: string[] },
289
290
  * }} opts
290
291
  * @returns {Promise<{
291
292
  * kind: string,
@@ -310,6 +311,7 @@ export async function refreshBaseline(opts = {}) {
310
311
  cwd = process.cwd(),
311
312
  requireRowsForScopeFiles = false,
312
313
  requiredScopeFilePredicate,
314
+ extrasContext,
313
315
  } = opts;
314
316
 
315
317
  validateOptions({ kind, scopeFiles, fullScope, writePath });
@@ -356,6 +358,12 @@ export async function refreshBaseline(opts = {}) {
356
358
  });
357
359
 
358
360
  const priorEnvelope = readPriorEnvelope(writePath, fs);
361
+ const writeFiles = resolveWriteScopeFiles({
362
+ kind,
363
+ scope,
364
+ rows: canonicalRows,
365
+ priorRows: priorEnvelope?.rows,
366
+ });
359
367
 
360
368
  const envelope = writeEnvelope({
361
369
  kind,
@@ -363,10 +371,11 @@ export async function refreshBaseline(opts = {}) {
363
371
  prior: priorEnvelope?.rows,
364
372
  priorEnvelope,
365
373
  epsilon,
374
+ extrasContext: extrasContext ?? defaultExtrasContext(kind, cwd),
366
375
  scope:
367
376
  scope.mode === 'full'
368
377
  ? null
369
- : { mode: 'diff', files: new Set(scope.files) },
378
+ : { mode: 'diff', files: new Set(writeFiles) },
370
379
  });
371
380
 
372
381
  // The writer returns the prior object itself when nothing changed; skip the
@@ -383,13 +392,47 @@ export async function refreshBaseline(opts = {}) {
383
392
  scope: {
384
393
  mode: scope.mode,
385
394
  ref: scope.ref,
386
- files: [...scope.files],
395
+ files: writeFiles,
387
396
  },
388
397
  envelope,
389
398
  wrote,
390
399
  };
391
400
  }
392
401
 
402
+ /**
403
+ * The files whose rows a scoped refresh rewrites. Duplication is pairwise, so
404
+ * a changed file also moves the rows of files it shares (or shared) a clone
405
+ * with; for that kind the scope widens to the head clone partners of every
406
+ * scoped file, plus every out-of-scope prior row that vanished or shrank (a
407
+ * removed clone's partner appears in no head pair). A rise in an unrelated
408
+ * file stays out of scope, so a branch never owns drift it did not cause.
409
+ *
410
+ * @param {{ kind: string, scope: { mode: string, files: string[] }, rows: object[], priorRows?: object[] }} args
411
+ * @returns {string[]}
412
+ */
413
+ function resolveWriteScopeFiles({ kind, scope, rows, priorRows }) {
414
+ if (kind !== 'duplication' || scope.mode === 'full') return [...scope.files];
415
+ const headByPath = new Map(rows.map((row) => [row.path, row]));
416
+ const partners = scope.files.flatMap(
417
+ (file) => headByPath.get(file)?.partners ?? [],
418
+ );
419
+ const shrunk = (priorRows ?? [])
420
+ .filter((prior) => isShrunk(prior, headByPath.get(prior.path)))
421
+ .map((prior) => prior.path);
422
+ return [
423
+ ...new Set([
424
+ ...scope.files,
425
+ ...partners.map(canonicalizeBaselinePath),
426
+ ...shrunk,
427
+ ]),
428
+ ];
429
+ }
430
+
431
+ /** A prior row whose clones vanished (no head row) or shrank. */
432
+ function isShrunk(prior, head) {
433
+ return !head || head.percentage < prior.percentage;
434
+ }
435
+
393
436
  /**
394
437
  * Rows leave the service canonical whatever scorer produced them. Only
395
438
  * path-keyed kinds carry a path; bundle-size rows are keyed on a name.
@@ -27,6 +27,7 @@ import { assertCanonical } from './path-canon.js';
27
27
  * priorEnvelope?: object,
28
28
  * epsilon?: number,
29
29
  * scope?: {mode: 'full'|'diff', files: Set<string>|Iterable<string>}|null,
30
+ * extrasContext?: object,
30
31
  * }} params
31
32
  * @returns {object}
32
33
  */
@@ -38,6 +39,7 @@ export function write({
38
39
  priorEnvelope,
39
40
  epsilon,
40
41
  scope,
42
+ extrasContext = {},
41
43
  } = {}) {
42
44
  if (typeof kind !== 'string' || kind.length === 0) {
43
45
  throw new TypeError('writer.write: kind is required');
@@ -87,7 +89,9 @@ export function write({
87
89
  rows: sortedRows,
88
90
  kernelVersion: kernelVersion ?? currentKernelVersion(kind),
89
91
  extras:
90
- typeof mod.envelopeExtras === 'function' ? mod.envelopeExtras() : null,
92
+ typeof mod.envelopeExtras === 'function'
93
+ ? mod.envelopeExtras(extrasContext)
94
+ : null,
91
95
  });
92
96
  assertEnvelope(envelope);
93
97
  return envelope;
@@ -14,6 +14,7 @@ import yaml from 'js-yaml';
14
14
  import picomatch from 'picomatch';
15
15
 
16
16
  import { Logger } from './Logger.js';
17
+ import { toPosix } from './util/paths.js';
17
18
 
18
19
  /** npm package name → pending tag. Preferred-first: the first match wins. */
19
20
  export const BDD_RUNNER_TAG_TABLE = Object.freeze({
@@ -28,14 +29,14 @@ export const BDD_RUNNER_TAG_TABLE = Object.freeze({
28
29
  * `skip` forms (parsers may strip the `@`).
29
30
  */
30
31
  export const PENDING_TAGS = Object.freeze(
31
- new Set(
32
- Object.values(BDD_RUNNER_TAG_TABLE).flatMap((tag) => [
33
- tag,
34
- tag.startsWith('@') ? tag.slice(1) : `@${tag}`,
35
- ]),
36
- ),
32
+ new Set(Object.values(BDD_RUNNER_TAG_TABLE).flatMap(withAndWithoutAt)),
37
33
  );
38
34
 
35
+ /** @param {string} tag */
36
+ function withAndWithoutAt(tag) {
37
+ return [tag, tag.startsWith('@') ? tag.slice(1) : `@${tag}`];
38
+ }
39
+
39
40
  const FALLBACK = Object.freeze({
40
41
  runner: null,
41
42
  pendingTag: null,
@@ -270,10 +271,6 @@ function hasGlobChar(s) {
270
271
  return /[*?[]/.test(s);
271
272
  }
272
273
 
273
- function toPosix(p) {
274
- return p.split(path.sep).join('/');
275
- }
276
-
277
274
  function existsSyncDir(p, logger) {
278
275
  try {
279
276
  return existsSync(p) && statSync(p).isDirectory();
@@ -9,9 +9,11 @@
9
9
  * @module lib/child-exec
10
10
  */
11
11
 
12
- import { execFile, execFileSync, spawnSync } from 'node:child_process';
12
+ import { execFile, execFileSync, spawn, spawnSync } from 'node:child_process';
13
13
  import { promisify } from 'node:util';
14
14
 
15
+ import { streamChild } from './child-stream.js';
16
+
15
17
  const MIB = 1024 * 1024;
16
18
 
17
19
  /**
@@ -147,6 +149,17 @@ export async function spawnCaptureAsync(file, args, opts = {}) {
147
149
  );
148
150
  }
149
151
 
152
+ /**
153
+ * Spawn and stream each output chunk to `opts.onChunk` while retaining a
154
+ * bounded tail; see `child-stream.js` for the contract.
155
+ *
156
+ * @param {string} file
157
+ * @param {string[]} args
158
+ * @param {object} [opts]
159
+ */
160
+ export const spawnStreamAsync = (file, args, opts = {}) =>
161
+ streamChild(file, args, { spawnImpl: spawn, ...opts });
162
+
150
163
  /**
151
164
  * `status=null` is printed verbatim: it means the child was killed.
152
165
  *
@@ -0,0 +1,122 @@
1
+ /**
2
+ * The streaming half of the child-process surface; `child-exec.js` owns the
3
+ * `node:child_process` import and injects `spawn`.
4
+ */
5
+
6
+ import { StringDecoder } from 'node:string_decoder';
7
+
8
+ import {
9
+ groupSpawnOptions,
10
+ superviseGroup,
11
+ TIMEOUT_EXIT_CODE,
12
+ } from './process-group.js';
13
+
14
+ /** `execFile`'s default `maxBuffer`: callers still see what they saw. */
15
+ const STREAM_TAIL_BYTES = 1024 * 1024;
16
+
17
+ /** Keeps the last `limit` bytes, compacting lazily. */
18
+ function createTail(limit) {
19
+ let chunks = [];
20
+ let size = 0;
21
+ const compact = () => {
22
+ if (size <= limit) return;
23
+ const all = Buffer.concat(chunks);
24
+ chunks = [all.subarray(all.length - limit)];
25
+ size = limit;
26
+ };
27
+ return {
28
+ push(buf) {
29
+ chunks.push(buf);
30
+ size += buf.length;
31
+ if (size > limit * 2) compact();
32
+ },
33
+ text() {
34
+ compact();
35
+ return Buffer.concat(chunks).toString('utf8');
36
+ },
37
+ };
38
+ }
39
+
40
+ /** Retain the tail and hand decoded text on; a throwing sink is ignored. */
41
+ function chunkForwarder(tail, name, onChunk) {
42
+ const decoder = new StringDecoder('utf8');
43
+ return (buf) => {
44
+ tail.push(buf);
45
+ const text = decoder.write(buf);
46
+ if (!onChunk || text.length === 0) return;
47
+ try {
48
+ onChunk(text, name);
49
+ } catch {}
50
+ };
51
+ }
52
+
53
+ /**
54
+ * Shell-free spawn streaming each chunk to `onChunk(text, stream)` in arrival
55
+ * order; only a bounded tail is retained. The process group is killed on
56
+ * `timeoutMs` (status 124, `timedOut`) or `signal` abort. Never rejects.
57
+ *
58
+ * @returns {Promise<{ status: number, stdout: string, stderr: string, timedOut: boolean, pid: number|null }>}
59
+ */
60
+ export function streamChild(file, args, opts = {}) {
61
+ const {
62
+ onChunk,
63
+ timeoutMs,
64
+ signal,
65
+ input,
66
+ tailBytes = STREAM_TAIL_BYTES,
67
+ spawnImpl,
68
+ ...rest
69
+ } = opts;
70
+ return new Promise((resolve) => {
71
+ const stdout = createTail(tailBytes);
72
+ const stderr = createTail(tailBytes);
73
+ let child;
74
+ try {
75
+ child = spawnImpl(file, args, {
76
+ ...rest,
77
+ ...groupSpawnOptions(),
78
+ shell: false,
79
+ stdio: ['pipe', 'pipe', 'pipe'],
80
+ });
81
+ } catch (err) {
82
+ resolve({
83
+ status: 1,
84
+ stdout: '',
85
+ stderr: err.message,
86
+ timedOut: false,
87
+ pid: null,
88
+ });
89
+ return;
90
+ }
91
+ const supervisor = superviseGroup(child, {
92
+ timeoutMs,
93
+ abortSignal: signal,
94
+ signalOnParentSignal: 'SIGTERM',
95
+ });
96
+ let spawnError = null;
97
+ let settled = false;
98
+ const settle = (code) => {
99
+ if (settled) return;
100
+ settled = true;
101
+ supervisor.release();
102
+ const { timedOut } = supervisor;
103
+ const exited = Number.isInteger(code) ? code : 1;
104
+ resolve({
105
+ status: timedOut ? TIMEOUT_EXIT_CODE : exited,
106
+ stdout: stdout.text().trim(),
107
+ stderr: (stderr.text() || spawnError?.message || '').trim(),
108
+ timedOut,
109
+ pid: child.pid ?? null,
110
+ });
111
+ };
112
+ child.stdout.on('data', chunkForwarder(stdout, 'stdout', onChunk));
113
+ child.stderr.on('data', chunkForwarder(stderr, 'stderr', onChunk));
114
+ child.on('error', (err) => {
115
+ spawnError = err;
116
+ if (!child.pid) settle(1);
117
+ });
118
+ child.on('close', settle);
119
+ child.stdin.on('error', () => {});
120
+ child.stdin.end(input ?? '');
121
+ });
122
+ }
@@ -22,6 +22,7 @@ import {
22
22
  resolveTempRetention,
23
23
  sweepTempRetention,
24
24
  } from './temp-retention.js';
25
+ import { concurrentMap, FANOUT_CONCURRENCY } from './util/concurrent-map.js';
25
26
 
26
27
  const MS_PER_DAY = 24 * 60 * 60 * 1000;
27
28
 
@@ -95,25 +96,30 @@ function resolveScopedTempRoot(projectRoot, config) {
95
96
  }
96
97
 
97
98
  /**
98
- * Issue states, read once per id. A failed read is `error`, which every
99
- * caller treats as "not closed" — reads fail safe.
99
+ * Issue states, read once per id with at most `FANOUT_CONCURRENCY` in
100
+ * flight. A failed read is `error`, which every caller treats as "not
101
+ * closed" — reads fail safe.
100
102
  *
101
103
  * @param {object|null} provider
102
104
  * @param {Iterable<number>} ids
103
105
  * @returns {Promise<Map<number, 'closed'|'open'|'error'>>}
104
106
  */
105
107
  async function readIssueStates(provider, ids) {
106
- const states = new Map();
107
- for (const id of ids) {
108
- try {
109
- const ticket = await provider.getTicket(id);
110
- const state = String(ticket?.state ?? '').toLowerCase();
111
- states.set(id, state === 'closed' ? 'closed' : 'open');
112
- } catch {
113
- states.set(id, 'error');
114
- }
115
- }
116
- return states;
108
+ const list = [...ids];
109
+ const read = await concurrentMap(
110
+ list,
111
+ async (id) => {
112
+ try {
113
+ const ticket = await provider.getTicket(id);
114
+ const state = String(ticket?.state ?? '').toLowerCase();
115
+ return state === 'closed' ? 'closed' : 'open';
116
+ } catch {
117
+ return 'error';
118
+ }
119
+ },
120
+ { concurrency: FANOUT_CONCURRENCY },
121
+ );
122
+ return new Map(list.map((id, i) => [id, read[i]]));
117
123
  }
118
124
 
119
125
  /** Top-level name of `target` beneath `tempRoot`. */
@@ -16,6 +16,55 @@ export function parseTicketId(value) {
16
16
  return Number.isInteger(n) && n > 0 ? n : null;
17
17
  }
18
18
 
19
+ /**
20
+ * `--story <id> [--cwd <path>]`; an invalid story id reads as `null`.
21
+ *
22
+ * @returns {{ storyId: number|null, cwd: string|null }}
23
+ */
24
+ export function parseStoryCwdArgv(argv) {
25
+ const { values } = parseArgs({
26
+ args: argv,
27
+ options: {
28
+ story: { type: 'string' },
29
+ cwd: { type: 'string' },
30
+ },
31
+ strict: false,
32
+ });
33
+ const storyId = Number.parseInt(values.story ?? '', 10);
34
+ return {
35
+ storyId: Number.isInteger(storyId) && storyId > 0 ? storyId : null,
36
+ cwd: values.cwd ?? null,
37
+ };
38
+ }
39
+
40
+ /**
41
+ * Ratchet-gate argv. A valueless string flag reads as `null` and never
42
+ * swallows the next `--flag`.
43
+ */
44
+ export function parseGateArgv(argv, { strings = [], booleans = [] }) {
45
+ const stringFlags = new Set(strings.map((name) => `--${name}`));
46
+ const args = argv.filter(
47
+ (arg, i) =>
48
+ !(stringFlags.has(arg) && String(argv[i + 1] ?? '').startsWith('--')),
49
+ );
50
+ const options = {};
51
+ for (const name of strings) options[name] = { type: 'string' };
52
+ for (const name of booleans) options[name] = { type: 'boolean' };
53
+ const { values } = parseArgs({
54
+ args,
55
+ options,
56
+ strict: false,
57
+ allowPositionals: true,
58
+ });
59
+ const out = {};
60
+ for (const name of strings) {
61
+ const value = values[name];
62
+ out[name] = typeof value === 'string' && value !== '' ? value : null;
63
+ }
64
+ for (const name of booleans) out[name] = values[name] === true;
65
+ return out;
66
+ }
67
+
19
68
  /**
20
69
  * Under `strict: false`, `--flag=false` arrives as the string `'false'`.
21
70
  *
@@ -4,7 +4,11 @@ import { existsSync } from 'node:fs';
4
4
 
5
5
  import { _internals as baselineReaderInternals } from '../baselines/reader.js';
6
6
  import { getChangedFiles } from '../changed-files.js';
7
- import { COVERAGE_GATE_DEFAULTS, getQuality } from '../config/quality.js';
7
+ import {
8
+ COVERAGE_GATE_DEFAULTS,
9
+ CRAP_GATE_DEFAULTS,
10
+ getQuality,
11
+ } from '../config/quality.js';
8
12
  import { filterFilesUnderTargets } from '../coverage-capture.js';
9
13
  import { hasNpmScript, readPackageScripts } from '../npm-scripts.js';
10
14
  import { KNOWN_KINDS } from '../orchestration/check-baselines/phases/parse-args.js';
@@ -70,7 +74,22 @@ export function isCrapGateEnabled(config) {
70
74
  }
71
75
 
72
76
  /**
73
- * Coverage-capture registers when the CRAP gate is on AND a `test:coverage`
77
+ * The npm script that writes the CRAP coverage artifact —
78
+ * `gates.crap.captureScript`, default `test:coverage`. Read
79
+ * from the unresolved block for the same reason as {@link isCrapGateEnabled}.
80
+ *
81
+ * @param {object|undefined|null} config - Canonical resolved config.
82
+ * @returns {string}
83
+ */
84
+ function crapCaptureScript(config) {
85
+ const script = config?.delivery?.quality?.gates?.crap?.captureScript;
86
+ return typeof script === 'string' && script.trim().length > 0
87
+ ? script.trim()
88
+ : CRAP_GATE_DEFAULTS.captureScript;
89
+ }
90
+
91
+ /**
92
+ * Coverage-capture registers when the CRAP gate is on AND the CRAP capture
74
93
  * script exists; {@link resolveCreditedDepositor} builds on it.
75
94
  *
76
95
  * @param {object|undefined|null} config - Canonical resolved config.
@@ -78,7 +97,10 @@ export function isCrapGateEnabled(config) {
78
97
  * @returns {boolean}
79
98
  */
80
99
  function isCoverageCaptureActive(config, scripts) {
81
- return isCrapGateEnabled(config) && hasNpmScript(scripts, 'test:coverage');
100
+ return (
101
+ isCrapGateEnabled(config) &&
102
+ hasNpmScript(scripts, crapCaptureScript(config))
103
+ );
82
104
  }
83
105
 
84
106
  /**
@@ -341,10 +363,19 @@ function coverageCaptureRunsSuite({
341
363
 
342
364
  /**
343
365
  * Names every suite the capture can run: under `captureScope: "affected"` a
344
- * red may come from a delta refresh the base-sync triggered, not the Story.
366
+ * red may come from a delta refresh the base-sync triggered, not the Story;
367
+ * a non-default `gates.crap.captureScript` is named beside `test:coverage`.
368
+ *
369
+ * @param {string} captureScript The CRAP capture script ({@link crapCaptureScript}).
370
+ * @returns {string}
345
371
  */
346
- const COVERAGE_CAPTURE_HINT =
347
- 'Coverage capture failed — its suite run (`npm run test:coverage`, or `npm run test:coverage:affected` under `captureScope: "affected"`, including a delta refresh keyed on the stamped commit after a base-sync) exited non-zero. The coverage-capture log names which ran; fix the failing tests or coverage-threshold breaches, then re-run close.';
372
+ function coverageCaptureHint(captureScript) {
373
+ const crapScript =
374
+ captureScript === CRAP_GATE_DEFAULTS.captureScript
375
+ ? ''
376
+ : `, the CRAP gate's own \`npm run ${captureScript}\` (\`gates.crap.captureScript\`)`;
377
+ return `Coverage capture failed — its suite run (\`npm run test:coverage\`${crapScript}, or \`npm run test:coverage:affected\` under \`captureScope: "affected"\`, including a delta refresh keyed on the stamped commit after a base-sync) exited non-zero. The coverage-capture log names which ran; fix the failing tests or coverage-threshold breaches, then re-run close.`;
378
+ }
348
379
 
349
380
  const COVERAGE_CAPTURE_ARGS = Object.freeze([
350
381
  '.agents/scripts/coverage-capture.js',
@@ -407,8 +438,8 @@ export const GATE_TIMEOUT_HINT = `The gate outran the suite timeout (\`delivery.
407
438
  /**
408
439
  * Build the close-validation gate list, cheapest fast-fail first: typecheck →
409
440
  * lint → [test] → format → [quality-preview-mi] → [coverage-capture →
410
- * quality-preview-crap] → check-baselines. Coverage-capture registers only when CRAP is enabled AND a
411
- * `test:coverage` script exists; it then carries test-failure signalling and
441
+ * quality-preview-crap] → check-baselines. Coverage-capture registers only when CRAP is enabled AND its
442
+ * capture script (`gates.crap.captureScript`, default `test:coverage`) exists; it then carries test-failure signalling and
412
443
  * the plain `test` gate is dropped, so there is always exactly one test gate.
413
444
  *
414
445
  * @param {{ config?: object, baseBranch?: string, cwd?: string, packageScripts?: Record<string, string>, presentBaselines?: string[]|Set<string>, log?: (message: string) => void, getChangedFilesImpl?: typeof getChangedFiles }} [opts]
@@ -520,7 +551,7 @@ export function buildDefaultGates({
520
551
  name: 'coverage-capture',
521
552
  cmd: 'node',
522
553
  args: [...COVERAGE_CAPTURE_ARGS],
523
- hint: COVERAGE_CAPTURE_HINT,
554
+ hint: coverageCaptureHint(crapCaptureScript(config)),
524
555
  lockEventChannel: true,
525
556
  ...(captureSkipPredicted
526
557
  ? { skip: { reason: 'incremental-no-crap-changes' } }
@@ -17,6 +17,7 @@ import {
17
17
  collectLocalSkillFiles,
18
18
  collectSkillFiles,
19
19
  } from '../skills/walk-skill-files.js';
20
+ import { dirExists } from '../util/paths.js';
20
21
 
21
22
  /**
22
23
  * Project-relative POSIX home of the projection. Outside the `core`/`stack`
@@ -34,18 +35,6 @@ const CODEX_SKILL_MARKER = '<!-- AUTO-GENERATED by mandrel';
34
35
 
35
36
  const LOOPS_NS = 'loops';
36
37
 
37
- /**
38
- * @param {string} dir
39
- * @returns {boolean}
40
- */
41
- function dirExists(dir) {
42
- try {
43
- return fs.statSync(dir).isDirectory();
44
- } catch {
45
- return false;
46
- }
47
- }
48
-
49
38
  /**
50
39
  * @param {string} dir
51
40
  * @param {(entry: import('node:fs').Dirent) => boolean} keep
@@ -49,6 +49,21 @@ export const CRAP_GATE = {
49
49
  default: [...CRAP_GATE_DEFAULTS.ignoreGlobs],
50
50
  },
51
51
  incrementalCoverage: INCREMENTAL_COVERAGE_SCHEMA,
52
+ coveragePath: {
53
+ type: ['string', 'null'],
54
+ minLength: 1,
55
+ description:
56
+ "Repo-relative Istanbul `coverage-final.json` the CRAP gate joins against (Story #5717). `null` or unset falls back to `delivery.quality.gates.coverage.coveragePath`. When it differs from that path the CRAP gate has its OWN coverage source: `coverage-capture.js` refreshes it full-scope via `captureScript`, and the handoff seat, close preview and `update-crap-baseline.js` read it. It must live in a different directory from the coverage gate's artifact (the capture stamp is per directory); a same-directory path is refused at config resolution.",
57
+ default: null,
58
+ },
59
+ captureScript: {
60
+ type: 'string',
61
+ minLength: 1,
62
+ pattern: '^[A-Za-z0-9@:._/-]+$',
63
+ description:
64
+ 'npm script name (run as `npm run <script>`, never a shell command) that writes the CRAP coverage artifact. Close registers the coverage-capture gate, and the capture refusal and credited-run probe key, on this script.',
65
+ default: CRAP_GATE_DEFAULTS.captureScript,
66
+ },
52
67
  },
53
68
  additionalProperties: false,
54
69
  };
@@ -5,10 +5,10 @@ import { gateBase } from './shared.js';
5
5
  export const MUTATION_GATE = {
6
6
  type: 'object',
7
7
  description:
8
- 'Stryker mutation-score ratchet. Off in practice for most consumers — the baseline kind is registered but no framework path runs Stryker.',
8
+ 'Stryker mutation-score ratchet. Disabled by default: no framework path runs Stryker, so enable it only alongside a consumer-provided Stryker run that writes the mutation report the baseline is scored from.',
9
9
  properties: {
10
10
  ...gateBase({
11
- enabled: true,
11
+ enabled: false,
12
12
  baselinePath: 'baselines/mutation.json',
13
13
  tolerance: { kind: 'percent', value: 0 },
14
14
  floors: { '*': { score: 60 } },