mandrel 2.69.0 → 2.70.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.
@@ -1,184 +0,0 @@
1
- /**
2
- * Persist the cross-run audit ledger, which an ephemeral checkout would
3
- * otherwise discard.
4
- */
5
-
6
- import { DEFAULT_LEDGER_PATH } from '../findings/audit-ledger.js';
7
- import { gh as defaultGh } from '../gh-exec.js';
8
- import { gitSync } from '../git-utils.js';
9
- import { openLedgerPullRequest, probeGit } from './ledger-pr.js';
10
-
11
- const DEFAULT_BASE_BRANCH = 'main';
12
-
13
- /**
14
- * @param {Date|string|number} [now]
15
- * @returns {string}
16
- */
17
- function isoDate(now) {
18
- const date = now instanceof Date ? now : new Date(now ?? Date.now());
19
- return date.toISOString().slice(0, 10);
20
- }
21
-
22
- /**
23
- * Explicit, then config, then `main`; a failed config resolve must never break
24
- * a sweep that has already done its work.
25
- * @param {string} [explicit]
26
- * @returns {Promise<string>}
27
- */
28
- async function resolveBaseBranch(explicit) {
29
- if (typeof explicit === 'string' && explicit.length > 0) return explicit;
30
- try {
31
- const { resolveConfig } = await import('../config-resolver.js');
32
- const branch = resolveConfig()?.project?.baseBranch;
33
- if (typeof branch === 'string' && branch.length > 0) return branch;
34
- } catch (_) {
35
- // fall through to the default
36
- }
37
- return DEFAULT_BASE_BRANCH;
38
- }
39
-
40
- /**
41
- * `unpersisted`: the ledger changed but there is no `origin` or HEAD is off
42
- * the base branch, so a commit here would not reach shared state.
43
- *
44
- * @param {object} [params]
45
- * @param {string} [params.ledgerPath]
46
- * @param {string} [params.baseBranch]
47
- * @param {string} [params.cwd]
48
- * @param {(cwd: string, ...args: string[]) => string} [params.git]
49
- * @returns {Promise<{ ledgerPath: string, baseBranch: string, changed: boolean,
50
- * hasOrigin: boolean, headBranch: string, onBaseBranch: boolean,
51
- * unpersisted: boolean }>}
52
- */
53
- async function assessLedgerPersistence({
54
- ledgerPath = DEFAULT_LEDGER_PATH,
55
- baseBranch,
56
- cwd = process.cwd(),
57
- git = gitSync,
58
- } = {}) {
59
- const base = await resolveBaseBranch(baseBranch);
60
- const probe = (args) => probeGit(git, cwd, args);
61
- const changed = ledgerIsDirty(probe, ledgerPath);
62
- const hasOrigin = hasOriginRemote(probe);
63
- const headBranch = headBranchOf(probe);
64
-
65
- return {
66
- ledgerPath,
67
- baseBranch: base,
68
- changed,
69
- hasOrigin,
70
- headBranch,
71
- onBaseBranch: headBranch === base,
72
- unpersisted: changed && (!hasOrigin || headBranch !== base),
73
- };
74
- }
75
-
76
- /**
77
- * Pathspec-scoped, so unrelated dirt never counts.
78
- * @param {(args: string[]) => string} probe
79
- * @param {string} ledgerPath
80
- * @returns {boolean}
81
- */
82
- function ledgerIsDirty(probe, ledgerPath) {
83
- return probe(['status', '--porcelain', '--', ledgerPath]).length > 0;
84
- }
85
-
86
- /**
87
- * @param {(args: string[]) => string} probe
88
- * @returns {boolean}
89
- */
90
- function hasOriginRemote(probe) {
91
- return probe(['remote'])
92
- .split('\n')
93
- .map((line) => line.trim())
94
- .includes('origin');
95
- }
96
-
97
- /**
98
- * `''` when detached or commitless — both read as "not the base branch".
99
- * @param {(args: string[]) => string} probe
100
- * @returns {string}
101
- */
102
- function headBranchOf(probe) {
103
- return probe(['rev-parse', '--abbrev-ref', 'HEAD']);
104
- }
105
-
106
- /**
107
- * @param {{ ledgerPath: string, baseBranch: string, hasOrigin: boolean, headBranch: string }} state
108
- * @returns {string}
109
- */
110
- function unpersistedWarning(state) {
111
- const cause = state.hasOrigin
112
- ? `HEAD is on "${state.headBranch || '(detached)'}", not the base branch "${state.baseBranch}"`
113
- : 'this checkout has no "origin" remote';
114
- return `ledger not persisted: ${state.ledgerPath} changed but ${cause}, so this sweep's memory will be lost when the checkout goes away. Re-run with --ledger-commit to open a PR for it, or commit ${state.ledgerPath} by hand.`;
115
- }
116
-
117
- /**
118
- * Marks the summary `unpersisted: true` (and warns) when the checkout cannot
119
- * keep the new memory.
120
- *
121
- * @param {object} [params]
122
- * @param {object|null} [params.ledger]
123
- * @param {string} [params.ledgerPath]
124
- * @param {boolean} [params.dryRun]
125
- * @param {boolean} [params.ledgerCommit]
126
- * @param {string} [params.cwd]
127
- * @param {(cwd: string, ...args: string[]) => string} [params.git]
128
- * @param {{ warn: Function }} [params.logger]
129
- * @returns {Promise<object|null>} the (possibly annotated) ledger summary.
130
- */
131
- export async function resolveLedgerSummary({
132
- ledger = null,
133
- ledgerPath = DEFAULT_LEDGER_PATH,
134
- dryRun,
135
- ledgerCommit,
136
- cwd,
137
- git,
138
- logger,
139
- } = {}) {
140
- if (dryRun || ledgerCommit) return ledger;
141
- const state = await assessLedgerPersistence({ ledgerPath, cwd, git });
142
- if (!state.unpersisted) return ledger;
143
- logger?.warn?.(unpersistedWarning(state));
144
- return { ...(ledger ?? { path: ledgerPath }), unpersisted: true };
145
- }
146
-
147
- /**
148
- * Failures are fatal and name their step; callers run this after printing the
149
- * run summary so a broken remote never costs the sweep's findings.
150
- *
151
- * @param {object} [params]
152
- * @param {string} [params.ledgerPath]
153
- * @param {string} [params.baseBranch]
154
- * @param {string} [params.cwd]
155
- * @param {(cwd: string, ...args: string[]) => string} [params.git]
156
- * @param {{ pr: { create: (flags: string[]) => Promise<unknown> } }} [params.gh]
157
- * @param {Date|string|number} [params.now]
158
- * @returns {Promise<{ committed: boolean, reason?: string, branch?: string,
159
- * subject?: string, baseBranch?: string, prUrl?: string|null,
160
- * resumed?: boolean, ledgerPath: string }>}
161
- */
162
- export async function runLedgerCommit({
163
- ledgerPath = DEFAULT_LEDGER_PATH,
164
- baseBranch,
165
- cwd = process.cwd(),
166
- git = gitSync,
167
- gh = defaultGh,
168
- now,
169
- } = {}) {
170
- const state = await assessLedgerPersistence({
171
- ledgerPath,
172
- baseBranch,
173
- cwd,
174
- git,
175
- });
176
- return openLedgerPullRequest({
177
- state,
178
- ledgerPath,
179
- cwd,
180
- git,
181
- gh,
182
- date: isoDate(now),
183
- });
184
- }
@@ -1,279 +0,0 @@
1
- /**
2
- * The `--ledger-commit` write sequence. Every refusal precedes the first
3
- * write.
4
- */
5
-
6
- /**
7
- * Read-only git probe that never throws; a checkout with no commits is an
8
- * answer, not a crash. Writes use `runStep`, where failure is fatal.
9
- *
10
- * @param {(cwd: string, ...args: string[]) => string} git
11
- * @param {string} cwd
12
- * @param {string[]} args
13
- * @returns {string} trimmed stdout, or `''` when git failed.
14
- */
15
- export function probeGit(git, cwd, args) {
16
- try {
17
- const out = git(cwd, ...args);
18
- return typeof out === 'string' ? out.trim() : '';
19
- } catch (_) {
20
- return '';
21
- }
22
- }
23
-
24
- /**
25
- * @param {(cwd: string, ...args: string[]) => string} git
26
- * @param {string} cwd
27
- * @param {string} ref
28
- * @returns {boolean}
29
- */
30
- function refExists(git, cwd, ref) {
31
- return (
32
- probeGit(git, cwd, ['rev-parse', '--verify', '--quiet', ref]).length > 0
33
- );
34
- }
35
-
36
- /**
37
- * Qualifies the branch name so it is unique across bases (a same-day retry
38
- * must not collide) yet deterministic per base (so a retry recognises its own
39
- * half-finished branch).
40
- *
41
- * @param {(cwd: string, ...args: string[]) => string} git
42
- * @param {string} cwd
43
- * @param {string} baseRef — `origin/<base>`.
44
- * @returns {string}
45
- */
46
- function shortSha(git, cwd, baseRef) {
47
- for (const ref of [baseRef, 'HEAD']) {
48
- const sha = probeGit(git, cwd, ['rev-parse', '--short', ref]);
49
- if (sha) return sha;
50
- }
51
- return 'initial';
52
- }
53
-
54
- /**
55
- * A local, never-pushed ledger branch is a failed run's commit: resume at the
56
- * push, so a failed push plus its retry yields exactly one PR.
57
- *
58
- * @param {{ git: Function, cwd: string, base: string, date: string }} params
59
- * @returns {{ branch: string, resuming: boolean }}
60
- */
61
- function resolveLedgerBranch({ git, cwd, base, date }) {
62
- const branch = `chore/audit-ledger-${date}-${shortSha(git, cwd, `origin/${base}`)}`;
63
- return {
64
- branch,
65
- resuming:
66
- refExists(git, cwd, `refs/heads/${branch}`) &&
67
- !refExists(git, cwd, `refs/remotes/origin/${branch}`),
68
- };
69
- }
70
-
71
- /**
72
- * Refuses before any write. HEAD off the base branch would cut the ledger
73
- * branch from a feature tip and carry its unrelated commits into the PR.
74
- *
75
- * @param {{ hasOrigin: boolean, onBaseBranch: boolean, headBranch: string,
76
- * baseBranch: string }} state
77
- * @param {string} branch — the ledger branch name, allowed as a resume HEAD.
78
- */
79
- function assertCommittable(state, branch) {
80
- if (!state.hasOrigin) {
81
- throw new Error(
82
- '--ledger-commit failed at step "verify-origin": this checkout has no "origin" remote, ' +
83
- 'so the ledger branch could never be pushed. Add the remote, or commit the ledger by hand.',
84
- );
85
- }
86
- if (!state.onBaseBranch && state.headBranch !== branch) {
87
- throw new Error(
88
- `--ledger-commit failed at step "verify-base-branch": HEAD is on "${state.headBranch || '(detached)'}", ` +
89
- `not the base branch "${state.baseBranch}". Nothing was committed — the ledger branch is cut from ` +
90
- `origin/${state.baseBranch}, and running from a feature branch would carry its commits into the ledger PR. ` +
91
- `Check out ${state.baseBranch} and re-run.`,
92
- );
93
- }
94
- }
95
-
96
- /**
97
- * @param {unknown} result
98
- * @returns {string|null}
99
- */
100
- function pullRequestUrl(result) {
101
- const text = typeof result === 'string' ? result : (result?.stdout ?? '');
102
- const match = /https?:\/\/\S+/.exec(String(text ?? ''));
103
- return match ? match[0] : null;
104
- }
105
-
106
- /**
107
- * @param {string} name
108
- * @param {() => unknown} fn
109
- * @returns {Promise<unknown>}
110
- */
111
- async function runStep(name, fn) {
112
- try {
113
- return await fn();
114
- } catch (error) {
115
- throw new Error(
116
- `--ledger-commit failed at step "${name}": ${error?.message ?? error}`,
117
- { cause: error },
118
- );
119
- }
120
- }
121
-
122
- /**
123
- * @param {string} ledgerPath
124
- * @param {string} date
125
- * @returns {string}
126
- */
127
- function pullRequestBody(ledgerPath, date) {
128
- return [
129
- `Reconciles the cross-run audit ledger (\`${ledgerPath}\`) written by the`,
130
- `unattended \`audit-to-stories --auto\` sweep on ${date}.`,
131
- '',
132
- 'Ledger-only change — no source, workflow or documentation file is touched.',
133
- 'Merging it is what gives the next sweep a memory: without it the ledger',
134
- 'dies with the checkout and every later run re-proposes findings this one',
135
- 'already filed, and re-surfaces findings a human already rejected.',
136
- '',
137
- 'Auto-merge is deliberately not requested: the ledger records machine-derived',
138
- 'lifecycle state, and a human glance before it lands is the point.',
139
- ].join('\n');
140
- }
141
-
142
- /**
143
- * @param {object} ctx
144
- * @returns {Promise<void>}
145
- */
146
- async function commitLedgerOnto({
147
- git,
148
- cwd,
149
- branch,
150
- base,
151
- ledgerPath,
152
- subject,
153
- resuming = false,
154
- }) {
155
- if (resuming) {
156
- await runStep('resume-branch', () => git(cwd, 'checkout', branch));
157
- return;
158
- }
159
- await runStep('fetch-base', () => git(cwd, 'fetch', 'origin', base));
160
- await runStep('create-branch', () =>
161
- git(cwd, 'checkout', '-b', branch, `origin/${base}`),
162
- );
163
- await runStep('stage-ledger', () => git(cwd, 'add', '--', ledgerPath));
164
- // The pathspec keeps the commit ledger-only in a dirty checkout.
165
- await runStep('commit-ledger', () =>
166
- git(cwd, 'commit', '-m', subject, '--', ledgerPath),
167
- );
168
- }
169
-
170
- /**
171
- * Never requests auto-merge: landing the ledger stays an operator decision.
172
- *
173
- * @param {object} ctx
174
- * @returns {Promise<string|null>}
175
- */
176
- async function pushAndOpenPullRequest({
177
- git,
178
- cwd,
179
- gh,
180
- branch,
181
- base,
182
- subject,
183
- ledgerPath,
184
- date,
185
- }) {
186
- await runStep('push-branch', () =>
187
- git(cwd, 'push', '--set-upstream', 'origin', branch),
188
- );
189
- return pullRequestUrl(
190
- await runStep('open-pull-request', () =>
191
- gh.pr.create([
192
- '--base',
193
- base,
194
- '--head',
195
- branch,
196
- '--title',
197
- subject,
198
- '--body',
199
- pullRequestBody(ledgerPath, date),
200
- ]),
201
- ),
202
- );
203
- }
204
-
205
- /**
206
- * Best-effort, from a `finally`: a failed restore must never mask the failure
207
- * that caused it.
208
- *
209
- * @param {{ git: Function, cwd: string, startBranch: string, branch: string }} params
210
- */
211
- function restoreBranch({ git, cwd, startBranch, branch }) {
212
- if (!startBranch || startBranch === branch) return;
213
- try {
214
- git(cwd, 'checkout', startBranch);
215
- } catch (_) {
216
- // Deliberately swallowed.
217
- }
218
- }
219
-
220
- /**
221
- * Re-runnable; always restores the starting branch.
222
- *
223
- * @param {{ state: object, ledgerPath: string, cwd: string, git: Function,
224
- * gh: object, date: string }} params
225
- * @returns {Promise<object>} the result the CLI summarises.
226
- */
227
- export async function openLedgerPullRequest({
228
- state,
229
- ledgerPath,
230
- cwd,
231
- git,
232
- gh,
233
- date,
234
- }) {
235
- const base = state.baseBranch;
236
- const subject = `chore(audit): reconcile audit ledger ${date}`;
237
- const { branch, resuming } = resolveLedgerBranch({ git, cwd, base, date });
238
-
239
- if (!state.changed && !resuming) {
240
- return { committed: false, reason: 'ledger-unchanged', ledgerPath };
241
- }
242
- assertCommittable(state, branch);
243
-
244
- const startBranch = state.headBranch;
245
- let prUrl = null;
246
- try {
247
- await commitLedgerOnto({
248
- git,
249
- cwd,
250
- branch,
251
- base,
252
- ledgerPath,
253
- subject,
254
- resuming,
255
- });
256
- prUrl = await pushAndOpenPullRequest({
257
- git,
258
- cwd,
259
- gh,
260
- branch,
261
- base,
262
- subject,
263
- ledgerPath,
264
- date,
265
- });
266
- } finally {
267
- restoreBranch({ git, cwd, startBranch, branch });
268
- }
269
-
270
- return {
271
- committed: true,
272
- resumed: resuming,
273
- branch,
274
- subject,
275
- baseBranch: base,
276
- prUrl,
277
- ledgerPath,
278
- };
279
- }
@@ -1,88 +0,0 @@
1
- /**
2
- * Record what a run filed onto the ledger so the next run suppresses it even
3
- * without search dedup. No network: runs before the provider loads.
4
- */
5
-
6
- import {
7
- DEFAULT_LEDGER_PATH,
8
- readLedger,
9
- reconcileLedger,
10
- writeLedger,
11
- } from '../findings/audit-ledger.js';
12
- import {
13
- fingerprintAuditFinding,
14
- toCanonicalFinding,
15
- } from './finding-adapter.js';
16
-
17
- /**
18
- * Only mapped groups contribute; inventing a state for an unopened group would
19
- * suppress a finding against an Issue that does not exist. Every state is
20
- * `open` — a later close is learned live next run and outranks this record.
21
- *
22
- * @param {object} params
23
- * @param {Array<object>} params.groups — the `create`-eligible groups.
24
- * @param {Record<string, number>} params.issueByGroupKey — group key → issue number.
25
- * @returns {{ findings: Array<object>, issueStates: Record<string, { state: string, number: number }>, groupsRecorded: number }}
26
- */
27
- function issueStatesFromIssueMap({ groups, issueByGroupKey }) {
28
- const findings = [];
29
- const issueStates = {};
30
- let groupsRecorded = 0;
31
-
32
- for (const group of groups ?? []) {
33
- const number = issueByGroupKey?.[group?.groupKey];
34
- if (typeof number !== 'number') continue;
35
- groupsRecorded += 1;
36
- for (const finding of group.findings ?? []) {
37
- findings.push(finding);
38
- issueStates[fingerprintAuditFinding(finding).full] = {
39
- state: 'open',
40
- number,
41
- };
42
- }
43
- }
44
-
45
- return { findings, issueStates, groupsRecorded };
46
- }
47
-
48
- /**
49
- * Other ledger entries survive untouched: `reconcileLedger` rewrites only the
50
- * findings it is handed.
51
- *
52
- * @param {object} params
53
- * @param {string} [params.ledgerPath]
54
- * @param {Array<object>} params.groups — the `create`-eligible groups.
55
- * @param {Record<string, number>} params.issueByGroupKey
56
- * @param {boolean} [params.write=true] — `false` for `--dry-run`.
57
- * @param {{ readLedgerImpl?: Function, writeLedgerImpl?: Function }} [seams]
58
- * @returns {{ path: string, written: boolean, groupsRecorded: number, findingsRecorded: number, filed: number }}
59
- */
60
- export function recordFiledIssues(
61
- { ledgerPath, groups, issueByGroupKey, write = true },
62
- { readLedgerImpl = readLedger, writeLedgerImpl = writeLedger } = {},
63
- ) {
64
- const path = ledgerPath ?? DEFAULT_LEDGER_PATH;
65
- const { findings, issueStates, groupsRecorded } = issueStatesFromIssueMap({
66
- groups,
67
- issueByGroupKey,
68
- });
69
-
70
- const { ledger: next, classifications } = reconcileLedger({
71
- ledger: readLedgerImpl(path),
72
- findings,
73
- issueStates,
74
- toCanonical: toCanonicalFinding,
75
- });
76
- // No findings → no write: a fresh `generatedAt` alone would make
77
- // `--ledger-commit` open an empty PR.
78
- const wrote = Boolean(write) && findings.length > 0;
79
- if (wrote) writeLedgerImpl(path, next);
80
-
81
- return {
82
- path,
83
- written: wrote,
84
- groupsRecorded,
85
- findingsRecorded: findings.length,
86
- filed: classifications.filter((c) => c.status === 'filed').length,
87
- };
88
- }