mandrel 2.115.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.
@@ -41,6 +41,9 @@ const FRAMEWORK_SCRIPT_BASENAMES = Object.freeze([
41
41
  'ceremony-derive.js',
42
42
  'clean-temp.js',
43
43
  'clean-worktrees.js',
44
+ 'closeout-audit.js',
45
+ 'orchestrate-inventory.js',
46
+ 'orchestrate-ledger.js',
44
47
  'cleanup-repo-test-temp.js',
45
48
  'coverage-capture.js',
46
49
  'coverage-ratchet.js',
@@ -0,0 +1,238 @@
1
+ /**
2
+ * classify.js — one state per open PR from a normalised snapshot, and the
3
+ * terse inventory envelope built around it. Pure: every read happened before.
4
+ */
5
+
6
+ import { conflictState } from './conflicts.js';
7
+ import { failureSignature, findInherited } from './inherited-failure.js';
8
+
9
+ /** A not-green PR with no push or check activity for this long is stale. */
10
+ const STALE_MS = 45 * 60_000;
11
+
12
+ const RED_SHOWN = 2;
13
+ const CONFLICTS_SHOWN = 10;
14
+ const BUDGET_BYTES = 16384;
15
+ const OVERLAPS_KEPT = 10;
16
+
17
+ /**
18
+ * Rollup over the required checks (every check when the required set is
19
+ * unknown). Green needs every required name present, done and not red.
20
+ *
21
+ * @param {Array<{ name: string, phase: string, red: boolean }>} checks
22
+ * @param {string[]|null} required
23
+ */
24
+ function rollup(checks, required) {
25
+ const want = required ? new Set(required) : null;
26
+ const relevant = want ? checks.filter((c) => want.has(c.name)) : checks;
27
+ const red = relevant.some((c) => c.red);
28
+ const running = relevant.some((c) => c.phase === 'running');
29
+ const queued = relevant.some((c) => c.phase === 'queued');
30
+ const present = new Set(relevant.map((c) => c.name));
31
+ const complete = want
32
+ ? [...want].every((n) => present.has(n))
33
+ : relevant.length > 0;
34
+ return {
35
+ red,
36
+ running,
37
+ queued,
38
+ green: complete && !red && !running && !queued,
39
+ };
40
+ }
41
+
42
+ /** The ejection is stale once the head moved past the commit it removed. */
43
+ function headMoved(pr) {
44
+ const event = pr.queueEvent;
45
+ if (event?.headSha) return pr.headSha !== event.headSha;
46
+ return Date.parse(pr.pushedAt ?? '') > Date.parse(event?.at ?? '');
47
+ }
48
+
49
+ function isEjected(pr, queueReadable) {
50
+ return (
51
+ queueReadable &&
52
+ pr.inQueue === false &&
53
+ pr.queueEvent?.type === 'removed' &&
54
+ !/merged/i.test(pr.queueEvent.reason ?? '')
55
+ );
56
+ }
57
+
58
+ /**
59
+ * The first rule that holds wins: ejected, conflicted-real / -driver-only,
60
+ * red-inherited, red-own-failure, waiting-on-runner, green-not-queued,
61
+ * stale, moving.
62
+ *
63
+ * @param {object} pr normalised snapshot row
64
+ * @param {{ queueReadable: boolean, inheritedPrs: Set<number>,
65
+ * required: string[]|null, now: number }} ctx
66
+ * @returns {{ state: string, checks: ReturnType<typeof rollup>, conflict?: object }}
67
+ */
68
+ function classifyPr(pr, ctx) {
69
+ const checks = rollup(pr.checks, ctx.required);
70
+ const done = (state, extra) => ({ state, checks, ...extra });
71
+ if (isEjected(pr, ctx.queueReadable)) return done('ejected');
72
+ if (pr.conflicting) {
73
+ const conflict = conflictState(pr.conflict);
74
+ return done(conflict.state, { conflict });
75
+ }
76
+ if (checks.red) {
77
+ return done(
78
+ ctx.inheritedPrs.has(pr.number) ? 'red-inherited' : 'red-own-failure',
79
+ );
80
+ }
81
+ return done(quietState(pr, checks, ctx));
82
+ }
83
+
84
+ /** The states below red: waiting-on-runner, green-not-queued, stale, moving. */
85
+ function quietState(pr, checks, ctx) {
86
+ if (checks.queued && !checks.running) return 'waiting-on-runner';
87
+ const unqueued = ctx.queueReadable && pr.inQueue === false && !pr.autoMerge;
88
+ if (checks.green && unqueued && !pr.draft) return 'green-not-queued';
89
+ const idleMs = ctx.now - Date.parse(pr.activityAt ?? '');
90
+ return !checks.green && idleMs > STALE_MS ? 'stale' : 'moving';
91
+ }
92
+
93
+ /**
94
+ * @param {{ cmd: string, args?: string[] }|null} requeueCommand
95
+ * @param {number} number
96
+ */
97
+ function substitute(requeueCommand, number) {
98
+ if (!requeueCommand) return null;
99
+ return {
100
+ cmd: requeueCommand.cmd,
101
+ args: (requeueCommand.args ?? []).map((a) =>
102
+ a.replaceAll('{pr}', String(number)),
103
+ ),
104
+ };
105
+ }
106
+
107
+ function requeueOf(pr, { green, vetoHeld, requeueCommand }) {
108
+ const blockedBy = [];
109
+ if (!headMoved(pr)) blockedBy.push('head-not-moved');
110
+ if (!green) blockedBy.push('checks-not-green');
111
+ if (vetoHeld) blockedBy.push('release-veto');
112
+ return {
113
+ eligible: blockedBy.length === 0,
114
+ blockedBy,
115
+ command: substitute(requeueCommand, pr.number),
116
+ };
117
+ }
118
+
119
+ /**
120
+ * Pairs of open PRs changing a common path, largest first.
121
+ *
122
+ * @param {Array<{ number: number, paths: string[] }>} prs
123
+ */
124
+ function findOverlaps(prs) {
125
+ const pairs = [];
126
+ for (let i = 0; i < prs.length; i += 1) {
127
+ const mine = new Set(prs[i].paths);
128
+ for (let j = i + 1; j < prs.length; j += 1) {
129
+ const shared = prs[j].paths.filter((p) => mine.has(p));
130
+ if (shared.length > 0) {
131
+ pairs.push({
132
+ prs: [prs[i].number, prs[j].number],
133
+ shared: shared.length,
134
+ paths: shared.slice(0, 2),
135
+ });
136
+ }
137
+ }
138
+ }
139
+ return pairs.sort((a, b) => b.shared - a.shared).slice(0, OVERLAPS_KEPT);
140
+ }
141
+
142
+ function redSigs(pr, required) {
143
+ const want = required ? new Set(required) : null;
144
+ return pr.checks
145
+ .filter((c) => c.red && (!want || want.has(c.name)))
146
+ .map(failureSignature);
147
+ }
148
+
149
+ function conflictFields({ paths }) {
150
+ return {
151
+ conflicted: paths ? paths.slice(0, CONFLICTS_SHOWN) : null,
152
+ conflictedCount: paths ? paths.length : null,
153
+ };
154
+ }
155
+
156
+ function prEntry(pr, verdict, opts) {
157
+ const vetoed = opts.vetoLabel ? pr.labels.includes(opts.vetoLabel) : false;
158
+ const entry = {
159
+ number: pr.number,
160
+ state: verdict.state,
161
+ storyId: pr.storyId,
162
+ author: pr.author,
163
+ assignees: pr.assignees,
164
+ head: pr.headSha?.slice(0, 7) ?? null,
165
+ pathCount: pr.pathCount,
166
+ };
167
+ if (verdict.state.startsWith('red-')) entry.red = pr.sigs.slice(0, RED_SHOWN);
168
+ if (verdict.conflict) Object.assign(entry, conflictFields(verdict.conflict));
169
+ if (vetoed) entry.veto = opts.vetoHeld ? 'held' : 'clear';
170
+ if (verdict.state === 'ejected') {
171
+ entry.requeue = requeueOf(pr, {
172
+ green: verdict.checks.green,
173
+ vetoHeld: vetoed && opts.vetoHeld,
174
+ requeueCommand: opts.requeueCommand,
175
+ });
176
+ }
177
+ return entry;
178
+ }
179
+
180
+ /**
181
+ * The inventory envelope, `changes[]` left empty for the ledger to fill.
182
+ *
183
+ * @param {object} snapshot normalised reads (see `inventory.js`)
184
+ * @param {{ now: number, vetoLabel?: string|null, vetoHeld?: boolean,
185
+ * requeueCommand?: object|null }} opts
186
+ */
187
+ export function buildEnvelope(snapshot, opts) {
188
+ const { required, queueReadable } = snapshot;
189
+ const prs = snapshot.prs.map((pr) => ({
190
+ ...pr,
191
+ sigs: redSigs(pr, required),
192
+ }));
193
+ const baseSigs = redSigs({ checks: snapshot.base.checks }, required);
194
+ const { inheritedPrs, inherited } = findInherited(prs, baseSigs);
195
+ const ctx = { queueReadable, inheritedPrs, required, now: opts.now };
196
+ return fitBudget({
197
+ kind: 'orchestrate-inventory',
198
+ base: {
199
+ branch: snapshot.base.branch,
200
+ sha: snapshot.base.sha?.slice(0, 7) ?? null,
201
+ red: baseSigs,
202
+ },
203
+ runners: snapshot.runners,
204
+ prs: prs.map((pr) => prEntry(pr, classifyPr(pr, ctx), opts)),
205
+ overlaps: findOverlaps(prs),
206
+ inherited,
207
+ landed: snapshot.merged.filter((m) => m.storyId !== null),
208
+ changes: [],
209
+ degraded: snapshot.degraded,
210
+ });
211
+ }
212
+
213
+ /** Trims applied in order, each only while the envelope is over budget. */
214
+ const TRIMS = [
215
+ (e) => {
216
+ for (const o of e.overlaps) o.paths = [];
217
+ },
218
+ (e) => {
219
+ for (const p of e.prs) {
220
+ if (p.red) p.red = p.red.slice(0, 1);
221
+ if (p.conflicted) p.conflicted = p.conflicted.slice(0, 3);
222
+ }
223
+ },
224
+ (e) => {
225
+ for (const i of e.inherited) i.sig = i.sig.slice(0, 40);
226
+ },
227
+ ];
228
+
229
+ const overBudget = (e) => Buffer.byteLength(JSON.stringify(e)) > BUDGET_BYTES;
230
+
231
+ function fitBudget(envelope) {
232
+ for (const trim of TRIMS) {
233
+ if (!overBudget(envelope)) break;
234
+ trim(envelope);
235
+ envelope.trimmed = true;
236
+ }
237
+ return envelope;
238
+ }
@@ -0,0 +1,119 @@
1
+ /**
2
+ * conflicts.js — which of a conflicting PR's paths a custom merge driver
3
+ * resolves. Reads a local `git merge-tree` of base and head, and
4
+ * `git check-attr merge` (so a consumer's own driver rows count).
5
+ */
6
+
7
+ import { gitSpawn } from '../git-utils.js';
8
+
9
+ /** `check-attr merge` values that name no custom driver. */
10
+ const BUILTIN_MERGE_VALUES = new Set([
11
+ 'unspecified',
12
+ 'set',
13
+ 'unset',
14
+ 'text',
15
+ 'binary',
16
+ 'union',
17
+ ]);
18
+
19
+ const ATTR_SEPARATOR = ': merge: ';
20
+
21
+ /**
22
+ * @param {string} stdout `git check-attr merge -- <paths>` output
23
+ * @returns {Map<string, string>} path → attribute value
24
+ */
25
+ function parseCheckAttr(stdout) {
26
+ const values = new Map();
27
+ for (const line of String(stdout ?? '').split('\n')) {
28
+ const at = line.lastIndexOf(ATTR_SEPARATOR);
29
+ if (at > 0)
30
+ values.set(
31
+ line.slice(0, at),
32
+ line.slice(at + ATTR_SEPARATOR.length).trim(),
33
+ );
34
+ }
35
+ return values;
36
+ }
37
+
38
+ /**
39
+ * Merge base and head locally (fetching only those two refs) and mark each
40
+ * conflicted path driver-merged or not. `null` when git could not tell.
41
+ *
42
+ * @param {{ cwd: string, base: string, number: number, headSha: string,
43
+ * spawn?: Function }} args
44
+ * @returns {{ clean: boolean, paths: Array<{ path: string, driver: boolean }> }|null}
45
+ */
46
+ export function resolveConflict({
47
+ cwd,
48
+ base,
49
+ number,
50
+ headSha,
51
+ spawn = gitSpawn,
52
+ }) {
53
+ const fetched = spawn(
54
+ cwd,
55
+ 'fetch',
56
+ '--no-tags',
57
+ '--quiet',
58
+ 'origin',
59
+ base,
60
+ `refs/pull/${number}/head`,
61
+ );
62
+ if (fetched.status !== 0) return null;
63
+ const merged = spawn(
64
+ cwd,
65
+ 'merge-tree',
66
+ '--write-tree',
67
+ '--name-only',
68
+ '--no-messages',
69
+ `origin/${base}`,
70
+ headSha,
71
+ );
72
+ if (merged.status === 0) return { clean: true, paths: [] };
73
+ if (merged.status !== 1) return null;
74
+ const paths = [
75
+ ...new Set(
76
+ merged.stdout
77
+ .split('\n')
78
+ .slice(1)
79
+ .map((l) => l.trim())
80
+ .filter(Boolean),
81
+ ),
82
+ ];
83
+ if (paths.length === 0) return null;
84
+ const attrs = spawn(cwd, 'check-attr', 'merge', '--', ...paths);
85
+ if (attrs.status !== 0) return null;
86
+ const values = parseCheckAttr(attrs.stdout);
87
+ return {
88
+ clean: false,
89
+ paths: paths.map((p) => ({
90
+ path: p,
91
+ driver: isCustomDriver(values.get(p)),
92
+ })),
93
+ };
94
+ }
95
+
96
+ function isCustomDriver(value) {
97
+ return (
98
+ typeof value === 'string' &&
99
+ value.length > 0 &&
100
+ !BUILTIN_MERGE_VALUES.has(value)
101
+ );
102
+ }
103
+
104
+ /**
105
+ * `conflicted-driver-only` when the local merge is clean or every conflicted
106
+ * path is driver-merged; otherwise `conflicted-real` with the other paths.
107
+ * An unreadable local merge is `conflicted-real` with `paths: null`.
108
+ *
109
+ * @param {{ clean: boolean, paths: Array<{ path: string, driver: boolean }> }|null} conflict
110
+ * @returns {{ state: string, paths: string[]|null }}
111
+ */
112
+ export function conflictState(conflict) {
113
+ if (!conflict) return { state: 'conflicted-real', paths: null };
114
+ const real = conflict.paths.filter((p) => !p.driver).map((p) => p.path);
115
+ if (conflict.clean || real.length === 0) {
116
+ return { state: 'conflicted-driver-only', paths: [] };
117
+ }
118
+ return { state: 'conflicted-real', paths: real };
119
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * inherited-failure.js — is a red PR failing for its own reasons, or for one
3
+ * it shares with the base branch or with an unrelated PR? Pure.
4
+ */
5
+
6
+ const SIGNATURE_MAX = 120;
7
+
8
+ /**
9
+ * A failure signature: the check name plus its first failure annotation.
10
+ *
11
+ * @param {{ name: string, note?: string|null }} check
12
+ * @returns {string}
13
+ */
14
+ export function failureSignature(check) {
15
+ const sig = check.note ? `${check.name}: ${check.note}` : check.name;
16
+ return sig.replace(/\s+/g, ' ').slice(0, SIGNATURE_MAX);
17
+ }
18
+
19
+ /**
20
+ * @param {string[]} a
21
+ * @param {string[]} b
22
+ * @returns {boolean}
23
+ */
24
+ function sharesPath(a, b) {
25
+ const seen = new Set(a);
26
+ return b.some((p) => seen.has(p));
27
+ }
28
+
29
+ /**
30
+ * A PR's failure is inherited when its signature is red on the base branch,
31
+ * or red on another PR that changes none of the same paths.
32
+ *
33
+ * @param {Array<{ number: number, sigs: string[], paths: string[] }>} prs
34
+ * @param {string[]} baseSigs
35
+ * @returns {{ inheritedPrs: Set<number>,
36
+ * inherited: Array<{ sig: string, onBase: boolean, prs: number[] }> }}
37
+ */
38
+ export function findInherited(prs, baseSigs) {
39
+ const onBase = new Set(baseSigs);
40
+ const bySig = new Map();
41
+ for (const pr of prs) {
42
+ for (const sig of pr.sigs) {
43
+ if (!onBase.has(sig) && !isSharedWithUnrelated(pr, sig, prs)) continue;
44
+ if (!bySig.has(sig)) bySig.set(sig, []);
45
+ bySig.get(sig).push(pr.number);
46
+ }
47
+ }
48
+ const inherited = [...bySig].map(([sig, numbers]) => ({
49
+ sig,
50
+ onBase: onBase.has(sig),
51
+ prs: numbers,
52
+ }));
53
+ return {
54
+ inheritedPrs: new Set(inherited.flatMap((entry) => entry.prs)),
55
+ inherited,
56
+ };
57
+ }
58
+
59
+ function isSharedWithUnrelated(pr, sig, prs) {
60
+ return prs.some(
61
+ (other) =>
62
+ other.number !== pr.number &&
63
+ other.sigs.includes(sig) &&
64
+ !sharesPath(pr.paths, other.paths),
65
+ );
66
+ }