mandrel 2.70.0 → 2.72.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 (79) hide show
  1. package/.agents/README.md +8 -9
  2. package/.agents/agents/acceptance-critic.md +1 -0
  3. package/.agents/agents/auditor.md +1 -0
  4. package/.agents/agents/plan-critic.md +1 -0
  5. package/.agents/agents/story-worker.md +63 -64
  6. package/.agents/docs/agentrc-reference.json +2 -1
  7. package/.agents/docs/configuration.md +7 -8
  8. package/.agents/rules/git-conventions-reference.md +2 -2
  9. package/.agents/schemas/agentrc.schema.json +19 -2
  10. package/.agents/schemas/story-deliver-terminal.schema.json +10 -1
  11. package/.agents/scripts/acceptance-eval.js +194 -15
  12. package/.agents/scripts/deliver-run.js +92 -43
  13. package/.agents/scripts/lib/audit-suite/index.js +1 -1
  14. package/.agents/scripts/lib/audit-suite/story-checklist.js +65 -0
  15. package/.agents/scripts/lib/audit-to-stories/audit-label-taxonomy.js +2 -2
  16. package/.agents/scripts/lib/bootstrap/issue-forms-template.js +1 -1
  17. package/.agents/scripts/lib/cli-args.js +22 -0
  18. package/.agents/scripts/lib/close-validation/gates.js +17 -3
  19. package/.agents/scripts/lib/config/agent-models.js +117 -0
  20. package/.agents/scripts/lib/config-settings-schema-delivery.js +13 -1
  21. package/.agents/scripts/lib/config-settings-schema-quality.js +1 -1
  22. package/.agents/scripts/lib/generated/agentrc-validator.js +1 -1
  23. package/.agents/scripts/lib/git/sync-from-base.js +89 -17
  24. package/.agents/scripts/lib/label-taxonomy.js +13 -3
  25. package/.agents/scripts/lib/notifications/notifier.js +11 -15
  26. package/.agents/scripts/lib/observability/close-telemetry.js +19 -3
  27. package/.agents/scripts/lib/observability/source-classifier.js +1 -0
  28. package/.agents/scripts/lib/orchestration/cancelled-run-discount.js +129 -0
  29. package/.agents/scripts/lib/orchestration/code-review.js +2 -2
  30. package/.agents/scripts/lib/orchestration/deliver-recover.js +166 -34
  31. package/.agents/scripts/lib/orchestration/file-assumptions.js +45 -11
  32. package/.agents/scripts/lib/orchestration/plan-context.js +17 -10
  33. package/.agents/scripts/lib/orchestration/plan-persist/changes-repair.js +130 -24
  34. package/.agents/scripts/lib/orchestration/plan-persist/run-plan-persist.js +19 -16
  35. package/.agents/scripts/lib/orchestration/plan-persist/story-ops.js +1 -0
  36. package/.agents/scripts/lib/orchestration/plan-persist/summary.js +4 -3
  37. package/.agents/scripts/lib/orchestration/pr-watch.js +14 -3
  38. package/.agents/scripts/lib/orchestration/resolve-stories.js +10 -2
  39. package/.agents/scripts/lib/orchestration/review-providers/native.js +5 -165
  40. package/.agents/scripts/lib/orchestration/single-story-close/failed-terminal.js +14 -2
  41. package/.agents/scripts/lib/orchestration/single-story-close/phases/auto-merge.js +45 -0
  42. package/.agents/scripts/lib/orchestration/single-story-close/phases/base-sync.js +162 -58
  43. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +58 -6
  44. package/.agents/scripts/lib/orchestration/single-story-close/phases/merge-wait-recovery.js +296 -0
  45. package/.agents/scripts/lib/orchestration/single-story-close/phases/options.js +20 -4
  46. package/.agents/scripts/lib/orchestration/single-story-close/phases/post-land.js +52 -6
  47. package/.agents/scripts/lib/orchestration/single-story-close/phases/pull-request.js +2 -2
  48. package/.agents/scripts/lib/orchestration/single-story-close/phases/story-branch-catch-up.js +50 -0
  49. package/.agents/scripts/lib/orchestration/single-story-close/phases/worktree-reap.js +64 -52
  50. package/.agents/scripts/lib/orchestration/single-story-close/phases/worktree-restore.js +133 -0
  51. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +187 -74
  52. package/.agents/scripts/lib/orchestration/story-deliver-terminal.js +46 -6
  53. package/.agents/scripts/lib/orchestration/story-handoff.js +849 -0
  54. package/.agents/scripts/lib/orchestration/story-init-result.js +83 -0
  55. package/.agents/scripts/lib/orchestration/task-body-validator.js +35 -5
  56. package/.agents/scripts/lib/orchestration/ticket-validator-sizing.js +1 -1
  57. package/.agents/scripts/lib/orchestration/ticket-validator.js +20 -2
  58. package/.agents/scripts/lib/single-story/confirm-merge.js +44 -7
  59. package/.agents/scripts/lib/story-body/story-body.js +40 -5
  60. package/.agents/scripts/lib/templates/decomposer-prompts.js +33 -36
  61. package/.agents/scripts/pr-watch-with-update.js +5 -0
  62. package/.agents/scripts/single-story-close.js +8 -0
  63. package/.agents/scripts/single-story-confirm-merge.js +34 -3
  64. package/.agents/scripts/single-story-init.js +17 -32
  65. package/.agents/scripts/story-handoff.js +112 -0
  66. package/.agents/scripts/sync-claude-agents.js +58 -27
  67. package/.agents/workflows/helpers/acceptance-self-eval.md +24 -18
  68. package/.agents/workflows/helpers/code-review.md +3 -3
  69. package/.agents/workflows/helpers/deliver-digest.md +79 -80
  70. package/.agents/workflows/helpers/deliver-light.md +9 -7
  71. package/.agents/workflows/helpers/deliver-reference.md +38 -22
  72. package/.agents/workflows/helpers/deliver-story-reference.md +39 -18
  73. package/.agents/workflows/helpers/deliver-story.md +30 -23
  74. package/.agents/workflows/helpers/plan-reference.md +24 -9
  75. package/.agents/workflows/helpers/worktree-lifecycle.md +5 -5
  76. package/docs/CHANGELOG.md +31 -0
  77. package/lib/cli/registry.js +7 -0
  78. package/package.json +4 -3
  79. package/.agents/scripts/lib/orchestration/review-providers/scoped-lint.js +0 -272
@@ -0,0 +1,849 @@
1
+ /**
2
+ * story-handoff.js — the story-worker's whole post-implementation tail as one
3
+ * deterministic sequence: blocking preflight (lint, quality-preview, baselined
4
+ * ratchets) → base merge → the one credited run → baseline seating → push +
5
+ * remote-ref check → held review. It runs
6
+ * exactly what deliver-digest § 5 and deliver-reference § Held review define,
7
+ * changing nothing close credits or adopts, and settles one envelope:
8
+ *
9
+ * - `ready` (exit 0) — hand off.
10
+ * - `fix-required` (exit 2) — the worker can fix it by editing the branch;
11
+ * labels untouched.
12
+ * - `blocked` (exit 1) — the worker cannot: a rejected push, an unreachable
13
+ * remote, an unconfirmed base branch or an unregistered baseline merge
14
+ * driver. Flips `agent::blocked` and posts a `friction` comment.
15
+ *
16
+ * Idempotent: a re-run skips every step whose result is still valid for the
17
+ * current HEAD, judged by the step's output signal, never its exit code alone.
18
+ * Never runs close, opens a PR or writes any label but `agent::blocked`.
19
+ */
20
+
21
+ import fs from 'node:fs';
22
+ import path from 'node:path';
23
+ import { fileURLToPath } from 'node:url';
24
+
25
+ import { spawnCaptureAsync } from '../child-exec.js';
26
+ import { resolveLintCommand } from '../close-validation/commands.js';
27
+ import {
28
+ isCoverageCaptureActive,
29
+ isCrapGateEnabled,
30
+ } from '../close-validation/gates.js';
31
+ import {
32
+ orchestrationLogDir,
33
+ storyReviewDepositPath,
34
+ } from '../config/temp-paths.js';
35
+ import { LOCK_WAIT_EXPIRED_EXIT_CODE } from '../full-suite-lock.js';
36
+ import { syncBranchFromBase } from '../git/sync-from-base.js';
37
+ import { getStoryBranch, gitSpawn } from '../git-utils.js';
38
+ import { readPackageScripts } from '../npm-scripts.js';
39
+ import { TIMEOUT_EXIT_CODE } from '../process-group.js';
40
+ import { probeHeldReviewDiff } from './review-deposit.js';
41
+ import {
42
+ STATE_LABELS,
43
+ transitionTicketState,
44
+ upsertStructuredComment,
45
+ } from './ticketing.js';
46
+
47
+ const SCRIPTS_DIR = path.resolve(
48
+ path.dirname(fileURLToPath(import.meta.url)),
49
+ '..',
50
+ '..',
51
+ );
52
+
53
+ const HANDOFF_STATUS = Object.freeze({
54
+ READY: 'ready',
55
+ FIX_REQUIRED: 'fix-required',
56
+ BLOCKED: 'blocked',
57
+ });
58
+
59
+ const EXIT_CODES = Object.freeze({
60
+ [HANDOFF_STATUS.READY]: 0,
61
+ [HANDOFF_STATUS.BLOCKED]: 1,
62
+ [HANDOFF_STATUS.FIX_REQUIRED]: 2,
63
+ });
64
+
65
+ /** The § 5 output signals — a depositor that prints none deposited nothing. */
66
+ const SIGNALS = Object.freeze({
67
+ captureRan: /Wrote content-digest capture stamp/,
68
+ captureFresh: /skipping capture/,
69
+ testRan: /✓ test passed/,
70
+ testFresh: /⏭ test skipped/,
71
+ seated: /seated:\s*(\d+)/,
72
+ gateFail: /\(gate fail\)/,
73
+ offending: /^[+!] /,
74
+ });
75
+
76
+ /** CI's standalone ratchets; each runs only when its baseline is committed. */
77
+ const RATCHETS = Object.freeze([
78
+ {
79
+ key: 'dead-exports',
80
+ script: 'check-dead-exports.js',
81
+ args: [],
82
+ baseline: 'baselines/dead-exports.json',
83
+ },
84
+ {
85
+ key: 'dead-exports-production',
86
+ script: 'check-dead-exports.js',
87
+ args: ['--production'],
88
+ baseline: 'baselines/dead-exports-production.json',
89
+ },
90
+ {
91
+ key: 'arch-cycles',
92
+ script: 'check-arch-cycles.js',
93
+ args: [],
94
+ baseline: 'baselines/arch-cycles.json',
95
+ },
96
+ {
97
+ key: 'cyclomatic',
98
+ script: 'check-cyclomatic.js',
99
+ args: [],
100
+ baseline: 'baselines/cyclomatic.json',
101
+ },
102
+ ]);
103
+
104
+ const MAX_OFFENDING_LINES = 10;
105
+
106
+ const SEAT_SCRIPTS = Object.freeze({
107
+ crap: 'update-crap-baseline.js',
108
+ maintainability: 'update-maintainability-baseline.js',
109
+ });
110
+
111
+ /**
112
+ * A settled step. `stop` carries the envelope status that ends the run.
113
+ *
114
+ * @typedef {{ name: string, outcome: 'ran'|'skipped'|'failed'|'error',
115
+ * detail: string, evidencePath?: string|null, conflictFiles?: string[],
116
+ * stop?: 'fix-required'|'blocked', reason?: string }} StepResult
117
+ */
118
+
119
+ const ran = (name, detail, extra = {}) => ({
120
+ name,
121
+ outcome: 'ran',
122
+ detail,
123
+ ...extra,
124
+ });
125
+ const skipped = (name, detail, extra = {}) => ({
126
+ name,
127
+ outcome: 'skipped',
128
+ detail,
129
+ ...extra,
130
+ });
131
+ const fixRequired = (name, detail, extra = {}) => ({
132
+ name,
133
+ outcome: 'failed',
134
+ detail,
135
+ stop: HANDOFF_STATUS.FIX_REQUIRED,
136
+ ...extra,
137
+ });
138
+ const blocked = (name, reason, detail, extra = {}) => ({
139
+ name,
140
+ outcome: 'failed',
141
+ detail,
142
+ reason,
143
+ stop: HANDOFF_STATUS.BLOCKED,
144
+ ...extra,
145
+ });
146
+
147
+ /**
148
+ * @param {Function} git
149
+ * @param {string} cwd
150
+ * @param {string[]} args
151
+ * @returns {string|null} trimmed stdout, `null` on a non-zero exit.
152
+ */
153
+ function gitLine(git, cwd, args) {
154
+ const res = git(cwd, ...args);
155
+ if (res?.status !== 0) return null;
156
+ return (res.stdout ?? '').toString().trim();
157
+ }
158
+
159
+ /** @param {object} ctx */
160
+ function headSha(ctx) {
161
+ return gitLine(ctx.git, ctx.cwd, ['rev-parse', 'HEAD']);
162
+ }
163
+
164
+ /**
165
+ * Run one child, write its combined output to the step's evidence log.
166
+ *
167
+ * @param {object} ctx
168
+ * @param {string} logName
169
+ * @param {string} cmd
170
+ * @param {string[]} args
171
+ * @returns {Promise<{ status: number, output: string, evidencePath: string }>}
172
+ */
173
+ async function runLogged(ctx, logName, cmd, args) {
174
+ ctx.progress(logName, `${cmd} ${args.join(' ')}`);
175
+ const res = await ctx.runCommand(cmd, args, { cwd: ctx.cwd });
176
+ const output = [res.stdout, res.stderr].filter(Boolean).join('\n');
177
+ const evidencePath = ctx.writeEvidence(logName, output);
178
+ return { status: res.status, output, evidencePath };
179
+ }
180
+
181
+ /**
182
+ * The suite exit codes § 5 distinguishes from a red run.
183
+ *
184
+ * @param {number} status
185
+ * @returns {string}
186
+ */
187
+ function describeSuiteFailure(status) {
188
+ if (status === LOCK_WAIT_EXPIRED_EXIT_CODE) {
189
+ return `suite deferred (exit ${status}): another full suite holds the host lock — re-run the handoff once it frees`;
190
+ }
191
+ if (status === TIMEOUT_EXIT_CODE) {
192
+ return `suite timed out (exit ${status}) — usually host contention; re-run the handoff`;
193
+ }
194
+ return `red suite (exit ${status}) — fix the failing tests, commit, re-run`;
195
+ }
196
+
197
+ /**
198
+ * Lint, quality-preview, then each ratchet whose baseline is committed.
199
+ *
200
+ * @param {object} ctx
201
+ * @returns {Array<{ key: string, cmd: string, args: string[], gated?: boolean }>}
202
+ */
203
+ function preflightChecks(ctx) {
204
+ const [lintCmd, ...lintArgs] = resolveLintCommand(ctx.config)
205
+ .split(/\s+/)
206
+ .filter(Boolean);
207
+ const ratchets = RATCHETS.filter((r) =>
208
+ fs.existsSync(path.join(ctx.cwd, r.baseline)),
209
+ ).map((r) => ({
210
+ key: r.key,
211
+ cmd: 'node',
212
+ args: [path.join(SCRIPTS_DIR, r.script), ...r.args],
213
+ gated: true,
214
+ }));
215
+ return [
216
+ { key: 'lint', cmd: lintCmd, args: lintArgs },
217
+ {
218
+ key: 'quality-preview',
219
+ cmd: 'node',
220
+ args: [
221
+ path.join(SCRIPTS_DIR, 'quality-preview.js'),
222
+ '--changed-since',
223
+ `origin/${ctx.baseBranch}`,
224
+ ],
225
+ },
226
+ ...ratchets,
227
+ ];
228
+ }
229
+
230
+ /**
231
+ * A ratchet also fails on `(gate fail)`; its finding names the `+`/`!` rows.
232
+ *
233
+ * @param {{ key: string, gated?: boolean }} check
234
+ * @param {{ status: number, output: string }} run
235
+ * @returns {string|null} the finding, `null` when the check passed.
236
+ */
237
+ function preflightFinding(check, run) {
238
+ const gateFailed = check.gated === true && SIGNALS.gateFail.test(run.output);
239
+ if (run.status === 0 && !gateFailed) return null;
240
+ const offending = check.gated
241
+ ? run.output
242
+ .split(/\r?\n/)
243
+ .filter((line) => SIGNALS.offending.test(line))
244
+ .slice(0, MAX_OFFENDING_LINES)
245
+ : [];
246
+ const rows = offending.length > 0 ? `: ${offending.join('; ')}` : '';
247
+ return `${check.key}${check.gated ? ' ratchet' : ''} finding${rows} — fix and commit, then re-run`;
248
+ }
249
+
250
+ /** @param {object} ctx @returns {Promise<StepResult>} */
251
+ async function stepPreflight(ctx) {
252
+ const name = 'preflight';
253
+ if (ctx.state.preflightHead === ctx.head) {
254
+ return skipped(
255
+ name,
256
+ `preflight already passed at ${ctx.head.slice(0, 12)}`,
257
+ );
258
+ }
259
+ const checks = preflightChecks(ctx);
260
+ for (const check of checks) {
261
+ const run = await runLogged(
262
+ ctx,
263
+ `preflight-${check.key}`,
264
+ check.cmd,
265
+ check.args,
266
+ );
267
+ const finding = preflightFinding(check, run);
268
+ if (finding) {
269
+ return fixRequired(name, finding, { evidencePath: run.evidencePath });
270
+ }
271
+ }
272
+ ctx.state.preflightHead = ctx.head;
273
+ return ran(name, `${checks.map((c) => c.key).join(', ')} clean`);
274
+ }
275
+
276
+ /** A baseline-only conflict the shared sync resolved is named. */
277
+ function mergedDetail(sync, baseBranch) {
278
+ const resolved = sync.resolvedBaselineFiles ?? [];
279
+ const suffix =
280
+ resolved.length > 0
281
+ ? `; baseline-only conflict resolved to the base: ${resolved.join(', ')}`
282
+ : '';
283
+ return `${sync.kind} from origin/${baseBranch}${suffix}`;
284
+ }
285
+
286
+ /** @param {object} ctx @returns {Promise<StepResult>} */
287
+ async function stepBaseMerge(ctx) {
288
+ const name = 'base-merge';
289
+ const sync = await ctx.syncFromBase({
290
+ cwd: ctx.cwd,
291
+ baseBranch: ctx.baseBranch,
292
+ log: ctx.progress,
293
+ });
294
+ if (sync.synced) {
295
+ ctx.head = headSha(ctx) ?? ctx.head;
296
+ return sync.kind === 'noop-already-current'
297
+ ? skipped(name, `origin/${ctx.baseBranch} already merged`)
298
+ : ran(name, mergedDetail(sync, ctx.baseBranch));
299
+ }
300
+ if (sync.kind === 'merge-driver-missing') {
301
+ return blocked(name, 'merge-driver-unregistered', sync.stderr);
302
+ }
303
+ if (sync.kind === 'fetch-failed') {
304
+ return blocked(
305
+ name,
306
+ 'base-branch-unconfirmed',
307
+ `could not fetch origin/${ctx.baseBranch}: ${sync.stderr}`.trim(),
308
+ );
309
+ }
310
+ if (sync.kind === 'conflict') {
311
+ return fixRequired(
312
+ name,
313
+ `merging origin/${ctx.baseBranch} conflicts; the merge was aborted, so the tree is clean — merge it yourself, resolve, commit, re-run`,
314
+ { conflictFiles: sync.conflictFiles },
315
+ );
316
+ }
317
+ return fixRequired(name, `merge failed: ${sync.stderr}`.trim());
318
+ }
319
+
320
+ /**
321
+ * The depositor close will credit, from the one shared predicate.
322
+ *
323
+ * @param {{ config: object, scripts: Record<string, string>|null }} args
324
+ * @returns {'coverage-capture'|'test'}
325
+ */
326
+ function selectCreditedDepositor({ config, scripts }) {
327
+ return isCoverageCaptureActive(config, scripts) ? 'coverage-capture' : 'test';
328
+ }
329
+
330
+ /** @param {object} ctx @returns {Promise<StepResult>} */
331
+ async function stepCreditedRun(ctx) {
332
+ const name = 'credited-run';
333
+ if (ctx.state.creditHead === ctx.head) {
334
+ return skipped(
335
+ name,
336
+ `${ctx.depositor} credit already deposited at ${ctx.head.slice(0, 12)}`,
337
+ { depositor: ctx.depositor },
338
+ );
339
+ }
340
+ const capture = ctx.depositor === 'coverage-capture';
341
+ const run = capture
342
+ ? await runLogged(ctx, 'credited-run', 'node', [
343
+ path.join(SCRIPTS_DIR, 'coverage-capture.js'),
344
+ '--cwd',
345
+ ctx.cwd,
346
+ ])
347
+ : await runLogged(ctx, 'credited-run', 'node', [
348
+ path.join(SCRIPTS_DIR, 'evidence-gate.js'),
349
+ '--standalone',
350
+ '--scope-id',
351
+ String(ctx.storyId),
352
+ '--gate',
353
+ 'test',
354
+ '--worktree',
355
+ ctx.cwd,
356
+ '--',
357
+ 'npm',
358
+ 'test',
359
+ ]);
360
+ const extra = { evidencePath: run.evidencePath, depositor: ctx.depositor };
361
+ if (run.status !== 0) {
362
+ return fixRequired(name, describeSuiteFailure(run.status), extra);
363
+ }
364
+ const [ranSignal, freshSignal] = capture
365
+ ? [SIGNALS.captureRan, SIGNALS.captureFresh]
366
+ : [SIGNALS.testRan, SIGNALS.testFresh];
367
+ if (ranSignal.test(run.output)) {
368
+ ctx.state.creditHead = ctx.head;
369
+ return ran(name, `${ctx.depositor} deposited credit`, extra);
370
+ }
371
+ if (freshSignal.test(run.output)) {
372
+ ctx.state.creditHead = ctx.head;
373
+ return skipped(name, `${ctx.depositor} credit already fresh`, extra);
374
+ }
375
+ return fixRequired(
376
+ name,
377
+ `${ctx.depositor} exited 0 but printed no credit signal, so it deposited nothing`,
378
+ extra,
379
+ );
380
+ }
381
+
382
+ /**
383
+ * @param {Function} git
384
+ * @param {string} cwd
385
+ * @returns {string[]} paths `git status` reports changed.
386
+ */
387
+ function changedPaths(git, cwd) {
388
+ const res = git(cwd, 'status', '--porcelain');
389
+ if (res?.status !== 0) return [];
390
+ // The runner trims stdout, so the first ` M path` line may arrive as
391
+ // `M path`: strip the status code by shape, never by a fixed width.
392
+ return (res.stdout ?? '')
393
+ .toString()
394
+ .split(/\r?\n/)
395
+ .map((line) => line.replace(PORCELAIN_STATUS, '').trim())
396
+ .filter((p) => p.length > 0);
397
+ }
398
+
399
+ /** @param {object} ctx @returns {Promise<StepResult>} */
400
+ async function commitSeatedRows(ctx, total, evidencePath) {
401
+ const name = 'seat';
402
+ const paths = changedPaths(ctx.git, ctx.cwd);
403
+ const add = ctx.git(ctx.cwd, 'add', '--', ...paths);
404
+ const commit =
405
+ add?.status === 0
406
+ ? ctx.git(
407
+ ctx.cwd,
408
+ 'commit',
409
+ '-m',
410
+ `chore(baselines): baseline-refresh: seat rows for new methods (refs #${ctx.storyId})`,
411
+ )
412
+ : add;
413
+ if (commit?.status !== 0) {
414
+ const detail = `${commit?.stderr ?? ''}${commit?.stdout ?? ''}`.trim();
415
+ return fixRequired(
416
+ name,
417
+ `committing the seated rows failed: ${detail}`.trim(),
418
+ { evidencePath: ctx.writeEvidence('seat-commit', detail) },
419
+ );
420
+ }
421
+ const creditedPrior = ctx.state.creditHead === ctx.head;
422
+ ctx.head = headSha(ctx) ?? ctx.head;
423
+ ctx.state.seatHead = ctx.head;
424
+ // The capture stamp digests scorable sources only, so a baseline-JSON-only
425
+ // commit keeps the credit it already holds.
426
+ if (creditedPrior && ctx.depositor === 'coverage-capture') {
427
+ ctx.state.creditHead = ctx.head;
428
+ }
429
+ return ran(name, `seated ${total} row(s) and committed them`, {
430
+ evidencePath,
431
+ });
432
+ }
433
+
434
+ /**
435
+ * The gates whose baselines take a `--seat-missing` pass: CRAP by close's own
436
+ * predicate, MI unless explicitly disabled (both default on).
437
+ *
438
+ * @param {object} config
439
+ * @returns {Array<keyof typeof SEAT_SCRIPTS>}
440
+ */
441
+ function seatKinds(config) {
442
+ const mi = config?.delivery?.quality?.gates?.maintainability?.enabled;
443
+ return [
444
+ ...(isCrapGateEnabled(config) ? ['crap'] : []),
445
+ ...(mi === false ? [] : ['maintainability']),
446
+ ];
447
+ }
448
+
449
+ /** @param {object} ctx @returns {Promise<StepResult>} */
450
+ async function stepSeat(ctx) {
451
+ const name = 'seat';
452
+ if (ctx.state.seatHead === ctx.head) {
453
+ return skipped(name, `nothing to seat at ${ctx.head.slice(0, 12)}`);
454
+ }
455
+ const kinds = seatKinds(ctx.config);
456
+ let total = 0;
457
+ let evidencePath = null;
458
+ for (const kind of kinds) {
459
+ const run = await runLogged(ctx, `seat-${kind}`, 'node', [
460
+ path.join(SCRIPTS_DIR, SEAT_SCRIPTS[kind]),
461
+ '--seat-missing',
462
+ ]);
463
+ evidencePath = run.evidencePath;
464
+ const match = SIGNALS.seated.exec(run.output);
465
+ if (run.status !== 0 || !match) {
466
+ return fixRequired(
467
+ name,
468
+ `${kind} --seat-missing ${run.status !== 0 ? `refused (exit ${run.status})` : 'printed no `seated: N`'} — read the log for the fix`,
469
+ { evidencePath: run.evidencePath },
470
+ );
471
+ }
472
+ total += Number(match[1]);
473
+ }
474
+ if (total === 0) {
475
+ ctx.state.seatHead = ctx.head;
476
+ return skipped(name, 'seated: 0 — nothing to seat', { evidencePath });
477
+ }
478
+ return commitSeatedRows(ctx, total, evidencePath);
479
+ }
480
+
481
+ /**
482
+ * @param {object} ctx
483
+ * @returns {{ reachable: boolean, sha: string|null, detail: string }}
484
+ */
485
+ function remoteBranchSha(ctx) {
486
+ const res = ctx.git(
487
+ ctx.cwd,
488
+ 'ls-remote',
489
+ 'origin',
490
+ `refs/heads/${ctx.branch}`,
491
+ );
492
+ if (res?.status !== 0) {
493
+ return {
494
+ reachable: false,
495
+ sha: null,
496
+ detail: `${res?.stderr ?? ''}`.trim(),
497
+ };
498
+ }
499
+ const sha = (res.stdout ?? '').toString().trim().split(/\s+/)[0] || null;
500
+ return { reachable: true, sha, detail: '' };
501
+ }
502
+
503
+ const PORCELAIN_STATUS = /^\s*[ MADRCUT?!]{1,2}\s/;
504
+
505
+ const REMOTE_REJECTED =
506
+ /\[remote rejected\]|permission to \S+ denied|returned error: 403/i;
507
+ const REF_BEHIND = /\[rejected\].*\((non-fast-forward|fetch first)\)/;
508
+ const REMOTE_UNREACHABLE =
509
+ /could not resolve host|unable to access|could not read from remote|connection (refused|timed out|reset)|network is unreachable/i;
510
+ const PUSH_FAILURES = [
511
+ [REMOTE_REJECTED, 'push-rejected'],
512
+ [REMOTE_UNREACHABLE, 'remote-unreachable'],
513
+ [REF_BEHIND, 'ref-behind'],
514
+ ];
515
+
516
+ /**
517
+ * A push the remote refused or could not be reached is blocked; a branch
518
+ * behind its remote or a failing `pre-push` hook is the worker's to fix.
519
+ *
520
+ * @param {string} output
521
+ * @returns {'push-rejected'|'remote-unreachable'|'ref-behind'|null}
522
+ */
523
+ function classifyPushFailure(output) {
524
+ for (const [pattern, reason] of PUSH_FAILURES) {
525
+ if (pattern.test(output)) return reason;
526
+ }
527
+ return null;
528
+ }
529
+
530
+ /**
531
+ * @param {object} ctx
532
+ * @param {{ output: string, evidencePath: string|null }} push
533
+ * @returns {StepResult}
534
+ */
535
+ function pushFailure(ctx, push) {
536
+ const reason = classifyPushFailure(push.output);
537
+ const evidence = { evidencePath: push.evidencePath };
538
+ if (reason === 'ref-behind') {
539
+ return fixRequired(
540
+ 'push',
541
+ `origin/${ctx.branch} has commits HEAD lacks — git fetch origin ${ctx.branch}, git merge origin/${ctx.branch}, re-run`,
542
+ evidence,
543
+ );
544
+ }
545
+ return reason
546
+ ? blocked('push', reason, `git push failed (${reason})`, evidence)
547
+ : fixRequired(
548
+ 'push',
549
+ 'git push failed locally (a pre-push hook?) — fix the cause with a NEW commit, re-run',
550
+ evidence,
551
+ );
552
+ }
553
+
554
+ /** @param {object} ctx @returns {Promise<StepResult>} */
555
+ async function stepPush(ctx) {
556
+ const name = 'push';
557
+ const before = remoteBranchSha(ctx);
558
+ if (!before.reachable) {
559
+ return blocked(name, 'remote-unreachable', before.detail);
560
+ }
561
+ if (before.sha === ctx.head) {
562
+ return skipped(name, `origin/${ctx.branch} already at HEAD`);
563
+ }
564
+ const push = await runLogged(ctx, 'push', 'git', [
565
+ 'push',
566
+ '-u',
567
+ 'origin',
568
+ ctx.branch,
569
+ ]);
570
+ if (push.status !== 0) return pushFailure(ctx, push);
571
+ const after = remoteBranchSha(ctx);
572
+ if (after.sha !== ctx.head) {
573
+ return blocked(
574
+ name,
575
+ 'push-unconfirmed',
576
+ `origin/${ctx.branch} reads ${after.sha ?? 'nothing'} after the push, not HEAD ${ctx.head}`,
577
+ { evidencePath: push.evidencePath },
578
+ );
579
+ }
580
+ return ran(name, `pushed ${ctx.branch} → ${ctx.head.slice(0, 12)}`, {
581
+ evidencePath: push.evidencePath,
582
+ });
583
+ }
584
+
585
+ /**
586
+ * @param {object} deposit
587
+ * @param {string|null} depositPath
588
+ * @param {StepResult} settled
589
+ * @returns {StepResult}
590
+ */
591
+ function reviewVerdict(deposit, depositPath, settled) {
592
+ if (deposit?.halted) {
593
+ return fixRequired(
594
+ 'review',
595
+ 'held review found a CRITICAL — fix, commit, re-run the handoff',
596
+ { evidencePath: depositPath },
597
+ );
598
+ }
599
+ return settled;
600
+ }
601
+
602
+ /** @param {object} ctx @returns {Promise<StepResult>} */
603
+ async function stepReview(ctx) {
604
+ const name = 'review';
605
+ const held = ctx.probeReview({
606
+ cwd: ctx.cwd,
607
+ storyId: ctx.storyId,
608
+ sha: ctx.head,
609
+ baseBranch: ctx.baseBranch,
610
+ gitSpawnFn: ctx.git,
611
+ config: ctx.config,
612
+ });
613
+ if (held?.deposit) {
614
+ ctx.review = held.deposit.severity ?? null;
615
+ return reviewVerdict(
616
+ held.deposit,
617
+ ctx.reviewPath,
618
+ skipped(name, 'held review already matches this diff'),
619
+ );
620
+ }
621
+ let outcome;
622
+ try {
623
+ outcome = await ctx.computeReview({
624
+ storyId: ctx.storyId,
625
+ cwd: ctx.cwd,
626
+ config: ctx.config,
627
+ });
628
+ } catch (err) {
629
+ return {
630
+ name,
631
+ outcome: 'error',
632
+ detail: `review provider threw (${err?.message ?? err}); close computes the review itself`,
633
+ };
634
+ }
635
+ if (!outcome?.written) {
636
+ return {
637
+ name,
638
+ outcome: 'error',
639
+ detail: `no held review written: ${outcome?.reason ?? 'unknown'}; close computes the review itself`,
640
+ };
641
+ }
642
+ ctx.review = outcome.deposit?.severity ?? null;
643
+ return reviewVerdict(
644
+ outcome.deposit,
645
+ outcome.path ?? null,
646
+ ran(name, 'held review computed and deposited', {
647
+ evidencePath: outcome.path ?? null,
648
+ }),
649
+ );
650
+ }
651
+
652
+ /**
653
+ * The run's step order. On the evidence-gate path the `test` credit is keyed
654
+ * on the tree, so seating (static MI) goes first and cannot void it; the
655
+ * capture stamp digests scorable sources only, so a baseline seat after it
656
+ * keeps the stamp fresh.
657
+ *
658
+ * @param {'coverage-capture'|'test'} depositor
659
+ * @returns {Array<(ctx: object) => Promise<StepResult>>}
660
+ */
661
+ function stepOrder(depositor) {
662
+ const middle =
663
+ depositor === 'test'
664
+ ? [stepSeat, stepCreditedRun]
665
+ : [stepCreditedRun, stepSeat];
666
+ return [stepPreflight, stepBaseMerge, ...middle, stepPush, stepReview];
667
+ }
668
+
669
+ /**
670
+ * Refusals before any step: the handoff runs on the Story branch with the
671
+ * implementation committed.
672
+ *
673
+ * @param {object} ctx
674
+ * @returns {StepResult|null}
675
+ */
676
+ function precheck(ctx) {
677
+ const current = gitLine(ctx.git, ctx.cwd, ['branch', '--show-current']);
678
+ if (current !== ctx.branch) {
679
+ return fixRequired(
680
+ 'precheck',
681
+ `checked-out branch is ${current || 'unknown'}, not ${ctx.branch} — re-run single-story-init.js (idempotent) and work in its workCwd`,
682
+ );
683
+ }
684
+ if (!ctx.head) {
685
+ return fixRequired('precheck', 'HEAD does not resolve');
686
+ }
687
+ const dirty = changedPaths(ctx.git, ctx.cwd);
688
+ if (dirty.length > 0) {
689
+ return fixRequired(
690
+ 'precheck',
691
+ `uncommitted changes (${dirty.slice(0, 5).join(', ')}) — commit the implementation, then re-run`,
692
+ );
693
+ }
694
+ return null;
695
+ }
696
+
697
+ /**
698
+ * @param {string} statePath
699
+ * @returns {{ preflightHead?: string, creditHead?: string, seatHead?: string }}
700
+ */
701
+ function readState(statePath) {
702
+ try {
703
+ return JSON.parse(fs.readFileSync(statePath, 'utf8'))?.state ?? {};
704
+ } catch {
705
+ return {};
706
+ }
707
+ }
708
+
709
+ /**
710
+ * Flip `agent::blocked` and post the `friction` comment naming the reason.
711
+ * Each write is best-effort: a failed write degrades, never masks the block.
712
+ *
713
+ * @param {{ storyId: number, config: object, reason: string, detail: string,
714
+ * createProviderFn: Function, warn: Function }} args
715
+ */
716
+ async function defaultBlock({
717
+ storyId,
718
+ config,
719
+ reason,
720
+ detail,
721
+ createProviderFn,
722
+ warn,
723
+ }) {
724
+ const provider = createProviderFn(config);
725
+ try {
726
+ await upsertStructuredComment(
727
+ provider,
728
+ storyId,
729
+ 'friction',
730
+ `### story-handoff blocked: ${reason}\n\n${detail}\n\nThe worker cannot fix this by editing the branch; an operator must clear it, then re-run \`story-handoff.js\`.`,
731
+ );
732
+ } catch (err) {
733
+ warn(`failed to post friction comment: ${err?.message ?? err}`);
734
+ }
735
+ try {
736
+ await transitionTicketState(provider, storyId, STATE_LABELS.BLOCKED, {});
737
+ } catch (err) {
738
+ warn(`failed to flip agent::blocked: ${err?.message ?? err}`);
739
+ }
740
+ }
741
+
742
+ /**
743
+ * @param {{ storyId: number, cwd: string, config: object }} input
744
+ * @param {{
745
+ * git?: typeof gitSpawn,
746
+ * runCommand?: (cmd: string, args: string[], opts: { cwd: string }) => Promise<{ status: number, stdout: string, stderr: string }>,
747
+ * syncFromBase?: typeof syncBranchFromBase,
748
+ * probeReview?: typeof probeHeldReviewDiff,
749
+ * computeReview: (input: { storyId: number, cwd: string, config: object }) => Promise<{ written: boolean, path?: string, reason?: string, deposit?: object }>,
750
+ * readPackageScriptsFn?: typeof readPackageScripts,
751
+ * block?: (args: { storyId: number, config: object, reason: string, detail: string }) => Promise<void>,
752
+ * createProviderFn?: Function,
753
+ * progress?: (tag: string, msg: string) => void,
754
+ * logDir?: string,
755
+ * }} deps
756
+ * @returns {Promise<{ envelope: object, exitCode: number }>}
757
+ */
758
+ export async function runStoryHandoff({ storyId, cwd, config }, deps) {
759
+ const {
760
+ git = gitSpawn,
761
+ runCommand = spawnCaptureAsync,
762
+ syncFromBase = syncBranchFromBase,
763
+ probeReview = probeHeldReviewDiff,
764
+ computeReview,
765
+ readPackageScriptsFn = readPackageScripts,
766
+ createProviderFn,
767
+ progress = () => {},
768
+ logDir = orchestrationLogDir(config),
769
+ } = deps;
770
+ const block =
771
+ deps.block ??
772
+ ((args) =>
773
+ defaultBlock({
774
+ ...args,
775
+ createProviderFn,
776
+ warn: (m) => progress('BLOCK', m),
777
+ }));
778
+ fs.mkdirSync(logDir, { recursive: true });
779
+ const statePath = path.join(logDir, `story-handoff-${storyId}.json`);
780
+ const branch = getStoryBranch(storyId);
781
+ const ctx = {
782
+ storyId,
783
+ cwd,
784
+ config,
785
+ branch,
786
+ baseBranch: config?.project?.baseBranch ?? 'main',
787
+ git,
788
+ runCommand,
789
+ syncFromBase,
790
+ probeReview,
791
+ computeReview,
792
+ progress,
793
+ state: readState(statePath),
794
+ review: null,
795
+ reviewPath: storyReviewDepositPath(storyId, config),
796
+ depositor: selectCreditedDepositor({
797
+ config,
798
+ scripts: readPackageScriptsFn(cwd),
799
+ }),
800
+ writeEvidence: (name, text) => {
801
+ const file = path.join(logDir, `story-handoff-${storyId}-${name}.log`);
802
+ fs.writeFileSync(file, text ?? '', 'utf8');
803
+ return file;
804
+ },
805
+ };
806
+ ctx.head = headSha(ctx);
807
+
808
+ const steps = [];
809
+ let stop = precheck(ctx);
810
+ if (stop) steps.push(stop);
811
+ for (const step of stop ? [] : stepOrder(ctx.depositor)) {
812
+ const result = await step(ctx);
813
+ steps.push(result);
814
+ progress(result.name, `${result.outcome} — ${result.detail}`);
815
+ if (result.stop) {
816
+ stop = result;
817
+ break;
818
+ }
819
+ }
820
+
821
+ const status = stop?.stop ?? HANDOFF_STATUS.READY;
822
+ if (status === HANDOFF_STATUS.BLOCKED) {
823
+ await block({ storyId, config, reason: stop.reason, detail: stop.detail });
824
+ }
825
+ const envelope = {
826
+ kind: 'story-handoff',
827
+ storyId,
828
+ branch,
829
+ headSha: ctx.head,
830
+ status,
831
+ depositor: ctx.depositor,
832
+ steps: steps.map(({ stop: _stop, ...rest }) => rest),
833
+ review: ctx.review,
834
+ ...(stop
835
+ ? {
836
+ failedStep: stop.name,
837
+ evidencePath: stop.evidencePath ?? null,
838
+ ...(stop.reason ? { reason: stop.reason } : {}),
839
+ ...(stop.conflictFiles ? { conflictFiles: stop.conflictFiles } : {}),
840
+ }
841
+ : {}),
842
+ };
843
+ fs.writeFileSync(
844
+ statePath,
845
+ `${JSON.stringify({ state: ctx.state, envelope }, null, 2)}\n`,
846
+ 'utf8',
847
+ );
848
+ return { envelope, exitCode: EXIT_CODES[status] };
849
+ }