mandrel 2.87.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 (156) 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 +12 -8
  5. package/.agents/docs/workflows.md +1 -1
  6. package/.agents/schemas/agentrc.schema.json +11 -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/deliver-run.js +11 -0
  17. package/.agents/scripts/diagnose-friction.js +3 -3
  18. package/.agents/scripts/lib/baselines/coverage-updater-cli.js +6 -14
  19. package/.agents/scripts/lib/baselines/crap-updater-cli.js +36 -26
  20. package/.agents/scripts/lib/baselines/duplication-scanner.js +20 -1
  21. package/.agents/scripts/lib/baselines/env-overrides.js +39 -34
  22. package/.agents/scripts/lib/baselines/kernel.js +3 -2
  23. package/.agents/scripts/lib/baselines/kinds/crap.js +14 -38
  24. package/.agents/scripts/lib/baselines/preview-gates.js +4 -1
  25. package/.agents/scripts/lib/baselines/refresh-service.js +65 -22
  26. package/.agents/scripts/lib/baselines/writer.js +5 -1
  27. package/.agents/scripts/lib/bdd-runner-detect.js +7 -10
  28. package/.agents/scripts/lib/child-exec.js +14 -1
  29. package/.agents/scripts/lib/child-stream.js +122 -0
  30. package/.agents/scripts/lib/clean-temp.js +19 -13
  31. package/.agents/scripts/lib/cli-args.js +49 -0
  32. package/.agents/scripts/lib/codex/skills-projection.js +1 -12
  33. package/.agents/scripts/lib/config/gates/mutation.schema.js +2 -2
  34. package/.agents/scripts/lib/config/gh-config-dir.js +63 -0
  35. package/.agents/scripts/lib/config/github.js +2 -0
  36. package/.agents/scripts/lib/config/paths.js +14 -3
  37. package/.agents/scripts/lib/config-resolver.js +78 -64
  38. package/.agents/scripts/lib/config-settings-schema-delivery.js +4 -3
  39. package/.agents/scripts/lib/config-settings-schema.js +7 -0
  40. package/.agents/scripts/lib/coverage-baseline.js +2 -2
  41. package/.agents/scripts/lib/coverage-capture.js +16 -1
  42. package/.agents/scripts/lib/crap-utils.js +59 -47
  43. package/.agents/scripts/lib/full-suite-lock.js +1 -10
  44. package/.agents/scripts/lib/gates/baseline-store.js +10 -0
  45. package/.agents/scripts/lib/generated/agentrc-validator.js +1 -1
  46. package/.agents/scripts/lib/gh-exec.js +45 -2
  47. package/.agents/scripts/lib/gh-transport.js +27 -0
  48. package/.agents/scripts/lib/git-utils.js +16 -9
  49. package/.agents/scripts/lib/maintainability-engine.js +27 -6
  50. package/.agents/scripts/lib/maintainability-utils.js +14 -1
  51. package/.agents/scripts/lib/orchestration/check-baselines/phases/evaluate.js +4 -1
  52. package/.agents/scripts/lib/orchestration/evidence-stream.js +186 -0
  53. package/.agents/scripts/lib/orchestration/file-assumptions.js +2 -19
  54. package/.agents/scripts/lib/orchestration/git-cleanup/phases/branches-reap.js +3 -7
  55. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes-ff.js +34 -40
  56. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes.js +4 -3
  57. package/.agents/scripts/lib/orchestration/plan-persist/persist-helpers.js +2 -19
  58. package/.agents/scripts/lib/orchestration/pr-watch.js +1 -5
  59. package/.agents/scripts/lib/orchestration/project-meta-cache.js +17 -4
  60. package/.agents/scripts/lib/orchestration/reassert-status-column.js +1 -8
  61. package/.agents/scripts/lib/orchestration/resolve-stories.js +1 -0
  62. package/.agents/scripts/lib/orchestration/review-providers/native.js +2 -2
  63. package/.agents/scripts/lib/orchestration/single-story-close/phase-timer.js +43 -0
  64. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +37 -13
  65. package/.agents/scripts/lib/orchestration/single-story-close/phases/finish.js +264 -0
  66. package/.agents/scripts/lib/orchestration/single-story-close/phases/open-pr.js +68 -0
  67. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-push.js +106 -0
  68. package/.agents/scripts/lib/orchestration/single-story-close/phases/reconcile-done.js +43 -35
  69. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-halt.js +52 -0
  70. package/.agents/scripts/lib/orchestration/single-story-close/result.js +273 -0
  71. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +68 -776
  72. package/.agents/scripts/lib/orchestration/story-close/context-budget-writeback.js +20 -9
  73. package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +2 -2
  74. package/.agents/scripts/lib/orchestration/story-close/ratchet-shrink-writeback.js +20 -12
  75. package/.agents/scripts/lib/orchestration/story-handoff.js +50 -21
  76. package/.agents/scripts/lib/orchestration/story-progress.js +32 -12
  77. package/.agents/scripts/lib/orchestration/ticket-validator.js +3 -13
  78. package/.agents/scripts/lib/qa/resolve-selection.js +1 -8
  79. package/.agents/scripts/lib/single-story/confirm-and-land.js +33 -0
  80. package/.agents/scripts/lib/single-story-sweep/reconcile-closing.js +43 -11
  81. package/.agents/scripts/lib/single-story-sweep/sweep-lock.js +130 -30
  82. package/.agents/scripts/lib/skills/parse-skill.js +1 -4
  83. package/.agents/scripts/lib/story-body/story-body.js +12 -1
  84. package/.agents/scripts/lib/suite-admission.js +3 -11
  85. package/.agents/scripts/lib/temp-retention.js +25 -11
  86. package/.agents/scripts/lib/test-run-credit.js +2 -5
  87. package/.agents/scripts/lib/transpile.js +193 -31
  88. package/.agents/scripts/lib/util/paths.js +31 -0
  89. package/.agents/scripts/lib/util/sleep.js +15 -0
  90. package/.agents/scripts/lib/validation-evidence.js +29 -3
  91. package/.agents/scripts/lib/wave-runner/live-probe.js +24 -0
  92. package/.agents/scripts/lib/workers/crap-worker.js +23 -12
  93. package/.agents/scripts/lib/workers/maintainability-report-worker.js +18 -12
  94. package/.agents/scripts/lib/workflow-closure.js +1 -8
  95. package/.agents/scripts/notify.js +83 -90
  96. package/.agents/scripts/plan-context.js +8 -4
  97. package/.agents/scripts/providers/github/auth.js +14 -30
  98. package/.agents/scripts/providers/github/blocked-by-add.js +11 -27
  99. package/.agents/scripts/providers/github/compose.js +1 -0
  100. package/.agents/scripts/providers/github/gh-token-diagnostics.js +130 -0
  101. package/.agents/scripts/providers/github/identity.js +158 -0
  102. package/.agents/scripts/providers/github/issues.js +2 -2
  103. package/.agents/scripts/providers/github/mappers.js +16 -19
  104. package/.agents/scripts/providers/github/projects-v2-graphql.js +4 -36
  105. package/.agents/scripts/providers/github/request-helpers.js +44 -0
  106. package/.agents/scripts/providers/github/sub-issue-add.js +11 -28
  107. package/.agents/scripts/providers/github.js +10 -2
  108. package/.agents/scripts/quality-preview.js +6 -19
  109. package/.agents/scripts/single-story-confirm-merge.js +8 -20
  110. package/.agents/scripts/single-story-init.js +0 -1
  111. package/.agents/scripts/stories-wave-tick.js +60 -46
  112. package/.agents/scripts/story-handoff.js +2 -23
  113. package/.agents/scripts/story-review-compute.js +3 -22
  114. package/.agents/scripts/sync-claude-agents.js +1 -12
  115. package/.agents/scripts/sync-claude-commands.js +1 -12
  116. package/.agents/scripts/update-crap-baseline.js +10 -19
  117. package/.agents/scripts/update-ticket-state.js +44 -45
  118. package/.agents/templates/docs/audit-sweep-runbook.md +1 -1
  119. package/.agents/workflows/audit-accessibility.md +1 -1
  120. package/.agents/workflows/audit-adrs.md +1 -1
  121. package/.agents/workflows/audit-architecture.md +1 -1
  122. package/.agents/workflows/audit-baselines.md +2 -2
  123. package/.agents/workflows/audit-clean-code.md +1 -1
  124. package/.agents/workflows/audit-data-model.md +1 -1
  125. package/.agents/workflows/audit-dependencies.md +1 -1
  126. package/.agents/workflows/audit-devops.md +1 -1
  127. package/.agents/workflows/audit-documentation.md +1 -1
  128. package/.agents/workflows/audit-exceptions.md +2 -2
  129. package/.agents/workflows/audit-mobile.md +1 -1
  130. package/.agents/workflows/audit-navigability.md +1 -1
  131. package/.agents/workflows/audit-performance.md +1 -1
  132. package/.agents/workflows/audit-privacy.md +1 -1
  133. package/.agents/workflows/audit-quality.md +1 -1
  134. package/.agents/workflows/audit-security.md +1 -1
  135. package/.agents/workflows/audit-seo.md +1 -1
  136. package/.agents/workflows/audit-sre.md +1 -1
  137. package/.agents/workflows/audit-to-stories.md +9 -7
  138. package/.agents/workflows/audit-ux-ui.md +1 -1
  139. package/.agents/workflows/helpers/audit-lens-core.md +8 -5
  140. package/.agents/workflows/helpers/deliver-digest.md +4 -5
  141. package/.agents/workflows/helpers/deliver-story-reference.md +4 -4
  142. package/.agents/workflows/mandrel-deliver.md +3 -1
  143. package/README.md +6 -3
  144. package/docs/CHANGELOG.md +29 -0
  145. package/lib/cli/doctor-checks/codex.js +240 -0
  146. package/lib/cli/doctor-checks/merge-driver.js +79 -0
  147. package/lib/cli/doctor-checks/payload.js +201 -0
  148. package/lib/cli/doctor-checks/read-json.js +16 -0
  149. package/lib/cli/doctor-checks/runtime-deps.js +146 -0
  150. package/lib/cli/doctor-checks/spawn.js +18 -0
  151. package/lib/cli/doctor-checks/sync-parity.js +205 -0
  152. package/lib/cli/doctor-checks/test-credit-path.js +270 -0
  153. package/lib/cli/doctor-checks/toolchain.js +137 -0
  154. package/lib/cli/doctor-checks/version-current.js +82 -0
  155. package/lib/cli/registry.js +40 -1330
  156. package/package.json +1 -1
@@ -4,6 +4,12 @@
4
4
  */
5
5
 
6
6
  import { spawn as defaultSpawn } from 'node:child_process';
7
+ import {
8
+ isTransportFailure,
9
+ sandboxDenialCode,
10
+ TRANSPORT_FAILURE_PATTERN,
11
+ TRANSPORT_REMEDY,
12
+ } from './gh-transport.js';
7
13
 
8
14
  let _spawnCount = 0;
9
15
 
@@ -52,6 +58,17 @@ export class GhAuthError extends GhExecError {
52
58
  }
53
59
  }
54
60
 
61
+ /**
62
+ * Sandbox or network fault: `gh` never reached GitHub (or its own config), so
63
+ * credentials were not assessed and re-authenticating will not help.
64
+ */
65
+ class GhTransportError extends GhExecError {
66
+ constructor(message, details = {}) {
67
+ super(message, details);
68
+ this.name = 'GhTransportError';
69
+ }
70
+ }
71
+
55
72
  /** Primary or secondary rate limit — callers back off, not re-auth. */
56
73
  export class GhRateLimitError extends GhExecError {
57
74
  constructor(message, details = {}) {
@@ -126,7 +143,16 @@ const CLASSIFY_RULES = [
126
143
  ),
127
144
  },
128
145
  {
129
- pattern: /requires authentication|not logged into|authentication required/,
146
+ pattern: TRANSPORT_FAILURE_PATTERN,
147
+ build: (d) =>
148
+ new GhTransportError(
149
+ `gh-exec: gh could not reach GitHub or its config — ${TRANSPORT_REMEDY}`,
150
+ d,
151
+ ),
152
+ },
153
+ {
154
+ pattern:
155
+ /requires authentication|not logged into|authentication required|http 401|bad credentials/,
130
156
  build: (d) =>
131
157
  new GhAuthError(
132
158
  'gh-exec: gh is not authenticated — run `gh auth login`',
@@ -164,7 +190,16 @@ function classifySpawnError(spawnError, details) {
164
190
  details,
165
191
  );
166
192
  }
167
- return null;
193
+ return classifySandboxDenial(spawnError, details);
194
+ }
195
+
196
+ function classifySandboxDenial(spawnError, details) {
197
+ const denied = sandboxDenialCode(spawnError);
198
+ if (!denied) return null;
199
+ return new GhTransportError(
200
+ `gh-exec: spawning gh was denied (${denied}) — ${TRANSPORT_REMEDY}`,
201
+ details,
202
+ );
168
203
  }
169
204
 
170
205
  export function classify({
@@ -211,6 +246,7 @@ export function exec({
211
246
  const spawnOpts = {
212
247
  stdio: ['pipe', 'pipe', 'pipe'],
213
248
  shell: false,
249
+ env: process.env,
214
250
  };
215
251
  if (typeof timeoutMs === 'number' && timeoutMs > 0) {
216
252
  spawnOpts.timeout = timeoutMs;
@@ -443,6 +479,13 @@ const GRAPHQL_PROBE_TIMEOUT_MS = 15_000;
443
479
  * @returns {{ verdict: 'available'|'unavailable'|'auth-failed', reason: string }}
444
480
  */
445
481
  function classifyGraphqlProbeFailure(err) {
482
+ // Transport first: a sandbox/network fault never earns the re-auth copy.
483
+ if (isTransportFailure(err))
484
+ return { verdict: 'available', reason: 'transport-inconclusive' };
485
+ return classifyReachableProbeFailure(err);
486
+ }
487
+
488
+ function classifyReachableProbeFailure(err) {
446
489
  const haystack = `${err?.stderr ?? ''}\n${err?.message ?? ''}`.toLowerCase();
447
490
  const authShaped =
448
491
  err instanceof GhAuthError ||
@@ -0,0 +1,27 @@
1
+ /** Transport / sandbox failure signatures: GitHub was never reached, so credentials were not assessed. */
2
+
3
+ export const TRANSPORT_FAILURE_PATTERN =
4
+ /etimedout|enotfound|econnrefused|econnreset|eai_again|dial tcp|error connecting to|could not resolve host|network is unreachable|operation not permitted|open [^\n]*: permission denied/i;
5
+
6
+ export const TRANSPORT_REMEDY =
7
+ 'credentials were not assessed and re-authenticating will not help — re-run with network access (the escalated, non-sandboxed execution path)';
8
+
9
+ const TRANSPORT_ERROR_NAMES = new Set([
10
+ 'GhTransportError',
11
+ 'GhExecTimeoutError',
12
+ ]);
13
+
14
+ const SANDBOX_SPAWN_CODES = new Set(['EPERM', 'EACCES']);
15
+
16
+ /** @returns {string|null} */
17
+ export function sandboxDenialCode(spawnError) {
18
+ const code = /** @type {any} */ (spawnError)?.code;
19
+ return SANDBOX_SPAWN_CODES.has(code) ? code : null;
20
+ }
21
+
22
+ export function isTransportFailure(err) {
23
+ if (TRANSPORT_ERROR_NAMES.has(err?.name)) return true;
24
+ return TRANSPORT_FAILURE_PATTERN.test(
25
+ `${err?.stderr ?? ''}\n${err?.message ?? ''}`,
26
+ );
27
+ }
@@ -5,6 +5,7 @@
5
5
 
6
6
  import { execFileSync, spawnSync } from 'node:child_process';
7
7
  import { execFileCapture, spawnCapture } from './child-exec.js';
8
+ import { defaultSleep } from './util/sleep.js';
8
9
 
9
10
  /**
10
11
  * `status` is 1 when null (signal); output is trimmed.
@@ -150,14 +151,6 @@ function isPackedRefsContention(stderr) {
150
151
  return PACKED_REFS_CONTENTION_PATTERNS.some((p) => p.test(stderr));
151
152
  }
152
153
 
153
- /**
154
- * @param {number} ms
155
- * @returns {Promise<void>}
156
- */
157
- function defaultSleep(ms) {
158
- return new Promise((resolve) => setTimeout(resolve, ms));
159
- }
160
-
161
154
  /**
162
155
  * @type {(ms: number) => Promise<void>}
163
156
  */
@@ -268,7 +261,21 @@ export function getStoryBranch(storyId) {
268
261
  return `story-${id}`;
269
262
  }
270
263
 
271
- const STORY_BRANCH_RE = /^story-(\d+)$/;
264
+ /**
265
+ * Whether `path` exists in the tree at `baseBranchRef` (`git cat-file -e`).
266
+ *
267
+ * @param {{ baseBranchRef: string, path: string, cwd?: string }} opts
268
+ * @returns {boolean}
269
+ */
270
+ export function pathExistsAtBase({ baseBranchRef, path, cwd }) {
271
+ return (
272
+ gitSpawn(cwd ?? process.cwd(), 'cat-file', '-e', `${baseBranchRef}:${path}`)
273
+ .status === 0
274
+ );
275
+ }
276
+
277
+ /** Positive ids only: `story-0` (and a zero-padded id) is not a Story branch. */
278
+ const STORY_BRANCH_RE = /^story-([1-9]\d*)$/;
272
279
 
273
280
  /**
274
281
  * @param {string} name
@@ -1,7 +1,12 @@
1
1
  import fs from 'node:fs';
2
2
  import { install as installAstCompat } from './escomplex-ast-compat.js';
3
3
  import { analyzeModule } from './escomplex-kernel.js';
4
- import { transpileIfNeeded } from './transpile.js';
4
+ import {
5
+ isCompilerMissing,
6
+ owningPackageDir,
7
+ transpileForReport,
8
+ transpileIfNeeded,
9
+ } from './transpile.js';
5
10
 
6
11
  installAstCompat();
7
12
 
@@ -33,6 +38,17 @@ function unscorable(reason) {
33
38
  return { score: UNSCORABLE, unscorable: true, reason };
34
39
  }
35
40
 
41
+ /** Not a kernel gap: the caller fails loud naming `packageDir`. */
42
+ function compilerMissing(filePath) {
43
+ return {
44
+ score: UNSCORABLE,
45
+ unscorable: true,
46
+ compilerMissing: true,
47
+ packageDir: owningPackageDir(filePath),
48
+ reason: 'typescript compiler not resolvable',
49
+ };
50
+ }
51
+
36
52
  /**
37
53
  * Ambiguous 0 when unscorable — prefer {@link scoreSource}.
38
54
  *
@@ -52,11 +68,12 @@ export function calculateForFile(filePath) {
52
68
  }
53
69
 
54
70
  /**
55
- * TS is transpiled first. Transpile and kernel failures need different
56
- * fixes, so they are reported separately.
71
+ * TS is transpiled first. Missing-compiler, transpile and kernel failures
72
+ * need different fixes, so they are reported separately.
57
73
  *
58
74
  * @param {string} filePath
59
- * @returns {{ score: number, unscorable: boolean, reason: string|null }}
75
+ * @returns {{ score: number, unscorable: boolean, reason: string|null,
76
+ * compilerMissing?: boolean, packageDir?: string }}
60
77
  */
61
78
  export function scoreFile(filePath) {
62
79
  let sourceCode;
@@ -69,7 +86,11 @@ export function scoreFile(filePath) {
69
86
  throw err;
70
87
  }
71
88
 
72
- const prepared = transpileIfNeeded(filePath, sourceCode);
89
+ return scorePrepared(filePath, transpileIfNeeded(filePath, sourceCode));
90
+ }
91
+
92
+ function scorePrepared(filePath, prepared) {
93
+ if (isCompilerMissing(prepared)) return compilerMissing(filePath);
73
94
  if (prepared === null) return unscorable('TypeScript transpile failed');
74
95
  return scoreSource(prepared);
75
96
  }
@@ -129,7 +150,7 @@ export function calculateReport(sourceCode) {
129
150
  export function calculateReportForFile(filePath) {
130
151
  try {
131
152
  const sourceCode = fs.readFileSync(filePath, 'utf-8');
132
- const prepared = transpileIfNeeded(filePath, sourceCode);
153
+ const prepared = transpileForReport(filePath, sourceCode);
133
154
  if (prepared === null) {
134
155
  return {
135
156
  moduleScore: 0,
@@ -7,6 +7,7 @@ import { Logger } from './Logger.js';
7
7
  import { scoreFile } from './maintainability-engine.js';
8
8
  import { isScored, reportUnscorable } from './maintainability-unscorable.js';
9
9
  import { isScorableSourceFile } from './source-extensions.js';
10
+ import { CompilerMissingError } from './transpile.js';
10
11
 
11
12
  const MAINTAINABILITY_WORKER_URL = new URL(
12
13
  './workers/maintainability-worker.js',
@@ -140,11 +141,22 @@ export function scanDirectory(dir, fileList = [], opts = {}) {
140
141
  return fileList;
141
142
  }
142
143
 
144
+ function assertCompilersResolved(perFile, cwd) {
145
+ const missingDirs = perFile
146
+ .filter((entry) => entry?.compilerMissing)
147
+ .map((entry) => entry.packageDir);
148
+ if (missingDirs.length > 0) {
149
+ throw new CompilerMissingError(missingDirs, { cwd });
150
+ }
151
+ }
152
+
143
153
  /**
144
154
  * Score files on a worker pool (serial below the cutover, where spawn cost
145
155
  * dominates). Output is sorted by path so it is stable across worker timing.
146
156
  * Failed and unscorable files are dropped — a phantom `mi: 0` poisons the
147
- * rollup — but unscorable ones are reported, never silently omitted.
157
+ * rollup — but unscorable ones are reported, never silently omitted. A
158
+ * TypeScript file with no resolvable compiler throws `CompilerMissingError`
159
+ * so no baseline is written from a partial scan.
148
160
  *
149
161
  * @param {string[]} paths
150
162
  * @param {{serialThreshold?: number}} [opts] Test seam for the cutover.
@@ -196,6 +208,7 @@ export async function calculateAll(paths, opts = {}) {
196
208
  a.relPath < b.relPath ? -1 : a.relPath > b.relPath ? 1 : 0,
197
209
  );
198
210
 
211
+ assertCompilersResolved(perFile, cwd);
199
212
  reportUnscorable(perFile);
200
213
 
201
214
  const scores = {};
@@ -126,7 +126,10 @@ export async function evaluateKind({
126
126
  const baseline = headLoad.baseline;
127
127
  // Rows from superseded scoring semantics pass schema but are incomparable;
128
128
  // fail closed.
129
- const semanticsError = checkBaselineSemantics(kind, baseline);
129
+ const semanticsError = checkBaselineSemantics(kind, baseline, {
130
+ cwd,
131
+ targetDirs: gateBlock?.targetDirs,
132
+ });
130
133
  if (semanticsError) {
131
134
  return {
132
135
  kind,
@@ -0,0 +1,186 @@
1
+ /**
2
+ * Run one handoff child with its evidence log written live, so an operator
3
+ * can tail a long suite. Streamed text is never inspected: the caller decides
4
+ * credit from the settled status and retained output. A log that cannot be
5
+ * written degrades to the completion-only write, never a failed step.
6
+ */
7
+
8
+ import fs from 'node:fs';
9
+
10
+ const HEARTBEAT_MS = 30_000;
11
+
12
+ const CANCEL_SIGNALS = Object.freeze(['SIGINT', 'SIGTERM']);
13
+
14
+ /** Reported when a cancelled child raced to exit 0. */
15
+ const CANCELLED_EXIT_CODE = 130;
16
+
17
+ /** With our listener gone, an unhandled signal terminates as it would have. */
18
+ function defaultReraise(signal) {
19
+ if (process.listenerCount(signal) > 0) return;
20
+ try {
21
+ process.kill(process.pid, signal);
22
+ } catch {}
23
+ }
24
+
25
+ /** Append-only sink; on any fs failure `finish` rewrites from the tail. */
26
+ function openSink(file, fsImpl) {
27
+ let fd = null;
28
+ let wrote = false;
29
+ try {
30
+ fd = fsImpl.openSync(file, 'w');
31
+ } catch {
32
+ fd = null;
33
+ }
34
+ const close = () => {
35
+ if (fd === null) return;
36
+ try {
37
+ fsImpl.closeSync(fd);
38
+ } catch {}
39
+ fd = null;
40
+ };
41
+ let broken = fd === null;
42
+ const write = (text) => {
43
+ if (broken) return;
44
+ try {
45
+ fsImpl.writeSync(fd, text);
46
+ wrote = true;
47
+ } catch {
48
+ broken = true;
49
+ close();
50
+ }
51
+ };
52
+ return {
53
+ write,
54
+ finish(output, terminal) {
55
+ const tail = terminal.map((line) => `${line}\n`).join('');
56
+ if (!broken && wrote) {
57
+ write(tail);
58
+ if (!broken) {
59
+ close();
60
+ return;
61
+ }
62
+ }
63
+ close();
64
+ const head = output && tail ? `${output}\n` : output;
65
+ try {
66
+ fsImpl.writeFileSync(file, `${head}${tail}`, 'utf8');
67
+ } catch {}
68
+ },
69
+ };
70
+ }
71
+
72
+ /** @param {number} ms */
73
+ const seconds = (ms) => Math.round(ms / 1000);
74
+
75
+ /** Report elapsed time on each tick that finds the child silent. */
76
+ function startHeartbeat({ progress, tag, heartbeatMs, now, lastOutput }) {
77
+ const startedAt = now();
78
+ const timer = setInterval(() => {
79
+ const at = now();
80
+ const silent = at - lastOutput();
81
+ if (silent < heartbeatMs) return;
82
+ progress(
83
+ tag,
84
+ `running ${seconds(at - startedAt)}s, last output ${seconds(silent)}s ago`,
85
+ );
86
+ }, heartbeatMs);
87
+ timer.unref?.();
88
+ return () => clearInterval(timer);
89
+ }
90
+
91
+ /** Abort the child on SIGINT/SIGTERM until `detach()`. */
92
+ function trapCancellation(signalTarget) {
93
+ const controller = new AbortController();
94
+ let cancelled = null;
95
+ const handlers = CANCEL_SIGNALS.map((signal) => {
96
+ const handler = () => {
97
+ cancelled ??= signal;
98
+ controller.abort();
99
+ };
100
+ signalTarget.on(signal, handler);
101
+ return [signal, handler];
102
+ });
103
+ return {
104
+ controller,
105
+ cancelled: () => cancelled,
106
+ detach() {
107
+ for (const [signal, handler] of handlers) {
108
+ signalTarget.off(signal, handler);
109
+ }
110
+ },
111
+ };
112
+ }
113
+
114
+ /** @param {number} ms */
115
+ function describeTimeout(ms) {
116
+ return `[handoff] child timed out after ${Number((ms / 1000).toFixed(1))}s`;
117
+ }
118
+
119
+ /**
120
+ * Run `cmd args` through `runCommand`, streaming its output to `file`.
121
+ *
122
+ * @param {{
123
+ * runCommand: Function, cmd: string, args: string[], opts: object,
124
+ * file: string, tag: string, progress: (tag: string, msg: string) => void,
125
+ * heartbeatMs?: number, timeoutMs?: number|null,
126
+ * signalTarget?: import('node:events').EventEmitter,
127
+ * reraise?: (signal: string) => void, now?: () => number,
128
+ * fsImpl?: typeof fs,
129
+ * }} request
130
+ * @returns {Promise<{ status: number, output: string, evidencePath: string }>}
131
+ */
132
+ export async function runStreamed({
133
+ runCommand,
134
+ cmd,
135
+ args,
136
+ opts,
137
+ file,
138
+ tag,
139
+ progress,
140
+ heartbeatMs = HEARTBEAT_MS,
141
+ timeoutMs = null,
142
+ signalTarget = process,
143
+ reraise = defaultReraise,
144
+ now = Date.now,
145
+ fsImpl = fs,
146
+ }) {
147
+ const sink = openSink(file, fsImpl);
148
+ progress(tag, `evidence ${file}`);
149
+ let lastOutputAt = now();
150
+ const trap = trapCancellation(signalTarget);
151
+ const stopHeartbeat = startHeartbeat({
152
+ progress,
153
+ tag,
154
+ heartbeatMs,
155
+ now,
156
+ lastOutput: () => lastOutputAt,
157
+ });
158
+ let res;
159
+ try {
160
+ res = await runCommand(cmd, args, {
161
+ ...opts,
162
+ signal: trap.controller.signal,
163
+ ...(timeoutMs ? { timeoutMs } : {}),
164
+ onChunk: (text) => {
165
+ lastOutputAt = now();
166
+ sink.write(text);
167
+ },
168
+ });
169
+ } catch (err) {
170
+ sink.finish('', []);
171
+ throw err;
172
+ } finally {
173
+ stopHeartbeat();
174
+ trap.detach();
175
+ }
176
+ const output = [res.stdout, res.stderr].filter(Boolean).join('\n');
177
+ const cancelled = trap.cancelled();
178
+ const terminal = [];
179
+ if (res.timedOut) terminal.push(describeTimeout(timeoutMs ?? 0));
180
+ if (cancelled) terminal.push('[handoff] cancelled');
181
+ sink.finish(output, terminal);
182
+ if (cancelled) reraise(cancelled);
183
+ const status =
184
+ cancelled && res.status === 0 ? CANCELLED_EXIT_CODE : res.status;
185
+ return { status, output, evidencePath: file };
186
+ }
@@ -8,29 +8,12 @@
8
8
  * on), which is an error.
9
9
  */
10
10
 
11
- import { gitSpawn } from '../git-utils.js';
11
+ import { gitSpawn, pathExistsAtBase } from '../git-utils.js';
12
12
  import { parse as parseStoryBody } from '../story-body/story-body.js';
13
13
  import { FILE_ASSUMPTION_VALUES } from './file-assumption-enum.js';
14
14
  import { computeStoryReachability } from './story-reachability.js';
15
15
  import { bareReferencePath, isObjectPathEntry } from './task-body-validator.js';
16
16
 
17
- /**
18
- * Existence probe at `baseBranchRef`; same semantics as
19
- * `ticket-validator.js#validateAcFreshness`.
20
- *
21
- * @param {{ baseBranchRef: string, path: string, cwd?: string }} opts
22
- * @returns {boolean}
23
- */
24
- function defaultGitRunner({ baseBranchRef, path, cwd }) {
25
- const result = gitSpawn(
26
- cwd ?? process.cwd(),
27
- 'cat-file',
28
- '-e',
29
- `${baseBranchRef}:${path}`,
30
- );
31
- return result.status === 0;
32
- }
33
-
34
17
  /**
35
18
  * Find `path`'s rename target in a commit's `--name-status -M` output. The
36
19
  * diff must be the whole commit, not pathspec-limited: limiting to the
@@ -292,7 +275,7 @@ export function validateStoryFileAssumptions(opts) {
292
275
  const {
293
276
  tickets,
294
277
  baseBranchRef,
295
- gitRunner = defaultGitRunner,
278
+ gitRunner = pathExistsAtBase,
296
279
  historyRunner = defaultHistoryRunner,
297
280
  cwd,
298
281
  } = opts;
@@ -5,6 +5,8 @@
5
5
  * @module lib/orchestration/git-cleanup/phases/branches-reap
6
6
  */
7
7
 
8
+ import { parseStoryBranch } from '../../../git-utils.js';
9
+
8
10
  const TAG = '[git-cleanup]';
9
11
 
10
12
  /**
@@ -67,7 +69,7 @@ function recordDeferredWorktree({
67
69
  worktreeRoot,
68
70
  }) {
69
71
  let pendingCleanup = null;
70
- const storyId = storyIdFromBranch(cand.branch);
72
+ const storyId = parseStoryBranch(cand.branch);
71
73
  if (recordPendingCleanupFn && worktreeRoot && storyId != null) {
72
74
  try {
73
75
  pendingCleanup = recordPendingCleanupFn(worktreeRoot, {
@@ -95,12 +97,6 @@ function recordDeferredWorktree({
95
97
  );
96
98
  }
97
99
 
98
- /** Story id of a `story-<id>` branch (the manifest key), else `null`. */
99
- function storyIdFromBranch(branch) {
100
- const m = /^story-(\d+)$/.exec(branch ?? '');
101
- return m ? Number(m[1]) : null;
102
- }
103
-
104
100
  export function reapLocalRef({ cand, deleteLocalFn, cwd, local, failures }) {
105
101
  if (cand.localExists === false) return true;
106
102
  const localRes = deleteLocalFn(cand.branch, cwd);
@@ -22,27 +22,22 @@ export function isWorktreeLockFailure(stderr) {
22
22
  return WORKTREE_LOCK_RE.test(stderr ?? '');
23
23
  }
24
24
 
25
- /* node:coverage ignore next */
26
25
  export function isWorkingTreeClean(cwd) {
27
26
  return defaultFfProbes.isClean(cwd);
28
27
  }
29
28
 
30
- /* node:coverage ignore next */
31
29
  export function fetchRef(cwd, remoteName, ref) {
32
30
  return defaultFfProbes.fetch(cwd, remoteName, ref);
33
31
  }
34
32
 
35
- /* node:coverage ignore next */
36
33
  export function canFastForward(cwd, baseBranch, remoteName) {
37
34
  return defaultFfProbes.canFastForward(cwd, baseBranch, remoteName);
38
35
  }
39
36
 
40
- /* node:coverage ignore next */
41
37
  export function checkoutBranch(cwd, branch) {
42
38
  return defaultFfProbes.checkout(cwd, branch);
43
39
  }
44
40
 
45
- /* node:coverage ignore next */
46
41
  export function mergeFastForward(cwd, ref) {
47
42
  return defaultFfProbes.merge(cwd, ref);
48
43
  }
@@ -116,42 +111,41 @@ export function makeFfProbes(spawn = gitSpawn) {
116
111
 
117
112
  const defaultFfProbes = makeFfProbes(gitSpawn);
118
113
 
119
- /* node:coverage ignore next */
120
- export function removeWorktree(worktreePath, cwd) {
121
- const plain = gitSpawn(cwd, 'worktree', 'remove', worktreePath);
122
- if (plain.status === 0) return { ok: true, dirty: false };
123
- const forced = gitSpawn(cwd, 'worktree', 'remove', '--force', worktreePath);
124
- if (forced.status === 0) {
125
- return { ok: true, dirty: true, stderr: plain.stderr };
126
- }
127
- const stderr = forced.stderr || plain.stderr;
128
- return {
129
- ok: false,
130
- dirty: true,
131
- lockClass: isWorktreeLockFailure(stderr),
132
- stderr,
133
- };
134
- }
135
-
136
114
  /**
137
- * Never `--quiet`: it suppresses the `[deleted]` lines that are the only
138
- * record of what was pruned, making real work read as "nothing to do".
115
+ * The destructive worktree / prune / stash wrappers over an injected spawn,
116
+ * like {@link makeFfProbes}.
139
117
  *
140
- * @param {string} cwd
141
- * @param {string} remoteName
142
- * @param {(output: string, remoteName: string) => string[]} parsePruneFn
143
- * @returns {{ ok: boolean, pruned: string[], stderr?: string }}
118
+ * @param {(cwd: string, ...args: string[]) => { status: number, stdout: string, stderr: string }} [spawn]
144
119
  */
145
- /* node:coverage ignore next */
146
- export function pruneRemoteTracking(cwd, remoteName, parsePruneFn) {
147
- const res = gitSpawn(cwd, 'fetch', '--prune', remoteName);
148
- if (res.status !== 0) return { ok: false, pruned: [], stderr: res.stderr };
149
- return { ok: true, pruned: parsePruneFn(res.stderr, remoteName) };
150
- }
151
-
152
- /* node:coverage ignore next */
153
- export function dropStash(ref, cwd) {
154
- const res = gitSpawn(cwd, 'stash', 'drop', ref);
155
- if (res.status !== 0) return { ok: false, stderr: res.stderr };
156
- return { ok: true };
120
+ export function makeWorktreeOps(spawn = gitSpawn) {
121
+ return {
122
+ removeWorktree: (worktreePath, cwd) => {
123
+ const plain = spawn(cwd, 'worktree', 'remove', worktreePath);
124
+ if (plain.status === 0) return { ok: true, dirty: false };
125
+ const forced = spawn(cwd, 'worktree', 'remove', '--force', worktreePath);
126
+ if (forced.status === 0) {
127
+ return { ok: true, dirty: true, stderr: plain.stderr };
128
+ }
129
+ const stderr = forced.stderr || plain.stderr;
130
+ return {
131
+ ok: false,
132
+ dirty: true,
133
+ lockClass: isWorktreeLockFailure(stderr),
134
+ stderr,
135
+ };
136
+ },
137
+ // Never `--quiet`: it hides the `[deleted]` lines the parser reads.
138
+ pruneRemoteTracking: (cwd, remoteName, parsePruneFn) => {
139
+ const res = spawn(cwd, 'fetch', '--prune', remoteName);
140
+ if (res.status !== 0) {
141
+ return { ok: false, pruned: [], stderr: res.stderr };
142
+ }
143
+ return { ok: true, pruned: parsePruneFn(res.stderr, remoteName) };
144
+ },
145
+ dropStash: (ref, cwd) => {
146
+ const res = spawn(cwd, 'stash', 'drop', ref);
147
+ if (res.status !== 0) return { ok: false, stderr: res.stderr };
148
+ return { ok: true };
149
+ },
150
+ };
157
151
  }
@@ -9,19 +9,20 @@ import { execFileSync } from 'node:child_process';
9
9
 
10
10
  import { gitSpawn } from '../../../git-utils.js';
11
11
  import { parseWorktreePorcelain } from '../../../worktree-manager.js';
12
+ import { makeWorktreeOps } from './git-probes-ff.js';
12
13
  import { resolveMergedTip } from './merged-tip.js';
13
14
 
14
15
  export {
15
16
  canFastForward,
16
17
  checkoutBranch,
17
- dropStash,
18
18
  fetchRef,
19
19
  isWorkingTreeClean,
20
20
  mergeFastForward,
21
- pruneRemoteTracking,
22
- removeWorktree,
23
21
  } from './git-probes-ff.js';
24
22
 
23
+ export const { removeWorktree, pruneRemoteTracking, dropStash } =
24
+ makeWorktreeOps(gitSpawn);
25
+
25
26
  /* node:coverage ignore next */
26
27
  export function listLocalBranches(cwd) {
27
28
  const res = gitSpawn(