mandrel 2.114.0 → 2.116.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 (44) hide show
  1. package/.agents/docs/agentrc-reference.json +1 -0
  2. package/.agents/docs/configuration.md +18 -4
  3. package/.agents/docs/workflows.md +2 -1
  4. package/.agents/schemas/agentrc.schema.json +54 -1
  5. package/.agents/scripts/acceptance-eval.js +2 -2
  6. package/.agents/scripts/ceremony-derive.js +15 -2
  7. package/.agents/scripts/closeout-audit.js +132 -0
  8. package/.agents/scripts/lib/baselines/crap-preview-scan.js +15 -8
  9. package/.agents/scripts/lib/baselines/crap-preview-touched.js +140 -0
  10. package/.agents/scripts/lib/baselines/crap-prune.js +86 -0
  11. package/.agents/scripts/lib/baselines/kinds/crap.js +12 -4
  12. package/.agents/scripts/lib/baselines/seat-missing.js +1 -1
  13. package/.agents/scripts/lib/config/gates/coverage.schema.js +1 -1
  14. package/.agents/scripts/lib/config/gates/crap.schema.js +7 -0
  15. package/.agents/scripts/lib/config/quality.js +3 -0
  16. package/.agents/scripts/lib/config/temp-paths.js +12 -0
  17. package/.agents/scripts/lib/config-settings-schema-delivery.js +34 -0
  18. package/.agents/scripts/lib/coverage-capture-delta.js +26 -3
  19. package/.agents/scripts/lib/coverage-capture-own-fix.js +35 -19
  20. package/.agents/scripts/lib/coverage-capture.js +62 -14
  21. package/.agents/scripts/lib/crap-engine.js +3 -5
  22. package/.agents/scripts/lib/crap-utils.js +12 -2
  23. package/.agents/scripts/lib/generated/agentrc-validator.js +2 -2
  24. package/.agents/scripts/lib/git-branch-lifecycle.js +2 -1
  25. package/.agents/scripts/lib/observability/source-classifier.js +3 -0
  26. package/.agents/scripts/lib/orchestrate/classify.js +238 -0
  27. package/.agents/scripts/lib/orchestrate/conflicts.js +119 -0
  28. package/.agents/scripts/lib/orchestrate/inherited-failure.js +66 -0
  29. package/.agents/scripts/lib/orchestrate/inventory.js +388 -0
  30. package/.agents/scripts/lib/orchestrate/ledger.js +223 -0
  31. package/.agents/scripts/lib/orchestration/closeout-audit.js +511 -0
  32. package/.agents/scripts/lib/orchestration/handoff-gates.js +25 -8
  33. package/.agents/scripts/lib/orchestration/merge-queue.js +1 -1
  34. package/.agents/scripts/lib/orchestration/required-checks.js +12 -2
  35. package/.agents/scripts/lib/orchestration/story-handoff.js +131 -41
  36. package/.agents/scripts/orchestrate-inventory.js +70 -0
  37. package/.agents/scripts/orchestrate-ledger.js +141 -0
  38. package/.agents/scripts/single-story-init.js +43 -5
  39. package/.agents/scripts/story-handoff.js +6 -2
  40. package/.agents/workflows/helpers/deliver-digest.md +3 -3
  41. package/.agents/workflows/helpers/deliver-reference.md +31 -4
  42. package/.agents/workflows/mandrel-orchestrate.md +140 -0
  43. package/docs/CHANGELOG.md +21 -0
  44. package/package.json +1 -1
@@ -0,0 +1,388 @@
1
+ /**
2
+ * inventory.js — the bounded GitHub and git reads behind
3
+ * `orchestrate-inventory.js`, normalised into one snapshot for `classify.js`.
4
+ * One paginated PR query, one workflow-run listing, the base's latest checks;
5
+ * never a job log. Over repo-scoped REST the merge queue is unreadable, so
6
+ * the snapshot says so instead of guessing.
7
+ */
8
+
9
+ import { spawnCapture } from '../child-exec.js';
10
+ import { gh as defaultGh, prTransportOf } from '../gh-exec.js';
11
+ import { parseApiJson } from '../gh-pr-rest.js';
12
+ import { gitSpawn, parseStoryBranch } from '../git-utils.js';
13
+ import {
14
+ isRunInFlight,
15
+ readRunName,
16
+ redConclusionOf,
17
+ } from '../orchestration/merge-poll.js';
18
+ import { parseGraphqlData } from '../orchestration/merge-queue.js';
19
+ import { readBaseRequiredNames } from '../orchestration/required-checks.js';
20
+ import { buildEnvelope } from './classify.js';
21
+ import { resolveConflict } from './conflicts.js';
22
+ import {
23
+ landedSince,
24
+ lastSweep,
25
+ readLedger,
26
+ recordSweep,
27
+ sweepChanges,
28
+ } from './ledger.js';
29
+
30
+ const REPO = 'repos/{owner}/{repo}';
31
+ const PAGE = 25;
32
+ // shortcut: stops at 4 pages (100 open PRs); page further if a fleet outgrows it.
33
+ const MAX_PAGES = 4;
34
+ const MERGED_LIMIT = 30;
35
+
36
+ const CHECK_FIELDS =
37
+ '__typename ... on CheckRun { name status conclusion startedAt completedAt annotations(first: 1) { nodes { message } } } ' +
38
+ '... on StatusContext { context state createdAt }';
39
+
40
+ const INVENTORY_QUERY =
41
+ 'query($owner: String!, $repo: String!, $base: String!, $after: String) { repository(owner: $owner, name: $repo) { ' +
42
+ `ref(qualifiedName: $base) { target { ... on Commit { oid statusCheckRollup { contexts(first: 60) { nodes { ${CHECK_FIELDS} } } } } } } ` +
43
+ `pullRequests(states: OPEN, first: ${PAGE}, after: $after) { pageInfo { hasNextPage endCursor } nodes { ` +
44
+ 'number isDraft headRefName headRefOid mergeable isInMergeQueue author { login } autoMergeRequest { enabledAt } ' +
45
+ 'labels(first: 10) { nodes { name } } files(first: 100) { totalCount nodes { path } } ' +
46
+ 'closingIssuesReferences(first: 3) { nodes { number assignees(first: 5) { nodes { login } } } } ' +
47
+ 'timelineItems(last: 1, itemTypes: [ADDED_TO_MERGE_QUEUE_EVENT, REMOVED_FROM_MERGE_QUEUE_EVENT]) { nodes { __typename ' +
48
+ '... on AddedToMergeQueueEvent { createdAt } ... on RemovedFromMergeQueueEvent { createdAt reason beforeCommit { oid } } } } ' +
49
+ `commits(last: 1) { nodes { commit { committedDate statusCheckRollup { contexts(first: 60) { nodes { ${CHECK_FIELDS} } } } } } } ` +
50
+ '} } } }';
51
+
52
+ const latest = (...times) => {
53
+ const ms = times.map((t) => Date.parse(t ?? '')).filter(Number.isFinite);
54
+ return ms.length ? new Date(Math.max(...ms)).toISOString() : null;
55
+ };
56
+
57
+ /** A rollup node (GraphQL, or REST mapped to the same shape) as a terse check. */
58
+ function normalizeCheck(node) {
59
+ const status = String(node?.status ?? '').toUpperCase();
60
+ let phase = 'done';
61
+ if (isRunInFlight(node))
62
+ phase = status === 'IN_PROGRESS' ? 'running' : 'queued';
63
+ return {
64
+ name: readRunName(node) ?? '',
65
+ phase,
66
+ red: Boolean(redConclusionOf(node)),
67
+ note: node?.annotations?.nodes?.[0]?.message ?? node?.output?.title ?? null,
68
+ at: latest(node?.startedAt, node?.completedAt, node?.createdAt),
69
+ };
70
+ }
71
+
72
+ const nodesOf = (conn) => (Array.isArray(conn?.nodes) ? conn.nodes : []);
73
+
74
+ function queueEventOf(node) {
75
+ if (!node) return null;
76
+ const removed = node.__typename === 'RemovedFromMergeQueueEvent';
77
+ return {
78
+ type: removed ? 'removed' : 'added',
79
+ at: node.createdAt ?? null,
80
+ reason: removed ? (node.reason ?? null) : null,
81
+ headSha: removed ? (node.beforeCommit?.oid ?? null) : null,
82
+ };
83
+ }
84
+
85
+ function assigneesFor(storyId, issues) {
86
+ const issue = issues.find((i) => i.number === storyId);
87
+ return nodesOf(issue?.assignees).map((a) => a.login);
88
+ }
89
+
90
+ /** A GraphQL PR node as a snapshot row. */
91
+ function normalizeGraphqlPr(node) {
92
+ const commit = nodesOf(node.commits)[0]?.commit ?? {};
93
+ const checks = nodesOf(commit.statusCheckRollup?.contexts).map(
94
+ normalizeCheck,
95
+ );
96
+ const storyId = parseStoryBranch(node.headRefName);
97
+ return {
98
+ number: node.number,
99
+ storyId,
100
+ author: node.author?.login ?? null,
101
+ assignees: storyId
102
+ ? assigneesFor(storyId, nodesOf(node.closingIssuesReferences))
103
+ : [],
104
+ headSha: node.headRefOid ?? null,
105
+ labels: nodesOf(node.labels).map((l) => l.name),
106
+ draft: node.isDraft === true,
107
+ conflicting: node.mergeable === 'CONFLICTING',
108
+ autoMerge: Boolean(node.autoMergeRequest),
109
+ inQueue: node.isInMergeQueue === true,
110
+ queueEvent: queueEventOf(nodesOf(node.timelineItems).at(-1)),
111
+ checks,
112
+ paths: nodesOf(node.files).map((f) => f.path),
113
+ pathCount: node.files?.totalCount ?? 0,
114
+ pushedAt: commit.committedDate ?? null,
115
+ activityAt: latest(commit.committedDate, ...checks.map((c) => c.at)),
116
+ };
117
+ }
118
+
119
+ async function readGraphql({ gh, owner, repo, base }) {
120
+ const prs = [];
121
+ let baseCommit = null;
122
+ let after = null;
123
+ for (let page = 0; page < MAX_PAGES; page += 1) {
124
+ const data = parseGraphqlData(
125
+ await gh.api({
126
+ method: 'POST',
127
+ endpoint: 'graphql',
128
+ body: {
129
+ query: INVENTORY_QUERY,
130
+ variables: { owner, repo, base, after },
131
+ },
132
+ }),
133
+ );
134
+ baseCommit ??= data?.repository?.ref?.target ?? null;
135
+ const conn = data?.repository?.pullRequests;
136
+ prs.push(...nodesOf(conn).map(normalizeGraphqlPr));
137
+ if (!conn?.pageInfo?.hasNextPage) break;
138
+ after = conn.pageInfo.endCursor;
139
+ }
140
+ return {
141
+ base: {
142
+ branch: base,
143
+ sha: baseCommit?.oid ?? null,
144
+ checks: nodesOf(baseCommit?.statusCheckRollup?.contexts).map(
145
+ normalizeCheck,
146
+ ),
147
+ },
148
+ prs,
149
+ };
150
+ }
151
+
152
+ const restGet = async (gh, endpoint) =>
153
+ parseApiJson(await gh.api({ method: 'GET', endpoint }));
154
+
155
+ /** A REST check run in the rollup-node shape `normalizeCheck` reads. */
156
+ const restCheck = (run) => ({
157
+ name: run?.name,
158
+ status: String(run?.status ?? '').toUpperCase(),
159
+ conclusion: String(run?.conclusion ?? '').toUpperCase(),
160
+ startedAt: run?.started_at,
161
+ completedAt: run?.completed_at,
162
+ output: run?.output,
163
+ });
164
+
165
+ async function readRestPr(gh, pull) {
166
+ const storyId = parseStoryBranch(pull.head?.ref);
167
+ const [detail, runs, files, issue] = await Promise.all([
168
+ restGet(gh, `${REPO}/pulls/${pull.number}`),
169
+ restGet(gh, `${REPO}/commits/${pull.head?.sha}/check-runs?per_page=100`),
170
+ restGet(gh, `${REPO}/pulls/${pull.number}/files?per_page=100`),
171
+ storyId ? restGet(gh, `${REPO}/issues/${storyId}`) : null,
172
+ ]);
173
+ const checks = (runs?.check_runs ?? []).map(restCheck).map(normalizeCheck);
174
+ const paths = (Array.isArray(files) ? files : []).map((f) => f.filename);
175
+ return {
176
+ number: pull.number,
177
+ storyId,
178
+ author: pull.user?.login ?? null,
179
+ assignees: (issue?.assignees ?? []).map((a) => a.login),
180
+ headSha: pull.head?.sha ?? null,
181
+ labels: (pull.labels ?? []).map((l) => l.name),
182
+ draft: pull.draft === true,
183
+ conflicting: detail?.mergeable_state === 'dirty',
184
+ autoMerge: Boolean(pull.auto_merge),
185
+ inQueue: null,
186
+ queueEvent: null,
187
+ checks,
188
+ paths,
189
+ pathCount: detail?.changed_files ?? paths.length,
190
+ pushedAt: pull.updated_at ?? null,
191
+ activityAt: latest(pull.updated_at, ...checks.map((c) => c.at)),
192
+ };
193
+ }
194
+
195
+ async function readRest({ gh, base }) {
196
+ const [pulls, baseRuns] = await Promise.all([
197
+ restGet(gh, `${REPO}/pulls?state=open&per_page=100`),
198
+ restGet(
199
+ gh,
200
+ `${REPO}/commits/${encodeURIComponent(base)}/check-runs?per_page=100`,
201
+ ),
202
+ ]);
203
+ const prs = [];
204
+ for (const pull of Array.isArray(pulls) ? pulls : [])
205
+ prs.push(await readRestPr(gh, pull));
206
+ const runs = baseRuns?.check_runs ?? [];
207
+ return {
208
+ base: {
209
+ branch: base,
210
+ sha: runs[0]?.head_sha ?? null,
211
+ checks: runs.map(restCheck).map(normalizeCheck),
212
+ },
213
+ prs,
214
+ };
215
+ }
216
+
217
+ const QUEUED_RUN = new Set(['queued', 'waiting', 'pending', 'requested']);
218
+
219
+ async function readRunners(gh, now) {
220
+ const body = await restGet(gh, `${REPO}/actions/runs?per_page=100`);
221
+ const runs = body?.workflow_runs ?? [];
222
+ const queued = runs.filter((r) => QUEUED_RUN.has(r.status));
223
+ const oldest = Math.min(
224
+ ...queued.map((r) => Date.parse(r.created_at)).filter(Number.isFinite),
225
+ );
226
+ return {
227
+ queued: queued.length,
228
+ inProgress: runs.filter((r) => r.status === 'in_progress').length,
229
+ oldestWaitMin: Number.isFinite(oldest)
230
+ ? Math.round((now - oldest) / 60_000)
231
+ : null,
232
+ };
233
+ }
234
+
235
+ async function readMerged(gh, base, since) {
236
+ const rows = await gh.pr.list(
237
+ ['--state', 'merged', '--base', base, '--limit', String(MERGED_LIMIT)],
238
+ ['number', 'headRefName', 'mergedAt'],
239
+ );
240
+ return (Array.isArray(rows) ? rows : [])
241
+ .filter((r) => Date.parse(r.mergedAt ?? '') > Date.parse(since))
242
+ .map((r) => ({
243
+ number: r.number,
244
+ storyId: parseStoryBranch(r.headRefName),
245
+ }));
246
+ }
247
+
248
+ /** A failed optional read degrades to `fallback` and names itself. */
249
+ async function settle(degraded, name, read, fallback) {
250
+ try {
251
+ return await read();
252
+ } catch {
253
+ degraded.push(name);
254
+ return fallback;
255
+ }
256
+ }
257
+
258
+ /**
259
+ * Every GitHub read, normalised. `since` (an ISO time) asks for the PRs
260
+ * merged after it; null skips that read.
261
+ */
262
+ async function readSnapshot({ gh, owner, repo, base, since = null, now }) {
263
+ const degraded = [];
264
+ const rest = (await prTransportOf(gh)) === 'rest';
265
+ if (rest) degraded.push('merge-queue');
266
+ const core = rest
267
+ ? await readRest({ gh, base })
268
+ : await readGraphql({ gh, owner, repo, base });
269
+ const required = await settle(
270
+ degraded,
271
+ 'required-checks',
272
+ () => readBaseRequiredNames({ api: gh.api, base }),
273
+ null,
274
+ );
275
+ return {
276
+ ...core,
277
+ required: required?.size ? [...required] : null,
278
+ queueReadable: !rest,
279
+ runners: await settle(
280
+ degraded,
281
+ 'runners',
282
+ () => readRunners(gh, now),
283
+ null,
284
+ ),
285
+ merged: since
286
+ ? await settle(degraded, 'landed', () => readMerged(gh, base, since), [])
287
+ : [],
288
+ degraded,
289
+ };
290
+ }
291
+
292
+ /** `delivery.orchestrate`, malformed commands dropped. */
293
+ function orchestrateConfig(config) {
294
+ const block = config?.delivery?.orchestrate ?? {};
295
+ const command = (c) =>
296
+ typeof c?.cmd === 'string' && c.cmd
297
+ ? { cmd: c.cmd, args: c.args ?? [] }
298
+ : null;
299
+ const veto = command(block.releaseVeto);
300
+ return {
301
+ requeueCommand: command(block.requeueCommand),
302
+ releaseVeto:
303
+ veto && block.releaseVeto.prLabel
304
+ ? { ...veto, prLabel: block.releaseVeto.prLabel }
305
+ : null,
306
+ };
307
+ }
308
+
309
+ /** The veto holds when its command exits non-zero (or cannot run). */
310
+ const runVetoCommand = ({ cmd, args }, cwd) =>
311
+ spawnCapture(cmd, args, { cwd }).status !== 0;
312
+
313
+ /**
314
+ * One sweep: read, resolve conflicts and the veto, classify, and with a
315
+ * run id append the sweep and fill `changes[]`.
316
+ */
317
+ export async function runInventory({
318
+ config,
319
+ cwd,
320
+ runId = null,
321
+ ledgerFile = null,
322
+ gh = defaultGh,
323
+ now = Date.now(),
324
+ spawn = gitSpawn,
325
+ runVeto = runVetoCommand,
326
+ }) {
327
+ const base = config?.project?.baseBranch ?? 'main';
328
+ const records = ledgerFile ? readLedger(ledgerFile) : [];
329
+ const since = runId
330
+ ? (landedSince(records) ?? new Date(now).toISOString())
331
+ : null;
332
+ const snapshot = await readSnapshot({
333
+ gh,
334
+ owner: config?.github?.owner,
335
+ repo: config?.github?.repo,
336
+ base,
337
+ since,
338
+ now,
339
+ });
340
+ for (const pr of snapshot.prs) {
341
+ if (pr.conflicting)
342
+ pr.conflict = resolveConflict({
343
+ cwd,
344
+ base,
345
+ number: pr.number,
346
+ headSha: pr.headSha,
347
+ spawn,
348
+ });
349
+ }
350
+ const { requeueCommand, releaseVeto } = orchestrateConfig(config);
351
+ const vetoNeeded =
352
+ releaseVeto &&
353
+ snapshot.prs.some((pr) => pr.labels.includes(releaseVeto.prLabel));
354
+ const envelope = buildEnvelope(snapshot, {
355
+ now,
356
+ requeueCommand,
357
+ vetoLabel: releaseVeto?.prLabel ?? null,
358
+ vetoHeld: vetoNeeded ? runVeto(releaseVeto, cwd) : false,
359
+ });
360
+ if (ledgerFile) {
361
+ const states = Object.fromEntries(
362
+ envelope.prs.map((pr) => [pr.number, pr.state]),
363
+ );
364
+ envelope.changes = sweepChanges(lastSweep(records)?.states ?? null, states);
365
+ recordSweep({ file: ledgerFile, states, merged: snapshot.merged, now });
366
+ }
367
+ return envelope;
368
+ }
369
+
370
+ /** One line per PR, for an operator reading the terminal. */
371
+ export function renderInventory(envelope) {
372
+ const lines = [
373
+ `base ${envelope.base.branch}@${envelope.base.sha ?? '?'}${envelope.base.red.length ? ` red: ${envelope.base.red.join('; ')}` : ''}`,
374
+ ];
375
+ for (const pr of envelope.prs) {
376
+ const owner = pr.storyId ? `Story #${pr.storyId}` : `@${pr.author ?? '?'}`;
377
+ lines.push(
378
+ `#${pr.number} ${pr.state} ${owner}${pr.red ? ` — ${pr.red.join('; ')}` : ''}`,
379
+ );
380
+ }
381
+ for (const c of envelope.changes)
382
+ lines.push(
383
+ `changed #${c.number}: ${c.from ?? '(new)'} -> ${c.to ?? '(gone)'}`,
384
+ );
385
+ if (envelope.degraded.length)
386
+ lines.push(`degraded: ${envelope.degraded.join(', ')}`);
387
+ return `${lines.join('\n')}\n`;
388
+ }
@@ -0,0 +1,223 @@
1
+ /**
2
+ * ledger.js — the append-only record of one `/mandrel-orchestrate` run:
3
+ * the operator's authority, every sweep's states, and every action taken.
4
+ * Authority is written only by `recordAuthority`, never from GitHub content.
5
+ */
6
+
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+
10
+ import { orchestrateRunDir } from '../config/temp-paths.js';
11
+
12
+ /** The closed action set and the default the operator is offered for each. */
13
+ export const ACTION_DEFAULTS = Object.freeze({
14
+ 'message-session': 'yes',
15
+ 'fix-base': 'yes',
16
+ requeue: 'ask',
17
+ 'arm-auto-merge': 'ask',
18
+ 'push-to-branch': 'no',
19
+ 'spawn-session': 'ask',
20
+ 'release-dispatch': 'no',
21
+ 'archive-and-reap': 'ask',
22
+ });
23
+
24
+ /** Recorded without a grant: putting an item to the operator, filing a follow-up. */
25
+ const ALWAYS_ALLOWED = new Set(['raise', 'follow-up']);
26
+
27
+ export function ledgerPath(runId, config) {
28
+ return path.join(orchestrateRunDir(runId, config), 'ledger.ndjson');
29
+ }
30
+
31
+ /** Every parseable record, oldest first; a missing ledger is empty. */
32
+ export function readLedger(file) {
33
+ if (!fs.existsSync(file)) return [];
34
+ const records = [];
35
+ for (const line of fs.readFileSync(file, 'utf8').split('\n')) {
36
+ if (!line.trim()) continue;
37
+ try {
38
+ records.push(JSON.parse(line));
39
+ } catch {
40
+ // A torn trailing line from an interrupted append is skipped.
41
+ }
42
+ }
43
+ return records;
44
+ }
45
+
46
+ function append(file, record) {
47
+ fs.mkdirSync(path.dirname(file), { recursive: true });
48
+ fs.appendFileSync(file, `${JSON.stringify(record)}\n`);
49
+ }
50
+
51
+ const authorityOf = (records) =>
52
+ records.find((r) => r.kind === 'authority') ?? null;
53
+
54
+ export const lastSweep = (records) =>
55
+ records.findLast((r) => r.kind === 'sweep') ?? null;
56
+
57
+ /**
58
+ * @returns {{ ok: boolean, reason?: string, record?: object }}
59
+ */
60
+ export function recordAuthority({ file, grants, now = Date.now() }) {
61
+ const unknown = grants.filter((g) => !Object.hasOwn(ACTION_DEFAULTS, g));
62
+ if (unknown.length > 0)
63
+ return { ok: false, reason: `unknown-action: ${unknown.join(', ')}` };
64
+ if (authorityOf(readLedger(file)))
65
+ return { ok: false, reason: 'authority-already-recorded' };
66
+ const record = {
67
+ kind: 'authority',
68
+ at: new Date(now).toISOString(),
69
+ grants: [...new Set(grants)],
70
+ };
71
+ append(file, record);
72
+ return { ok: true, record };
73
+ }
74
+
75
+ function refusal(records, { action, text }) {
76
+ if (typeof text !== 'string' || !text.trim() || /[\r\n]/.test(text))
77
+ return 'text-must-be-one-line';
78
+ const authority = authorityOf(records);
79
+ if (!authority) return 'no-authority';
80
+ if (ALWAYS_ALLOWED.has(action)) return null;
81
+ if (!Object.hasOwn(ACTION_DEFAULTS, action))
82
+ return `unknown-action: ${action}`;
83
+ if (!authority.grants.includes(action)) return `not-granted: ${action}`;
84
+ return null;
85
+ }
86
+
87
+ /**
88
+ * Record an action before it is taken. A refused action writes nothing.
89
+ * A second `raise` for the same PR and state is refused: each case reaches
90
+ * the operator once.
91
+ *
92
+ * @returns {{ ok: boolean, reason?: string, record?: object }}
93
+ */
94
+ export function recordAction({
95
+ file,
96
+ action,
97
+ pr = null,
98
+ story = null,
99
+ text,
100
+ now = Date.now(),
101
+ }) {
102
+ const records = readLedger(file);
103
+ const reason = refusal(records, { action, text });
104
+ if (reason) return { ok: false, reason };
105
+ const state = pr == null ? null : (lastSweep(records)?.states?.[pr] ?? null);
106
+ if (action === 'raise') {
107
+ const twice = records.some(
108
+ (r) =>
109
+ r.kind === 'action' &&
110
+ r.action === 'raise' &&
111
+ r.pr === pr &&
112
+ r.story === story &&
113
+ r.state === state,
114
+ );
115
+ if (twice) return { ok: false, reason: 'already-raised' };
116
+ }
117
+ const record = {
118
+ kind: 'action',
119
+ at: new Date(now).toISOString(),
120
+ action,
121
+ pr,
122
+ story,
123
+ state,
124
+ text: text.trim(),
125
+ };
126
+ append(file, record);
127
+ return { ok: true, record };
128
+ }
129
+
130
+ /**
131
+ * PRs whose state differs from the previous sweep; a new PR comes `from:
132
+ * null`, a gone one goes `to: null`.
133
+ *
134
+ * @param {Record<string, string>|null} before
135
+ * @param {Record<string, string>} after
136
+ */
137
+ export function sweepChanges(before, after) {
138
+ const prior = before ?? {};
139
+ const numbers = new Set([...Object.keys(prior), ...Object.keys(after)]);
140
+ return [...numbers]
141
+ .filter((n) => prior[n] !== after[n])
142
+ .map((n) => ({
143
+ number: Number(n),
144
+ from: prior[n] ?? null,
145
+ to: after[n] ?? null,
146
+ }))
147
+ .sort((a, b) => a.number - b.number);
148
+ }
149
+
150
+ /** Merges are counted from here: the previous sweep, else the authority. */
151
+ export function landedSince(records) {
152
+ return lastSweep(records)?.at ?? authorityOf(records)?.at ?? null;
153
+ }
154
+
155
+ export function recordSweep({ file, states, merged, now = Date.now() }) {
156
+ append(file, {
157
+ kind: 'sweep',
158
+ at: new Date(now).toISOString(),
159
+ states,
160
+ merged,
161
+ });
162
+ }
163
+
164
+ /**
165
+ * The hand-back, from the ledger alone.
166
+ *
167
+ * @param {object[]} records
168
+ */
169
+ export function summarize(records) {
170
+ const sweep = lastSweep(records);
171
+ const states = sweep?.states ?? {};
172
+ const merged = new Map();
173
+ for (const r of records) {
174
+ if (r.kind === 'sweep')
175
+ for (const m of r.merged ?? []) merged.set(m.number, m);
176
+ }
177
+ const actions = records.filter((r) => r.kind === 'action');
178
+ const stillCurrent = (r) => r.pr == null || states[r.pr] === r.state;
179
+ return {
180
+ merged: [...merged.values()],
181
+ open: Object.entries(states).map(([number, state]) => ({
182
+ number: Number(number),
183
+ state,
184
+ })),
185
+ waiting: actions.filter((r) => r.action === 'raise' && stillCurrent(r)),
186
+ followUps: actions.filter((r) => r.action === 'follow-up'),
187
+ taken: actions.filter((r) => !ALWAYS_ALLOWED.has(r.action)),
188
+ };
189
+ }
190
+
191
+ const prLabel = (r) =>
192
+ r.pr == null ? (r.story ? `Story #${r.story}` : 'run') : `PR #${r.pr}`;
193
+
194
+ export function renderSummary(summary) {
195
+ const section = (title, rows) => [
196
+ `${title} (${rows.length})`,
197
+ ...rows.map((row) => `- ${row}`),
198
+ ];
199
+ return `${[
200
+ ...section(
201
+ 'Merged',
202
+ summary.merged.map(
203
+ (m) => `PR #${m.number}${m.storyId ? ` (Story #${m.storyId})` : ''}`,
204
+ ),
205
+ ),
206
+ ...section(
207
+ 'Still open',
208
+ summary.open.map((o) => `PR #${o.number}: ${o.state}`),
209
+ ),
210
+ ...section(
211
+ 'Waiting on the operator',
212
+ summary.waiting.map((r) => `${prLabel(r)}: ${r.text}`),
213
+ ),
214
+ ...section(
215
+ 'Follow-ups filed',
216
+ summary.followUps.map((r) => `${prLabel(r)}: ${r.text}`),
217
+ ),
218
+ ...section(
219
+ 'Actions taken',
220
+ summary.taken.map((r) => `${r.action} ${prLabel(r)}: ${r.text}`),
221
+ ),
222
+ ].join('\n')}\n`;
223
+ }