mandrel 2.69.0 → 2.71.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 (76) hide show
  1. package/.agents/README.md +8 -9
  2. package/.agents/agents/acceptance-critic.md +1 -0
  3. package/.agents/agents/auditor.md +1 -0
  4. package/.agents/agents/plan-critic.md +1 -0
  5. package/.agents/agents/story-worker.md +63 -64
  6. package/.agents/docs/agentrc-reference.json +2 -1
  7. package/.agents/docs/configuration.md +7 -8
  8. package/.agents/rules/git-conventions-reference.md +2 -2
  9. package/.agents/schemas/agentrc.schema.json +19 -2
  10. package/.agents/scripts/acceptance-eval.js +194 -15
  11. package/.agents/scripts/audit-to-stories.js +39 -247
  12. package/.agents/scripts/deliver-run.js +92 -43
  13. package/.agents/scripts/lib/audit-suite/index.js +1 -1
  14. package/.agents/scripts/lib/audit-suite/story-checklist.js +65 -0
  15. package/.agents/scripts/lib/audit-to-stories/audit-label-taxonomy.js +2 -2
  16. package/.agents/scripts/lib/audit-to-stories/finding-adapter.js +1 -1
  17. package/.agents/scripts/lib/bootstrap/issue-forms-template.js +1 -1
  18. package/.agents/scripts/lib/cli-args.js +22 -0
  19. package/.agents/scripts/lib/close-validation/gates.js +17 -3
  20. package/.agents/scripts/lib/config/agent-models.js +117 -0
  21. package/.agents/scripts/lib/config-settings-schema-delivery.js +13 -1
  22. package/.agents/scripts/lib/config-settings-schema-quality.js +1 -1
  23. package/.agents/scripts/lib/findings/route-finding.js +15 -0
  24. package/.agents/scripts/lib/generated/agentrc-validator.js +1 -1
  25. package/.agents/scripts/lib/git/sync-from-base.js +89 -17
  26. package/.agents/scripts/lib/label-taxonomy.js +13 -3
  27. package/.agents/scripts/lib/notifications/notifier.js +11 -15
  28. package/.agents/scripts/lib/observability/close-telemetry.js +19 -3
  29. package/.agents/scripts/lib/observability/source-classifier.js +1 -0
  30. package/.agents/scripts/lib/orchestration/code-review.js +2 -2
  31. package/.agents/scripts/lib/orchestration/file-assumptions.js +45 -11
  32. package/.agents/scripts/lib/orchestration/plan-context.js +31 -11
  33. package/.agents/scripts/lib/orchestration/plan-persist/audit-provenance.js +35 -117
  34. package/.agents/scripts/lib/orchestration/plan-persist/changes-repair.js +130 -24
  35. package/.agents/scripts/lib/orchestration/plan-persist/run-plan-persist.js +24 -22
  36. package/.agents/scripts/lib/orchestration/plan-persist/story-ops.js +1 -0
  37. package/.agents/scripts/lib/orchestration/plan-persist/summary.js +4 -3
  38. package/.agents/scripts/lib/orchestration/resolve-stories.js +10 -2
  39. package/.agents/scripts/lib/orchestration/review-providers/native.js +5 -165
  40. package/.agents/scripts/lib/orchestration/single-story-close/failed-terminal.js +14 -2
  41. package/.agents/scripts/lib/orchestration/single-story-close/phases/base-sync.js +151 -56
  42. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +4 -0
  43. package/.agents/scripts/lib/orchestration/single-story-close/phases/options.js +20 -4
  44. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +26 -17
  45. package/.agents/scripts/lib/orchestration/story-handoff.js +849 -0
  46. package/.agents/scripts/lib/orchestration/story-init-result.js +83 -0
  47. package/.agents/scripts/lib/orchestration/task-body-validator.js +35 -5
  48. package/.agents/scripts/lib/orchestration/ticket-validator-sizing.js +1 -1
  49. package/.agents/scripts/lib/orchestration/ticket-validator.js +20 -2
  50. package/.agents/scripts/lib/single-story/confirm-merge.js +44 -7
  51. package/.agents/scripts/lib/story-body/story-body.js +40 -5
  52. package/.agents/scripts/lib/templates/decomposer-prompts.js +33 -36
  53. package/.agents/scripts/single-story-close.js +8 -0
  54. package/.agents/scripts/single-story-init.js +17 -32
  55. package/.agents/scripts/story-handoff.js +112 -0
  56. package/.agents/scripts/sync-claude-agents.js +58 -27
  57. package/.agents/templates/docs/audit-sweep-runbook.md +29 -59
  58. package/.agents/workflows/audit-to-stories.md +40 -67
  59. package/.agents/workflows/helpers/acceptance-self-eval.md +24 -18
  60. package/.agents/workflows/helpers/code-review.md +3 -3
  61. package/.agents/workflows/helpers/deliver-digest.md +79 -80
  62. package/.agents/workflows/helpers/deliver-light.md +9 -7
  63. package/.agents/workflows/helpers/deliver-reference.md +38 -22
  64. package/.agents/workflows/helpers/deliver-story-reference.md +11 -9
  65. package/.agents/workflows/helpers/deliver-story.md +30 -23
  66. package/.agents/workflows/helpers/plan-reference.md +24 -9
  67. package/docs/CHANGELOG.md +30 -0
  68. package/lib/cli/registry.js +7 -0
  69. package/lib/migrations/index.js +2 -0
  70. package/lib/migrations/steps/2.70.0-retire-audit-ledger.js +36 -0
  71. package/package.json +4 -3
  72. package/.agents/scripts/lib/audit-to-stories/ledger-commit.js +0 -184
  73. package/.agents/scripts/lib/audit-to-stories/ledger-pr.js +0 -279
  74. package/.agents/scripts/lib/audit-to-stories/ledger-record.js +0 -88
  75. package/.agents/scripts/lib/findings/audit-ledger.js +0 -289
  76. package/.agents/scripts/lib/orchestration/review-providers/scoped-lint.js +0 -272
@@ -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
- }
@@ -1,289 +0,0 @@
1
- /**
2
- * lib/findings/audit-ledger.js — committed cross-run memory of audit
3
- * findings, keyed by fingerprint and `semanticKey`. Status: `new` · `filed` ·
4
- * `fixed` · `accepted-risk` (closed `not_planned`; suppressed) · `regressed`.
5
- */
6
-
7
- import nodeFs from 'node:fs';
8
- import nodePath from 'node:path';
9
- import { fingerprintFinding, semanticKeyFor } from './route-finding.js';
10
-
11
- export const DEFAULT_LEDGER_PATH = 'baselines/audit-ledger.json';
12
- const LEDGER_SCHEMA_URL =
13
- 'https://mandrel.dev/baselines/audit-ledger.schema.json';
14
-
15
- /**
16
- * @param {string} [now] — ISO timestamp to stamp.
17
- * @returns {{ $schema: string, generatedAt: string, entries: [] }}
18
- */
19
- function createEmptyLedger(now = new Date().toISOString()) {
20
- return { $schema: LEDGER_SCHEMA_URL, generatedAt: now, entries: [] };
21
- }
22
-
23
- /**
24
- * `toCanonical` is injected: importing the audit adapter would close a cycle.
25
- *
26
- * @param {object} finding
27
- * @param {(finding: object) => object} [toCanonical]
28
- * @returns {{ fingerprint: string, semanticKey: string }}
29
- */
30
- function findingIdentity(finding, toCanonical) {
31
- const canonical = toCanonical ? toCanonical(finding) : finding;
32
- return {
33
- fingerprint: fingerprintFinding(canonical).full,
34
- semanticKey: semanticKeyFor(canonical),
35
- };
36
- }
37
-
38
- /**
39
- * An absent or unparseable file reads as an empty ledger, never an error.
40
- * @param {string} filePath
41
- * @param {{ fs?: typeof import('node:fs') }} [deps]
42
- * @returns {{ $schema?: string, generatedAt?: string, entries: object[] }}
43
- */
44
- export function readLedger(filePath, { fs } = {}) {
45
- const fsLike = fs ?? nodeFs;
46
- if (!fsLike || !fsLike.existsSync(filePath)) return createEmptyLedger();
47
- try {
48
- const parsed = JSON.parse(fsLike.readFileSync(filePath, 'utf8'));
49
- if (!parsed || !Array.isArray(parsed.entries)) return createEmptyLedger();
50
- return parsed;
51
- } catch (_) {
52
- return createEmptyLedger();
53
- }
54
- }
55
-
56
- /**
57
- * @param {string} filePath
58
- * @param {object} ledger
59
- * @param {{ fs?: typeof import('node:fs'), path?: typeof import('node:path') }} [deps]
60
- */
61
- export function writeLedger(filePath, ledger, { fs, path } = {}) {
62
- const fsLike = fs ?? nodeFs;
63
- const pathLike = path ?? nodePath;
64
- if (!fsLike) return;
65
- fsLike.mkdirSync(pathLike.dirname(filePath), { recursive: true });
66
- fsLike.writeFileSync(filePath, `${JSON.stringify(ledger, null, 2)}\n`);
67
- }
68
-
69
- /**
70
- * @param {{ entries?: object[] }} ledger
71
- */
72
- function indexLedger(ledger) {
73
- const byFingerprint = new Map();
74
- const bySemanticKey = new Map();
75
- for (const entry of ledger?.entries ?? []) {
76
- if (entry?.fingerprint) byFingerprint.set(entry.fingerprint, entry);
77
- if (entry?.semanticKey) bySemanticKey.set(entry.semanticKey, entry);
78
- }
79
- return { byFingerprint, bySemanticKey };
80
- }
81
-
82
- /**
83
- * An `issueStates` override beats the recorded Issue.
84
- * @param {{ fingerprint: string, semanticKey: string }} id
85
- * @param {object|null} existing
86
- * @param {Record<string, { state?: string, stateReason?: string|null, number?: number }>} issueStates
87
- * @returns {{ state: string, stateReason: string|null, number: number|null }|null}
88
- */
89
- function resolveIssueState(id, existing, issueStates) {
90
- const override = issueStates[id.fingerprint] ?? issueStates[id.semanticKey];
91
- const raw = override ?? existing?.issue ?? null;
92
- if (!raw) return null;
93
- return {
94
- state: (raw.state ?? '').toLowerCase(),
95
- stateReason: raw.stateReason ? String(raw.stateReason).toLowerCase() : null,
96
- number: typeof raw.number === 'number' ? raw.number : null,
97
- };
98
- }
99
-
100
- /**
101
- * @type {Record<string, { status: string, action: string }>}
102
- */
103
- const VERDICT = Object.freeze({
104
- filed: Object.freeze({ status: 'filed', action: 'known' }),
105
- propose: Object.freeze({ status: 'new', action: 'propose' }),
106
- suppress: Object.freeze({ status: 'accepted-risk', action: 'suppress' }),
107
- regressed: Object.freeze({ status: 'regressed', action: 'regressed' }),
108
- });
109
-
110
- /**
111
- * The whole reconciliation policy.
112
- * @param {object|null} existing — prior ledger entry (or null when unseen).
113
- * @param {{ state: string, stateReason: string|null }|null} issue
114
- * @returns {{ status: string, action: 'propose'|'known'|'suppress'|'regressed' }}
115
- */
116
- function decideStatus(existing, issue) {
117
- // A closed Issue outranks any recorded status.
118
- if (issue && issue.state === 'closed') {
119
- return issue.stateReason === 'not_planned'
120
- ? VERDICT.suppress
121
- : VERDICT.regressed;
122
- }
123
-
124
- // An open Issue means filed even with no prior entry.
125
- const unseen = issue?.state === 'open' ? VERDICT.filed : VERDICT.propose;
126
- if (!existing) return unseen;
127
-
128
- switch (existing.status) {
129
- case 'accepted-risk':
130
- return VERDICT.suppress;
131
- case 'filed':
132
- return VERDICT.filed;
133
- // Recorded fixed yet detected again: a regression, open Issue or not.
134
- case 'fixed':
135
- return VERDICT.regressed;
136
- case 'regressed':
137
- return VERDICT.regressed;
138
- default:
139
- return unseen;
140
- }
141
- }
142
-
143
- /**
144
- * Fold a scan and live Issue states onto the prior ledger; untouched entries
145
- * are preserved.
146
- *
147
- * @param {object} params
148
- * @param {{ entries?: object[] }} [params.ledger]
149
- * @param {Array<object>} params.findings
150
- * @param {Record<string, { state?: string, stateReason?: string|null, number?: number }>} [params.issueStates]
151
- * @param {string} [params.now]
152
- * @param {(finding: object) => object} [params.toCanonical]
153
- * @returns {{
154
- * ledger: { $schema: string, generatedAt: string, entries: object[] },
155
- * classifications: Array<{ fingerprint: string, semanticKey: string, status: string, action: string, issue: object|null }>,
156
- * }}
157
- */
158
- export function reconcileLedger({
159
- ledger = createEmptyLedger(),
160
- findings,
161
- issueStates = {},
162
- now = new Date().toISOString(),
163
- toCanonical,
164
- } = {}) {
165
- if (!Array.isArray(findings)) {
166
- throw new Error('reconcileLedger: findings must be an array');
167
- }
168
-
169
- const { byFingerprint, bySemanticKey } = indexLedger(ledger);
170
- const nextByFingerprint = new Map(byFingerprint);
171
- const classifications = [];
172
-
173
- for (const finding of findings) {
174
- const id = findingIdentity(finding, toCanonical);
175
- const existing =
176
- byFingerprint.get(id.fingerprint) ??
177
- (id.semanticKey ? bySemanticKey.get(id.semanticKey) : undefined) ??
178
- null;
179
-
180
- const issue = resolveIssueState(id, existing, issueStates);
181
- const { status, action } = decideStatus(existing, issue);
182
-
183
- const entry = {
184
- fingerprint: id.fingerprint,
185
- semanticKey: id.semanticKey,
186
- title: finding?.title ?? existing?.title ?? '',
187
- dimension: finding?.dimension ?? existing?.dimension ?? '',
188
- primaryFile:
189
- (Array.isArray(finding?.files) && finding.files[0]) ??
190
- existing?.primaryFile ??
191
- '',
192
- status,
193
- issue: issue
194
- ? {
195
- number: issue.number,
196
- state: issue.state,
197
- stateReason: issue.stateReason,
198
- }
199
- : (existing?.issue ?? null),
200
- firstSeen: existing?.firstSeen ?? now,
201
- lastSeen: now,
202
- };
203
-
204
- // Re-key a reworded finding matched by semanticKey.
205
- if (existing?.fingerprint && existing.fingerprint !== id.fingerprint) {
206
- nextByFingerprint.delete(existing.fingerprint);
207
- }
208
- nextByFingerprint.set(id.fingerprint, entry);
209
-
210
- classifications.push({
211
- fingerprint: id.fingerprint,
212
- semanticKey: id.semanticKey,
213
- status,
214
- action,
215
- issue: entry.issue,
216
- });
217
- }
218
-
219
- return {
220
- ledger: {
221
- $schema: ledger?.$schema ?? LEDGER_SCHEMA_URL,
222
- generatedAt: now,
223
- entries: [...nextByFingerprint.values()],
224
- },
225
- classifications,
226
- };
227
- }
228
-
229
- /**
230
- * Record identity strings (`plan-persist` has no findings) as filed. An
231
- * identity whose Issue is closed is skipped, so its verdict survives.
232
- *
233
- * @param {object} params
234
- * @param {{ entries?: object[] }} [params.ledger]
235
- * @param {Array<{ fingerprint: string, semanticKey?: string, title?: string, dimension?: string, primaryFile?: string }>} params.identities
236
- * @param {{ number: number }} params.issue
237
- * @param {string} [params.now]
238
- * @returns {{ ledger: object, recorded: number, skipped: number }}
239
- */
240
- export function recordFiledIdentities({
241
- ledger = createEmptyLedger(),
242
- identities,
243
- issue,
244
- now = new Date().toISOString(),
245
- } = {}) {
246
- if (!Array.isArray(identities)) {
247
- throw new Error('recordFiledIdentities: identities must be an array');
248
- }
249
- if (!issue || typeof issue.number !== 'number') {
250
- throw new Error('recordFiledIdentities: issue.number must be a number');
251
- }
252
-
253
- const { byFingerprint } = indexLedger(ledger);
254
- const next = new Map(byFingerprint);
255
- let recorded = 0;
256
- let skipped = 0;
257
-
258
- for (const identity of identities) {
259
- const fingerprint = identity?.fingerprint;
260
- if (typeof fingerprint !== 'string' || fingerprint.length === 0) continue;
261
- const existing = byFingerprint.get(fingerprint) ?? null;
262
- if (existing?.issue && existing.issue.state === 'closed') {
263
- skipped += 1;
264
- continue;
265
- }
266
- next.set(fingerprint, {
267
- fingerprint,
268
- semanticKey: identity.semanticKey ?? existing?.semanticKey ?? '',
269
- title: identity.title ?? existing?.title ?? '',
270
- dimension: identity.dimension ?? existing?.dimension ?? '',
271
- primaryFile: identity.primaryFile ?? existing?.primaryFile ?? '',
272
- status: 'filed',
273
- issue: { number: issue.number, state: 'open', stateReason: null },
274
- firstSeen: existing?.firstSeen ?? now,
275
- lastSeen: now,
276
- });
277
- recorded += 1;
278
- }
279
-
280
- return {
281
- ledger: {
282
- $schema: ledger?.$schema ?? LEDGER_SCHEMA_URL,
283
- generatedAt: now,
284
- entries: [...next.values()],
285
- },
286
- recorded,
287
- skipped,
288
- };
289
- }