mandrel 2.115.0 → 2.117.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.
- package/.agents/docs/configuration.md +8 -0
- package/.agents/docs/workflows.md +2 -1
- package/.agents/schemas/agentrc.schema.json +47 -0
- package/.agents/scripts/closeout-audit.js +132 -0
- package/.agents/scripts/lib/config/temp-paths.js +12 -0
- package/.agents/scripts/lib/config-settings-schema-delivery.js +34 -0
- package/.agents/scripts/lib/coverage-baseline.js +11 -3
- package/.agents/scripts/lib/generated/agentrc-validator.js +2 -2
- package/.agents/scripts/lib/observability/source-classifier.js +3 -0
- package/.agents/scripts/lib/orchestrate/classify.js +238 -0
- package/.agents/scripts/lib/orchestrate/conflicts.js +119 -0
- package/.agents/scripts/lib/orchestrate/inherited-failure.js +66 -0
- package/.agents/scripts/lib/orchestrate/inventory.js +388 -0
- package/.agents/scripts/lib/orchestrate/ledger.js +223 -0
- package/.agents/scripts/lib/orchestration/closeout-audit.js +511 -0
- package/.agents/scripts/lib/orchestration/merge-queue.js +1 -1
- package/.agents/scripts/lib/orchestration/required-checks.js +12 -2
- package/.agents/scripts/orchestrate-inventory.js +70 -0
- package/.agents/scripts/orchestrate-ledger.js +141 -0
- package/.agents/workflows/helpers/deliver-reference.md +18 -0
- package/.agents/workflows/mandrel-orchestrate.md +140 -0
- package/docs/CHANGELOG.md +15 -0
- package/package.json +1 -1
|
@@ -0,0 +1,511 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* closeout-audit — report every landed Story whose close-out did not finish,
|
|
3
|
+
* and (on `execute`) repair each drifted check through the seam that already
|
|
4
|
+
* owns it. Probes, repairs and the lock are injected; the evaluation is pure.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { spawnChild } from '../child-exec.js';
|
|
9
|
+
import { readDeferralMarker } from '../coverage-deferral.js';
|
|
10
|
+
import { gh as defaultGh } from '../gh-exec.js';
|
|
11
|
+
import { deleteBranchRemote } from '../git-branch-cleanup.js';
|
|
12
|
+
import {
|
|
13
|
+
gitSpawn as defaultGitSpawn,
|
|
14
|
+
getStoryBranch,
|
|
15
|
+
parseStoryBranch,
|
|
16
|
+
} from '../git-utils.js';
|
|
17
|
+
import { AGENT_LABELS } from '../label-constants.js';
|
|
18
|
+
import { buildProtectionCtx } from '../single-story-sweep/protection-ctx.js';
|
|
19
|
+
import {
|
|
20
|
+
acquireSweepLock,
|
|
21
|
+
resolveSweepLockPath,
|
|
22
|
+
} from '../single-story-sweep/sweep-lock.js';
|
|
23
|
+
import { sweepMergedBranches } from '../single-story-sweep.js';
|
|
24
|
+
import { purgeStoryTempArtifacts } from '../temp-retention.js';
|
|
25
|
+
import { ColumnSync, columnForLabels } from './column-sync.js';
|
|
26
|
+
import { probeBranch, probePr, probeTicket } from './deliver-recover.js';
|
|
27
|
+
import { isPrMerged } from './merge-poll.js';
|
|
28
|
+
import { sweepStaleStoryWorktrees } from './plan-runner/worktree-sweep.js';
|
|
29
|
+
import { NEXT_COMMANDS } from './story-deliver-terminal.js';
|
|
30
|
+
|
|
31
|
+
/** Repair order: `story-state` first, its land tail clears most of the rest. */
|
|
32
|
+
const CHECKS = Object.freeze([
|
|
33
|
+
'story-state',
|
|
34
|
+
'board-status',
|
|
35
|
+
'remote-branch',
|
|
36
|
+
'local-branch',
|
|
37
|
+
'worktree',
|
|
38
|
+
'scratch',
|
|
39
|
+
]);
|
|
40
|
+
|
|
41
|
+
export const DEFAULT_SINCE_HOURS = 24;
|
|
42
|
+
|
|
43
|
+
// shortcut: one page of 100 recent merged PRs, raise it if a window holds more.
|
|
44
|
+
const MERGED_PR_PAGE = 100;
|
|
45
|
+
|
|
46
|
+
const auditCommand = (id) =>
|
|
47
|
+
`node .agents/scripts/closeout-audit.js --story ${id} --execute`;
|
|
48
|
+
|
|
49
|
+
function repairCommandFor(check, storyId) {
|
|
50
|
+
if (check === 'story-state') return NEXT_COMMANDS.confirmMerge(storyId);
|
|
51
|
+
if (check === 'board-status') return NEXT_COMMANDS.resync(storyId);
|
|
52
|
+
return auditCommand(storyId);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function row(check, storyId, status, evidence) {
|
|
56
|
+
return {
|
|
57
|
+
check,
|
|
58
|
+
status,
|
|
59
|
+
evidence,
|
|
60
|
+
repair: status === 'drift' ? repairCommandFor(check, storyId) : null,
|
|
61
|
+
repaired: false,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function storyStateRow(storyId, { ticket, pr }) {
|
|
66
|
+
if (!ticket?.ok) {
|
|
67
|
+
return row(
|
|
68
|
+
'story-state',
|
|
69
|
+
storyId,
|
|
70
|
+
'unknown',
|
|
71
|
+
`ticket unreadable: ${ticket?.error}`,
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
const issue = String(ticket.issueState ?? 'unknown').toLowerCase();
|
|
75
|
+
const label = ticket.stateLabel ?? 'none';
|
|
76
|
+
const marker = readDeferralMarker(pr?.body);
|
|
77
|
+
const evidence =
|
|
78
|
+
`issue=${issue} label=${label} pr=#${pr.number} merged` +
|
|
79
|
+
(marker ? `; Coverage-deferred: ${marker}` : '');
|
|
80
|
+
const ok = issue === 'closed' && label === AGENT_LABELS.DONE;
|
|
81
|
+
return row('story-state', storyId, ok ? 'ok' : 'drift', evidence);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function boardRow(storyId, { ticket, board }) {
|
|
85
|
+
const expected = ticket?.ok ? columnForLabels(ticket.labels) : null;
|
|
86
|
+
if (!board?.ok || !expected || !board.column) {
|
|
87
|
+
const why = board?.ok === false ? board.error : 'no Status to compare';
|
|
88
|
+
return row('board-status', storyId, 'unknown', `board unreadable: ${why}`);
|
|
89
|
+
}
|
|
90
|
+
const ok = board.column === expected;
|
|
91
|
+
return row(
|
|
92
|
+
'board-status',
|
|
93
|
+
storyId,
|
|
94
|
+
ok ? 'ok' : 'drift',
|
|
95
|
+
`Status=${board.column} expected=${expected}`,
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function presenceRow(check, storyId, present, evidence) {
|
|
100
|
+
return row(check, storyId, present ? 'drift' : 'ok', evidence);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Pure: one row per check from a Story's probe readings.
|
|
105
|
+
*
|
|
106
|
+
* @param {number} storyId
|
|
107
|
+
* @param {object} r `{ ticket, pr, board, branch, remote, scratch }`
|
|
108
|
+
* @returns {object[]}
|
|
109
|
+
*/
|
|
110
|
+
function evaluateStory(storyId, r) {
|
|
111
|
+
const branchName = getStoryBranch(storyId);
|
|
112
|
+
if (!isPrMerged(r.pr)) {
|
|
113
|
+
const why = r.pr?.error
|
|
114
|
+
? `PR probe failed: ${r.pr.error}`
|
|
115
|
+
: `no merged ${branchName} PR — not landed`;
|
|
116
|
+
return CHECKS.map((c) => row(c, storyId, 'unknown', why));
|
|
117
|
+
}
|
|
118
|
+
const remote = r.remote?.ok
|
|
119
|
+
? presenceRow(
|
|
120
|
+
'remote-branch',
|
|
121
|
+
storyId,
|
|
122
|
+
Boolean(r.remote.sha),
|
|
123
|
+
r.remote.sha
|
|
124
|
+
? `origin/${branchName} at ${r.remote.sha}`
|
|
125
|
+
: `origin/${branchName} absent`,
|
|
126
|
+
)
|
|
127
|
+
: row(
|
|
128
|
+
'remote-branch',
|
|
129
|
+
storyId,
|
|
130
|
+
'unknown',
|
|
131
|
+
`ls-remote failed: ${r.remote?.error}`,
|
|
132
|
+
);
|
|
133
|
+
const scratch = r.scratch?.error
|
|
134
|
+
? row('scratch', storyId, 'unknown', `temp scan failed: ${r.scratch.error}`)
|
|
135
|
+
: presenceRow(
|
|
136
|
+
'scratch',
|
|
137
|
+
storyId,
|
|
138
|
+
r.scratch.paths.length > 0,
|
|
139
|
+
r.scratch.paths.length
|
|
140
|
+
? r.scratch.paths.join(', ')
|
|
141
|
+
: 'no per-Story temp artifacts',
|
|
142
|
+
);
|
|
143
|
+
return [
|
|
144
|
+
storyStateRow(storyId, r),
|
|
145
|
+
boardRow(storyId, r),
|
|
146
|
+
remote,
|
|
147
|
+
presenceRow(
|
|
148
|
+
'local-branch',
|
|
149
|
+
storyId,
|
|
150
|
+
r.branch.local,
|
|
151
|
+
r.branch.local ? `refs/heads/${branchName}` : 'no local ref',
|
|
152
|
+
),
|
|
153
|
+
presenceRow(
|
|
154
|
+
'worktree',
|
|
155
|
+
storyId,
|
|
156
|
+
Boolean(r.branch.worktreePath),
|
|
157
|
+
r.branch.worktreePath ?? 'no worktree',
|
|
158
|
+
),
|
|
159
|
+
scratch,
|
|
160
|
+
];
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async function auditStory(storyId, probes) {
|
|
164
|
+
const pr = await probes.pr(storyId);
|
|
165
|
+
const ticket = await probes.ticket(storyId);
|
|
166
|
+
const readings = {
|
|
167
|
+
ticket,
|
|
168
|
+
pr,
|
|
169
|
+
board: await probes.board(storyId),
|
|
170
|
+
branch: await probes.branch(storyId),
|
|
171
|
+
remote: await probes.remote(storyId),
|
|
172
|
+
scratch: await probes.scratch(storyId),
|
|
173
|
+
};
|
|
174
|
+
return {
|
|
175
|
+
storyId,
|
|
176
|
+
pr: pr?.number ?? null,
|
|
177
|
+
readings,
|
|
178
|
+
checks: evaluateStory(storyId, readings),
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
async function safeRepair(fn, entry) {
|
|
183
|
+
try {
|
|
184
|
+
return (await fn(entry)) ?? { ok: true };
|
|
185
|
+
} catch (err) {
|
|
186
|
+
return { ok: false, reason: String(err?.message ?? err) };
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
async function repairStory(before, { probes, repairs }) {
|
|
191
|
+
const reasons = new Map();
|
|
192
|
+
let current = before;
|
|
193
|
+
for (const check of CHECKS) {
|
|
194
|
+
if (current.checks.find((c) => c.check === check)?.status !== 'drift')
|
|
195
|
+
continue;
|
|
196
|
+
const res = await safeRepair(repairs[check], current);
|
|
197
|
+
if (!res.ok) reasons.set(check, res.reason ?? 'refused');
|
|
198
|
+
if (check === 'story-state')
|
|
199
|
+
current = await auditStory(before.storyId, probes);
|
|
200
|
+
}
|
|
201
|
+
const after = await auditStory(before.storyId, probes);
|
|
202
|
+
return markOutcome(before, after, (check) =>
|
|
203
|
+
reasons.has(check)
|
|
204
|
+
? `repair refused: ${reasons.get(check)}`
|
|
205
|
+
: 'still drifted after repair',
|
|
206
|
+
);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function markOutcome(before, after, reasonFor) {
|
|
210
|
+
const checks = after.checks.map((c) => {
|
|
211
|
+
const was = before.checks.find((b) => b.check === c.check)?.status;
|
|
212
|
+
if (c.status === 'drift' && was === 'drift') {
|
|
213
|
+
return { ...c, evidence: `${c.evidence}; ${reasonFor(c.check)}` };
|
|
214
|
+
}
|
|
215
|
+
return { ...c, repaired: was === 'drift' && c.status === 'ok' };
|
|
216
|
+
});
|
|
217
|
+
return { ...after, checks };
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function summarize(stories) {
|
|
221
|
+
const all = stories.flatMap((s) => s.checks);
|
|
222
|
+
const count = (pred) => all.filter(pred).length;
|
|
223
|
+
return {
|
|
224
|
+
stories: stories.length,
|
|
225
|
+
ok: count((c) => c.status === 'ok'),
|
|
226
|
+
drift: count((c) => c.status === 'drift'),
|
|
227
|
+
unknown: count((c) => c.status === 'unknown'),
|
|
228
|
+
repaired: count((c) => c.repaired),
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Audit each Story; on `execute`, repair drift under one lock and re-audit.
|
|
234
|
+
*
|
|
235
|
+
* @param {{ storyIds: number[], scope: object, probes: object, repairs?: object,
|
|
236
|
+
* execute?: boolean, withLock?: Function }} args
|
|
237
|
+
* @returns {Promise<object>} the `closeout-audit` envelope.
|
|
238
|
+
*/
|
|
239
|
+
export async function runCloseoutAudit({
|
|
240
|
+
storyIds,
|
|
241
|
+
scope,
|
|
242
|
+
probes,
|
|
243
|
+
repairs,
|
|
244
|
+
execute = false,
|
|
245
|
+
withLock,
|
|
246
|
+
}) {
|
|
247
|
+
let stories = [];
|
|
248
|
+
for (const id of storyIds) stories.push(await auditStory(id, probes));
|
|
249
|
+
const drifted = stories.some((s) =>
|
|
250
|
+
s.checks.some((c) => c.status === 'drift'),
|
|
251
|
+
);
|
|
252
|
+
if (execute && drifted) {
|
|
253
|
+
const locked = await withLock(async () => {
|
|
254
|
+
const out = [];
|
|
255
|
+
for (const s of stories)
|
|
256
|
+
out.push(await repairStory(s, { probes, repairs }));
|
|
257
|
+
return out;
|
|
258
|
+
});
|
|
259
|
+
stories = locked.locked
|
|
260
|
+
? locked.value
|
|
261
|
+
: stories.map((s) =>
|
|
262
|
+
markOutcome(
|
|
263
|
+
s,
|
|
264
|
+
s,
|
|
265
|
+
() => `repair skipped: sweep lock ${locked.reason}`,
|
|
266
|
+
),
|
|
267
|
+
);
|
|
268
|
+
}
|
|
269
|
+
const clean = stories.map(({ readings, ...s }) => s);
|
|
270
|
+
return {
|
|
271
|
+
kind: 'closeout-audit',
|
|
272
|
+
scope,
|
|
273
|
+
stories: clean,
|
|
274
|
+
summary: summarize(clean),
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** 0 nothing drifted (or all repaired), 2 drift remains. */
|
|
279
|
+
export function exitCodeFor(envelope) {
|
|
280
|
+
return envelope.summary.drift > 0 ? 2 : 0;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
export function renderAudit(envelope) {
|
|
284
|
+
const lines = [];
|
|
285
|
+
for (const s of envelope.stories) {
|
|
286
|
+
lines.push(`Story #${s.storyId} (PR ${s.pr ? `#${s.pr}` : 'none'})`);
|
|
287
|
+
for (const c of s.checks) {
|
|
288
|
+
const mark = c.repaired ? 'repaired' : c.status;
|
|
289
|
+
lines.push(` ${c.check.padEnd(14)} ${mark.padEnd(8)} ${c.evidence}`);
|
|
290
|
+
if (c.status === 'drift')
|
|
291
|
+
lines.push(` ${''.padEnd(14)} fix: ${c.repair}`);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
const t = envelope.summary;
|
|
295
|
+
lines.push(
|
|
296
|
+
`${t.stories} Story(ies): ${t.drift} drift, ${t.unknown} unknown, ${t.repaired} repaired.`,
|
|
297
|
+
);
|
|
298
|
+
return `${lines.join('\n')}\n`;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Pure scope filter: exact `story-<id>` heads merged at or after the cutoff.
|
|
303
|
+
*
|
|
304
|
+
* @param {Array<{ headRefName?: string, mergedAt?: string }>} rows
|
|
305
|
+
* @param {{ sinceHours: number, nowMs: number }} window
|
|
306
|
+
* @returns {number[]}
|
|
307
|
+
*/
|
|
308
|
+
function selectMergedStoryIds(rows, { sinceHours, nowMs }) {
|
|
309
|
+
const cutoff = nowMs - sinceHours * 3_600_000;
|
|
310
|
+
const ids = new Set();
|
|
311
|
+
for (const r of Array.isArray(rows) ? rows : []) {
|
|
312
|
+
const id = parseStoryBranch(r?.headRefName);
|
|
313
|
+
const merged = Date.parse(r?.mergedAt ?? '');
|
|
314
|
+
if (id !== null && Number.isFinite(merged) && merged >= cutoff) ids.add(id);
|
|
315
|
+
}
|
|
316
|
+
return [...ids];
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
export async function listMergedStoryIds({
|
|
320
|
+
gh = defaultGh,
|
|
321
|
+
baseBranch,
|
|
322
|
+
sinceHours,
|
|
323
|
+
nowMs = Date.now(),
|
|
324
|
+
}) {
|
|
325
|
+
const rows = await gh.pr.list(
|
|
326
|
+
[
|
|
327
|
+
'--state',
|
|
328
|
+
'merged',
|
|
329
|
+
'--base',
|
|
330
|
+
baseBranch,
|
|
331
|
+
'--limit',
|
|
332
|
+
String(MERGED_PR_PAGE),
|
|
333
|
+
],
|
|
334
|
+
['number', 'headRefName', 'mergedAt'],
|
|
335
|
+
);
|
|
336
|
+
return selectMergedStoryIds(rows, { sinceHours, nowMs });
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/** Live probes over the main checkout; every one settles, none throws. */
|
|
340
|
+
export function buildProbes({
|
|
341
|
+
cwd,
|
|
342
|
+
config,
|
|
343
|
+
provider,
|
|
344
|
+
gh = defaultGh,
|
|
345
|
+
gitSpawnFn = defaultGitSpawn,
|
|
346
|
+
purgeFn = purgeStoryTempArtifacts,
|
|
347
|
+
logger,
|
|
348
|
+
}) {
|
|
349
|
+
const branchOf = (id) => getStoryBranch(id);
|
|
350
|
+
return {
|
|
351
|
+
ticket: (id) => probeTicket({ provider, storyId: id }),
|
|
352
|
+
pr: async (id) => {
|
|
353
|
+
const pr = await probePr({ storyBranch: branchOf(id), gh });
|
|
354
|
+
if (!isPrMerged(pr)) return pr;
|
|
355
|
+
const view = await gh.pr.view(pr.number, ['body']).catch(() => null);
|
|
356
|
+
return { ...pr, body: view?.body ?? null };
|
|
357
|
+
},
|
|
358
|
+
board: async (id) => {
|
|
359
|
+
if (typeof provider?.graphql !== 'function')
|
|
360
|
+
return { ok: false, error: 'no GraphQL transport' };
|
|
361
|
+
try {
|
|
362
|
+
const column = await new ColumnSync({
|
|
363
|
+
provider,
|
|
364
|
+
logger,
|
|
365
|
+
config,
|
|
366
|
+
}).readCurrentColumn(id);
|
|
367
|
+
return { ok: true, column };
|
|
368
|
+
} catch (err) {
|
|
369
|
+
return { ok: false, error: String(err?.message ?? err) };
|
|
370
|
+
}
|
|
371
|
+
},
|
|
372
|
+
branch: (id) =>
|
|
373
|
+
probeBranch({ cwd, storyBranch: branchOf(id), config, gitSpawnFn }),
|
|
374
|
+
// ls-remote, not the tracking ref: a stale tracking ref would read as drift forever.
|
|
375
|
+
remote: (id) => {
|
|
376
|
+
const res = gitSpawnFn(
|
|
377
|
+
cwd,
|
|
378
|
+
'ls-remote',
|
|
379
|
+
'--heads',
|
|
380
|
+
'origin',
|
|
381
|
+
`refs/heads/${branchOf(id)}`,
|
|
382
|
+
);
|
|
383
|
+
if (res.status !== 0)
|
|
384
|
+
return {
|
|
385
|
+
ok: false,
|
|
386
|
+
error: (res.stderr || `exit ${res.status}`).trim(),
|
|
387
|
+
};
|
|
388
|
+
return {
|
|
389
|
+
ok: true,
|
|
390
|
+
sha:
|
|
391
|
+
String(res.stdout ?? '')
|
|
392
|
+
.trim()
|
|
393
|
+
.split(/\s+/)[0] || null,
|
|
394
|
+
};
|
|
395
|
+
},
|
|
396
|
+
scratch: async (id) => {
|
|
397
|
+
const res = await purgeFn({ storyId: id, config, dryRun: true, logger });
|
|
398
|
+
if (res.errors?.length) return { error: res.errors[0] };
|
|
399
|
+
return { paths: res.purged.map((p) => p.path) };
|
|
400
|
+
},
|
|
401
|
+
};
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
function runScript({ cwd, spawnFn }, script, storyId) {
|
|
405
|
+
const res = spawnFn(
|
|
406
|
+
process.execPath,
|
|
407
|
+
[path.join(cwd, '.agents', 'scripts', script), '--story', String(storyId)],
|
|
408
|
+
{
|
|
409
|
+
cwd,
|
|
410
|
+
stdio: ['ignore', process.stderr, process.stderr],
|
|
411
|
+
},
|
|
412
|
+
);
|
|
413
|
+
return res.status === 0
|
|
414
|
+
? { ok: true }
|
|
415
|
+
: { ok: false, reason: `${script} exited ${res.status}` };
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
function refusalFromSweep(result, branch) {
|
|
419
|
+
if (result?.reaped?.includes(branch)) return { ok: true };
|
|
420
|
+
const prot = result?.protected?.find((p) => p.branch === branch);
|
|
421
|
+
if (prot) return { ok: false, reason: prot.reason };
|
|
422
|
+
if (result?.contentMerged?.some((p) => p.branch === branch))
|
|
423
|
+
return { ok: false, reason: 'content-merged, left for /clean-git' };
|
|
424
|
+
const fail = result?.failures?.find((f) => f.branch === branch);
|
|
425
|
+
return {
|
|
426
|
+
ok: false,
|
|
427
|
+
reason:
|
|
428
|
+
fail?.stderr ||
|
|
429
|
+
result?.error ||
|
|
430
|
+
result?.reason ||
|
|
431
|
+
'not a merged sweep candidate',
|
|
432
|
+
};
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/** Each check's existing repair seam, wrapped to `{ ok, reason? }`. */
|
|
436
|
+
export function buildRepairs({
|
|
437
|
+
cwd,
|
|
438
|
+
config,
|
|
439
|
+
provider,
|
|
440
|
+
logger,
|
|
441
|
+
spawnFn = spawnChild,
|
|
442
|
+
deleteRemoteFn = deleteBranchRemote,
|
|
443
|
+
sweepBranchesFn = sweepMergedBranches,
|
|
444
|
+
sweepWorktreesFn = sweepStaleStoryWorktrees,
|
|
445
|
+
purgeFn = purgeStoryTempArtifacts,
|
|
446
|
+
}) {
|
|
447
|
+
const ctx = { cwd, spawnFn };
|
|
448
|
+
return {
|
|
449
|
+
'story-state': (e) =>
|
|
450
|
+
runScript(ctx, 'single-story-confirm-merge.js', e.storyId),
|
|
451
|
+
'board-status': (e) => runScript(ctx, 'resync-status-column.js', e.storyId),
|
|
452
|
+
'remote-branch': (e) => {
|
|
453
|
+
const { sha } = e.readings.remote;
|
|
454
|
+
const merged = e.readings.pr.headSha;
|
|
455
|
+
if (merged && sha !== merged)
|
|
456
|
+
return {
|
|
457
|
+
ok: false,
|
|
458
|
+
reason: `origin head ${sha} is not the merged head ${merged}`,
|
|
459
|
+
};
|
|
460
|
+
const res = deleteRemoteFn(getStoryBranch(e.storyId), { cwd });
|
|
461
|
+
return res.deleted
|
|
462
|
+
? { ok: true }
|
|
463
|
+
: { ok: false, reason: res.stderr || res.reason };
|
|
464
|
+
},
|
|
465
|
+
'local-branch': async (e) => {
|
|
466
|
+
const branch = getStoryBranch(e.storyId);
|
|
467
|
+
const result = await sweepBranchesFn({
|
|
468
|
+
cwd,
|
|
469
|
+
baseBranch: config?.project?.baseBranch ?? 'main',
|
|
470
|
+
include: [branch],
|
|
471
|
+
logger,
|
|
472
|
+
protectionCtx: buildProtectionCtx({ cwd, provider }),
|
|
473
|
+
});
|
|
474
|
+
return refusalFromSweep(result, branch);
|
|
475
|
+
},
|
|
476
|
+
worktree: async (e) => {
|
|
477
|
+
const result = await sweepWorktreesFn({
|
|
478
|
+
provider,
|
|
479
|
+
repoRoot: cwd,
|
|
480
|
+
logger,
|
|
481
|
+
});
|
|
482
|
+
const skip = result?.skipped?.find((s) => s.storyId === e.storyId);
|
|
483
|
+
return skip ? { ok: false, reason: skip.reason } : { ok: true };
|
|
484
|
+
},
|
|
485
|
+
scratch: async (e) => {
|
|
486
|
+
const res = await purgeFn({ storyId: e.storyId, config, logger });
|
|
487
|
+
return res.errors?.length
|
|
488
|
+
? { ok: false, reason: res.errors[0] }
|
|
489
|
+
: { ok: true };
|
|
490
|
+
},
|
|
491
|
+
};
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/** The sweep lock boot-sweep and init share, held across every repair. */
|
|
495
|
+
export function buildWithLock({ cwd, config, acquireFn = acquireSweepLock }) {
|
|
496
|
+
return async (fn) => {
|
|
497
|
+
const lock = acquireFn({
|
|
498
|
+
lockPath: resolveSweepLockPath({
|
|
499
|
+
cwd,
|
|
500
|
+
tempRoot: config?.project?.paths?.tempRoot ?? 'temp',
|
|
501
|
+
}),
|
|
502
|
+
timeoutMs: config?.delivery?.worktreeIsolation?.sweepLockMs ?? 60_000,
|
|
503
|
+
});
|
|
504
|
+
if (!lock.acquired) return { locked: false, reason: lock.reason };
|
|
505
|
+
try {
|
|
506
|
+
return { locked: true, value: await fn() };
|
|
507
|
+
} finally {
|
|
508
|
+
lock.release();
|
|
509
|
+
}
|
|
510
|
+
};
|
|
511
|
+
}
|
|
@@ -59,7 +59,7 @@ async function readMergeQueueStateRest({ prRef, prNodeId, facade, timeoutMs }) {
|
|
|
59
59
|
* @param {{ stdout?: string }|string|undefined} result
|
|
60
60
|
* @returns {object|null}
|
|
61
61
|
*/
|
|
62
|
-
function parseGraphqlData(result) {
|
|
62
|
+
export function parseGraphqlData(result) {
|
|
63
63
|
const text = typeof result === 'string' ? result : result?.stdout;
|
|
64
64
|
const parsed = JSON.parse(String(text ?? ''));
|
|
65
65
|
if (Array.isArray(parsed?.errors) && parsed.errors.length > 0) {
|
|
@@ -108,9 +108,19 @@ async function readRequiredNamesRest({ prNumber, gh, timeoutMs }) {
|
|
|
108
108
|
const view = await gh.pr.view(String(prNumber), ['baseRefName']);
|
|
109
109
|
const base = view?.baseRefName;
|
|
110
110
|
if (!base) throw new Error('PR base branch unreadable');
|
|
111
|
+
return readBaseRequiredNames({ api: gh.api, base, timeoutMs });
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* The base branch's required check names, over REST on either transport.
|
|
116
|
+
*
|
|
117
|
+
* @param {{ api: Function, base: string, timeoutMs?: number }} args
|
|
118
|
+
* @returns {Promise<Set<string>>}
|
|
119
|
+
*/
|
|
120
|
+
export async function readBaseRequiredNames({ api, base, timeoutMs }) {
|
|
111
121
|
const [rules, contexts] = await Promise.all([
|
|
112
|
-
readBranchRules({ api
|
|
113
|
-
readProtectionContexts({ api
|
|
122
|
+
readBranchRules({ api, base, timeoutMs }),
|
|
123
|
+
readProtectionContexts({ api, base, timeoutMs }),
|
|
114
124
|
]);
|
|
115
125
|
const names = new Set(contexts.filter(Boolean));
|
|
116
126
|
for (const rule of rules) {
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* orchestrate-inventory.js — read-only: every open PR in exactly one state,
|
|
5
|
+
* plus overlaps, inherited failures, landed Stories and runner backlog.
|
|
6
|
+
* With `--run-id` it appends the sweep to the run ledger and fills `changes[]`.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import { parseArgs } from 'node:util';
|
|
11
|
+
|
|
12
|
+
import { runAsCli } from './lib/cli-utils.js';
|
|
13
|
+
import { PROJECT_ROOT, resolveConfig } from './lib/config-resolver.js';
|
|
14
|
+
import { renderInventory, runInventory } from './lib/orchestrate/inventory.js';
|
|
15
|
+
import { ledgerPath } from './lib/orchestrate/ledger.js';
|
|
16
|
+
|
|
17
|
+
const USAGE = {
|
|
18
|
+
invocation:
|
|
19
|
+
'node .agents/scripts/orchestrate-inventory.js [--run-id <id>] [--json] [--cwd <main-repo>]',
|
|
20
|
+
summary:
|
|
21
|
+
'Classify every open PR for /mandrel-orchestrate. Reads GitHub and git only; never a job log.',
|
|
22
|
+
flags: [
|
|
23
|
+
[
|
|
24
|
+
'--run-id <id>',
|
|
25
|
+
'Append this sweep to the run ledger and report the PRs whose state changed.',
|
|
26
|
+
],
|
|
27
|
+
['--json', 'Print the orchestrate-inventory envelope as JSON.'],
|
|
28
|
+
['--cwd <path>', 'Main-repo checkout (default: project root).'],
|
|
29
|
+
],
|
|
30
|
+
notes: [
|
|
31
|
+
'Over repo-scoped REST the merge queue is unreadable: `merge-queue` is listed in degraded[].',
|
|
32
|
+
],
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
export function parseInventoryArgv(argv) {
|
|
36
|
+
const { values } = parseArgs({
|
|
37
|
+
args: argv,
|
|
38
|
+
options: {
|
|
39
|
+
'run-id': { type: 'string' },
|
|
40
|
+
json: { type: 'boolean', default: false },
|
|
41
|
+
cwd: { type: 'string' },
|
|
42
|
+
},
|
|
43
|
+
strict: true,
|
|
44
|
+
});
|
|
45
|
+
return {
|
|
46
|
+
runId: values['run-id'] ?? null,
|
|
47
|
+
json: values.json,
|
|
48
|
+
cwd: path.resolve(values.cwd ?? PROJECT_ROOT),
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/* node:coverage ignore next -- CLI wiring over the tested lib */
|
|
53
|
+
async function main() {
|
|
54
|
+
const args = parseInventoryArgv(process.argv.slice(2));
|
|
55
|
+
const config = resolveConfig({ cwd: args.cwd });
|
|
56
|
+
const envelope = await runInventory({
|
|
57
|
+
config,
|
|
58
|
+
cwd: args.cwd,
|
|
59
|
+
runId: args.runId,
|
|
60
|
+
ledgerFile: args.runId ? ledgerPath(args.runId, config) : null,
|
|
61
|
+
});
|
|
62
|
+
process.stdout.write(
|
|
63
|
+
args.json ? `${JSON.stringify(envelope)}\n` : renderInventory(envelope),
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
runAsCli(import.meta.url, main, {
|
|
68
|
+
source: 'orchestrate-inventory',
|
|
69
|
+
usage: USAGE,
|
|
70
|
+
});
|