mandrel 2.81.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.
Files changed (33) hide show
  1. package/.agents/docs/configuration.md +4 -3
  2. package/.agents/schemas/agentrc.schema.json +1 -1
  3. package/.agents/scripts/coverage-capture.js +55 -24
  4. package/.agents/scripts/evidence-gate.js +7 -1
  5. package/.agents/scripts/lib/audit-to-stories/parse-audit-md.js +49 -24
  6. package/.agents/scripts/lib/baselines/duplication-scanner.js +35 -7
  7. package/.agents/scripts/lib/bootstrap/manifest.js +128 -159
  8. package/.agents/scripts/lib/close-lock-events.js +109 -0
  9. package/.agents/scripts/lib/close-validation/commands.js +12 -0
  10. package/.agents/scripts/lib/close-validation/gates.js +6 -0
  11. package/.agents/scripts/lib/close-validation/process.js +5 -2
  12. package/.agents/scripts/lib/close-validation/runner.js +14 -4
  13. package/.agents/scripts/lib/config-settings-schema.js +1 -1
  14. package/.agents/scripts/lib/full-suite-lock.js +20 -0
  15. package/.agents/scripts/lib/full-suite-queue.js +24 -56
  16. package/.agents/scripts/lib/generated/agentrc-validator.js +1 -1
  17. package/.agents/scripts/lib/orchestration/git-cleanup/phases/cli.js +31 -27
  18. package/.agents/scripts/lib/orchestration/git-cleanup/phases/render.js +25 -21
  19. package/.agents/scripts/lib/orchestration/pr-watch-poll.js +107 -0
  20. package/.agents/scripts/lib/orchestration/pr-watch.js +168 -235
  21. package/.agents/scripts/lib/orchestration/reassert-status-column.js +102 -72
  22. package/.agents/scripts/lib/orchestration/single-story-close/phases/close-validation.js +73 -63
  23. package/.agents/scripts/lib/orchestration/single-story-close/phases/post-land.js +21 -3
  24. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-gate-steps.js +44 -2
  25. package/.agents/scripts/lib/orchestration/single-story-close/phases/reconcile-done.js +63 -0
  26. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +3 -0
  27. package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +257 -0
  28. package/.agents/scripts/lib/orchestration/story-close/ratchet-shrink-writeback.js +341 -0
  29. package/.agents/scripts/lib/orchestration/ticketing.js +0 -9
  30. package/.agents/scripts/lib/supervised-suite.js +8 -28
  31. package/README.md +167 -216
  32. package/docs/CHANGELOG.md +29 -0
  33. package/package.json +1 -1
@@ -9,7 +9,15 @@ import { spawnSync } from 'node:child_process';
9
9
 
10
10
  import { applyBehindUpdate } from './behind-recovery.js';
11
11
  import { createCancelledRunDiscount } from './cancelled-run-discount.js';
12
- import { checkVerdict, classifyRequiredCheck } from './check-state.js';
12
+ import { checkVerdict } from './check-state.js';
13
+ import {
14
+ allTerminal,
15
+ hasFailingCheck,
16
+ parseGhPrChecks,
17
+ pollUntilTerminal,
18
+ promotePendingToStillRunning,
19
+ reduceOutcomes,
20
+ } from './pr-watch-poll.js';
13
21
 
14
22
  /**
15
23
  * `gh` has no `<owner/repo>#<number>` form (it parses one as a branch), so
@@ -23,10 +31,22 @@ function ghRepoFlag(repo) {
23
31
  return trimmed.length > 0 ? ['--repo', trimmed] : [];
24
32
  }
25
33
 
34
+ function runGh(args, { cwd, repo, spawnFn = spawnSync }) {
35
+ const result = spawnFn('gh', [...args, ...ghRepoFlag(repo)], {
36
+ cwd,
37
+ encoding: 'utf-8',
38
+ shell: false,
39
+ });
40
+ return {
41
+ status: result.status ?? 1,
42
+ stdout: result.stdout ?? '',
43
+ stderr: result.stderr ?? '',
44
+ };
45
+ }
46
+
26
47
  /** `--required` makes the returned set authoritative for protection gating. */
27
- function ghPrChecks({ prUrl, cwd, repo, spawnFn = spawnSync }) {
28
- const result = spawnFn(
29
- 'gh',
48
+ function ghPrChecks({ prUrl, ...port }) {
49
+ return runGh(
30
50
  [
31
51
  'pr',
32
52
  'checks',
@@ -34,28 +54,13 @@ function ghPrChecks({ prUrl, cwd, repo, spawnFn = spawnSync }) {
34
54
  '--required',
35
55
  '--json',
36
56
  'name,state,bucket,workflow,link',
37
- ...ghRepoFlag(repo),
38
57
  ],
39
- { cwd, encoding: 'utf-8', shell: false },
58
+ port,
40
59
  );
41
- return {
42
- status: result.status ?? 1,
43
- stdout: result.stdout ?? '',
44
- stderr: result.stderr ?? '',
45
- };
46
60
  }
47
61
 
48
- function ghPrView({ prUrl, cwd, repo, spawnFn = spawnSync }) {
49
- const result = spawnFn(
50
- 'gh',
51
- ['pr', 'view', prUrl, '--json', 'mergeStateStatus', ...ghRepoFlag(repo)],
52
- { cwd, encoding: 'utf-8', shell: false },
53
- );
54
- return {
55
- status: result.status ?? 1,
56
- stdout: result.stdout ?? '',
57
- stderr: result.stderr ?? '',
58
- };
62
+ function ghPrView({ prUrl, ...port }) {
63
+ return runGh(['pr', 'view', prUrl, '--json', 'mergeStateStatus'], port);
59
64
  }
60
65
 
61
66
  /** Malformed input → `''`, which callers treat as "not BEHIND". */
@@ -72,21 +77,8 @@ function parseMergeStateStatus(stdout) {
72
77
  }
73
78
  }
74
79
 
75
- function ghPrUpdateBranch({ prUrl, cwd, repo, spawnFn = spawnSync }) {
76
- const result = spawnFn(
77
- 'gh',
78
- ['pr', 'update-branch', prUrl, ...ghRepoFlag(repo)],
79
- {
80
- cwd,
81
- encoding: 'utf-8',
82
- shell: false,
83
- },
84
- );
85
- return {
86
- status: result.status ?? 1,
87
- stdout: result.stdout ?? '',
88
- stderr: result.stderr ?? '',
89
- };
80
+ function ghPrUpdateBranch({ prUrl, ...port }) {
81
+ return runGh(['pr', 'update-branch', prUrl], port);
90
82
  }
91
83
 
92
84
  /** Gate for BEHIND recovery: never auto-update into a failing PR. */
@@ -96,109 +88,132 @@ function allGreen(outcomes) {
96
88
  return values.every((v) => checkVerdict(v) === 'pass');
97
89
  }
98
90
 
99
- /** Entries with a string `name`; `[]` for malformed input. */
100
- export function parseGhPrChecks(stdout) {
101
- const trimmed = String(stdout ?? '').trim();
102
- if (trimmed.length === 0) return [];
103
- try {
104
- const parsed = JSON.parse(trimmed);
105
- if (!Array.isArray(parsed)) return [];
106
- return parsed.filter(
107
- (e) => e && typeof e === 'object' && typeof e.name === 'string',
108
- );
109
- } catch {
110
- return [];
111
- }
91
+ function defaultSleep(ms) {
92
+ return new Promise((resolve) => setTimeout(resolve, ms));
112
93
  }
113
94
 
114
- /** `{ checkName: outcome }`; a repeated name (matrix, retry) — last wins. */
115
- export function reduceOutcomes(entries) {
116
- const out = {};
117
- for (const e of entries) {
118
- out[e.name] = classifyRequiredCheck(e);
95
+ /**
96
+ * Never poll an empty name set: `allTerminal({})` is vacuously true and would
97
+ * report a red verdict with no failing check. `gh` overloads non-zero for
98
+ * "none attached yet" and a real fault, so classification is the caller's.
99
+ */
100
+ function emptyRequiredChecksResult(first, logger) {
101
+ // `gh` exits 8 while checks are pending — expected, not a failure.
102
+ const ghFaulted = first.status !== 0 && first.status !== 8;
103
+ if (ghFaulted) {
104
+ logger.warn?.(
105
+ `[Watcher] gh pr checks failed (status=${first.status}): ${first.stderr}`,
106
+ );
119
107
  }
120
- return out;
108
+ return {
109
+ outcomes: {},
110
+ requiredChecks: [],
111
+ polls: 0,
112
+ updatesApplied: 0,
113
+ resumesApplied: 0,
114
+ terminal: false,
115
+ green: false,
116
+ stillRunning: false,
117
+ requiredChecksEmpty: true,
118
+ error: `gh-checks-${ghFaulted ? 'failed' : 'empty'}:status=${first.status}`,
119
+ };
121
120
  }
122
121
 
123
- /** Only `'pending'` is non-terminal (the classifier collapses running states). */
124
- export function allTerminal(outcomes) {
125
- for (const v of Object.values(outcomes)) {
126
- if (v === 'pending') return false;
127
- }
128
- return true;
122
+ function updateBranchPort(ctx) {
123
+ return async () => {
124
+ const update = ctx.ghPrUpdateBranchFn(ctx.target);
125
+ return update.status === 0
126
+ ? { ok: true }
127
+ : { ok: false, detail: `status=${update.status}: ${update.stderr}` };
128
+ };
129
129
  }
130
130
 
131
- /** Slow CI, not red: "re-arm the watch", never "the change is broken". */
132
- const STILL_RUNNING = 'still-running';
133
-
134
- /** Leftover `'pending'` → `'still-running'` (the schema forbids pending). */
135
- export function promotePendingToStillRunning(outcomes) {
136
- const out = {};
137
- for (const [k, v] of Object.entries(outcomes)) {
138
- out[k] = v === 'pending' ? STILL_RUNNING : v;
131
+ /** One BEHIND-recovery attempt; true only when the branch head moved. */
132
+ async function recoverBehind(ctx, updatesUsed) {
133
+ const view = ctx.ghPrViewFn(ctx.target);
134
+ if (view.status !== 0) {
135
+ ctx.logger.warn?.(
136
+ `[Watcher] gh pr view failed (status=${view.status}): ${view.stderr}`,
137
+ );
138
+ return false;
139
139
  }
140
- return out;
140
+ const recovery = await applyBehindUpdate({
141
+ mergeStateStatus: parseMergeStateStatus(view.stdout),
142
+ updatesUsed,
143
+ maxUpdates: ctx.maxUpdates,
144
+ updateBranch: updateBranchPort(ctx),
145
+ onUpdateFailed: (detail) =>
146
+ ctx.logger.warn?.(`[Watcher] gh pr update-branch failed (${detail})`),
147
+ });
148
+ return recovery.updated;
141
149
  }
142
150
 
143
- /** A genuinely red check: the hard stop that consumes no resume budget. */
144
- export function hasFailingCheck(outcomes) {
145
- return Object.values(outcomes).some((v) => checkVerdict(v) === 'fail');
151
+ /** BEHIND recovery only when all green; `maxUpdates` stops a base race. */
152
+ function canRecoverBehind(ctx, state) {
153
+ return (
154
+ allTerminal(state.outcomes) &&
155
+ allGreen(state.outcomes) &&
156
+ state.updatesApplied < ctx.maxUpdates
157
+ );
146
158
  }
147
159
 
148
- async function identityDiscount(_entries, outcomes) {
149
- return outcomes;
160
+ /** One poll-to-cap + BEHIND-recovery arm; mutates `state`. */
161
+ async function runPollArm(ctx, state) {
162
+ while (state.polls < ctx.maxPolls) {
163
+ const polled = await pollUntilTerminal({
164
+ ...ctx.target,
165
+ outcomes: state.outcomes,
166
+ polls: state.polls,
167
+ maxPolls: ctx.maxPolls,
168
+ ghPrChecksFn: ctx.ghPrChecksFn,
169
+ pollIntervalMs: ctx.pollIntervalMs,
170
+ sleepFn: ctx.sleepFn,
171
+ discountFn: ctx.discountFn,
172
+ logger: ctx.logger,
173
+ });
174
+ state.outcomes = polled.outcomes;
175
+ state.polls = polled.polls;
176
+ if (!canRecoverBehind(ctx, state)) return;
177
+ // A failed update must not re-poll as though the head moved.
178
+ if (!(await recoverBehind(ctx, state.updatesApplied))) return;
179
+ state.updatesApplied += 1;
180
+ ctx.logger.info?.(
181
+ `[Watcher] PR BEHIND base — issued gh pr update-branch (#${state.updatesApplied}/${ctx.maxUpdates}); re-polling required checks.`,
182
+ );
183
+ await ctx.sleepFn(ctx.pollIntervalMs);
184
+ // The new head invalidates the previous terminal outcomes.
185
+ state.outcomes = Object.fromEntries(
186
+ ctx.requiredChecks.map((name) => [name, 'pending']),
187
+ );
188
+ }
150
189
  }
151
190
 
152
- function defaultSleep(ms) {
153
- return new Promise((resolve) => setTimeout(resolve, ms));
191
+ /** Re-arm only when pending-but-not-failed with resume budget left. */
192
+ function shouldResume(ctx, state) {
193
+ return (
194
+ !allTerminal(state.outcomes) &&
195
+ !hasFailingCheck(state.outcomes) &&
196
+ state.resumesApplied < ctx.maxResumes
197
+ );
154
198
  }
155
199
 
156
- /**
157
- * A transient `gh` failure is skipped; `maxPolls` bounds a broken `gh`.
158
- *
159
- * @param {object} opts
160
- * @param {string} opts.prUrl
161
- * @param {string} opts.cwd
162
- * @param {string|null} [opts.repo] `owner/repo` passed to `gh` as `--repo`.
163
- * @param {object} opts.outcomes Initial `{ checkName: outcome }` map.
164
- * @param {number} opts.polls Current poll counter.
165
- * @param {number} opts.maxPolls Hard cap on total poll iterations.
166
- * @param {Function} opts.ghPrChecksFn
167
- * @param {number} opts.pollIntervalMs
168
- * @param {Function} opts.sleepFn
169
- * @param {Function} [opts.discountFn]
170
- * @param {{ warn?: Function }} opts.logger
171
- * @returns {Promise<{ outcomes: object, polls: number }>}
172
- */
173
- export async function pollUntilTerminal({
174
- prUrl,
175
- cwd,
176
- repo = null,
177
- outcomes,
178
- polls,
179
- maxPolls,
180
- ghPrChecksFn,
181
- pollIntervalMs,
182
- sleepFn,
183
- discountFn = identityDiscount,
184
- logger,
185
- }) {
186
- let currentOutcomes = outcomes;
187
- let currentPolls = polls;
188
- while (!allTerminal(currentOutcomes) && currentPolls < maxPolls) {
189
- await sleepFn(pollIntervalMs);
190
- currentPolls += 1;
191
- const probe = ghPrChecksFn({ prUrl, cwd, repo });
192
- const entries = parseGhPrChecks(probe.stdout);
193
- if (entries.length === 0 && probe.status !== 0 && probe.status !== 8) {
194
- logger.warn?.(
195
- `[Watcher] gh pr checks transient failure (status=${probe.status}): ${probe.stderr}`,
196
- );
197
- continue;
198
- }
199
- currentOutcomes = await discountFn(entries, reduceOutcomes(entries));
200
- }
201
- return { outcomes: currentOutcomes, polls: currentPolls };
200
+ function finalVerdict(ctx, state) {
201
+ const terminal = allTerminal(state.outcomes);
202
+ // Never `'timed_out'` — the auto-merge predicate would read it as failure.
203
+ const stillRunning = !terminal && !hasFailingCheck(state.outcomes);
204
+ const outcomes = terminal
205
+ ? state.outcomes
206
+ : promotePendingToStillRunning(state.outcomes);
207
+ return {
208
+ outcomes,
209
+ requiredChecks: ctx.requiredChecks,
210
+ polls: state.polls,
211
+ updatesApplied: state.updatesApplied,
212
+ resumesApplied: state.resumesApplied,
213
+ terminal,
214
+ green: terminal && allGreen(outcomes),
215
+ stillRunning,
216
+ };
202
217
  }
203
218
 
204
219
  /**
@@ -255,123 +270,41 @@ export async function watchPrToTerminal({
255
270
  logger,
256
271
  firstProbe,
257
272
  }) {
258
- const first = firstProbe ?? ghPrChecksFn({ prUrl, cwd, repo });
259
- // `gh` exits 8 while checks are pending — expected, not a failure.
273
+ const target = { prUrl, cwd, repo };
274
+ const first = firstProbe ?? ghPrChecksFn(target);
260
275
  const firstEntries = parseGhPrChecks(first.stdout);
261
276
  if (firstEntries.length === 0) {
262
- // Never poll an empty name set: `allTerminal({})` is vacuously true and
263
- // would report a red verdict with no failing check. Names resolve once
264
- // per call, so the caller's attach window re-resolves by calling again.
265
- const ghFaulted = first.status !== 0 && first.status !== 8;
266
- if (ghFaulted) {
267
- logger.warn?.(
268
- `[Watcher] gh pr checks failed (status=${first.status}): ${first.stderr}`,
269
- );
270
- }
271
- return {
272
- outcomes: {},
273
- requiredChecks: [],
274
- polls: 0,
275
- updatesApplied: 0,
276
- resumesApplied: 0,
277
- terminal: false,
278
- green: false,
279
- stillRunning: false,
280
- requiredChecksEmpty: true,
281
- // `gh` overloads non-zero for "none attached yet" and a real fault, and
282
- // stderr is not a contract, so classification is left to the caller.
283
- error: `gh-checks-${ghFaulted ? 'failed' : 'empty'}:status=${first.status}`,
284
- };
277
+ return emptyRequiredChecksResult(first, logger);
285
278
  }
286
-
287
- const requiredChecks = firstEntries.map((e) => e.name);
288
-
289
279
  const discountFn = createCancelledRunDiscount({ repo, ghApiFn, logger });
290
- let outcomes = await discountFn(firstEntries, reduceOutcomes(firstEntries));
291
- let polls = 0;
292
- let updatesApplied = 0;
293
- let resumesApplied = 0;
294
- // Each outer iteration is one poll-to-cap + BEHIND-recovery arm.
280
+ const ctx = {
281
+ target,
282
+ requiredChecks: firstEntries.map((e) => e.name),
283
+ maxPolls,
284
+ maxUpdates,
285
+ maxResumes,
286
+ pollIntervalMs,
287
+ ghPrChecksFn,
288
+ ghPrViewFn,
289
+ ghPrUpdateBranchFn,
290
+ sleepFn,
291
+ discountFn,
292
+ logger,
293
+ };
294
+ const state = {
295
+ outcomes: await discountFn(firstEntries, reduceOutcomes(firstEntries)),
296
+ polls: 0,
297
+ updatesApplied: 0,
298
+ resumesApplied: 0,
299
+ };
295
300
  for (;;) {
296
- while (polls < maxPolls) {
297
- ({ outcomes, polls } = await pollUntilTerminal({
298
- prUrl,
299
- cwd,
300
- repo,
301
- outcomes,
302
- polls,
303
- maxPolls,
304
- ghPrChecksFn,
305
- pollIntervalMs,
306
- sleepFn,
307
- discountFn,
308
- logger,
309
- }));
310
- // BEHIND recovery only when all green; `maxUpdates` stops a racing
311
- // base from ping-ponging forever.
312
- if (!allTerminal(outcomes) || !allGreen(outcomes)) break;
313
- // Checked before the `gh pr view` spawn to save the round-trip.
314
- if (updatesApplied >= maxUpdates) break;
315
- const view = ghPrViewFn({ prUrl, cwd, repo });
316
- if (view.status !== 0) {
317
- logger.warn?.(
318
- `[Watcher] gh pr view failed (status=${view.status}): ${view.stderr}`,
319
- );
320
- break;
321
- }
322
- const recovery = await applyBehindUpdate({
323
- mergeStateStatus: parseMergeStateStatus(view.stdout),
324
- updatesUsed: updatesApplied,
325
- maxUpdates,
326
- updateBranch: async () => {
327
- const update = ghPrUpdateBranchFn({ prUrl, cwd, repo });
328
- return update.status === 0
329
- ? { ok: true }
330
- : {
331
- ok: false,
332
- detail: `status=${update.status}: ${update.stderr}`,
333
- };
334
- },
335
- onUpdateFailed: (detail) =>
336
- logger.warn?.(`[Watcher] gh pr update-branch failed (${detail})`),
337
- });
338
- // A failed update must not re-poll as though the head moved.
339
- if (!recovery.updated) break;
340
- updatesApplied += 1;
341
- logger.info?.(
342
- `[Watcher] PR BEHIND base — issued gh pr update-branch (#${updatesApplied}/${maxUpdates}); re-polling required checks.`,
343
- );
344
- await sleepFn(pollIntervalMs);
345
- // The new head invalidates the previous terminal outcomes.
346
- outcomes = {};
347
- for (const name of requiredChecks) outcomes[name] = 'pending';
348
- }
349
-
350
- // Re-arm only when pending-but-not-failed with resume budget left.
351
- if (allTerminal(outcomes) || hasFailingCheck(outcomes)) break;
352
- if (resumesApplied >= maxResumes) break;
353
- resumesApplied += 1;
354
- polls = 0;
301
+ await runPollArm(ctx, state);
302
+ if (!shouldResume(ctx, state)) break;
303
+ state.resumesApplied += 1;
304
+ state.polls = 0;
355
305
  logger.info?.(
356
- `[Watcher] poll cap reached with checks still pending; re-arming watch (resume #${resumesApplied}/${maxResumes}).`,
306
+ `[Watcher] poll cap reached with checks still pending; re-arming watch (resume #${state.resumesApplied}/${maxResumes}).`,
357
307
  );
358
308
  }
359
-
360
- const terminal = allTerminal(outcomes);
361
- const failing = hasFailingCheck(outcomes);
362
- // Never `'timed_out'` — the auto-merge predicate would read it as failure.
363
- const stillRunning = !terminal && !failing;
364
- const finalOutcomes = terminal
365
- ? outcomes
366
- : promotePendingToStillRunning(outcomes);
367
- return {
368
- outcomes: finalOutcomes,
369
- requiredChecks,
370
- polls,
371
- updatesApplied,
372
- resumesApplied,
373
- terminal,
374
- green: terminal && allGreen(finalOutcomes),
375
- stillRunning,
376
- };
309
+ return finalVerdict(ctx, state);
377
310
  }
@@ -20,6 +20,94 @@ function defaultSleep(ms) {
20
20
  return new Promise((resolve) => setTimeout(resolve, ms));
21
21
  }
22
22
 
23
+ function requirePositiveInt(value, name) {
24
+ if (!Number.isInteger(value) || value <= 0) {
25
+ throw new TypeError(
26
+ `reassertStatusColumn requires a positive integer ${name}`,
27
+ );
28
+ }
29
+ }
30
+
31
+ function assertArgs({ provider, ticketId, pollAttempts }) {
32
+ if (!provider || typeof provider.getTicket !== 'function') {
33
+ throw new TypeError(
34
+ 'reassertStatusColumn requires a provider with getTicket',
35
+ );
36
+ }
37
+ if (typeof provider.graphql !== 'function') {
38
+ throw new TypeError(
39
+ 'reassertStatusColumn requires a provider with graphql (for ColumnSync)',
40
+ );
41
+ }
42
+ requirePositiveInt(ticketId, 'ticketId');
43
+ requirePositiveInt(pollAttempts, 'pollAttempts');
44
+ }
45
+
46
+ /** `undefined` on a transient read failure (logged), else the column. */
47
+ async function readColumnOrSkip(ctx, i) {
48
+ try {
49
+ return await ctx.sync.readCurrentColumn(ctx.ticketId);
50
+ } catch (err) {
51
+ ctx.logger?.warn?.(
52
+ `[reassertStatusColumn] drift-check #${i} failed (transient): ${
53
+ err?.message ?? err
54
+ }. Continuing.`,
55
+ );
56
+ return undefined;
57
+ }
58
+ }
59
+
60
+ /** The re-fire envelope, or `null` on a transient failure (logged). */
61
+ async function refire(ctx, i) {
62
+ try {
63
+ return await ctx.sync.sync(ctx.ticketId, ctx.labels);
64
+ } catch (err) {
65
+ ctx.logger?.warn?.(
66
+ `[reassertStatusColumn] re-fire attempt ${i} failed (transient): ${
67
+ err?.message ?? err
68
+ }. Continuing.`,
69
+ );
70
+ return null;
71
+ }
72
+ }
73
+
74
+ /**
75
+ * One drift-check tick. Returns a terminal envelope to stop polling, or
76
+ * `null` to keep going; `state` carries `attempts` and the last envelope.
77
+ */
78
+ async function pollTick(ctx, state, i) {
79
+ await ctx.sleepFn(ctx.pollDelayMs);
80
+ const current = await readColumnOrSkip(ctx, i);
81
+ if (current === undefined) return null;
82
+ if (current === ctx.targetColumn) return state.lastEnvelope;
83
+ ctx.logger?.info?.(
84
+ `[reassertStatusColumn] drift detected on attempt ${i} (current=${
85
+ current ?? '<null>'
86
+ } target=${ctx.targetColumn}); re-firing.`,
87
+ );
88
+ const next = await refire(ctx, i);
89
+ if (next === null) return null;
90
+ state.attempts += 1;
91
+ state.lastEnvelope = { ...next, attempts: state.attempts };
92
+ // A skip after a successful sync is unexpected: stop retrying.
93
+ return next.status === 'synced' ? null : state.lastEnvelope;
94
+ }
95
+
96
+ async function finalVerdict(ctx, state) {
97
+ let final = null;
98
+ try {
99
+ final = await ctx.sync.readCurrentColumn(ctx.ticketId);
100
+ } catch {
101
+ // An unreadable column after the budget reads as drift.
102
+ }
103
+ if (final === ctx.targetColumn) return state.lastEnvelope;
104
+ return {
105
+ status: 'drifted',
106
+ column: ctx.targetColumn,
107
+ attempts: state.attempts,
108
+ };
109
+ }
110
+
23
111
  /**
24
112
  * Re-assert one ticket's Status column. Returns `ColumnSync.sync`'s envelope
25
113
  * plus `attempts`: `synced` (confirmed), `drifted` (budget exhausted, still
@@ -48,26 +136,7 @@ export async function reassertStatusColumn(args) {
48
136
  sleepFn = defaultSleep,
49
137
  config,
50
138
  } = args ?? {};
51
- if (!provider || typeof provider.getTicket !== 'function') {
52
- throw new TypeError(
53
- 'reassertStatusColumn requires a provider with getTicket',
54
- );
55
- }
56
- if (typeof provider.graphql !== 'function') {
57
- throw new TypeError(
58
- 'reassertStatusColumn requires a provider with graphql (for ColumnSync)',
59
- );
60
- }
61
- if (!Number.isInteger(ticketId) || ticketId <= 0) {
62
- throw new TypeError(
63
- 'reassertStatusColumn requires a positive integer ticketId',
64
- );
65
- }
66
- if (!Number.isInteger(pollAttempts) || pollAttempts <= 0) {
67
- throw new TypeError(
68
- 'reassertStatusColumn requires a positive integer pollAttempts',
69
- );
70
- }
139
+ assertArgs({ provider, ticketId, pollAttempts });
71
140
 
72
141
  const ticket = await provider.getTicket(ticketId);
73
142
  const labels = Array.isArray(ticket?.labels) ? ticket.labels : [];
@@ -81,60 +150,21 @@ export async function reassertStatusColumn(args) {
81
150
  if (initial.status !== 'synced') {
82
151
  return initial;
83
152
  }
84
- let attempts = 1;
85
- let lastEnvelope = { ...initial, attempts };
153
+ const ctx = {
154
+ sync,
155
+ ticketId,
156
+ labels,
157
+ targetColumn,
158
+ logger,
159
+ sleepFn,
160
+ pollDelayMs,
161
+ };
162
+ const state = { attempts: 1, lastEnvelope: { ...initial, attempts: 1 } };
86
163
 
87
164
  // Bounded so a hostile bot cannot stall the close path.
88
165
  for (let i = 1; i < pollAttempts; i += 1) {
89
- await sleepFn(pollDelayMs);
90
- let current;
91
- try {
92
- current = await sync.readCurrentColumn(ticketId);
93
- } catch (err) {
94
- logger?.warn?.(
95
- `[reassertStatusColumn] drift-check #${i} failed (transient): ${
96
- err?.message ?? err
97
- }. Continuing.`,
98
- );
99
- continue;
100
- }
101
- if (current === targetColumn) {
102
- return lastEnvelope;
103
- }
104
- logger?.info?.(
105
- `[reassertStatusColumn] drift detected on attempt ${i} (current=${
106
- current ?? '<null>'
107
- } target=${targetColumn}); re-firing.`,
108
- );
109
- try {
110
- const next = await sync.sync(ticketId, labels);
111
- attempts += 1;
112
- // A skip after a successful sync is unexpected: stop retrying.
113
- if (next.status !== 'synced') {
114
- return { ...next, attempts };
115
- }
116
- lastEnvelope = { ...next, attempts };
117
- } catch (err) {
118
- logger?.warn?.(
119
- `[reassertStatusColumn] re-fire attempt ${i} failed (transient): ${
120
- err?.message ?? err
121
- }. Continuing.`,
122
- );
123
- }
166
+ const done = await pollTick(ctx, state, i);
167
+ if (done) return done;
124
168
  }
125
-
126
- let final;
127
- try {
128
- final = await sync.readCurrentColumn(ticketId);
129
- } catch {
130
- final = null;
131
- }
132
- if (final === targetColumn) {
133
- return lastEnvelope;
134
- }
135
- return {
136
- status: 'drifted',
137
- column: targetColumn,
138
- attempts,
139
- };
169
+ return finalVerdict(ctx, state);
140
170
  }