mandrel 2.111.0 → 2.112.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 (178) hide show
  1. package/.agents/agents/acceptance-critic.md +14 -0
  2. package/.agents/agents/auditor.md +14 -0
  3. package/.agents/agents/plan-critic.md +5 -0
  4. package/.agents/agents/story-worker.md +4 -1
  5. package/.agents/docs/agentrc-reference.json +22 -10
  6. package/.agents/docs/configuration.md +351 -37
  7. package/.agents/docs/execution-reference.md +11 -0
  8. package/.agents/rules/git-conventions-reference.md +7 -0
  9. package/.agents/schemas/agentrc.schema.json +174 -14
  10. package/.agents/schemas/baselines/baseline-envelope.schema.json +16 -4
  11. package/.agents/schemas/baselines/bundle-size.schema.json +1 -0
  12. package/.agents/schemas/baselines/coverage.schema.json +1 -0
  13. package/.agents/schemas/baselines/crap.schema.json +37 -10
  14. package/.agents/schemas/baselines/duplication.schema.json +1 -0
  15. package/.agents/schemas/baselines/maintainability.schema.json +1 -0
  16. package/.agents/schemas/baselines/mutation.schema.json +1 -0
  17. package/.agents/schemas/crap-report.schema.json +6 -5
  18. package/.agents/schemas/story-deliver-terminal.schema.json +41 -2
  19. package/.agents/schemas/story-progress.schema.json +1 -1
  20. package/.agents/schemas/validation-evidence.schema.json +2 -2
  21. package/.agents/scripts/boot-sweep.js +41 -3
  22. package/.agents/scripts/coverage-capture.js +37 -3
  23. package/.agents/scripts/coverage-ratchet.js +106 -0
  24. package/.agents/scripts/evidence-gate.js +84 -21
  25. package/.agents/scripts/lib/audit-baselines/read.js +8 -1
  26. package/.agents/scripts/lib/audit-baselines/trend.js +2 -1
  27. package/.agents/scripts/lib/baseline-loader.js +4 -2
  28. package/.agents/scripts/lib/baselines/codec.js +57 -0
  29. package/.agents/scripts/lib/baselines/crap-preview-incremental.js +8 -3
  30. package/.agents/scripts/lib/baselines/crap-preview-scan.js +10 -16
  31. package/.agents/scripts/lib/baselines/crap-updater-cli.js +4 -13
  32. package/.agents/scripts/lib/baselines/kernel.js +19 -1
  33. package/.agents/scripts/lib/baselines/kinds/_crap-codec.js +171 -0
  34. package/.agents/scripts/lib/baselines/kinds/_crap-read.js +56 -16
  35. package/.agents/scripts/lib/baselines/kinds/_shared-metric.js +0 -59
  36. package/.agents/scripts/lib/baselines/kinds/crap.js +283 -319
  37. package/.agents/scripts/lib/baselines/preview-gates.js +29 -10
  38. package/.agents/scripts/lib/baselines/reader.js +36 -9
  39. package/.agents/scripts/lib/baselines/refresh-service.js +79 -18
  40. package/.agents/scripts/lib/baselines/seat-missing.js +173 -7
  41. package/.agents/scripts/lib/baselines/writer.js +36 -21
  42. package/.agents/scripts/lib/changed-files.js +70 -6
  43. package/.agents/scripts/lib/child-exec.js +10 -0
  44. package/.agents/scripts/lib/claude/agents-projection.js +5 -5
  45. package/.agents/scripts/lib/close-lock-events.js +8 -3
  46. package/.agents/scripts/lib/close-validation/ci-deferral.js +40 -0
  47. package/.agents/scripts/lib/close-validation/gates.js +111 -35
  48. package/.agents/scripts/lib/close-validation/process.js +16 -7
  49. package/.agents/scripts/lib/close-validation/projections/crap.js +43 -10
  50. package/.agents/scripts/lib/close-validation/runner.js +55 -23
  51. package/.agents/scripts/lib/close-validation/skip-branch-test.js +144 -0
  52. package/.agents/scripts/lib/close-validation/test-delta.js +33 -8
  53. package/.agents/scripts/lib/codex/agents-projection.js +6 -0
  54. package/.agents/scripts/lib/config/agentrc-overlay.js +9 -5
  55. package/.agents/scripts/lib/config/explain.js +5 -2
  56. package/.agents/scripts/lib/config/gates/coverage.schema.js +45 -1
  57. package/.agents/scripts/lib/config/gates/crap-incremental-coverage.schema.js +1 -1
  58. package/.agents/scripts/lib/config/git-roots.js +38 -4
  59. package/.agents/scripts/lib/config/handoff.js +24 -0
  60. package/.agents/scripts/lib/config/quality.js +26 -13
  61. package/.agents/scripts/lib/config/worktree-isolation.js +2 -5
  62. package/.agents/scripts/lib/config-resolver.js +22 -2
  63. package/.agents/scripts/lib/config-settings-schema-delivery.js +87 -4
  64. package/.agents/scripts/lib/config-settings-schema-quality.js +36 -1
  65. package/.agents/scripts/lib/config-settings-schema.js +1 -1
  66. package/.agents/scripts/lib/coverage-capture-affected.js +1 -0
  67. package/.agents/scripts/lib/coverage-capture-delta.js +164 -32
  68. package/.agents/scripts/lib/coverage-capture-own-fix.js +232 -0
  69. package/.agents/scripts/lib/coverage-capture-usage.js +2 -2
  70. package/.agents/scripts/lib/coverage-capture.js +15 -0
  71. package/.agents/scripts/lib/coverage-deferral.js +96 -0
  72. package/.agents/scripts/lib/coverage-ratchet.js +187 -0
  73. package/.agents/scripts/lib/crap-baseline-join.js +5 -5
  74. package/.agents/scripts/lib/crap-engine.js +3 -3
  75. package/.agents/scripts/lib/crap-method-identity.js +104 -48
  76. package/.agents/scripts/lib/escomplex-anchor.js +135 -0
  77. package/.agents/scripts/lib/escomplex-kernel.js +30 -1
  78. package/.agents/scripts/lib/failure-rows.js +121 -0
  79. package/.agents/scripts/lib/full-suite-lock.js +44 -4
  80. package/.agents/scripts/lib/full-suite-queue.js +89 -13
  81. package/.agents/scripts/lib/generated/agentrc-validator.js +8 -2
  82. package/.agents/scripts/lib/gh-env.js +3 -6
  83. package/.agents/scripts/lib/gh-pr-rest.js +1 -0
  84. package/.agents/scripts/lib/git/base-sync-probe.js +182 -0
  85. package/.agents/scripts/lib/git-branch-lifecycle.js +9 -0
  86. package/.agents/scripts/lib/observability/close-telemetry.js +37 -2
  87. package/.agents/scripts/lib/observability/handoff-telemetry.js +170 -0
  88. package/.agents/scripts/lib/observability/review-dispositions.js +23 -6
  89. package/.agents/scripts/lib/observability/runtime-friction.js +17 -4
  90. package/.agents/scripts/lib/observability/source-classifier.js +3 -0
  91. package/.agents/scripts/lib/observability/story-outcome.js +393 -0
  92. package/.agents/scripts/lib/orchestration/check-baselines/phases/compare.js +2 -1
  93. package/.agents/scripts/lib/orchestration/check-baselines/phases/evaluate.js +19 -1
  94. package/.agents/scripts/lib/orchestration/check-baselines/phases/fail-detail.js +84 -0
  95. package/.agents/scripts/lib/orchestration/check-baselines/phases/pipeline.js +14 -5
  96. package/.agents/scripts/lib/orchestration/check-baselines/phases/refresh-ack.js +3 -2
  97. package/.agents/scripts/lib/orchestration/check-baselines/phases/report.js +26 -6
  98. package/.agents/scripts/lib/orchestration/code-review.js +223 -19
  99. package/.agents/scripts/lib/orchestration/handoff-gates.js +129 -62
  100. package/.agents/scripts/lib/orchestration/handoff-rescore.js +169 -0
  101. package/.agents/scripts/lib/orchestration/handoff-suite-of-record.js +45 -0
  102. package/.agents/scripts/lib/orchestration/preflight-lanes.js +208 -0
  103. package/.agents/scripts/lib/orchestration/review-base-ref.js +40 -17
  104. package/.agents/scripts/lib/orchestration/review-deposit.js +38 -12
  105. package/.agents/scripts/lib/orchestration/review-depth.js +21 -0
  106. package/.agents/scripts/lib/orchestration/review-history.js +124 -20
  107. package/.agents/scripts/lib/orchestration/review-providers/claude-verdict.js +23 -8
  108. package/.agents/scripts/lib/orchestration/review-providers/code-review.js +82 -39
  109. package/.agents/scripts/lib/orchestration/review-providers/critical-verifier.js +64 -11
  110. package/.agents/scripts/lib/orchestration/review-providers/degraded-gates.js +98 -3
  111. package/.agents/scripts/lib/orchestration/review-providers/finding-identity.js +6 -2
  112. package/.agents/scripts/lib/orchestration/review-providers/findings-renderer.js +55 -8
  113. package/.agents/scripts/lib/orchestration/review-providers/review-guidance.js +1 -0
  114. package/.agents/scripts/lib/orchestration/review-providers/review-provider-factory.js +42 -15
  115. package/.agents/scripts/lib/orchestration/review-providers/types.js +6 -0
  116. package/.agents/scripts/lib/orchestration/single-story-close/failed-terminal.js +10 -1
  117. package/.agents/scripts/lib/orchestration/single-story-close/gate-log.js +10 -0
  118. package/.agents/scripts/lib/orchestration/single-story-close/phases/base-sync.js +7 -4
  119. package/.agents/scripts/lib/orchestration/single-story-close/phases/close-validation.js +15 -3
  120. package/.agents/scripts/lib/orchestration/single-story-close/phases/code-review.js +59 -2
  121. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +6 -0
  122. package/.agents/scripts/lib/orchestration/single-story-close/phases/finish.js +15 -4
  123. package/.agents/scripts/lib/orchestration/single-story-close/phases/land-review-record.js +213 -0
  124. package/.agents/scripts/lib/orchestration/single-story-close/phases/normalize-pr-title.js +9 -12
  125. package/.agents/scripts/lib/orchestration/single-story-close/phases/open-pr.js +26 -12
  126. package/.agents/scripts/lib/orchestration/single-story-close/phases/post-land.js +51 -26
  127. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-push.js +3 -2
  128. package/.agents/scripts/lib/orchestration/single-story-close/phases/pull-request.js +50 -17
  129. package/.agents/scripts/lib/orchestration/single-story-close/phases/push.js +59 -11
  130. package/.agents/scripts/lib/orchestration/single-story-close/phases/reconcile-done.js +1 -0
  131. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-block.js +31 -13
  132. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-halt.js +29 -6
  133. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-outcome.js +10 -12
  134. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-override.js +19 -4
  135. package/.agents/scripts/lib/orchestration/single-story-close/result.js +30 -13
  136. package/.agents/scripts/lib/orchestration/single-story-close/review-overlap.js +73 -39
  137. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +11 -3
  138. package/.agents/scripts/lib/orchestration/story-close/baseline-upward-writeback.js +3 -2
  139. package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +20 -8
  140. package/.agents/scripts/lib/orchestration/story-deliver-terminal.js +7 -0
  141. package/.agents/scripts/lib/orchestration/story-handoff.js +774 -196
  142. package/.agents/scripts/lib/orchestration/ticketing/reads.js +2 -0
  143. package/.agents/scripts/lib/pr-body-lines.js +32 -0
  144. package/.agents/scripts/lib/single-story/ci-ratchet-gate.js +140 -0
  145. package/.agents/scripts/lib/single-story/confirm-and-land.js +17 -7
  146. package/.agents/scripts/lib/single-story/confirm-merge.js +12 -3
  147. package/.agents/scripts/lib/single-story-sweep/report-stalled-executing.js +202 -0
  148. package/.agents/scripts/lib/standalone-ratchets.js +37 -0
  149. package/.agents/scripts/lib/suite-admission.js +20 -8
  150. package/.agents/scripts/lib/suite-sizing.js +146 -0
  151. package/.agents/scripts/lib/workspace-provisioner.js +2 -2
  152. package/.agents/scripts/merge-baseline.js +14 -3
  153. package/.agents/scripts/providers/github/comments.js +19 -3
  154. package/.agents/scripts/providers/github.js +1 -0
  155. package/.agents/scripts/review-dispositions-report.js +1 -1
  156. package/.agents/scripts/role-scope-guard.js +267 -0
  157. package/.agents/scripts/single-story-close.js +4 -4
  158. package/.agents/scripts/single-story-confirm-merge.js +31 -5
  159. package/.agents/scripts/single-story-init.js +24 -4
  160. package/.agents/scripts/story-handoff.js +3 -3
  161. package/.agents/scripts/story-outcomes-report.js +231 -0
  162. package/.agents/scripts/story-review-compute.js +9 -5
  163. package/.agents/scripts/update-coverage-baseline.js +12 -2
  164. package/.agents/scripts/update-crap-baseline.js +9 -1
  165. package/.agents/workflows/helpers/code-review.md +63 -9
  166. package/.agents/workflows/helpers/deliver-digest.md +53 -54
  167. package/.agents/workflows/helpers/deliver-reference.md +233 -67
  168. package/.agents/workflows/helpers/deliver-story-reference.md +19 -8
  169. package/.agents/workflows/helpers/deliver-story.md +7 -2
  170. package/.agents/workflows/helpers/parallel-tooling.md +29 -0
  171. package/docs/CHANGELOG.md +46 -0
  172. package/lib/cli/doctor-checks/coverage-ratchet.js +54 -0
  173. package/lib/cli/doctor-checks/effective-agentrc.js +23 -0
  174. package/lib/cli/doctor-checks/llm-review.js +2 -11
  175. package/lib/cli/doctor-checks/sync-parity.js +5 -1
  176. package/lib/cli/doctor-checks/test-credit-path.js +7 -2
  177. package/lib/cli/registry.js +5 -0
  178. package/package.json +1 -1
@@ -75,12 +75,12 @@
75
75
  "scope": {
76
76
  "type": "string",
77
77
  "enum": ["full", "delta"],
78
- "description": "Optional note on how the pass was earned. `delta` is close's `test` delta re-credit: after a base sync, only the tests affected by the commits since `since` ran (`project.commands.testChanged`), and the record credits the merged tree under the full-suite identity."
78
+ "description": "Optional note on how the pass was earned. `delta` is close's `test` delta re-credit: after a base sync, only the tests affected by the commits since `since` ran (`project.commands.testChanged`), and the record credits the merged tree under the full-suite identity. It also marks the skip-branch first credit: a Story with no change under `crap.targetDirs` ran `testChanged` keyed on the `origin/<baseBranch>` merge-base `since`, credited under the same identity."
79
79
  },
80
80
  "since": {
81
81
  "type": "string",
82
82
  "pattern": "^[0-9a-f]{7,64}$",
83
- "description": "With `scope: delta`, the credited commit the affected-tests run was keyed on."
83
+ "description": "With `scope: delta`, the commit the affected-tests run was keyed on (the credited pre-sync head, or the skip-branch merge-base)."
84
84
  },
85
85
  "timestamp": {
86
86
  "type": "string",
@@ -13,7 +13,8 @@
13
13
  * tree and the tree this process runs from are never touched.
14
14
  *
15
15
  * Then it flips closed Stories stranded at `agent::closing` to
16
- * `agent::done` (`closingReconcile`).
16
+ * `agent::done` (`closingReconcile`), and reports — never touches — open
17
+ * `agent::executing` Stories stalled with no open PR (`stalledExecuting`).
17
18
  *
18
19
  * `content-merged` branches (merge-tree equivalence — no merge check ever
19
20
  * validated their exact diff) are never reaped here, only reported for
@@ -31,6 +32,7 @@ import { sweepStaleStoryWorktrees } from './lib/orchestration/plan-runner/worktr
31
32
  import { createProvider } from './lib/provider-factory.js';
32
33
  import { buildProtectionCtx } from './lib/single-story-sweep/protection-ctx.js';
33
34
  import { reconcileStrandedClosing } from './lib/single-story-sweep/reconcile-closing.js';
35
+ import { reportStalledExecuting } from './lib/single-story-sweep/report-stalled-executing.js';
34
36
  import {
35
37
  acquireSweepLock,
36
38
  resolveSweepLockPath,
@@ -66,6 +68,10 @@ the outcome lands under "worktreeSweep".
66
68
  Then flips closed Stories still labelled agent::closing whose story-<id> PR
67
69
  is MERGED to agent::done (at most 10 per run); the outcome lands under
68
70
  "closingReconcile".
71
+ Then reports (read-only) open agent::executing Stories whose story-<id>
72
+ origin head is older than the stall threshold and that have no open PR,
73
+ each with its deliver-recover.js command (at most 20 probed per run); the
74
+ outcome lands under "stalledExecuting".
69
75
  Branches detected only via the weaker content-equivalence signal
70
76
  (detectedBy: 'content-merged') are never reaped here — they are reported
71
77
  under "contentMerged" (and a routing hint in the summary line) for the
@@ -77,6 +83,8 @@ Options:
77
83
  --current <branch> A branch to always exclude (e.g. the active story).
78
84
  --base <branch> Base branch to fast-forward. Default: project baseBranch.
79
85
  --no-fast-forward Skip the base-branch fast-forward step.
86
+ --stalled-after-hours <n>
87
+ Stall threshold in hours (positive). Default: 6.
80
88
  --json Emit the result envelope as JSON.
81
89
  `;
82
90
 
@@ -154,10 +162,12 @@ export async function runWorktreeSweep({
154
162
  * acquireLockFn?: Function,
155
163
  * purgeFn?: Function,
156
164
  * closingReconcileFn?: Function,
165
+ * stalledExecutingFn?: Function,
166
+ * stalledAfterHours?: unknown,
157
167
  * logger?: { info?: Function, warn?: Function },
158
168
  * }} [args]
159
169
  * @returns {Promise<object>} the {@link sweepMergedBranches} envelope plus
160
- * `worktreeSweep`, `closingReconcile` and `tempPurge`.
170
+ * `worktreeSweep`, `closingReconcile`, `stalledExecuting` and `tempPurge`.
161
171
  */
162
172
  export async function runBootSweep({
163
173
  cwd,
@@ -173,6 +183,8 @@ export async function runBootSweep({
173
183
  acquireLockFn = acquireSweepLock,
174
184
  purgeFn = sweepTempRetention,
175
185
  closingReconcileFn = reconcileStrandedClosing,
186
+ stalledExecutingFn = reportStalledExecuting,
187
+ stalledAfterHours,
176
188
  logger = Logger,
177
189
  } = {}) {
178
190
  const root = path.resolve(cwd ?? PROJECT_ROOT);
@@ -233,6 +245,17 @@ export async function runBootSweep({
233
245
  },
234
246
  });
235
247
 
248
+ const stalledExecuting = await stalledExecutingFn({
249
+ provider,
250
+ config,
251
+ stalledAfterHours,
252
+ excludeStoryIds: [parseStoryBranch(current)],
253
+ logger: {
254
+ info: (m) => logger.info?.(`[boot-sweep] ${m}`),
255
+ warn: (m) => logger.warn?.(`[boot-sweep] ${m}`),
256
+ },
257
+ });
258
+
236
259
  // Temp-retention catch-up: reaped branches are confirmed merges, so their
237
260
  // artifacts are spent; the age floor collects the rest.
238
261
  const purge = await purgeFn({
@@ -241,7 +264,13 @@ export async function runBootSweep({
241
264
  label: 'boot-sweep',
242
265
  logger,
243
266
  });
244
- return { ...result, worktreeSweep, closingReconcile, tempPurge: purge };
267
+ return {
268
+ ...result,
269
+ worktreeSweep,
270
+ closingReconcile,
271
+ stalledExecuting,
272
+ tempPurge: purge,
273
+ };
245
274
  } catch (err) {
246
275
  const msg = err?.message ?? String(err);
247
276
  logger.warn?.(`[boot-sweep] sweep threw (host continues): ${msg}`);
@@ -282,6 +311,13 @@ export function buildSummaryLine(result) {
282
311
  result.closingReconcile?.reconciled,
283
312
  (n) => `flipped ${n} stranded agent::closing Story(ies) to agent::done`,
284
313
  ),
314
+ countSuffix(
315
+ result.stalledExecuting?.stalled,
316
+ (n) =>
317
+ `${n} agent::executing Story(ies) idle over ${result.stalledExecuting.thresholdHours}h with no open PR — run ${result.stalledExecuting.stalled
318
+ .map((s) => `deliver-recover.js --story ${s.storyId}`)
319
+ .join(', ')}`,
320
+ ),
285
321
  countSuffix(
286
322
  result.contentMerged,
287
323
  (n) => `${n} content-merged branch(es) left for /clean-git`,
@@ -310,6 +346,7 @@ export async function runBootSweepCli(
310
346
  exclude: { type: 'string', multiple: true, default: [] },
311
347
  current: { type: 'string' },
312
348
  'no-fast-forward': { type: 'boolean', default: false },
349
+ 'stalled-after-hours': { type: 'string' },
313
350
  json: { type: 'boolean', default: false },
314
351
  help: { type: 'boolean', short: 'h' },
315
352
  },
@@ -328,6 +365,7 @@ export async function runBootSweepCli(
328
365
  exclude: Array.isArray(values.exclude) ? values.exclude : [],
329
366
  current: typeof values.current === 'string' ? values.current : undefined,
330
367
  fastForward: values['no-fast-forward'] !== true,
368
+ stalledAfterHours: values['stalled-after-hours'],
331
369
  });
332
370
 
333
371
  if (values.json) {
@@ -16,9 +16,10 @@
16
16
  * Exit codes: 0 fresh/skipped/captured; 1 capture failed or refused (callers
17
17
  * MUST surface it); 75 lock wait expired, nothing spawned; 76 the capture
18
18
  * script declared its slice over this host's budget, nothing ran or was
19
- * stamped (callers settle it by `coverage.onOverBudget`); 124 suite timed out.
19
+ * stamped (callers settle it by `coverage.onOverBudget`); 77 the run lost
20
+ * workers to host memory with no failing test (callers block); 124 suite timed out.
20
21
  */
21
- import { getChangedFiles } from './lib/changed-files.js';
22
+ import { getChangedFiles, resolveCaptureBaseRef } from './lib/changed-files.js';
22
23
  import { isDirectInvocation } from './lib/cli-utils.js';
23
24
  import { claimLockEventSink, lockEventHooks } from './lib/close-lock-events.js';
24
25
  import { getQuality, resolveConfig } from './lib/config-resolver.js';
@@ -45,7 +46,7 @@ import { hasNpmScript, readPackageScripts } from './lib/npm-scripts.js';
45
46
  import { formatSuiteTimings } from './lib/supervised-suite.js';
46
47
 
47
48
  /**
48
- * A `null` ref defers the fallback to `resolveChangedFilesRef`.
49
+ * A `null` ref defers the fallback to `resolveCaptureBaseRef`.
49
50
  * @param {string[]} argv
50
51
  * @returns {{ skipWhenNoCrapFiles: boolean, requireCredited: boolean, ref: string | null, cwd: string }}
51
52
  */
@@ -72,6 +73,7 @@ export function parseArgs(argv) {
72
73
  * resolveConfigImpl?: typeof resolveConfig,
73
74
  * getQualityImpl?: typeof getQuality,
74
75
  * getChangedFilesImpl?: typeof getChangedFiles,
76
+ * resolveBaseRefImpl?: typeof resolveCaptureBaseRef,
75
77
  * readPackageScriptsImpl?: typeof readPackageScripts,
76
78
  * hasNpmScriptImpl?: typeof hasNpmScript,
77
79
  * isCoverageFreshImpl?: typeof isCoverageFresh,
@@ -116,6 +118,7 @@ export async function runCoverageCapture(argv = process.argv, deps = {}) {
116
118
  logger,
117
119
  });
118
120
  if (refused !== null) return refused;
121
+ resolveRunRefs({ crap, args, config, deps, logger });
119
122
 
120
123
  // Outermost first: the credit probe announces or refuses the run, and only
121
124
  // a surviving run reaches the host-level full-suite lock.
@@ -164,6 +167,37 @@ export async function runCoverageCapture(argv = process.argv, deps = {}) {
164
167
  return code;
165
168
  }
166
169
 
170
+ /**
171
+ * Resolves the changed-files ref once so every pass, and the affected
172
+ * script's `MANDREL_COVERAGE_BASE_REF`, measures against the same ref.
173
+ */
174
+ function resolveRunRefs({ crap, args, config, deps, logger }) {
175
+ const baseBranch = config?.project?.baseBranch;
176
+ args.baseBranchRef = `origin/${baseBranch ?? 'main'}`;
177
+ const resolve = deps.resolveBaseRefImpl ?? resolveCaptureBaseRef;
178
+ const resolved = resolve({ crap, ref: args.ref, baseBranch, cwd: args.cwd });
179
+ args.ref = resolved.ref;
180
+ logRunRef(resolved, logger);
181
+ }
182
+
183
+ function logRunRef({ ref, source, unresolved }, logger) {
184
+ if (source === 'local-fallback') {
185
+ logger.warn(
186
+ `[coverage-capture] ⚠ ${unresolved} does not resolve in this clone — measuring changed files against the local ${ref} instead.`,
187
+ );
188
+ return;
189
+ }
190
+ logger.info(
191
+ `[coverage-capture] Changed files measured against ${ref} (${SOURCE_LABELS[source]}).`,
192
+ );
193
+ }
194
+
195
+ const SOURCE_LABELS = {
196
+ flag: '--ref',
197
+ config: 'incrementalCoverage.baseRef',
198
+ remote: 'default: origin/<baseBranch>',
199
+ };
200
+
167
201
  /**
168
202
  * The credited runner, failing a green run that wrote no artifact at the
169
203
  * pass's source.
@@ -0,0 +1,106 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * coverage-ratchet.js — CI's hand-back for a Story whose coverage capture was
4
+ * deferred to CI (`Coverage-deferred:` in the PR body). Adopts the artifact
5
+ * CI produced at `--head`, then runs the per-file coverage and CRAP value
6
+ * ratchet over it against `--base`. Exit 0: the ratchet holds; 1: refused
7
+ * or a ratchet step failed (named on stderr).
8
+ */
9
+
10
+ import path from 'node:path';
11
+ import { fileURLToPath } from 'node:url';
12
+
13
+ import { spawnChild } from './lib/child-exec.js';
14
+ import { runAsCli } from './lib/cli-utils.js';
15
+ import { getQuality, resolveConfig } from './lib/config-resolver.js';
16
+ import {
17
+ adoptArtifact,
18
+ parseRatchetArgs,
19
+ ratchetSteps,
20
+ scoreRatchet,
21
+ } from './lib/coverage-ratchet.js';
22
+ import { Logger } from './lib/Logger.js';
23
+
24
+ const SCRIPTS_DIR = path.dirname(fileURLToPath(import.meta.url));
25
+
26
+ const USAGE = {
27
+ invocation:
28
+ 'node .agents/scripts/coverage-ratchet.js --artifact <path> --head <sha> [--scope affected|full] [--base <ref>] [--adopt-only]',
29
+ summary:
30
+ "Adopt a CI-produced Istanbul coverage-final.json at the checked-out HEAD (placed at `delivery.quality.gates.coverage.coveragePath` and stamped like a green local capture), then run the coverage and CRAP value ratchet over it. CI's sharding and artifact merging stay the consumer's job.",
31
+ flags: [
32
+ ['--artifact <path>', 'The CI-produced coverage-final.json.'],
33
+ [
34
+ '--head <sha>',
35
+ 'The commit the artifact measured; refused unless it is the checked-out HEAD.',
36
+ ],
37
+ [
38
+ '--scope affected|full',
39
+ 'What the artifact measured. Default `affected`.',
40
+ ],
41
+ ['--base <ref>', 'The ratchet base. Default `origin/<baseBranch>`.'],
42
+ [
43
+ '--adopt-only',
44
+ 'Place and stamp the artifact, skip the ratchet (seat rows from it next).',
45
+ ],
46
+ ],
47
+ notes: [
48
+ 'Refuses (exit 1) a dirty tracked tree and a missing or unparseable artifact.',
49
+ 'On a pull_request event pass `--head "$(git rev-parse HEAD)"` from the job that produced the artifact; this job must check out the same ref.',
50
+ ],
51
+ };
52
+
53
+ /** Spawn one ratchet step in `cwd`, output passed through. */
54
+ function runStep(cwd) {
55
+ return (args, env) =>
56
+ spawnChild(process.execPath, args, {
57
+ cwd,
58
+ stdio: 'inherit',
59
+ env: env ? { ...process.env, ...env } : process.env,
60
+ }).status ?? 1;
61
+ }
62
+
63
+ async function main() {
64
+ const cwd = process.cwd();
65
+ const args = parseRatchetArgs(process.argv.slice(2));
66
+ if (args.error) {
67
+ Logger.error(`[coverage-ratchet] ✖ ${args.error}`);
68
+ return 1;
69
+ }
70
+ const config = resolveConfig({ cwd });
71
+ const base = args.base ?? `origin/${config?.project?.baseBranch ?? 'main'}`;
72
+ const refusal = adoptArtifact({
73
+ cwd,
74
+ quality: getQuality(config),
75
+ ...args,
76
+ base,
77
+ });
78
+ if (refusal) {
79
+ Logger.error(`[coverage-ratchet] ✖ refused: ${refusal}`);
80
+ return 1;
81
+ }
82
+ Logger.info(
83
+ `[coverage-ratchet] adopted ${args.artifact} at ${args.head} (${args.scope} scope)`,
84
+ );
85
+ if (args.adoptOnly) return 0;
86
+ const { failedStep, status } = await scoreRatchet(
87
+ ratchetSteps(SCRIPTS_DIR, base),
88
+ runStep(cwd),
89
+ );
90
+ if (failedStep) {
91
+ Logger.error(
92
+ `[coverage-ratchet] ✖ ${failedStep} failed (exit ${status}) — the coverage/CRAP ratchet does not hold against ${base}`,
93
+ );
94
+ return 1;
95
+ }
96
+ Logger.info(
97
+ `[coverage-ratchet] ✅ coverage and CRAP ratchet hold against ${base}`,
98
+ );
99
+ return 0;
100
+ }
101
+
102
+ runAsCli(import.meta.url, main, {
103
+ source: 'coverage-ratchet',
104
+ usage: USAGE,
105
+ propagateExitCode: true,
106
+ });
@@ -12,7 +12,12 @@ import { spawnSync } from 'node:child_process';
12
12
  import { parseArgs } from 'node:util';
13
13
  import { runAsCli } from './lib/cli-utils.js';
14
14
  import { claimLockEventSink, lockEventHooks } from './lib/close-lock-events.js';
15
+ import {
16
+ changedSinceError,
17
+ scopedEvidenceRun,
18
+ } from './lib/close-validation/skip-branch-test.js';
15
19
  import { getQuality, resolveConfig } from './lib/config-resolver.js';
20
+ import { COVERAGE_HOST_RESOURCES_EXIT_CODE } from './lib/coverage-capture.js';
16
21
  import {
17
22
  fullSuiteLockPolicy,
18
23
  LOCK_WAIT_EXPIRED_EXIT_CODE,
@@ -53,6 +58,7 @@ export function parseWrapperArgs(argv) {
53
58
  standalone: { type: 'boolean', default: false },
54
59
  cwd: { type: 'string' },
55
60
  worktree: { type: 'string' },
61
+ 'changed-since': { type: 'string' },
56
62
  },
57
63
  strict: false,
58
64
  });
@@ -64,9 +70,37 @@ export function parseWrapperArgs(argv) {
64
70
  useEvidence: values['no-evidence'] !== true,
65
71
  cwd: values.cwd ?? PROJECT_ROOT,
66
72
  worktreePath: values.worktree ?? null,
73
+ changedSince: values['changed-since'] ?? null,
67
74
  };
68
75
  }
69
76
 
77
+ const USAGE =
78
+ 'Usage: node evidence-gate.js --standalone --scope-id <id> --gate <name> [--worktree <path>] [--no-evidence] [--changed-since <sha>] -- <cmd> [args...]';
79
+
80
+ /** The usage refusal, or `null` when the params may run. */
81
+ function usageError({ scopeId, standalone, gate, runnerArgs, changedSince }) {
82
+ if (!scopeId || !standalone || !gate || !runnerArgs?.length) return USAGE;
83
+ const scoped = changedSinceError(gate, changedSince);
84
+ return scoped ? `[evidence-gate] ${scoped}` : null;
85
+ }
86
+
87
+ /** The spawned argv and evidence identity; `--changed-since` scopes a `test` run. */
88
+ function resolveRun({ runnerArgs, changedSince }, cwd, loadConfigFn) {
89
+ const [cmd, ...args] = runnerArgs;
90
+ return changedSince
91
+ ? scopedRun({ cmd, args, since: changedSince, cwd, loadConfigFn })
92
+ : plainRun(cmd, args, cwd);
93
+ }
94
+
95
+ function scopedRun({ loadConfigFn, ...run }) {
96
+ return scopedEvidenceRun({ ...run, config: loadConfigFn(run.cwd) });
97
+ }
98
+
99
+ function plainRun(cmd, args, cwd) {
100
+ const configHash = hashCommandConfig({ cmd, args, cwd });
101
+ return { cmd, cmdArgs: args, configHash, note: {} };
102
+ }
103
+
70
104
  function resolveHeadShaDefault(cwd, gitSpawnFn) {
71
105
  const res = gitSpawnFn(cwd, 'rev-parse', 'HEAD');
72
106
  if (res.status !== 0) return null;
@@ -98,6 +132,7 @@ function resolveEvidenceKeys({ spawnCwd, gitSpawnFn, useEvidence }) {
98
132
  * @param {string} params.cwd — evidence cwd (locates the temp tree)
99
133
  * @param {string|null} [params.worktreePath] — spawn cwd and HEAD source
100
134
  * @param {string[]} params.runnerArgs
135
+ * @param {string|null} [params.changedSince] — skip-branch scoped `test` deposit
101
136
  * @param {object} [deps]
102
137
  * @param {Function} [deps.gitSpawnFn]
103
138
  * @param {Function} [deps.spawnFn]
@@ -105,6 +140,7 @@ function resolveEvidenceKeys({ spawnCwd, gitSpawnFn, useEvidence }) {
105
140
  * @param {Function} [deps.recordPassFn]
106
141
  * @param {object} [deps.logger]
107
142
  * @param {Function} [deps.runSuiteFn]
143
+ * @param {Function} [deps.loadConfigFn]
108
144
  * @returns {{ status: number, skipped: boolean }}
109
145
  */
110
146
  export async function runEvidenceGate(params, deps = {}) {
@@ -115,6 +151,7 @@ export async function runEvidenceGate(params, deps = {}) {
115
151
  recordPassFn = recordPass,
116
152
  logger = Logger,
117
153
  runSuiteFn = runLockedSuite,
154
+ loadConfigFn = loadConfig,
118
155
  } = deps;
119
156
  const {
120
157
  scopeId,
@@ -123,19 +160,11 @@ export async function runEvidenceGate(params, deps = {}) {
123
160
  useEvidence,
124
161
  cwd,
125
162
  worktreePath,
126
- runnerArgs,
127
163
  } = params ?? {};
128
164
 
129
- if (
130
- !scopeId ||
131
- !standalone ||
132
- !gate ||
133
- !runnerArgs ||
134
- runnerArgs.length === 0
135
- ) {
136
- logger.fatal(
137
- 'Usage: node evidence-gate.js --standalone --scope-id <id> --gate <name> [--worktree <path>] [--no-evidence] -- <cmd> [args...]',
138
- );
165
+ const usage = usageError(params ?? {});
166
+ if (usage) {
167
+ logger.fatal(usage);
139
168
  return { status: 1, skipped: false };
140
169
  }
141
170
  const evidenceStoreOpts = { cwd, standalone };
@@ -143,8 +172,11 @@ export async function runEvidenceGate(params, deps = {}) {
143
172
  // The gate runs in the worktree; evidence stays anchored to the main
144
173
  // checkout so the temp tree resolves under the main `.git/`.
145
174
  const spawnCwd = worktreePath ?? cwd;
146
- const [cmd, ...cmdArgs] = runnerArgs;
147
- const configHash = hashCommandConfig({ cmd, args: cmdArgs, cwd: spawnCwd });
175
+ const { cmd, cmdArgs, env, note, configHash } = resolveRun(
176
+ params,
177
+ spawnCwd,
178
+ loadConfigFn,
179
+ );
148
180
  const { headSha, inputFingerprint } = resolveEvidenceKeys({
149
181
  spawnCwd,
150
182
  gitSpawnFn,
@@ -179,6 +211,7 @@ export async function runEvidenceGate(params, deps = {}) {
179
211
  gate,
180
212
  cmd,
181
213
  cmdArgs,
214
+ env,
182
215
  spawnCwd,
183
216
  logger,
184
217
  spawnFn,
@@ -202,6 +235,7 @@ export async function runEvidenceGate(params, deps = {}) {
202
235
  exitCode: 0,
203
236
  durationMs: Date.now() - startedAt,
204
237
  inputFingerprint,
238
+ ...note,
205
239
  },
206
240
  evidenceStoreOpts,
207
241
  );
@@ -215,12 +249,12 @@ export async function runEvidenceGate(params, deps = {}) {
215
249
  }
216
250
 
217
251
  /**
218
- * @param {{ cmd: string, args: string[], cwd: string, log: (m: string) => void }} run
252
+ * @param {{ cmd: string, args: string[], cwd: string, log: (m: string) => void, childEnv?: Record<string, string> }} run
219
253
  * @param {{ config?: object|null, env?: object, lockOptions?: object, runSuiteImpl?: typeof runSupervisedSuite }} [seams]
220
254
  * @returns {Promise<number>} 75 when the lock wait expired.
221
255
  */
222
256
  export function runLockedSuite(
223
- { cmd, args, cwd, log },
257
+ { cmd, args, cwd, log, childEnv },
224
258
  {
225
259
  config = loadConfig(cwd),
226
260
  env = process.env,
@@ -247,6 +281,7 @@ export function runLockedSuite(
247
281
  cwd,
248
282
  timeoutMs,
249
283
  ...lock,
284
+ env: { ...childEnv, ...lock.env },
250
285
  onTimings: (t) => {
251
286
  log(`[evidence-gate] ${formatSuiteTimings(t)}`);
252
287
  lockHooks.onTimings(t);
@@ -264,6 +299,7 @@ async function runGateCommand({
264
299
  gate,
265
300
  cmd,
266
301
  cmdArgs,
302
+ env,
267
303
  spawnCwd,
268
304
  logger,
269
305
  spawnFn,
@@ -271,7 +307,13 @@ async function runGateCommand({
271
307
  }) {
272
308
  if (gate === FULL_SUITE_GATE) {
273
309
  const log = (m) => logger.info(m);
274
- return await runSuiteFn({ cmd, args: cmdArgs, cwd: spawnCwd, log });
310
+ return await runSuiteFn({
311
+ cmd,
312
+ args: cmdArgs,
313
+ cwd: spawnCwd,
314
+ log,
315
+ childEnv: env,
316
+ });
275
317
  }
276
318
  const result = spawnFn(cmd, cmdArgs, {
277
319
  cwd: spawnCwd,
@@ -281,11 +323,28 @@ async function runGateCommand({
281
323
  return result.status ?? 1;
282
324
  }
283
325
 
326
+ function deferredLine(gate, status) {
327
+ return `⏸ ${gate} deferred (exit ${status}) — another full suite still holds the host lock, so nothing ran and no evidence was recorded.`;
328
+ }
329
+
330
+ function hostResourcesLine(gate, status) {
331
+ return `⛔ ${gate} lost workers to host memory (exit ${status}) — no test failed and no evidence was recorded.`;
332
+ }
333
+
334
+ /** Suite-gate exits that are not a failed gate, each logged as what happened. */
335
+ const NON_FAILURE_EXITS = {
336
+ [LOCK_WAIT_EXPIRED_EXIT_CODE]: ['info', deferredLine],
337
+ [COVERAGE_HOST_RESOURCES_EXIT_CODE]: ['error', hostResourcesLine],
338
+ };
339
+
340
+ function nonFailureExit(gate, status) {
341
+ return gate === FULL_SUITE_GATE ? NON_FAILURE_EXITS[status] : undefined;
342
+ }
343
+
284
344
  function reportGateExit({ gate, status, spawnCwd, logger }) {
285
- if (status === LOCK_WAIT_EXPIRED_EXIT_CODE) {
286
- logger.info(
287
- `[evidence-gate] ⏸ ${gate} deferred (exit ${status}) — another full suite still holds the host lock, so nothing ran and no evidence was recorded.`,
288
- );
345
+ const exit = nonFailureExit(gate, status);
346
+ if (exit) {
347
+ logger[exit[0]](`[evidence-gate] ${exit[1](gate, status)}`);
289
348
  return;
290
349
  }
291
350
  logger.error(
@@ -312,7 +371,7 @@ runAsCli(import.meta.url, main, {
312
371
  source: 'evidence-gate',
313
372
  usage: {
314
373
  invocation:
315
- 'node .agents/scripts/evidence-gate.js --scope-id <id> --gate <name> [--standalone] [--no-evidence] [--cwd <path>] [--worktree <path>] -- <cmd> [args...]',
374
+ 'node .agents/scripts/evidence-gate.js --scope-id <id> --gate <name> [--standalone] [--no-evidence] [--cwd <path>] [--worktree <path>] [--changed-since <sha>] -- <cmd> [args...]',
316
375
  summary:
317
376
  'Run one named gate, reusing a prior evidence stamp for the same HEAD instead of re-running it.',
318
377
  flags: [
@@ -325,6 +384,10 @@ runAsCli(import.meta.url, main, {
325
384
  ],
326
385
  ['--cwd <path>', 'Repository root (default: project root).'],
327
386
  ['--worktree <path>', 'Worktree the gate runs in.'],
387
+ [
388
+ '--changed-since <sha>',
389
+ "With --gate test only: substitute $MANDREL_CHANGED_SINCE in the command, set it in the env, and credit the run as close's full-suite test (scope: delta).",
390
+ ],
328
391
  [
329
392
  '-- <cmd> [args...]',
330
393
  'Required. The command this gate runs, passed through verbatim (never via a shell).',
@@ -7,9 +7,12 @@
7
7
 
8
8
  import fs from 'node:fs';
9
9
  import path from 'node:path';
10
+ import { decodeEnvelope } from '../baselines/codec.js';
10
11
  import { toPosix } from '../util/paths.js';
11
12
 
12
13
  /**
14
+ * A baseline envelope comes back decoded by the layout codec.
15
+ *
13
16
  * @param {string} absolutePath
14
17
  * @returns {{ exists: boolean, parsed: object | null, parseError: string | null }}
15
18
  */
@@ -21,7 +24,11 @@ export function readJsonFile(absolutePath) {
21
24
  return { exists: false, parsed: null, parseError: null };
22
25
  }
23
26
  try {
24
- return { exists: true, parsed: JSON.parse(raw), parseError: null };
27
+ return {
28
+ exists: true,
29
+ parsed: decodeEnvelope(JSON.parse(raw)),
30
+ parseError: null,
31
+ };
25
32
  } catch (err) {
26
33
  return {
27
34
  exists: true,
@@ -6,6 +6,7 @@
6
6
  * @module lib/audit-baselines/trend
7
7
  */
8
8
 
9
+ import { decodeEnvelope } from '../baselines/codec.js';
9
10
  import { execFileCapture } from '../child-exec.js';
10
11
  import { trendRollupOf } from './kinds.js';
11
12
 
@@ -52,7 +53,7 @@ function rollupAt({ cwd, kind, sha, relPath, run }) {
52
53
  return null;
53
54
  }
54
55
  try {
55
- return trendRollupOf(kind, JSON.parse(stdout));
56
+ return trendRollupOf(kind, decodeEnvelope(JSON.parse(stdout)));
56
57
  } catch {
57
58
  return null;
58
59
  }
@@ -1,3 +1,4 @@
1
+ import { decodeEnvelope } from './baselines/codec.js';
1
2
  import { createGitInterface } from './git-utils.js';
2
3
 
3
4
  /**
@@ -30,7 +31,8 @@ export function clearBaselineCache() {
30
31
  * @param {object} [opts]
31
32
  * @param {string} [opts.cwd]
32
33
  * @param {ReturnType<typeof createGitInterface>} [opts.git]
33
- * @returns {unknown} Parsed JSON; the schema is the caller's contract.
34
+ * @returns {unknown} Parsed JSON, decoded by the layout codec; the schema is
35
+ * the caller's contract.
34
36
  * @throws {Error} Naming ref and path, on an unresolvable blob or bad JSON.
35
37
  */
36
38
  export function readBaselineAtRef(ref, path, opts = {}) {
@@ -57,7 +59,7 @@ export function readBaselineAtRef(ref, path, opts = {}) {
57
59
  const raw = res.stdout ?? '';
58
60
  let parsed;
59
61
  try {
60
- parsed = JSON.parse(raw);
62
+ parsed = decodeEnvelope(JSON.parse(raw));
61
63
  } catch (err) {
62
64
  throw new Error(
63
65
  `[baseline-loader] parse-error reading "${path}" at ref "${ref}": ${err?.message ?? err}`,
@@ -0,0 +1,57 @@
1
+ /**
2
+ * The one baseline layout codec: every path that turns baseline JSON into
3
+ * rows, or rows into JSON, goes through here. CRAP persists rows grouped by
4
+ * path under `files`; every other kind persists `rows[]` verbatim.
5
+ *
6
+ * @module lib/baselines/codec
7
+ */
8
+
9
+ import { decodeCrapFiles, encodeCrapFiles } from './kinds/_crap-codec.js';
10
+
11
+ /** Fixed top-level order; a stamp reaches disk only if named here. */
12
+ const STAMP_KEYS = Object.freeze([
13
+ '$schema',
14
+ 'kernelVersion',
15
+ 'scoringSemantics',
16
+ 'tsTranspilerVersion',
17
+ ]);
18
+
19
+ function isCrapEnvelope(value) {
20
+ return (
21
+ typeof value?.$schema === 'string' &&
22
+ /(?:^|\/)crap\.schema\.json$/.test(value.$schema)
23
+ );
24
+ }
25
+
26
+ /**
27
+ * In-memory envelope to its on-disk object. Unset stamps stay undefined, so
28
+ * JSON omits them.
29
+ *
30
+ * @param {{rows: Array<object>}} envelope
31
+ * @returns {object}
32
+ */
33
+ export function encodeEnvelope(envelope) {
34
+ const out = {};
35
+ for (const key of STAMP_KEYS) out[key] = envelope[key];
36
+ if (isCrapEnvelope(envelope)) out.files = encodeCrapFiles(envelope.rows);
37
+ else out.rows = envelope.rows;
38
+ return out;
39
+ }
40
+
41
+ /**
42
+ * Parsed baseline JSON to the in-memory `rows` envelope. Anything that is
43
+ * not a grouped CRAP envelope — another kind, the previous CRAP `rows[]`
44
+ * layout, unparseable junk — is returned unchanged, so an old layout reaches
45
+ * the compat axes rather than a shape error.
46
+ *
47
+ * @param {unknown} parsed
48
+ * @returns {unknown}
49
+ */
50
+ export function decodeEnvelope(parsed) {
51
+ if (!isCrapEnvelope(parsed)) return parsed;
52
+ const { files, ...stamps } = parsed;
53
+ if (!files || typeof files !== 'object' || Array.isArray(files)) {
54
+ return parsed;
55
+ }
56
+ return { ...stamps, rows: decodeCrapFiles(files) };
57
+ }