mandrel 2.82.0 → 2.83.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.
@@ -6,13 +6,16 @@
6
6
  * replays its tail inline. Full-suite lock-wait lines are also teed to
7
7
  * `progress()` so a long wait doesn't read as a hang, and an expired wait
8
8
  * defers to `pending` rather than failing.
9
+ * `lockWait` / `suiteTimings` come from the lock-event channel, never output.
9
10
  */
10
11
 
12
+ import {
13
+ createLockEventChannel as defaultCreateLockEventChannel,
14
+ summarizeLockEvents,
15
+ } from '../../../close-lock-events.js';
11
16
  import { buildDefaultGates as defaultBuildDefaultGates } from '../../../close-validation/gates.js';
12
17
  import { runCloseValidation as defaultRunCloseValidation } from '../../../close-validation/runner.js';
13
18
  import { LOCK_WAIT_EXPIRED_EXIT_CODE } from '../../../full-suite-lock.js';
14
- import { parseLockWaitOutcome } from '../../../full-suite-queue.js';
15
- import { parseSuiteTimings } from '../../../supervised-suite.js';
16
19
  import { createGateLogSink as defaultCreateGateLogSink } from '../gate-log.js';
17
20
  import { runPreGateSteps as defaultRunPreGateSteps } from './pre-gate-steps.js';
18
21
 
@@ -36,6 +39,7 @@ import { runPreGateSteps as defaultRunPreGateSteps } from './pre-gate-steps.js';
36
39
  * runBaselineUpwardWriteback?: Function,
37
40
  * runContextBudgetWriteback?: Function,
38
41
  * createGateLogSink?: typeof defaultCreateGateLogSink,
42
+ * createLockEventChannel?: typeof defaultCreateLockEventChannel,
39
43
  * onPreGateStepsDone?: () => void,
40
44
  * }} args
41
45
  * @returns {Promise<{
@@ -61,29 +65,28 @@ export async function runCloseValidationPhase({
61
65
  runBaselineUpwardWriteback,
62
66
  runContextBudgetWriteback,
63
67
  createGateLogSink = defaultCreateGateLogSink,
68
+ createLockEventChannel = defaultCreateLockEventChannel,
64
69
  onPreGateStepsDone,
65
70
  }) {
66
- await runPreGateSteps({
67
- cwd,
68
- worktreePath,
69
- storyId,
70
- baseBranch,
71
- storyBranch,
72
- config,
73
- progress,
74
- runScopedFormatAutofix,
75
- runBaselineUpwardWriteback,
76
- runContextBudgetWriteback,
71
+ await prepareTree({
72
+ runPreGateSteps,
73
+ onPreGateStepsDone,
74
+ stepArgs: {
75
+ cwd,
76
+ worktreePath,
77
+ storyId,
78
+ baseBranch,
79
+ storyBranch,
80
+ config,
81
+ progress,
82
+ runScopedFormatAutofix,
83
+ runBaselineUpwardWriteback,
84
+ runContextBudgetWriteback,
85
+ },
77
86
  });
78
- onPreGateStepsDone?.();
79
-
80
- progress(
81
- 'VALIDATE',
82
- `Running close-validation gates against baseline ${baseBranch}${worktreePath ? ` in ${worktreePath}` : ''}...`,
83
- );
84
87
  // One sink for both `log` seams so nothing routes around the artifact.
85
88
  const gateLog = createGateLogSink({ storyId, config });
86
- const lockWaits = trackLockWaits({ sink: gateLog.log, progress });
89
+ const lockEvents = createLockEventChannel();
87
90
  const gateList = buildDefaultGates({
88
91
  config,
89
92
  baseBranch,
@@ -92,13 +95,15 @@ export async function runCloseValidationPhase({
92
95
  storyId,
93
96
  evidenceCwd: cwd,
94
97
  });
95
- let validation;
96
- try {
97
- validation = await runCloseValidation({
98
+ const { validation, lockWait, suiteTimings } = await runGateChain({
99
+ runCloseValidation,
100
+ gateLog,
101
+ lockEvents,
102
+ progress,
103
+ validationArgs: {
98
104
  cwd,
99
105
  worktreePath,
100
106
  gates: gateList,
101
- log: lockWaits.log,
102
107
  storyId,
103
108
  // Anchors the evidence cache on the Story id, so a re-close at an
104
109
  // unchanged HEAD skips already-passed gates.
@@ -107,13 +112,8 @@ export async function runCloseValidationPhase({
107
112
  baseBranch,
108
113
  storyBranch,
109
114
  config,
110
- });
111
- } finally {
112
- // The sink is async-buffered; settle it before anything reads it, on
113
- // the throw path too.
114
- await gateLog.flush();
115
- }
116
- const lockWait = lockWaits.summary();
115
+ },
116
+ });
117
117
  if (!validation.ok) {
118
118
  return settleFailedValidation({ validation, lockWait, gateLog, progress });
119
119
  }
@@ -121,11 +121,46 @@ export async function runCloseValidationPhase({
121
121
  return {
122
122
  gates: gateOutcomes(gateList, validation),
123
123
  lockWait,
124
- suiteTimings: lockWaits.suiteTimings(),
124
+ suiteTimings,
125
125
  pending: false,
126
126
  };
127
127
  }
128
128
 
129
+ async function prepareTree({ runPreGateSteps, onPreGateStepsDone, stepArgs }) {
130
+ await runPreGateSteps(stepArgs);
131
+ onPreGateStepsDone?.();
132
+ const { baseBranch, worktreePath, progress } = stepArgs;
133
+ progress(
134
+ 'VALIDATE',
135
+ `Running close-validation gates against baseline ${baseBranch}${worktreePath ? ` in ${worktreePath}` : ''}...`,
136
+ );
137
+ }
138
+
139
+ async function runGateChain({
140
+ runCloseValidation,
141
+ gateLog,
142
+ lockEvents,
143
+ progress,
144
+ validationArgs,
145
+ }) {
146
+ let validation;
147
+ let events;
148
+ try {
149
+ validation = await runCloseValidation({
150
+ ...validationArgs,
151
+ log: teeLockLines({ sink: gateLog.log, progress }),
152
+ lockEvents,
153
+ });
154
+ } finally {
155
+ // The sink is async-buffered; settle it before anything reads it, on
156
+ // the throw path too.
157
+ await gateLog.flush();
158
+ events = lockEvents.read();
159
+ lockEvents.dispose();
160
+ }
161
+ return { validation, ...summarizeLockEvents(events) };
162
+ }
163
+
129
164
  /**
130
165
  * Deferred on an expired lock wait → `pending`; otherwise throws.
131
166
  *
@@ -157,40 +192,15 @@ function settleFailedValidation({ validation, lockWait, gateLog, progress }) {
157
192
  }
158
193
 
159
194
  /**
160
- * Parsed from the gate log: the one place that sees waits and timings both
161
- * in-process and in gate children.
195
+ * Display only: no figure is read back from these lines.
162
196
  *
163
197
  * @param {{ sink: (m: string) => void, progress: (tag: string, msg: string) => void }} args
164
- * @returns {{ log: (m: string) => void, summary: () => { waitedSeconds: number, expired: boolean, holder?: object }|null, suiteTimings: () => object|null }}
165
- */
166
- function trackLockWaits({ sink, progress }) {
167
- let tally = null;
168
- let timings = null;
169
- return {
170
- log(line) {
171
- sink(line);
172
- timings = parseSuiteTimings(line) ?? timings;
173
- if (!String(line).includes('[full-suite-lock]')) return;
174
- progress('LOCK', line);
175
- const outcome = parseLockWaitOutcome(line);
176
- if (!outcome) return;
177
- tally = mergeLockWait(tally, outcome);
178
- },
179
- summary: () => tally,
180
- suiteTimings: () => timings,
181
- };
182
- }
183
-
184
- /**
185
- * @param {{ waitedSeconds: number, expired: boolean, holder?: object }|null} tally
186
- * @param {{ waitedSeconds: number, expired: boolean, holder?: object }} outcome
198
+ * @returns {(line: string) => void}
187
199
  */
188
- function mergeLockWait(tally, outcome) {
189
- const holder = outcome.holder ?? tally?.holder;
190
- return {
191
- waitedSeconds: (tally?.waitedSeconds ?? 0) + outcome.waitedSeconds,
192
- expired: Boolean(tally?.expired) || outcome.expired,
193
- ...(holder ? { holder } : {}),
200
+ function teeLockLines({ sink, progress }) {
201
+ return (line) => {
202
+ sink(line);
203
+ if (String(line).includes('[full-suite-lock]')) progress('LOCK', line);
194
204
  };
195
205
  }
196
206
 
@@ -0,0 +1,63 @@
1
+ /**
2
+ * phases/reconcile-done.js — a Story closed as completed can still carry a
3
+ * stale lifecycle label: a close that blocked before auto-merge landed its
4
+ * PR leaves `agent::blocked` on the closed issue, and the re-run takes the
5
+ * already-closed early return. With merge evidence on the Story branch, this
6
+ * finishes the flip through the shared `agent::done` confirm. Best-effort —
7
+ * the land already happened, so nothing here may change the `landed`
8
+ * terminal; every failure is logged and swallowed.
9
+ */
10
+
11
+ import { gh as defaultGh } from '../../../gh-exec.js';
12
+ import { Logger } from '../../../Logger.js';
13
+ import { confirmStoryMerged } from '../../../single-story/confirm-merge.js';
14
+ import { STATE_LABELS } from '../../ticketing.js';
15
+ import { parsePrNumber } from './code-review.js';
16
+ import { pickHeadPullRequest } from './pull-request.js';
17
+
18
+ /** Close reasons meaning nothing merged — no label is owed. */
19
+ const UNLANDED_CLOSE_REASONS = new Set(['not_planned', 'duplicate']);
20
+
21
+ /**
22
+ * @param {{ storyId: number, storyBranch: string, options: { cwd: string },
23
+ * story: { labels?: string[], stateReason?: string|null } }} ctx
24
+ * @param {{ provider: object, config: object, gh?: object,
25
+ * notify?: Function, sleep?: Function }} deps
26
+ * @param {(tag: string, msg: string) => void} progress
27
+ * @returns {Promise<void>}
28
+ */
29
+ export async function reconcileDoneLabel(ctx, deps, progress) {
30
+ const { storyId, story, storyBranch } = ctx;
31
+ if (UNLANDED_CLOSE_REASONS.has(story.stateReason)) return;
32
+ if (story.labels?.includes(STATE_LABELS.DONE)) return;
33
+ try {
34
+ const rows = await (deps.gh ?? defaultGh).pr.list(
35
+ ['--head', storyBranch, '--state', 'all'],
36
+ ['url', 'state', 'mergedAt'],
37
+ );
38
+ const head = pickHeadPullRequest(rows);
39
+ if (head?.state !== 'MERGED') {
40
+ progress(
41
+ 'NOOP',
42
+ `No merged PR on ${storyBranch} — leaving Story #${storyId}'s labels as they are.`,
43
+ );
44
+ return;
45
+ }
46
+ await confirmStoryMerged({
47
+ provider: deps.provider,
48
+ storyId,
49
+ prNumber: parsePrNumber(head.url),
50
+ prUrl: head.url,
51
+ cwd: ctx.options.cwd,
52
+ config: deps.config,
53
+ progress,
54
+ injectedNotify: deps.notify,
55
+ prState: { state: 'MERGED', mergedAt: null },
56
+ sleepFn: deps.sleep,
57
+ });
58
+ } catch (err) {
59
+ Logger.warn(
60
+ `[single-story-close] ⚠️ Could not reconcile Story #${storyId} to agent::done: ${err?.message ?? err}`,
61
+ );
62
+ }
63
+ }
@@ -47,6 +47,7 @@ import {
47
47
  pickHeadPullRequest,
48
48
  } from './phases/pull-request.js';
49
49
  import { pushStoryBranch } from './phases/push.js';
50
+ import { reconcileDoneLabel } from './phases/reconcile-done.js';
50
51
  import { handleCriticalReviewBlock } from './phases/review-block.js';
51
52
  import { handleOverriddenReviewBlock } from './phases/review-override.js';
52
53
  import {
@@ -588,6 +589,7 @@ function resolveCloseDeps(options, injected) {
588
589
  gitSpawn: injected.injectedGitSpawn,
589
590
  releaseLease: injected.injectedReleaseLease ?? releaseStoryLease,
590
591
  graphqlProbe: injected.injectedGraphqlProbe,
592
+ sleep: injected.injectedSleep,
591
593
  };
592
594
  }
593
595
 
@@ -934,6 +936,7 @@ async function loadStoryPhase(ctx, deps) {
934
936
  progress('INIT', `Closing standalone Story #${ctx.storyId}...`);
935
937
  ctx.story = await deps.provider.getTicket(ctx.storyId);
936
938
  if (ctx.story.state !== 'closed') return null;
939
+ await reconcileDoneLabel(ctx, deps, progress);
937
940
  return await alreadyClosedResult(
938
941
  ctx.storyId,
939
942
  ctx.story.stateReason,
@@ -2,7 +2,7 @@
2
2
  * A full suite supervised as a process group. The suite may write
3
3
  * `$MANDREL_SUITE_READY_FILE` when its tests start; the kill timer then
4
4
  * re-arms a fresh `timeoutMs`, so a pre-test wait (bounded by `timeoutMs`
5
- * too) never spends the test budget. Close parses the timing line back.
5
+ * too) never spends the test budget.
6
6
  */
7
7
  import { spawn } from 'node:child_process';
8
8
  import crypto from 'node:crypto';
@@ -38,23 +38,6 @@ export function formatSuiteTimings({ lockWaitMs, hostWaitMs, testRunMs }) {
38
38
  return `⏲ suite timings: lockWaitMs=${Math.round(lockWaitMs)} hostWaitMs=${host} testRunMs=${Math.round(testRunMs)}`;
39
39
  }
40
40
 
41
- /**
42
- * @param {string} line
43
- * @returns {SuiteTimings|null}
44
- */
45
- export function parseSuiteTimings(line) {
46
- const match =
47
- /suite timings: lockWaitMs=(\d+) hostWaitMs=(\d+|n\/a) testRunMs=(\d+)/u.exec(
48
- String(line ?? ''),
49
- );
50
- if (!match) return null;
51
- return {
52
- lockWaitMs: Number(match[1]),
53
- hostWaitMs: match[2] === NO_HOST_WAIT ? null : Number(match[2]),
54
- testRunMs: Number(match[3]),
55
- };
56
- }
57
-
58
41
  function fileExists(fsImpl, file) {
59
42
  try {
60
43
  return fsImpl.existsSync(file);
@@ -160,9 +143,9 @@ export function superviseSuite(child, opts) {
160
143
  /**
161
144
  * A bare suite gets SIGKILL on a parent signal; a gate with its own cleanup
162
145
  * (a capture holding the lock) SIGTERM. A full-suite gate also gets the
163
- * handshake and emits its timing line on release.
146
+ * handshake and reports its timings on release.
164
147
  *
165
- * @param {{ fullSuiteLock?: boolean, timeoutMs?: number, signal?: AbortSignal, env?: Record<string, string> }} opts
148
+ * @param {{ fullSuiteLock?: boolean, timeoutMs?: number, signal?: AbortSignal, env?: Record<string, string>, onLockEvent?: (event: object) => void }} opts
166
149
  * @param {{ lockWaitMs?: number }} [lock]
167
150
  */
168
151
  export function gateSupervision(opts, lock = {}) {
@@ -180,14 +163,11 @@ export function gateSupervision(opts, lock = {}) {
180
163
  supervise: (child, output) =>
181
164
  reportOnRelease(
182
165
  superviseSuite(child, { ...base, readyFile: handshake.file }),
183
- (timings) =>
184
- output.emit(
185
- output.prefix +
186
- formatSuiteTimings({
187
- lockWaitMs: lock.lockWaitMs ?? 0,
188
- ...timings,
189
- }),
190
- ),
166
+ (timings) => {
167
+ const full = { lockWaitMs: lock.lockWaitMs ?? 0, ...timings };
168
+ output.emit(output.prefix + formatSuiteTimings(full));
169
+ opts.onLockEvent?.({ kind: 'suite-timings', ...full });
170
+ },
191
171
  ),
192
172
  };
193
173
  }