mandrel 2.74.0 → 2.76.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 (41) hide show
  1. package/.agents/audit-checklists/exceptions.md +24 -0
  2. package/.agents/docs/runbooks/mods.md +78 -16
  3. package/.agents/docs/workflows.md +2 -1
  4. package/.agents/mods/mandrel-status/hooks/register.tsx +942 -108
  5. package/.agents/mods/mandrel-status/types/index.d.ts +67 -11
  6. package/.agents/schemas/audit-exceptions-envelope.schema.json +268 -0
  7. package/.agents/schemas/audit-rules.json +43 -0
  8. package/.agents/schemas/story-progress.schema.json +48 -0
  9. package/.agents/scripts/audit-exceptions.js +145 -0
  10. package/.agents/scripts/lib/audit-exceptions/adapters/ci-gates.js +65 -0
  11. package/.agents/scripts/lib/audit-exceptions/adapters/code-allowlists.js +143 -0
  12. package/.agents/scripts/lib/audit-exceptions/adapters/dependency-audit.js +160 -0
  13. package/.agents/scripts/lib/audit-exceptions/adapters/dependency-patches.js +124 -0
  14. package/.agents/scripts/lib/audit-exceptions/adapters/dependency-pins.js +177 -0
  15. package/.agents/scripts/lib/audit-exceptions/adapters/dependency-policy.js +243 -0
  16. package/.agents/scripts/lib/audit-exceptions/adapters/index.js +30 -0
  17. package/.agents/scripts/lib/audit-exceptions/adapters/inline-suppressions.js +107 -0
  18. package/.agents/scripts/lib/audit-exceptions/adapters/sca-exceptions.js +55 -0
  19. package/.agents/scripts/lib/audit-exceptions/adapters/test-skips.js +96 -0
  20. package/.agents/scripts/lib/audit-exceptions/adapters/tool-config.js +273 -0
  21. package/.agents/scripts/lib/audit-exceptions/classify.js +64 -0
  22. package/.agents/scripts/lib/audit-exceptions/dependency-index.js +266 -0
  23. package/.agents/scripts/lib/audit-exceptions/engine.js +249 -0
  24. package/.agents/scripts/lib/audit-exceptions/globs.js +106 -0
  25. package/.agents/scripts/lib/audit-exceptions/history.js +126 -0
  26. package/.agents/scripts/lib/audit-exceptions/locate.js +59 -0
  27. package/.agents/scripts/lib/audit-exceptions/probe.js +196 -0
  28. package/.agents/scripts/lib/audit-exceptions/range-subset.js +153 -0
  29. package/.agents/scripts/lib/audit-exceptions/read.js +101 -0
  30. package/.agents/scripts/lib/audit-exceptions/record.js +102 -0
  31. package/.agents/scripts/lib/audit-exceptions/scope.js +131 -0
  32. package/.agents/scripts/lib/audit-exceptions/tickets.js +98 -0
  33. package/.agents/scripts/lib/audit-to-stories/audit-lenses.js +1 -0
  34. package/.agents/scripts/lib/config/temp-paths.js +15 -0
  35. package/.agents/scripts/lib/observability/source-classifier.js +1 -0
  36. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +24 -3
  37. package/.agents/scripts/lib/orchestration/story-handoff.js +7 -0
  38. package/.agents/scripts/lib/orchestration/story-progress.js +127 -0
  39. package/.agents/workflows/audit-exceptions.md +235 -0
  40. package/docs/CHANGELOG.md +20 -0
  41. package/package.json +1 -1
@@ -0,0 +1,196 @@
1
+ /**
2
+ * The opt-in `--probe` pass: ask each tool installed in the analysed repo which
3
+ * of its own suppressions suppress nothing — biome's unused-suppression
4
+ * diagnostics, eslint's unused disable directives, TypeScript's TS2578 and
5
+ * knip's configuration hints. Tools run read-only (no write or fix flag) from
6
+ * their package's own JS bin under the current `node`, so the pass works the
7
+ * same on Windows. An absent, failing or timed-out tool is a degradation.
8
+ *
9
+ * @module lib/audit-exceptions/probe
10
+ */
11
+
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+ import process from 'node:process';
15
+ import { spawnCaptureAsync } from '../child-exec.js';
16
+ import { readJsonc } from './read.js';
17
+
18
+ const PROBE_TIMEOUT_MS = 180_000;
19
+
20
+ const relTo = (root, file) =>
21
+ path.relative(root, path.resolve(root, file)).split(path.sep).join('/');
22
+
23
+ /** Each tool: package + bin, when it applies, its args, and how to read hits. */
24
+ const TOOLS = Object.freeze([
25
+ {
26
+ id: 'biome',
27
+ pkg: '@biomejs/biome',
28
+ bin: 'biome',
29
+ applies: (scope) =>
30
+ scope.fileSet.has('biome.json') || scope.fileSet.has('biome.jsonc'),
31
+ args: ['lint', '--reporter=github', '--max-diagnostics=none', '.'],
32
+ hits: (out, root) =>
33
+ [
34
+ ...out.matchAll(
35
+ /^::\w+ title=suppressions\/unused,file=([^,]+),line=(\d+)/gm,
36
+ ),
37
+ ].map((m) => ({
38
+ file: relTo(root, m[1]),
39
+ line: Number(m[2]),
40
+ })),
41
+ },
42
+ {
43
+ id: 'eslint',
44
+ pkg: 'eslint',
45
+ bin: 'eslint',
46
+ applies: (scope) =>
47
+ scope.files.some((f) =>
48
+ /(?:^|\/)(?:eslint\.config\.[cm]?[jt]s|\.eslintrc(?:\.\w+)?)$/.test(f),
49
+ ),
50
+ args: ['.', '--report-unused-disable-directives', '--format', 'json'],
51
+ hits: (out, root) => {
52
+ let results;
53
+ try {
54
+ results = JSON.parse(out);
55
+ } catch {
56
+ return [];
57
+ }
58
+ return results.flatMap((r) =>
59
+ (r.messages ?? [])
60
+ .filter(
61
+ (m) =>
62
+ m.ruleId === null &&
63
+ /unused eslint-disable/i.test(m.message ?? ''),
64
+ )
65
+ .map((m) => ({ file: relTo(root, r.filePath), line: m.line })),
66
+ );
67
+ },
68
+ },
69
+ {
70
+ id: 'typescript',
71
+ pkg: 'typescript',
72
+ bin: 'tsc',
73
+ applies: (scope) => scope.fileSet.has('tsconfig.json'),
74
+ args: [
75
+ '--noEmit',
76
+ '--incremental',
77
+ 'false',
78
+ '--pretty',
79
+ 'false',
80
+ '-p',
81
+ 'tsconfig.json',
82
+ ],
83
+ hits: (out, root) =>
84
+ [...out.matchAll(/^(.+?)\((\d+),\d+\): error TS2578:/gm)].map((m) => ({
85
+ file: relTo(root, m[1]),
86
+ line: Number(m[2]),
87
+ })),
88
+ },
89
+ {
90
+ id: 'knip',
91
+ pkg: 'knip',
92
+ bin: 'knip',
93
+ applies: (scope) => scope.files.some((f) => /^\.?knip\.jsonc?$/.test(f)),
94
+ args: ['--no-progress'],
95
+ hits: (out, root) =>
96
+ [...out.matchAll(/^(\S+)\s+(\S+)\s+Remove from (\w+)/gm)].map((m) => ({
97
+ file: relTo(root, m[2]),
98
+ target: m[1],
99
+ })),
100
+ },
101
+ ]);
102
+
103
+ /**
104
+ * @param {string} root
105
+ * @param {string} pkg
106
+ * @param {string} binName
107
+ * @returns {string|null} absolute path of the package's JS bin.
108
+ */
109
+ function resolveBin(root, pkg, binName) {
110
+ const dir = path.join(root, 'node_modules', pkg);
111
+ const manifest = readJsonc(dir, 'package.json');
112
+ const bin =
113
+ typeof manifest?.bin === 'string' ? manifest.bin : manifest?.bin?.[binName];
114
+ if (!bin) return null;
115
+ const abs = path.join(dir, bin);
116
+ return fs.existsSync(abs) ? abs : null;
117
+ }
118
+
119
+ function matches(record, hit) {
120
+ if (record.file !== hit.file) return false;
121
+ return hit.target === undefined
122
+ ? record.line === hit.line
123
+ : record.target === hit.target;
124
+ }
125
+
126
+ /**
127
+ * @param {object} tool
128
+ * @param {object[]} records
129
+ * @param {object} opts
130
+ * @returns {Promise<{ flagged: number, degradation: object|null }>}
131
+ */
132
+ async function runTool(tool, records, { root, timeoutMs, spawn }) {
133
+ const bin = resolveBin(root, tool.pkg, tool.bin);
134
+ if (!bin) {
135
+ return {
136
+ flagged: 0,
137
+ degradation: {
138
+ input: `probe:${tool.id}`,
139
+ reason: 'tool not installed',
140
+ detail: tool.pkg,
141
+ },
142
+ };
143
+ }
144
+ const res = await spawn(process.execPath, [bin, ...tool.args], {
145
+ cwd: root,
146
+ timeout: timeoutMs,
147
+ });
148
+ const hits = tool.hits(`${res.stdout}\n${res.stderr}`, root);
149
+ if (res.status !== 0 && hits.length === 0 && res.stdout === '') {
150
+ return {
151
+ flagged: 0,
152
+ degradation: {
153
+ input: `probe:${tool.id}`,
154
+ reason: 'tool run failed',
155
+ detail: res.stderr.slice(0, 500),
156
+ },
157
+ };
158
+ }
159
+ let flagged = 0;
160
+ for (const record of records) {
161
+ if (hits.some((h) => matches(record, h))) {
162
+ record.probe = { verdict: 'dead', basis: 'tool' };
163
+ flagged += 1;
164
+ }
165
+ }
166
+ return { flagged, degradation: null };
167
+ }
168
+
169
+ /**
170
+ * Flip every record a tool reports unused to `probe: dead (tool)`.
171
+ *
172
+ * @param {object[]} records
173
+ * @param {object} opts
174
+ * @param {string} opts.root
175
+ * @param {object} opts.scope
176
+ * @param {number} [opts.timeoutMs]
177
+ * @param {Function} [opts.spawn] - `spawnCaptureAsync` seam.
178
+ * @returns {Promise<{ tools: Array<{id: string, flagged: number}>, degradations: object[] }>}
179
+ */
180
+ export async function runProbes(
181
+ records,
182
+ { root, scope, timeoutMs = PROBE_TIMEOUT_MS, spawn = spawnCaptureAsync },
183
+ ) {
184
+ const tools = [];
185
+ const degradations = [];
186
+ for (const tool of TOOLS.filter((t) => t.applies(scope))) {
187
+ const { flagged, degradation } = await runTool(tool, records, {
188
+ root,
189
+ timeoutMs,
190
+ spawn,
191
+ });
192
+ if (degradation) degradations.push(degradation);
193
+ else tools.push({ id: tool.id, flagged });
194
+ }
195
+ return { tools, degradations };
196
+ }
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Semver-free range comparison for the dependency probes. The engine runs from
3
+ * a consumer's `node_modules`, and the runtime closure stays semver-free on
4
+ * purpose (see `lib/runtime-deps/dep-resolution.js`), so this handles only the
5
+ * shapes it can decide exactly — exact, `^`, `~`, `>=` / `>` / `<=` / `<`
6
+ * comparator sets, x-ranges and `||` unions of those — and answers `null` for
7
+ * anything else (prereleases, aliases, tags, protocols). `null` is "cannot
8
+ * decide", never "no".
9
+ *
10
+ * Each range becomes a list of half-open intervals `[lo, hi)` over
11
+ * `[major, minor, patch]` tuples; `hi` of `null` is unbounded.
12
+ *
13
+ * @module lib/audit-exceptions/range-subset
14
+ */
15
+
16
+ const VERSION_RE = /^v?(\d+|[xX*])(?:\.(\d+|[xX*]))?(?:\.(\d+|[xX*]))?$/;
17
+ const COMPARATOR_RE = /^(>=|<=|>|<|=|\^|~)?\s*(.+)$/;
18
+
19
+ /**
20
+ * @param {string} raw
21
+ * @returns {{ parts: number[], wild: number }|null} `wild` = index of the
22
+ * first wildcard / missing part (3 when fully specified).
23
+ */
24
+ function parseVersion(raw) {
25
+ const m = VERSION_RE.exec(raw.trim());
26
+ if (!m) return null;
27
+ const parts = [];
28
+ for (const p of [m[1], m[2], m[3]]) {
29
+ if (p === undefined || /^[xX*]$/.test(p)) break;
30
+ parts.push(Number(p));
31
+ }
32
+ const wild = parts.length;
33
+ while (parts.length < 3) parts.push(0);
34
+ return { parts, wild };
35
+ }
36
+
37
+ const ZERO = Object.freeze([0, 0, 0]);
38
+
39
+ function cmp(a, b) {
40
+ for (let i = 0; i < 3; i += 1) {
41
+ if (a[i] !== b[i]) return a[i] - b[i];
42
+ }
43
+ return 0;
44
+ }
45
+
46
+ /** The smallest version strictly above every version sharing `parts[0..idx)`. */
47
+ function bump(parts, idx) {
48
+ if (idx === 0) return null;
49
+ const out = parts.slice(0, idx);
50
+ out[idx - 1] += 1;
51
+ while (out.length < 3) out.push(0);
52
+ return out;
53
+ }
54
+
55
+ function nextPatch(parts) {
56
+ return [parts[0], parts[1], parts[2] + 1];
57
+ }
58
+
59
+ function caretHi({ parts, wild }) {
60
+ const firstNonZero = parts.findIndex((n, i) => n !== 0 && i < wild);
61
+ const idx = firstNonZero === -1 ? Math.max(wild, 1) : firstNonZero + 1;
62
+ return bump(parts, Math.min(idx, Math.max(wild, 1)));
63
+ }
64
+
65
+ function tildeHi({ parts, wild }) {
66
+ return bump(parts, Math.min(Math.max(wild, 1), 2));
67
+ }
68
+
69
+ /**
70
+ * @param {string} op
71
+ * @param {{ parts: number[], wild: number }} v
72
+ * @returns {{ lo: number[], hi: number[]|null }}
73
+ */
74
+ function comparatorInterval(op, v) {
75
+ const exactHi = v.wild === 3 ? nextPatch(v.parts) : bump(v.parts, v.wild);
76
+ switch (op) {
77
+ case '^':
78
+ return { lo: v.parts, hi: caretHi(v) };
79
+ case '~':
80
+ return { lo: v.parts, hi: tildeHi(v) };
81
+ case '>=':
82
+ return { lo: v.parts, hi: null };
83
+ case '>':
84
+ return { lo: exactHi ?? v.parts, hi: exactHi === null ? ZERO : null };
85
+ case '<':
86
+ return { lo: ZERO, hi: v.parts };
87
+ case '<=':
88
+ return { lo: ZERO, hi: exactHi };
89
+ default:
90
+ return { lo: v.parts, hi: exactHi };
91
+ }
92
+ }
93
+
94
+ function intersect(a, b) {
95
+ const lo = cmp(a.lo, b.lo) >= 0 ? a.lo : b.lo;
96
+ let hi = a.hi ?? b.hi;
97
+ if (a.hi && b.hi) hi = cmp(a.hi, b.hi) <= 0 ? a.hi : b.hi;
98
+ return { lo, hi };
99
+ }
100
+
101
+ /**
102
+ * @param {string} set - a space-separated comparator set (one `||` arm).
103
+ * @returns {{ lo: number[], hi: number[]|null }|null}
104
+ */
105
+ function parseSet(set) {
106
+ const tokens = set
107
+ .trim()
108
+ .replace(/([<>=^~])\s+/g, '$1')
109
+ .split(/\s+/);
110
+ let acc = { lo: ZERO, hi: null };
111
+ for (const token of tokens) {
112
+ if (token === '' || token === '*' || /^[xX]$/.test(token)) continue;
113
+ const m = COMPARATOR_RE.exec(token);
114
+ const v = m ? parseVersion(m[2]) : null;
115
+ if (!v) return null;
116
+ acc = intersect(acc, comparatorInterval(m[1] ?? '=', v));
117
+ }
118
+ return acc;
119
+ }
120
+
121
+ /**
122
+ * @param {unknown} range
123
+ * @returns {Array<{ lo: number[], hi: number[]|null }>|null}
124
+ */
125
+ function parseRange(range) {
126
+ if (typeof range !== 'string') return null;
127
+ const arms = range.split('||').map((arm) => parseSet(arm));
128
+ return arms.some((arm) => arm === null) ? null : arms;
129
+ }
130
+
131
+ function within(inner, outer) {
132
+ if (cmp(inner.lo, outer.lo) < 0) return false;
133
+ if (outer.hi === null) return true;
134
+ if (inner.hi === null) return false;
135
+ return cmp(inner.hi, outer.hi) <= 0;
136
+ }
137
+
138
+ /**
139
+ * Is every version `inner` admits also admitted by `outer`?
140
+ *
141
+ * @param {string} inner
142
+ * @param {string} outer
143
+ * @returns {boolean|null} `null` when either range is outside the supported shapes,
144
+ * or when only a union of `outer` arms could cover an `inner` arm.
145
+ */
146
+ export function rangeIsSubset(inner, outer) {
147
+ const a = parseRange(inner);
148
+ const b = parseRange(outer);
149
+ if (!a || !b) return null;
150
+ const covered = a.every((arm) => b.some((o) => within(arm, o)));
151
+ if (covered) return true;
152
+ return b.length === 1 ? false : null;
153
+ }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Tolerant readers for the `/audit-exceptions` engine. Every reader returns
3
+ * `null` on an absent or unparseable file rather than throwing: a consumer's
4
+ * malformed config is evidence to record, never a reason to abort the run.
5
+ * Nothing here evaluates code — JS-format configs are read as text only.
6
+ *
7
+ * @module lib/audit-exceptions/read
8
+ */
9
+
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import yaml from 'js-yaml';
13
+
14
+ /**
15
+ * @param {string} root
16
+ * @param {string} rel
17
+ * @returns {string|null}
18
+ */
19
+ export function readText(root, rel) {
20
+ try {
21
+ return fs.readFileSync(path.join(root, rel), 'utf8');
22
+ } catch {
23
+ return null;
24
+ }
25
+ }
26
+
27
+ /**
28
+ * Strip `//` and `/* *\/` comments plus trailing commas, outside strings, so a
29
+ * JSONC config (`biome.jsonc`, `tsconfig.json`) parses with `JSON.parse`.
30
+ *
31
+ * @param {string} text
32
+ * @returns {string}
33
+ */
34
+ function stripJsonc(text) {
35
+ let out = '';
36
+ let i = 0;
37
+ while (i < text.length) {
38
+ const ch = text[i];
39
+ if (ch === '"') {
40
+ const end = stringEnd(text, i);
41
+ out += text.slice(i, end);
42
+ i = end;
43
+ } else if (ch === '/' && text[i + 1] === '/') {
44
+ i = lineEnd(text, i);
45
+ } else if (ch === '/' && text[i + 1] === '*') {
46
+ i = blockEnd(text, i);
47
+ } else {
48
+ out += ch;
49
+ i += 1;
50
+ }
51
+ }
52
+ return out.replace(/,(\s*[}\]])/g, '$1');
53
+ }
54
+
55
+ function stringEnd(text, start) {
56
+ let i = start + 1;
57
+ while (i < text.length && text[i] !== '"') {
58
+ i += text[i] === '\\' ? 2 : 1;
59
+ }
60
+ return i + 1;
61
+ }
62
+
63
+ function lineEnd(text, start) {
64
+ const nl = text.indexOf('\n', start);
65
+ return nl === -1 ? text.length : nl;
66
+ }
67
+
68
+ function blockEnd(text, start) {
69
+ const close = text.indexOf('*/', start + 2);
70
+ return close === -1 ? text.length : close + 2;
71
+ }
72
+
73
+ /**
74
+ * @param {string} root
75
+ * @param {string} rel
76
+ * @returns {any}
77
+ */
78
+ export function readJsonc(root, rel) {
79
+ const text = readText(root, rel);
80
+ if (text === null) return null;
81
+ try {
82
+ return JSON.parse(stripJsonc(text));
83
+ } catch {
84
+ return null;
85
+ }
86
+ }
87
+
88
+ /**
89
+ * @param {string} root
90
+ * @param {string} rel
91
+ * @returns {any}
92
+ */
93
+ export function readYaml(root, rel) {
94
+ const text = readText(root, rel);
95
+ if (text === null) return null;
96
+ try {
97
+ return yaml.load(text) ?? null;
98
+ } catch {
99
+ return null;
100
+ }
101
+ }
@@ -0,0 +1,102 @@
1
+ /**
2
+ * The one normalized record shape every adapter emits, and the extraction of
3
+ * the three facts a justification can carry: the reason text, the tickets it
4
+ * cites, and an expiry date.
5
+ *
6
+ * @module lib/audit-exceptions/record
7
+ */
8
+
9
+ /** `#N`, `owner/repo#N`, or a GitHub issue / pull URL. */
10
+ const TICKET_RE =
11
+ /(?:https:\/\/github\.com\/([\w.-]+\/[\w.-]+)\/(?:issues|pull)\/(\d+))|(?:(?<![\w/&])([\w.-]+\/[\w.-]+)?#(\d+)\b)/g;
12
+
13
+ /**
14
+ * A ref only counts as what an exception waits on when a tracking word leads
15
+ * into it (`TODO(#N)`, "until #N", "tracked in #N", "remove once #N").
16
+ * Citing the Story that introduced an exception is provenance, not a
17
+ * dependency — a closed one must not make the exception read as orphaned.
18
+ */
19
+ const TRACKING_LEAD_RE =
20
+ /\b(?:todo|fixme|hack|until|track(?:ed|ing)?|blocked|pending|remove|drop|revisit|follow[- ]?up|workaround|waiting|depends|upstream)\b[^.;\n#]{0,25}$/i;
21
+
22
+ const EXPIRY_RE =
23
+ /\b(?:expires?|expiry|review[- ]by|until|revisit(?:\s+by)?)\s*[:=]?\s*(\d{4}-\d{2}-\d{2})\b/i;
24
+
25
+ /**
26
+ * @param {string|null|undefined} text
27
+ * @returns {string[]} unique tracking refs, `#N` for this repo, `owner/repo#N` otherwise.
28
+ */
29
+ function ticketRefsIn(text) {
30
+ if (typeof text !== 'string' || text.length === 0) return [];
31
+ const refs = new Set();
32
+ for (const m of text.matchAll(TICKET_RE)) {
33
+ if (!TRACKING_LEAD_RE.test(text.slice(Math.max(0, m.index - 60), m.index)))
34
+ continue;
35
+ const repo = m[1] ?? m[3] ?? '';
36
+ const num = m[2] ?? m[4];
37
+ refs.add(`${repo}#${num}`);
38
+ }
39
+ return [...refs];
40
+ }
41
+
42
+ /**
43
+ * @param {string|null|undefined} text
44
+ * @returns {string|null} ISO date
45
+ */
46
+ function expiryIn(text) {
47
+ if (typeof text !== 'string') return null;
48
+ return EXPIRY_RE.exec(text)?.[1] ?? null;
49
+ }
50
+
51
+ /**
52
+ * Normalize a justification fragment: trim punctuation-only or empty text to
53
+ * `null`, so "no reason given" has exactly one representation.
54
+ *
55
+ * @param {unknown} text
56
+ * @returns {string|null}
57
+ */
58
+ function cleanJustification(text) {
59
+ if (typeof text !== 'string') return null;
60
+ const trimmed = text
61
+ .replace(/\s+/g, ' ')
62
+ .replace(/^[\s:—–-]+|[\s*/>-]+$/g, '')
63
+ .trim();
64
+ return /[A-Za-z0-9]/.test(trimmed) ? trimmed : null;
65
+ }
66
+
67
+ /**
68
+ * @param {object} fields
69
+ * @param {string} fields.adapter
70
+ * @param {string} fields.category
71
+ * @param {string} fields.surface
72
+ * @param {string} fields.file
73
+ * @param {number} fields.line
74
+ * @param {string} fields.target - what the exception exempts (rule, package, glob, …).
75
+ * @param {string} [fields.rule] - cluster key within the adapter.
76
+ * @param {string|null} [fields.justification]
77
+ * @param {{ verdict: string, basis: string }|null} [fields.probe] - mechanical probe outcome.
78
+ * @param {string|null} [fields.permanentHint]
79
+ * @returns {object}
80
+ */
81
+ export function makeRecord(fields) {
82
+ const justification = cleanJustification(fields.justification);
83
+ return {
84
+ id: `${fields.adapter}:${fields.file}:${fields.line}:${fields.target}`,
85
+ adapter: fields.adapter,
86
+ category: fields.category,
87
+ surface: fields.surface,
88
+ file: fields.file,
89
+ line: fields.line,
90
+ target: fields.target,
91
+ rule: fields.rule ?? fields.target,
92
+ justification,
93
+ ticketRefs: ticketRefsIn(justification),
94
+ expires: expiryIn(justification),
95
+ addedAt: null,
96
+ introduced: false,
97
+ verdict: 'live',
98
+ verdictBasis: 'none',
99
+ permanentHint: fields.permanentHint ?? fields.probe?.permanentHint ?? null,
100
+ probe: fields.probe ?? null,
101
+ };
102
+ }
@@ -0,0 +1,131 @@
1
+ /**
2
+ * The file universe an `/audit-exceptions` run reads: tracked files only (so a
3
+ * gitignored local override is never read), minus vendored trees, worktrees
4
+ * and the temp root, minus the materialized `.agents/` payload in a consumer —
5
+ * a consumer cannot fix framework files, so findings there are noise to it.
6
+ *
7
+ * @module lib/audit-exceptions/scope
8
+ */
9
+
10
+ import path from 'node:path';
11
+ import picomatch from 'picomatch';
12
+ import { gitSpawn } from '../git-utils.js';
13
+ import { readJsonc, readYaml } from './read.js';
14
+
15
+ const ALWAYS_EXCLUDED = Object.freeze([
16
+ 'node_modules/',
17
+ '.worktrees/',
18
+ '.claude/worktrees/',
19
+ ]);
20
+
21
+ /** Gitignored by convention; listed so a force-added copy is still skipped. */
22
+ const LOCAL_OVERRIDE_FILES = Object.freeze([
23
+ '.agentrc.local.json',
24
+ '.agents/instructions.local.md',
25
+ ]);
26
+
27
+ /** The package that ships `.agents/`; only there is the payload source. */
28
+ const FRAMEWORK_PACKAGE = 'mandrel';
29
+
30
+ /**
31
+ * @param {string} root
32
+ * @returns {{ files: string[]|null, detail: string }}
33
+ */
34
+ function listTracked(root) {
35
+ const res = gitSpawn(root, 'ls-files', '-z');
36
+ if (res.status !== 0) return { files: null, detail: res.stderr };
37
+ return { files: res.stdout.split('\0').filter(Boolean), detail: '' };
38
+ }
39
+
40
+ /**
41
+ * @param {string[]} prefixes
42
+ * @returns {(rel: string) => boolean}
43
+ */
44
+ function excludedBy(prefixes) {
45
+ return (rel) =>
46
+ prefixes.some((p) => rel.startsWith(p)) ||
47
+ LOCAL_OVERRIDE_FILES.includes(rel) ||
48
+ rel.includes('/node_modules/');
49
+ }
50
+
51
+ /**
52
+ * Workspace globs from `package.json#workspaces` (array or `{packages}`) and
53
+ * `pnpm-workspace.yaml#packages`.
54
+ *
55
+ * @param {object|null} rootPkg
56
+ * @param {object|null} pnpmWorkspace
57
+ * @returns {string[]}
58
+ */
59
+ function workspaceGlobs(rootPkg, pnpmWorkspace) {
60
+ const ws = rootPkg?.workspaces;
61
+ const npm = Array.isArray(ws) ? ws : (ws?.packages ?? []);
62
+ const pnpm = pnpmWorkspace?.packages ?? [];
63
+ return [...npm, ...pnpm].filter(
64
+ (g) => typeof g === 'string' && !g.startsWith('!'),
65
+ );
66
+ }
67
+
68
+ /**
69
+ * Every manifest the dependency adapters read: the root plus each tracked
70
+ * `package.json` whose directory a workspace glob matches.
71
+ *
72
+ * @param {string} root
73
+ * @param {object|null} rootPkg
74
+ * @param {string[]} files
75
+ * @param {object|null} pnpmWorkspace
76
+ * @returns {Array<{ dir: string, rel: string, pkg: object }>}
77
+ */
78
+ function collectManifests(root, rootPkg, files, pnpmWorkspace) {
79
+ const manifests = rootPkg
80
+ ? [{ dir: '', rel: 'package.json', pkg: rootPkg }]
81
+ : [];
82
+ const globs = workspaceGlobs(rootPkg, pnpmWorkspace);
83
+ if (globs.length === 0) return manifests;
84
+ const isWorkspace = picomatch(globs);
85
+ for (const rel of files) {
86
+ if (path.posix.basename(rel) !== 'package.json' || rel === 'package.json')
87
+ continue;
88
+ const dir = path.posix.dirname(rel);
89
+ if (!isWorkspace(dir)) continue;
90
+ const pkg = readJsonc(root, rel);
91
+ if (pkg) manifests.push({ dir, rel, pkg });
92
+ }
93
+ return manifests;
94
+ }
95
+
96
+ /**
97
+ * @param {object} opts
98
+ * @param {string} opts.root - analysed repository root.
99
+ * @param {string} [opts.tempRel] - tempRoot relative to `root` (default `temp`).
100
+ * @returns {{ files: string[], fileSet: Set<string>, isFrameworkSource: boolean,
101
+ * manifests: Array<{dir: string, rel: string, pkg: object}>,
102
+ * pnpmWorkspace: object|null, degradations: object[] }}
103
+ */
104
+ export function buildScope({ root, tempRel = 'temp' }) {
105
+ const degradations = [];
106
+ const tracked = listTracked(root);
107
+ if (tracked.files === null) {
108
+ degradations.push({
109
+ input: 'git',
110
+ reason: 'tracked files unavailable; no file-borne exception was read',
111
+ detail: tracked.detail,
112
+ });
113
+ }
114
+ const rootPkg = readJsonc(root, 'package.json');
115
+ const isFrameworkSource = rootPkg?.name === FRAMEWORK_PACKAGE;
116
+ const prefixes = [...ALWAYS_EXCLUDED, `${tempRel.replace(/\/+$/, '')}/`];
117
+ if (!isFrameworkSource) prefixes.push('.agents/');
118
+ const isExcluded = excludedBy(prefixes);
119
+ const files = (tracked.files ?? []).filter((rel) => !isExcluded(rel));
120
+ const pnpmWorkspace = files.includes('pnpm-workspace.yaml')
121
+ ? readYaml(root, 'pnpm-workspace.yaml')
122
+ : null;
123
+ return {
124
+ files,
125
+ fileSet: new Set(files),
126
+ isFrameworkSource,
127
+ manifests: collectManifests(root, rootPkg, files, pnpmWorkspace),
128
+ pnpmWorkspace,
129
+ degradations,
130
+ };
131
+ }