mandrel 2.86.0 → 2.88.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 (165) hide show
  1. package/.agents/README.md +29 -0
  2. package/.agents/agents/auditor.md +4 -3
  3. package/.agents/docs/agentrc-reference.json +2 -1
  4. package/.agents/docs/configuration.md +44 -20
  5. package/.agents/docs/workflows.md +1 -1
  6. package/.agents/schemas/agentrc.schema.json +18 -12
  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 +23 -3
  17. package/.agents/scripts/deliver-run.js +11 -0
  18. package/.agents/scripts/diagnose-friction.js +3 -3
  19. package/.agents/scripts/lib/baselines/bundle-size-scorer.js +115 -0
  20. package/.agents/scripts/lib/baselines/coverage-updater-cli.js +122 -29
  21. package/.agents/scripts/lib/baselines/crap-updater-cli.js +45 -14
  22. package/.agents/scripts/lib/baselines/duplication-scanner.js +45 -2
  23. package/.agents/scripts/lib/baselines/env-overrides.js +39 -34
  24. package/.agents/scripts/lib/baselines/kernel.js +3 -2
  25. package/.agents/scripts/lib/baselines/kinds/crap.js +14 -38
  26. package/.agents/scripts/lib/baselines/preview-gates.js +4 -1
  27. package/.agents/scripts/lib/baselines/refresh-service.js +101 -22
  28. package/.agents/scripts/lib/baselines/writer.js +5 -1
  29. package/.agents/scripts/lib/bdd-runner-detect.js +7 -10
  30. package/.agents/scripts/lib/child-exec.js +14 -1
  31. package/.agents/scripts/lib/child-stream.js +122 -0
  32. package/.agents/scripts/lib/clean-temp.js +19 -13
  33. package/.agents/scripts/lib/cli-args.js +49 -0
  34. package/.agents/scripts/lib/codex/skills-projection.js +1 -12
  35. package/.agents/scripts/lib/config/gates/coverage.schema.js +1 -1
  36. package/.agents/scripts/lib/config/gates/mutation.schema.js +2 -2
  37. package/.agents/scripts/lib/config/gates/shared.js +1 -1
  38. package/.agents/scripts/lib/config/gh-config-dir.js +63 -0
  39. package/.agents/scripts/lib/config/github.js +2 -0
  40. package/.agents/scripts/lib/config/paths.js +14 -3
  41. package/.agents/scripts/lib/config/quality.js +6 -2
  42. package/.agents/scripts/lib/config-resolver.js +78 -64
  43. package/.agents/scripts/lib/config-settings-schema-delivery.js +4 -3
  44. package/.agents/scripts/lib/config-settings-schema.js +7 -0
  45. package/.agents/scripts/lib/coverage-baseline.js +7 -6
  46. package/.agents/scripts/lib/coverage-capture.js +59 -0
  47. package/.agents/scripts/lib/crap-utils.js +59 -47
  48. package/.agents/scripts/lib/full-suite-lock.js +1 -10
  49. package/.agents/scripts/lib/gates/baseline-store.js +10 -0
  50. package/.agents/scripts/lib/generated/agentrc-validator.js +1 -1
  51. package/.agents/scripts/lib/gh-exec.js +45 -2
  52. package/.agents/scripts/lib/gh-transport.js +27 -0
  53. package/.agents/scripts/lib/git-utils.js +16 -9
  54. package/.agents/scripts/lib/maintainability-engine.js +27 -6
  55. package/.agents/scripts/lib/maintainability-utils.js +14 -1
  56. package/.agents/scripts/lib/observability/source-classifier.js +1 -0
  57. package/.agents/scripts/lib/orchestration/check-baselines/phases/evaluate.js +33 -3
  58. package/.agents/scripts/lib/orchestration/evidence-stream.js +186 -0
  59. package/.agents/scripts/lib/orchestration/file-assumptions.js +2 -19
  60. package/.agents/scripts/lib/orchestration/git-cleanup/phases/branches-reap.js +3 -7
  61. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes-ff.js +34 -40
  62. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes.js +4 -3
  63. package/.agents/scripts/lib/orchestration/plan-persist/persist-helpers.js +2 -19
  64. package/.agents/scripts/lib/orchestration/pr-watch.js +1 -5
  65. package/.agents/scripts/lib/orchestration/project-meta-cache.js +17 -4
  66. package/.agents/scripts/lib/orchestration/reassert-status-column.js +1 -8
  67. package/.agents/scripts/lib/orchestration/resolve-stories.js +1 -0
  68. package/.agents/scripts/lib/orchestration/review-providers/native.js +2 -2
  69. package/.agents/scripts/lib/orchestration/single-story-close/phase-timer.js +43 -0
  70. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +37 -13
  71. package/.agents/scripts/lib/orchestration/single-story-close/phases/finish.js +264 -0
  72. package/.agents/scripts/lib/orchestration/single-story-close/phases/open-pr.js +68 -0
  73. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-push.js +106 -0
  74. package/.agents/scripts/lib/orchestration/single-story-close/phases/reconcile-done.js +43 -35
  75. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-halt.js +52 -0
  76. package/.agents/scripts/lib/orchestration/single-story-close/result.js +273 -0
  77. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +68 -776
  78. package/.agents/scripts/lib/orchestration/story-close/context-budget-writeback.js +20 -9
  79. package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +2 -2
  80. package/.agents/scripts/lib/orchestration/story-close/ratchet-shrink-writeback.js +20 -12
  81. package/.agents/scripts/lib/orchestration/story-handoff.js +50 -21
  82. package/.agents/scripts/lib/orchestration/story-progress.js +32 -12
  83. package/.agents/scripts/lib/orchestration/ticket-validator.js +3 -13
  84. package/.agents/scripts/lib/qa/resolve-selection.js +1 -8
  85. package/.agents/scripts/lib/single-story/confirm-and-land.js +33 -0
  86. package/.agents/scripts/lib/single-story-sweep/reconcile-closing.js +43 -11
  87. package/.agents/scripts/lib/single-story-sweep/sweep-lock.js +130 -30
  88. package/.agents/scripts/lib/skills/parse-skill.js +1 -4
  89. package/.agents/scripts/lib/story-body/story-body.js +12 -1
  90. package/.agents/scripts/lib/suite-admission.js +3 -11
  91. package/.agents/scripts/lib/temp-retention.js +25 -11
  92. package/.agents/scripts/lib/test-run-credit.js +2 -5
  93. package/.agents/scripts/lib/transpile.js +193 -31
  94. package/.agents/scripts/lib/util/paths.js +31 -0
  95. package/.agents/scripts/lib/util/sleep.js +15 -0
  96. package/.agents/scripts/lib/validation-evidence.js +29 -3
  97. package/.agents/scripts/lib/wave-runner/live-probe.js +24 -0
  98. package/.agents/scripts/lib/workers/crap-worker.js +23 -12
  99. package/.agents/scripts/lib/workers/maintainability-report-worker.js +18 -12
  100. package/.agents/scripts/lib/workflow-closure.js +1 -8
  101. package/.agents/scripts/notify.js +83 -90
  102. package/.agents/scripts/plan-context.js +8 -4
  103. package/.agents/scripts/providers/github/auth.js +14 -30
  104. package/.agents/scripts/providers/github/blocked-by-add.js +11 -27
  105. package/.agents/scripts/providers/github/compose.js +1 -0
  106. package/.agents/scripts/providers/github/gh-token-diagnostics.js +130 -0
  107. package/.agents/scripts/providers/github/identity.js +158 -0
  108. package/.agents/scripts/providers/github/issues.js +2 -2
  109. package/.agents/scripts/providers/github/mappers.js +16 -19
  110. package/.agents/scripts/providers/github/projects-v2-graphql.js +4 -36
  111. package/.agents/scripts/providers/github/request-helpers.js +44 -0
  112. package/.agents/scripts/providers/github/sub-issue-add.js +11 -28
  113. package/.agents/scripts/providers/github.js +10 -2
  114. package/.agents/scripts/quality-preview.js +6 -19
  115. package/.agents/scripts/single-story-confirm-merge.js +8 -20
  116. package/.agents/scripts/single-story-init.js +0 -1
  117. package/.agents/scripts/stories-wave-tick.js +60 -46
  118. package/.agents/scripts/story-handoff.js +2 -23
  119. package/.agents/scripts/story-review-compute.js +3 -22
  120. package/.agents/scripts/sync-claude-agents.js +1 -12
  121. package/.agents/scripts/sync-claude-commands.js +1 -12
  122. package/.agents/scripts/update-bundle-size-baseline.js +56 -0
  123. package/.agents/scripts/update-coverage-baseline.js +16 -41
  124. package/.agents/scripts/update-crap-baseline.js +10 -19
  125. package/.agents/scripts/update-duplication-baseline.js +13 -3
  126. package/.agents/scripts/update-ticket-state.js +44 -45
  127. package/.agents/templates/docs/audit-sweep-runbook.md +1 -1
  128. package/.agents/workflows/audit-accessibility.md +1 -1
  129. package/.agents/workflows/audit-adrs.md +1 -1
  130. package/.agents/workflows/audit-architecture.md +1 -1
  131. package/.agents/workflows/audit-baselines.md +2 -2
  132. package/.agents/workflows/audit-clean-code.md +1 -1
  133. package/.agents/workflows/audit-data-model.md +1 -1
  134. package/.agents/workflows/audit-dependencies.md +1 -1
  135. package/.agents/workflows/audit-devops.md +1 -1
  136. package/.agents/workflows/audit-documentation.md +1 -1
  137. package/.agents/workflows/audit-exceptions.md +2 -2
  138. package/.agents/workflows/audit-mobile.md +1 -1
  139. package/.agents/workflows/audit-navigability.md +1 -1
  140. package/.agents/workflows/audit-performance.md +1 -1
  141. package/.agents/workflows/audit-privacy.md +1 -1
  142. package/.agents/workflows/audit-quality.md +1 -1
  143. package/.agents/workflows/audit-security.md +1 -1
  144. package/.agents/workflows/audit-seo.md +1 -1
  145. package/.agents/workflows/audit-sre.md +1 -1
  146. package/.agents/workflows/audit-to-stories.md +9 -7
  147. package/.agents/workflows/audit-ux-ui.md +1 -1
  148. package/.agents/workflows/helpers/audit-lens-core.md +8 -5
  149. package/.agents/workflows/helpers/deliver-digest.md +4 -5
  150. package/.agents/workflows/helpers/deliver-story-reference.md +4 -4
  151. package/.agents/workflows/mandrel-deliver.md +3 -1
  152. package/README.md +6 -3
  153. package/docs/CHANGELOG.md +36 -0
  154. package/lib/cli/doctor-checks/codex.js +240 -0
  155. package/lib/cli/doctor-checks/merge-driver.js +79 -0
  156. package/lib/cli/doctor-checks/payload.js +201 -0
  157. package/lib/cli/doctor-checks/read-json.js +16 -0
  158. package/lib/cli/doctor-checks/runtime-deps.js +146 -0
  159. package/lib/cli/doctor-checks/spawn.js +18 -0
  160. package/lib/cli/doctor-checks/sync-parity.js +205 -0
  161. package/lib/cli/doctor-checks/test-credit-path.js +270 -0
  162. package/lib/cli/doctor-checks/toolchain.js +137 -0
  163. package/lib/cli/doctor-checks/version-current.js +82 -0
  164. package/lib/cli/registry.js +40 -1330
  165. package/package.json +7 -1
@@ -11,11 +11,13 @@ import nodeFs from 'node:fs';
11
11
  import { createRequire } from 'node:module';
12
12
  import path from 'node:path';
13
13
  import { execFileCaptureAsync } from '../child-exec.js';
14
+ import { COVERAGE_GATE_DEFAULTS } from '../config/quality.js';
14
15
  import { getQuality, resolveConfig } from '../config-resolver.js';
15
16
  import {
16
17
  buildScopePredicate,
17
18
  scoreCoverageFinal,
18
19
  } from '../coverage-baseline.js';
20
+ import { MissingCoverageArtifactError } from '../coverage-capture.js';
19
21
  import { loadCoverage } from '../coverage-utils.js';
20
22
  import {
21
23
  resolveEscomplexVersion,
@@ -27,7 +29,9 @@ import {
27
29
  isIgnoredByGlobs as isIgnoredByGlobsMi,
28
30
  scanDirectory as scanDirectoryMi,
29
31
  } from '../maintainability-utils.js';
32
+ import { buildBundleSizeScorer } from './bundle-size-scorer.js';
30
33
  import { resolveDetectClones, scanDuplication } from './duplication-scanner.js';
34
+ import { getKindModule } from './kernel.js';
31
35
  import { filterExcludedRows } from './kinds/maintainability.js';
32
36
  import { canonicalizeBaselinePath } from './path-canon.js';
33
37
  import {
@@ -42,6 +46,7 @@ const SUPPORTED_KINDS = Object.freeze([
42
46
  'crap',
43
47
  'coverage',
44
48
  'duplication',
49
+ 'bundle-size',
45
50
  ]);
46
51
 
47
52
  /**
@@ -56,6 +61,8 @@ const KIND_FILE_PREDICATES = Object.freeze({
56
61
  // Over-inclusive is inert for JS-only jscpd; under-inclusive would pin a
57
62
  // changed file's prior row.
58
63
  duplication: (p) => /\.(?:m?[jt]sx?)$/i.test(p),
64
+ // Bundle names are not paths: no changed file scopes a bundle row.
65
+ 'bundle-size': () => false,
59
66
  });
60
67
 
61
68
  /**
@@ -71,6 +78,11 @@ function resolveQualityBlock({ quality, config } = {}) {
71
78
  return {};
72
79
  }
73
80
 
81
+ /** @param {string} absPath */
82
+ function refuseMissingArtifact(absPath) {
83
+ throw new MissingCoverageArtifactError(absPath);
84
+ }
85
+
74
86
  /**
75
87
  * @param {{ cwd: string, config?: object, quality?: object }} opts
76
88
  * @returns {(files: string[], opts: object) => Promise<object[]>}
@@ -92,7 +104,7 @@ function buildDefaultCrapScorer({ cwd, config, quality } = {}) {
92
104
  ? coverageRelPath
93
105
  : path.resolve(effectiveCwd, coverageRelPath);
94
106
  const coverage = loadCoverage(coverageAbs);
95
- if (!coverage && requireCoverage) return [];
107
+ if (!coverage && requireCoverage) refuseMissingArtifact(coverageAbs);
96
108
  const scopeFiles = opts?.fullScope ? null : (files ?? null);
97
109
  const { rows } = await scanAndScore({
98
110
  targetDirs,
@@ -103,7 +115,7 @@ function buildDefaultCrapScorer({ cwd, config, quality } = {}) {
103
115
  scopeFiles,
104
116
  });
105
117
  resolveEscomplexVersion(effectiveCwd);
106
- resolveTsTranspilerVersion();
118
+ resolveTsTranspilerVersion({ cwd: effectiveCwd, targetDirs });
107
119
  return (rows ?? []).filter(
108
120
  (r) => typeof r?.crap === 'number' && Number.isFinite(r.crap),
109
121
  );
@@ -111,24 +123,23 @@ function buildDefaultCrapScorer({ cwd, config, quality } = {}) {
111
123
  }
112
124
 
113
125
  /**
114
- * Coverage rows from coverage-final.json, scoped by the optional `.c8rc.cjs`.
126
+ * Coverage rows from the configured `coverage.coveragePath` artifact, scoped by
127
+ * the optional `.c8rc.cjs`. A missing artifact throws on every scope.
115
128
  *
116
- * @param {{ cwd: string }} opts
129
+ * @param {{ cwd: string, config?: object, quality?: object }} opts
117
130
  * @returns {(files: string[], opts: object) => object[]}
118
131
  */
119
- function buildDefaultCoverageScorer({ cwd } = {}) {
132
+ function buildDefaultCoverageScorer({ cwd, config, quality } = {}) {
133
+ const coverageRelPath =
134
+ resolveQualityBlock({ quality, config })?.coverage?.coveragePath ??
135
+ COVERAGE_GATE_DEFAULTS.coveragePath;
120
136
  return (files, opts) => {
121
137
  const effectiveCwd = opts?.cwd ?? cwd ?? process.cwd();
122
- const coverageFinalPath = path.resolve(
123
- effectiveCwd,
124
- 'coverage/coverage-final.json',
125
- );
126
- let raw;
127
- try {
128
- raw = JSON.parse(nodeFs.readFileSync(coverageFinalPath, 'utf-8'));
129
- } catch {
130
- return [];
138
+ const coverageFinalPath = path.resolve(effectiveCwd, coverageRelPath);
139
+ if (!nodeFs.existsSync(coverageFinalPath)) {
140
+ refuseMissingArtifact(coverageFinalPath);
131
141
  }
142
+ const raw = JSON.parse(nodeFs.readFileSync(coverageFinalPath, 'utf-8'));
132
143
  let c8Scope;
133
144
  try {
134
145
  const c8rcPath = path.resolve(effectiveCwd, '.c8rc.cjs');
@@ -217,6 +228,7 @@ const KIND_SCORER_BUILDERS = Object.freeze({
217
228
  crap: buildDefaultCrapScorer,
218
229
  coverage: buildDefaultCoverageScorer,
219
230
  duplication: buildDefaultDuplicationScorer,
231
+ 'bundle-size': buildBundleSizeScorer,
220
232
  });
221
233
 
222
234
  /**
@@ -242,6 +254,18 @@ export function resolveDefaultScorer(kind, { cwd } = {}) {
242
254
  return builder({ cwd: effectiveCwd, quality });
243
255
  }
244
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
+
245
269
  /**
246
270
  * Refresh the on-disk baseline for `kind`. `scopeFiles: null` without
247
271
  * `fullScope` derives scope from `git diff baseRef..headRef`; `fullScope`
@@ -249,7 +273,7 @@ export function resolveDefaultScorer(kind, { cwd } = {}) {
249
273
  * scoped file produced no row.
250
274
  *
251
275
  * @param {{
252
- * kind: 'maintainability' | 'crap' | 'coverage' | 'duplication',
276
+ * kind: 'maintainability' | 'crap' | 'coverage' | 'duplication' | 'bundle-size',
253
277
  * baseRef?: string,
254
278
  * headRef?: string,
255
279
  * scopeFiles?: string[] | null,
@@ -262,6 +286,7 @@ export function resolveDefaultScorer(kind, { cwd } = {}) {
262
286
  * cwd?: string,
263
287
  * requireRowsForScopeFiles?: boolean,
264
288
  * requiredScopeFilePredicate?: (file: string) => boolean,
289
+ * extrasContext?: { cwd?: string, targetDirs?: string[] },
265
290
  * }} opts
266
291
  * @returns {Promise<{
267
292
  * kind: string,
@@ -286,6 +311,7 @@ export async function refreshBaseline(opts = {}) {
286
311
  cwd = process.cwd(),
287
312
  requireRowsForScopeFiles = false,
288
313
  requiredScopeFilePredicate,
314
+ extrasContext,
289
315
  } = opts;
290
316
 
291
317
  validateOptions({ kind, scopeFiles, fullScope, writePath });
@@ -321,11 +347,7 @@ export async function refreshBaseline(opts = {}) {
321
347
  );
322
348
  }
323
349
 
324
- // Rows leave the service canonical whatever scorer produced them.
325
- const canonicalRows = scoredRows.map((row) => ({
326
- ...row,
327
- path: canonicalizeBaselinePath(row.path ?? row.file),
328
- }));
350
+ const canonicalRows = canonicalizeRows(kind, scoredRows);
329
351
 
330
352
  assertRequiredScopeRows({
331
353
  kind,
@@ -336,6 +358,12 @@ export async function refreshBaseline(opts = {}) {
336
358
  });
337
359
 
338
360
  const priorEnvelope = readPriorEnvelope(writePath, fs);
361
+ const writeFiles = resolveWriteScopeFiles({
362
+ kind,
363
+ scope,
364
+ rows: canonicalRows,
365
+ priorRows: priorEnvelope?.rows,
366
+ });
339
367
 
340
368
  const envelope = writeEnvelope({
341
369
  kind,
@@ -343,10 +371,11 @@ export async function refreshBaseline(opts = {}) {
343
371
  prior: priorEnvelope?.rows,
344
372
  priorEnvelope,
345
373
  epsilon,
374
+ extrasContext: extrasContext ?? defaultExtrasContext(kind, cwd),
346
375
  scope:
347
376
  scope.mode === 'full'
348
377
  ? null
349
- : { mode: 'diff', files: new Set(scope.files) },
378
+ : { mode: 'diff', files: new Set(writeFiles) },
350
379
  });
351
380
 
352
381
  // The writer returns the prior object itself when nothing changed; skip the
@@ -363,13 +392,63 @@ export async function refreshBaseline(opts = {}) {
363
392
  scope: {
364
393
  mode: scope.mode,
365
394
  ref: scope.ref,
366
- files: [...scope.files],
395
+ files: writeFiles,
367
396
  },
368
397
  envelope,
369
398
  wrote,
370
399
  };
371
400
  }
372
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
+
436
+ /**
437
+ * Rows leave the service canonical whatever scorer produced them. Only
438
+ * path-keyed kinds carry a path; bundle-size rows are keyed on a name.
439
+ *
440
+ * @param {string} kind
441
+ * @param {object[]} rows
442
+ * @returns {object[]}
443
+ */
444
+ function canonicalizeRows(kind, rows) {
445
+ if (getKindModule(kind).keyField !== 'path') return rows;
446
+ return rows.map((row) => ({
447
+ ...row,
448
+ path: canonicalizeBaselinePath(row.path ?? row.file),
449
+ }));
450
+ }
451
+
373
452
  function assertRequiredScopeRows({
374
453
  kind,
375
454
  scope,
@@ -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
  *
@@ -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
@@ -24,7 +24,7 @@ export const COVERAGE_GATE = {
24
24
  ...SAFE_STRING,
25
25
  minLength: 1,
26
26
  description:
27
- 'Repo-relative path to the Istanbul `coverage-final.json` the capture step writes and the gate reads.',
27
+ 'Repo-relative path to the Istanbul `coverage-final.json` the capture step writes and the gate reads. The capture contract: `npm run test:coverage` MUST write Istanbul per-file JSON (the `json` reporter) here — the coverage and CRAP refreshes both read it. A `json-summary` (`coverage-summary.json`) alone cannot feed them, so a green capture that leaves no file here fails and a full-scope refresh refuses to run.',
28
28
  default: COVERAGE_GATE_DEFAULTS.coveragePath,
29
29
  },
30
30
  captureScope: {
@@ -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 } },
@@ -60,7 +60,7 @@ const FLOORS_SCHEMA = {
60
60
  const COMPONENTS_SCHEMA = {
61
61
  type: 'object',
62
62
  description:
63
- 'Per-gate component map — component name to the glob list whose files roll up under it. Defaults to `{ "*": ["**"] }` at the resolver layer.',
63
+ 'Per-gate component map — component name to the glob list whose rows roll up under it (matched against the row key: the file path, or the bundle name for bundle-size). `check-baselines` reports one rollup per component that matches a row and holds it to `floors.<component>`, falling back to `floors["*"]`. Defaults to `{ "*": ["**"] }` at the resolver layer.',
64
64
  additionalProperties: {
65
65
  type: 'array',
66
66
  items: { type: 'string', minLength: 1 },