@flyingrobots/footprint 0.0.0-stage → 0.6.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.
package/src/exports.ts ADDED
@@ -0,0 +1,356 @@
1
+ // The export-surface diff: which exported symbols a change added, removed or re-signed.
2
+ //
3
+ // The facts come from graft's CLI contract, `graft struct exports <base-ref> <head-ref> --json`,
4
+ // which carries `_schema` `graft.cli.struct_exports` 1.0.0 (AGENTS.md, flyingrobots/footprint#8).
5
+ // footprint binds to that exact (id, version) pair: a different version is an unavailable section
6
+ // with a stated reason, never a crash and never a silent omission. Nothing here imports a graft
7
+ // module, and nothing reaches into its dist.
8
+ //
9
+ // Reading graft's answer is `parseExportSurface`, a pure function over the parsed JSON, so the
10
+ // test suite needs no graft at all; `exportSurface` is the only part that runs a process.
11
+
12
+ import { readFileSync } from "node:fs";
13
+ import { join } from "node:path";
14
+ import { $ } from "bun";
15
+ import { canonical, sha256 } from "@flyingrobots/parley-emit";
16
+ import { SCAN_METHOD, notRunScan, scanCallSites, sitesFor, type CallSiteScan } from "./callsites.ts";
17
+ import {
18
+ MITIGATION_RULE,
19
+ SYSTEM_RULE,
20
+ SYSTEM_RULE_DETAIL,
21
+ UNASSIGNED_SYSTEM,
22
+ assignCallSite,
23
+ systemCounts,
24
+ type AssignedCallSite,
25
+ type SystemRow,
26
+ } from "./systems.ts";
27
+ import type { UnsupportedLanguage } from "./languages.ts";
28
+
29
+ export const BLAST_RADIUS_SCHEMA = JSON.parse(
30
+ readFileSync(join(import.meta.dir, "../schemas/footprint.blast_radius.schema.json"), "utf8"),
31
+ ) as Record<string, unknown>;
32
+ export const BLAST_RADIUS_TYPE = { id: "footprint.blast_radius", version: "1.1.0" } as const;
33
+
34
+ /** The one graft contract this reads. A different version is stated as unavailable. */
35
+ export const GRAFT_EXPORTS_CONTRACT = { id: "graft.cli.struct_exports", version: "1.0.0" } as const;
36
+
37
+ export type UnavailableCode =
38
+ | "graft.not_resolved"
39
+ | "graft.exports_failed"
40
+ | "graft.output_unreadable"
41
+ | "graft.schema_mismatch"
42
+ | "range.unresolved";
43
+
44
+ export interface ExportedSymbol {
45
+ readonly symbol: string;
46
+ readonly file: string;
47
+ readonly kind?: string;
48
+ readonly signature?: string;
49
+ readonly previousSignature?: string;
50
+ /**
51
+ * Where the symbol's name occurs in the tracked files at head, with file and line, the system
52
+ * that contains it and the mitigation its row carries (flyingrobots/footprint#11). Present once
53
+ * a call-site scan has been attached (`withCallSites`); absent, never `[]`, when none has, so an
54
+ * unscanned symbol can never be read as one nothing references.
55
+ */
56
+ readonly callSites?: readonly AssignedCallSite[];
57
+ }
58
+
59
+ export interface ExportSurface {
60
+ readonly base: string;
61
+ readonly head: string;
62
+ readonly added: readonly ExportedSymbol[];
63
+ readonly removed: readonly ExportedSymbol[];
64
+ readonly signatureChanged: readonly ExportedSymbol[];
65
+ /** graft's own judgement, passed through verbatim; footprint derives no semver impact. */
66
+ readonly semverImpact: string | null;
67
+ /** How the call sites on the symbols above were found, or that they were not looked for. */
68
+ readonly callSiteScan: CallSiteScan;
69
+ }
70
+
71
+ export type Exports =
72
+ | { readonly available: true; readonly surface: ExportSurface }
73
+ | { readonly available: false; readonly reason: { readonly code: UnavailableCode; readonly detail: string } };
74
+
75
+ export function unavailableExports(code: UnavailableCode, detail: string): Exports {
76
+ return { available: false, reason: { code, detail } };
77
+ }
78
+
79
+ /**
80
+ * Read graft's answer. Pure: the same JSON always gives the same surface, in the same order.
81
+ *
82
+ * Entries are sorted by file then symbol so the result's digest follows the surface rather than
83
+ * graft's internal ordering. An entry without a symbol or a file makes the whole section
84
+ * unavailable with a reason: dropping it would be a silent omission, which is worse.
85
+ */
86
+ export function parseExportSurface(value: unknown): Exports {
87
+ if (value === null || typeof value !== "object") {
88
+ return unavailableExports("graft.output_unreadable", `graft struct exports --json answered with ${value === null ? "null" : typeof value} rather than an object`);
89
+ }
90
+ const o = value as Record<string, unknown>;
91
+ const schema = o._schema as { id?: unknown; version?: unknown } | undefined;
92
+ const id = typeof schema?.id === "string" ? schema.id : null;
93
+ const version = typeof schema?.version === "string" ? schema.version : null;
94
+ if (id !== GRAFT_EXPORTS_CONTRACT.id || version !== GRAFT_EXPORTS_CONTRACT.version) {
95
+ return unavailableExports(
96
+ "graft.schema_mismatch",
97
+ `graft answered under ${id ?? "no _schema id"}@${version ?? "no version"}; footprint reads ${GRAFT_EXPORTS_CONTRACT.id}@${GRAFT_EXPORTS_CONTRACT.version} and will not guess at another`,
98
+ );
99
+ }
100
+
101
+ const lists: Array<[keyof ExportSurface & ("added" | "removed" | "signatureChanged"), string]> = [
102
+ ["added", "added"],
103
+ ["removed", "removed"],
104
+ ["signatureChanged", "changed"],
105
+ ];
106
+ const parsed: Partial<Record<"added" | "removed" | "signatureChanged", ExportedSymbol[]>> = {};
107
+ for (const [field, key] of lists) {
108
+ const raw = o[key];
109
+ if (!Array.isArray(raw)) {
110
+ return unavailableExports("graft.output_unreadable", `graft's answer carries no ${key} array; footprint reads added, removed and changed`);
111
+ }
112
+ const out: ExportedSymbol[] = [];
113
+ for (const [i, entry] of raw.entries()) {
114
+ const symbol = str((entry as Record<string, unknown> | null)?.symbol);
115
+ const file = str((entry as Record<string, unknown> | null)?.filePath);
116
+ if (symbol === null || file === null) {
117
+ return unavailableExports("graft.output_unreadable", `graft's ${key}[${i}] carries no symbol or no filePath; a symbol footprint cannot name is not reported as if it were absent`);
118
+ }
119
+ const kind = str((entry as Record<string, unknown>).kind);
120
+ const signature = str((entry as Record<string, unknown>).signature);
121
+ const previous = str((entry as Record<string, unknown>).previousSignature);
122
+ out.push({
123
+ symbol,
124
+ file,
125
+ ...(kind === null ? {} : { kind }),
126
+ ...(signature === null ? {} : { signature }),
127
+ ...(previous === null ? {} : { previousSignature: previous }),
128
+ });
129
+ }
130
+ parsed[field] = out.sort((a, b) => a.file.localeCompare(b.file) || a.symbol.localeCompare(b.symbol));
131
+ }
132
+
133
+ const base = str(o.base);
134
+ const head = str(o.head);
135
+ if (base === null || head === null) {
136
+ return unavailableExports("graft.output_unreadable", "graft's answer names no base or no head; the result would not say what was compared");
137
+ }
138
+ return {
139
+ available: true,
140
+ surface: {
141
+ base,
142
+ head,
143
+ added: parsed.added!,
144
+ removed: parsed.removed!,
145
+ signatureChanged: parsed.signatureChanged!,
146
+ semverImpact: str(o.semverImpact),
147
+ callSiteScan: notRunScan(),
148
+ },
149
+ };
150
+ }
151
+
152
+ /** The same, from the raw stdout of the command; text that is not JSON is stated, never thrown. */
153
+ export function parseExportSurfaceText(text: string): Exports {
154
+ let value: unknown;
155
+ try {
156
+ value = JSON.parse(text);
157
+ } catch (e) {
158
+ const msg = e instanceof Error ? e.message : String(e);
159
+ return unavailableExports("graft.output_unreadable", `graft struct exports --json did not answer with JSON: ${msg}`);
160
+ }
161
+ return parseExportSurface(value);
162
+ }
163
+
164
+ /**
165
+ * Run the contract. `graft` is null when it could not be resolved, which is a stated limitation
166
+ * rather than an error: enrichment is optional and the section is never omitted.
167
+ *
168
+ * A three-dot range is compared from the merge base, matching the composition's own semantics, so
169
+ * exported symbols the default branch moved elsewhere are not reported as this change's doing.
170
+ */
171
+ export async function exportSurface(graft: string | null, repo: string, range: string): Promise<Exports> {
172
+ if (graft === null) {
173
+ return unavailableExports("graft.not_resolved", "graft could not be resolved through the package dependency, PATH or FOOTPRINT_GRAFT");
174
+ }
175
+ const { head } = rangeEnds(range);
176
+ const resolved = await rangeBase(repo, range);
177
+ if (!resolved.ok) return unavailableExports("range.unresolved", `${resolved.detail}, so there is no merge base to compare the export surface from`);
178
+ const baseRef = resolved.ref;
179
+ const run = await $`${graft} --cwd ${repo} struct exports ${baseRef} ${head} --json`.quiet().nothrow();
180
+ if (run.exitCode !== 0) {
181
+ const why = run.stderr.toString().trim().split("\n")[0] ?? "(no message)";
182
+ return unavailableExports("graft.exports_failed", `graft struct exports ${baseRef} ${head} --json exited ${run.exitCode}: ${why}`);
183
+ }
184
+ return parseExportSurfaceText(run.text());
185
+ }
186
+
187
+ /**
188
+ * The ref graft is given as the base of a range: the merge base for a three-dot range, so what
189
+ * the default branch gained after the branch was cut is not attributed to the branch
190
+ * (flyingrobots/footprint#39), and the written base itself for a two-dot range. Every graft call
191
+ * in a run takes its base from here, so the sections cannot disagree about what was compared.
192
+ */
193
+ export async function rangeBase(repo: string, range: string): Promise<{ ok: true; ref: string } | { ok: false; detail: string }> {
194
+ const { base, head, threeDot } = rangeEnds(range);
195
+ if (!threeDot) return { ok: true, ref: base };
196
+ const mb = await $`git -C ${repo} merge-base ${base} ${head}`.quiet().nothrow();
197
+ const sha = mb.text().trim();
198
+ if (mb.exitCode !== 0 || sha === "") return { ok: false, detail: `git merge-base ${base} ${head} found no common commit` };
199
+ return { ok: true, ref: sha };
200
+ }
201
+
202
+ /** The two ends of a range, and whether it was written with three dots (merge-base semantics). */
203
+ export function rangeEnds(range: string): { base: string; head: string; threeDot: boolean } {
204
+ const threeDot = range.includes("...");
205
+ const [base = range, head = ""] = range.split(/\.{2,3}/);
206
+ return { base, head: head === "" ? "HEAD" : head, threeDot };
207
+ }
208
+
209
+ /**
210
+ * Attach a call-site scan to every symbol of a surface (flyingrobots#10). Pure: the same surface
211
+ * and the same scan always give the same answer.
212
+ *
213
+ * A symbol the scan ran for always gets a list, empty included -- the issue's "listed with an
214
+ * empty list, not dropped". A scan that did not run attaches nothing at all, so the wire carries
215
+ * the stated reason rather than a column of zeroes. An unavailable surface has no symbol to look
216
+ * up and passes through untouched.
217
+ */
218
+ export function withCallSites(exports: Exports, scan: CallSiteScan): Exports {
219
+ if (!exports.available) return exports;
220
+ const attach = (s: ExportedSymbol): ExportedSymbol => {
221
+ const sites = sitesFor(scan, s.symbol);
222
+ // The system and the mitigation are attached here, not in the scan, because the mitigation
223
+ // reads the symbol's declaring file and the scan is per *name*: two symbols sharing a name
224
+ // share one site list and can honestly carry different mitigations for the same `file:line`.
225
+ return sites === null ? s : { ...s, callSites: sites.map((site) => assignCallSite(s.file, site)) };
226
+ };
227
+ const s = exports.surface;
228
+ return {
229
+ available: true,
230
+ surface: {
231
+ ...s,
232
+ added: s.added.map(attach),
233
+ removed: s.removed.map(attach),
234
+ signatureChanged: s.signatureChanged.map(attach),
235
+ callSiteScan: scan,
236
+ },
237
+ };
238
+ }
239
+
240
+ /** Every symbol the surface names, in the order the result lists them. */
241
+ export function surfaceSymbols(surface: ExportSurface): readonly ExportedSymbol[] {
242
+ return [...surface.added, ...surface.removed, ...surface.signatureChanged];
243
+ }
244
+
245
+ /**
246
+ * One row per (symbol, call site) pair: what a blast-radius table is a table of
247
+ * (flyingrobots/footprint#11). Empty when no scan has been attached, which is the same thing the
248
+ * record says with `call_site_scan.available: false` -- not a claim that nothing is called.
249
+ */
250
+ export function surfaceCallSiteRows(surface: ExportSurface): readonly SystemRow[] {
251
+ const rows: SystemRow[] = [];
252
+ for (const s of surfaceSymbols(surface)) {
253
+ for (const site of s.callSites ?? []) rows.push({ symbol: s.symbol, site });
254
+ }
255
+ return rows;
256
+ }
257
+
258
+ /**
259
+ * Run the scan for a surface's symbols and attach it. The one impure step: it reads the tracked
260
+ * files of the working tree. An unavailable surface is returned unchanged and no tree is read.
261
+ */
262
+ export async function attachCallSites(exports: Exports, repo: string): Promise<Exports> {
263
+ if (!exports.available) return exports;
264
+ const scan = await scanCallSites(repo, surfaceSymbols(exports.surface).map((s) => s.symbol));
265
+ return withCallSites(exports, scan);
266
+ }
267
+
268
+ /**
269
+ * The result record. Semantic content only enters the digest, so two runs compare with one
270
+ * string. `unanalysed` is independent of `exports`: it names changed files in languages graft's
271
+ * grammars cannot parse at all, regardless of whether graft ran or what it returned
272
+ * (flyingrobots/footprint#12).
273
+ */
274
+ export function exportsRecord(range: string, exports: Exports, unanalysed: readonly UnsupportedLanguage[]): Record<string, unknown> {
275
+ const semantic = { range, exports: exportsPayload(exports), unanalysed_languages: unanalysed.map((u) => ({ ...u })) };
276
+ return { event: "result", ...semantic, digest: sha256(canonical(semantic)) };
277
+ }
278
+
279
+ function exportsPayload(exports: Exports): Record<string, unknown> {
280
+ if (!exports.available) return { available: false, reason: { ...exports.reason } };
281
+ const s = exports.surface;
282
+ const scan = s.callSiteScan;
283
+ const sites = scan.available ? surfaceSymbols(s).reduce((n, x) => n + (x.callSites?.length ?? 0), 0) : null;
284
+ return {
285
+ available: true,
286
+ base: s.base,
287
+ head: s.head,
288
+ added: s.added.map(wire),
289
+ removed: s.removed.map(wire),
290
+ signature_changed: s.signatureChanged.map(wire),
291
+ counts: {
292
+ added: s.added.length,
293
+ removed: s.removed.length,
294
+ signature_changed: s.signatureChanged.length,
295
+ // Present only when the scan ran: a count of call sites nobody looked for is not a figure.
296
+ ...(sites === null ? {} : { call_sites: sites }),
297
+ },
298
+ semver_impact: s.semverImpact,
299
+ call_site_scan: scanPayload(scan),
300
+ // Present only when the scan ran, for the same reason `counts.call_sites` is: a grouping of
301
+ // call sites nobody looked for is not a figure (flyingrobots/footprint#11).
302
+ ...(scan.available ? { call_site_systems: systemsPayload(s) } : {}),
303
+ contract: { ...GRAFT_EXPORTS_CONTRACT },
304
+ };
305
+ }
306
+
307
+ /**
308
+ * The grouping, with the rule named on it. The per-system counts are the grouping: every call site
309
+ * is in exactly one system, `(unassigned)` included, so they sum to `counts.call_sites`, and the
310
+ * system of each individual call site rides the call site itself rather than being listed twice.
311
+ */
312
+ function systemsPayload(surface: ExportSurface): Record<string, unknown> {
313
+ return {
314
+ rule: SYSTEM_RULE,
315
+ rule_detail: SYSTEM_RULE_DETAIL,
316
+ mitigation_rule: MITIGATION_RULE,
317
+ unassigned: UNASSIGNED_SYSTEM,
318
+ systems: systemCounts(surfaceCallSiteRows(surface).map((r) => r.site)).map((c) => ({ system: c.system, call_sites: c.callSites })),
319
+ };
320
+ }
321
+
322
+ /** How the call sites were found, or why they were not. Always stated, like every other section. */
323
+ function scanPayload(scan: CallSiteScan): Record<string, unknown> {
324
+ if (!scan.available) return { available: false, method: SCAN_METHOD, reason: { ...scan.reason } };
325
+ return {
326
+ available: true,
327
+ method: SCAN_METHOD,
328
+ files_scanned: scan.filesScanned,
329
+ files_skipped: { ...scan.skipped },
330
+ };
331
+ }
332
+
333
+ function wire(s: ExportedSymbol): Record<string, unknown> {
334
+ return {
335
+ symbol: s.symbol,
336
+ file: s.file,
337
+ ...(s.kind === undefined ? {} : { kind: s.kind }),
338
+ ...(s.signature === undefined ? {} : { signature: s.signature }),
339
+ ...(s.previousSignature === undefined ? {} : { previous_signature: s.previousSignature }),
340
+ ...(s.callSites === undefined
341
+ ? {}
342
+ : {
343
+ call_sites: s.callSites.map((c) => ({
344
+ file: c.file,
345
+ line: c.line,
346
+ system: c.system,
347
+ mitigation: c.mitigation,
348
+ mitigation_basis: c.mitigationBasis,
349
+ })),
350
+ }),
351
+ };
352
+ }
353
+
354
+ function str(v: unknown): string | null {
355
+ return typeof v === "string" && v !== "" ? v : null;
356
+ }
@@ -0,0 +1,95 @@
1
+ // Composition of a change. Every figure here is computed from the file list; nothing is
2
+ // estimated. A footprint that reports a number it did not derive is worse than no footprint,
3
+ // because it is believed.
4
+
5
+ import { classify, type Category } from "./classify.ts";
6
+
7
+ export interface FileChange {
8
+ readonly path: string;
9
+ readonly added: number;
10
+ readonly removed: number;
11
+ /** Binary files report no line counts. */
12
+ readonly binary: boolean;
13
+ }
14
+
15
+ export interface CategoryTotal {
16
+ readonly category: Category;
17
+ readonly files: number;
18
+ readonly added: number;
19
+ readonly removed: number;
20
+ /** Share of total changed lines, 0-100, rounded to one decimal. */
21
+ readonly share: number;
22
+ }
23
+
24
+ export interface Composition {
25
+ readonly files: number;
26
+ readonly added: number;
27
+ readonly removed: number;
28
+ readonly binaryFiles: number;
29
+ readonly byCategory: readonly CategoryTotal[];
30
+ }
31
+
32
+ const ORDER: readonly Category[] = ["source", "test", "docs", "config", "ci", "generated", "assets"];
33
+
34
+ export function compose(changes: readonly FileChange[]): Composition {
35
+ const buckets = new Map<Category, { files: number; added: number; removed: number }>();
36
+ let added = 0;
37
+ let removed = 0;
38
+ let binaryFiles = 0;
39
+
40
+ for (const change of changes) {
41
+ const category = classify(change.path);
42
+ const bucket = buckets.get(category) ?? { files: 0, added: 0, removed: 0 };
43
+ bucket.files += 1;
44
+ bucket.added += change.added;
45
+ bucket.removed += change.removed;
46
+ buckets.set(category, bucket);
47
+ added += change.added;
48
+ removed += change.removed;
49
+ if (change.binary) binaryFiles += 1;
50
+ }
51
+
52
+ const totalLines = added + removed;
53
+ const byCategory = ORDER.filter((c) => buckets.has(c)).map((category) => {
54
+ const b = buckets.get(category)!;
55
+ const lines = b.added + b.removed;
56
+ return {
57
+ category,
58
+ files: b.files,
59
+ added: b.added,
60
+ removed: b.removed,
61
+ // Guard the zero case: a pure rename or mode change has files but no lines.
62
+ share: totalLines === 0 ? 0 : Math.round((lines / totalLines) * 1000) / 10,
63
+ };
64
+ });
65
+
66
+ return { files: changes.length, added, removed, binaryFiles, byCategory };
67
+ }
68
+
69
+ /** `git diff --numstat` output. Binary files appear as `-\t-\tpath`. */
70
+ export function parseNumstat(numstat: string): FileChange[] {
71
+ const out: FileChange[] = [];
72
+ for (const line of numstat.split("\n")) {
73
+ if (line.trim() === "") continue;
74
+ const [a, r, ...rest] = line.split("\t");
75
+ if (a === undefined || r === undefined || rest.length === 0) continue;
76
+ // A rename reads `old => new`; git already gives the new path last.
77
+ const path = rest.join("\t");
78
+ const binary = a === "-" || r === "-";
79
+ out.push({
80
+ path,
81
+ added: binary ? 0 : Number.parseInt(a, 10),
82
+ removed: binary ? 0 : Number.parseInt(r, 10),
83
+ binary,
84
+ });
85
+ }
86
+ return out;
87
+ }
88
+
89
+ export function mermaidPie(composition: Composition): string {
90
+ if (composition.byCategory.length === 0) return "";
91
+ const rows = composition.byCategory
92
+ .map((c) => ` "${c.category}" : ${c.added + c.removed}`)
93
+ .join("\n");
94
+ return ["```mermaid", "pie showData", ' title Changed lines by file kind', rows, "```"].join("\n");
95
+ }
package/src/graft.ts ADDED
@@ -0,0 +1,121 @@
1
+ // Optional structural enrichment via graft.
2
+ //
3
+ // Graft classifies a changed file by what happened to its symbols, which path-based
4
+ // classification cannot do: a source file with no symbol added, removed or changed is a
5
+ // formatting change, not a behavior change.
6
+ //
7
+ // One-shot subcommands only. Never `graft serve` or `graft daemon`: footprint must not hold a
8
+ // long-lived process, and the daemon has known memory growth.
9
+
10
+ import { $ } from "bun";
11
+
12
+ export interface StructuralFile {
13
+ readonly path: string;
14
+ readonly category: "structural" | "formatting" | "test" | "docs" | "config";
15
+ readonly added?: number;
16
+ readonly removed?: number;
17
+ readonly changed?: number;
18
+ }
19
+
20
+ export interface StructuralReview {
21
+ readonly files: readonly StructuralFile[];
22
+ readonly breakingChanges: readonly string[];
23
+ readonly semverImpact?: string;
24
+ }
25
+
26
+ /**
27
+ * Find a graft executable. Checked in order so a caller can always override, and a project
28
+ * dependency beats whatever happens to be on PATH.
29
+ */
30
+ export async function resolveGraft(explicit?: string): Promise<string | null> {
31
+ if (explicit !== undefined && explicit !== "") return explicit;
32
+
33
+ // graft's exports map publishes "./package.json", so this resolves without a deep import.
34
+ try {
35
+ const pkgUrl = import.meta.resolve("@flyingrobots/graft/package.json");
36
+ const pkgPath = Bun.fileURLToPath(pkgUrl);
37
+ const pkg = await Bun.file(pkgPath).json();
38
+ const rel = typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.graft;
39
+ if (typeof rel === "string") {
40
+ const dir = pkgPath.slice(0, pkgPath.lastIndexOf("/"));
41
+ const bin = `${dir}/${rel.replace(/^\.\//, "")}`;
42
+ if (await Bun.file(bin).exists()) return bin;
43
+ }
44
+ } catch {
45
+ // Not installed as a dependency; fall through.
46
+ }
47
+
48
+ const onPath = await $`command -v graft`.quiet().nothrow();
49
+ if (onPath.exitCode === 0) {
50
+ const found = onPath.text().trim();
51
+ if (found !== "") return found;
52
+ }
53
+ return null;
54
+ }
55
+
56
+ /**
57
+ * Run `graft struct review`. Returns null rather than throwing when graft is absent or fails:
58
+ * enrichment is optional, and a missing enrichment must be reported as a limitation rather
59
+ * than failing the report.
60
+ */
61
+ export async function structuralReview(
62
+ graft: string,
63
+ repo: string,
64
+ base: string,
65
+ head: string,
66
+ ): Promise<StructuralReview | null> {
67
+ const run = await $`${graft} --cwd ${repo} struct review --base ${base} --head ${head} --json`
68
+ .quiet()
69
+ .nothrow();
70
+ if (run.exitCode !== 0) return null;
71
+ return parseStructuralReview(run.text());
72
+ }
73
+
74
+ /** Parse `graft struct review --json` output; null when it is not JSON. Pure, so a captured answer can be tested. */
75
+ export function parseStructuralReview(text: string): StructuralReview | null {
76
+ try {
77
+ const parsed = JSON.parse(text) as {
78
+ files?: Array<{ path: string; category: string; structuralChanges?: { added: number; removed: number; changed: number } }>;
79
+ breakingChanges?: unknown[];
80
+ };
81
+ const files: StructuralFile[] = (parsed.files ?? []).flatMap((f) => {
82
+ if (!isCategory(f.category)) return [];
83
+ const sc = f.structuralChanges;
84
+ return [{
85
+ path: f.path,
86
+ category: f.category,
87
+ ...(sc === undefined ? {} : { added: sc.added, removed: sc.removed, changed: sc.changed }),
88
+ }];
89
+ });
90
+ return {
91
+ files,
92
+ breakingChanges: (parsed.breakingChanges ?? []).map((b) => (typeof b === "string" ? b : JSON.stringify(b))),
93
+ };
94
+ } catch {
95
+ return null;
96
+ }
97
+ }
98
+
99
+ const CATEGORIES = new Set(["structural", "formatting", "test", "docs", "config"]);
100
+ function isCategory(v: string): v is StructuralFile["category"] {
101
+ return CATEGORIES.has(v);
102
+ }
103
+
104
+ /** How many files changed shape versus merely changed text. */
105
+ export function structuralSummary(review: StructuralReview): {
106
+ structural: number;
107
+ formatting: number;
108
+ symbolsAdded: number;
109
+ symbolsRemoved: number;
110
+ symbolsChanged: number;
111
+ } {
112
+ let structural = 0, formatting = 0, symbolsAdded = 0, symbolsRemoved = 0, symbolsChanged = 0;
113
+ for (const f of review.files) {
114
+ if (f.category === "structural") structural += 1;
115
+ if (f.category === "formatting") formatting += 1;
116
+ symbolsAdded += f.added ?? 0;
117
+ symbolsRemoved += f.removed ?? 0;
118
+ symbolsChanged += f.changed ?? 0;
119
+ }
120
+ return { structural, formatting, symbolsAdded, symbolsRemoved, symbolsChanged };
121
+ }
package/src/impact.ts ADDED
@@ -0,0 +1,109 @@
1
+ // The Impact and Data flow columns of the call-site tables (flyingrobots/footprint#59).
2
+ //
3
+ // footprint cannot know what a change does at a call site at run time: it reports and does not
4
+ // judge (AGENTS.md), and its call sites are a whole-word scan. The agent running the skill can,
5
+ // by reading the code, and supplies its reading with `--impact <file>`: one JSON object per line,
6
+ //
7
+ // {"symbol": "...", "system": "...", "file": "...", "impact": "...", "dataFlow": "..."}
8
+ //
9
+ // with `file` optional. footprint renders the text in the `--human` tables, labelled as the
10
+ // agent's reading, and never puts it in a result line: those stay footprint's measurement.
11
+ import type { SystemRow } from "./systems.ts";
12
+
13
+ /**
14
+ * The two column headers, in one place. The owner named "impact"; "Data flow" is the
15
+ * coordinator's reading of the second column (flyingrobots/footprint#59) and may be renamed here.
16
+ */
17
+ export const IMPACT_COLUMNS = { impact: "Impact", dataFlow: "Data flow" } as const;
18
+
19
+ /** What a row no entry covers says: never blank, never invented. */
20
+ export const NOT_ASSESSED = "not assessed";
21
+
22
+ export const IMPACT_NOTE =
23
+ `<sub>**${IMPACT_COLUMNS.impact}** and **${IMPACT_COLUMNS.dataFlow}** are the reading of the agent that posted this report, from the code at this head, ` +
24
+ `not footprint's measurement: footprint found the call sites and cannot see run-time behaviour. \`${NOT_ASSESSED}\` marks a row the agent did not assess.</sub>`;
25
+
26
+ export interface ImpactEntry {
27
+ readonly symbol: string;
28
+ readonly system: string;
29
+ readonly file?: string;
30
+ readonly impact: string;
31
+ readonly dataFlow: string;
32
+ }
33
+
34
+ export interface Assessment {
35
+ readonly impact: string;
36
+ readonly dataFlow: string;
37
+ }
38
+
39
+ const KEYS = new Set(["symbol", "system", "file", "impact", "dataFlow"]);
40
+ const REQUIRED = ["symbol", "system", "impact", "dataFlow"] as const;
41
+
42
+ export type ParsedImpact = { readonly ok: true; readonly entries: readonly ImpactEntry[] } | { readonly ok: false; readonly line: number; readonly problem: string };
43
+
44
+ /** One JSON object per line; blank lines are skipped. Line numbers are 1-based. */
45
+ export function parseImpact(text: string): ParsedImpact {
46
+ const entries: ImpactEntry[] = [];
47
+ const seen = new Set<string>();
48
+ const lines = text.split(/\r?\n/);
49
+ for (let i = 0; i < lines.length; i++) {
50
+ const raw = lines[i]!;
51
+ if (raw.trim() === "") continue;
52
+ const line = i + 1;
53
+ let v: unknown;
54
+ try {
55
+ v = JSON.parse(raw);
56
+ } catch (e) {
57
+ return { ok: false, line, problem: `not JSON: ${e instanceof Error ? e.message : String(e)}` };
58
+ }
59
+ if (typeof v !== "object" || v === null || Array.isArray(v)) return { ok: false, line, problem: "not a JSON object" };
60
+ const o = v as Record<string, unknown>;
61
+ const unknown = Object.keys(o).filter((k) => !KEYS.has(k));
62
+ if (unknown.length > 0) return { ok: false, line, problem: `unknown key${unknown.length === 1 ? "" : "s"} ${unknown.join(", ")}; the keys are ${[...KEYS].join(", ")}` };
63
+ for (const k of [...REQUIRED, ...("file" in o ? (["file"] as const) : [])]) {
64
+ if (typeof o[k] !== "string" || (o[k] as string).trim() === "") return { ok: false, line, problem: `${k} must be a non-empty string` };
65
+ }
66
+ const entry = o as unknown as ImpactEntry;
67
+ const key = keyOf(entry.symbol, entry.system, entry.file);
68
+ if (seen.has(key)) return { ok: false, line, problem: `a second entry for symbol ${entry.symbol} in ${entry.system}${entry.file === undefined ? "" : ` at ${entry.file}`}` };
69
+ seen.add(key);
70
+ entries.push(entry);
71
+ }
72
+ return { ok: true, entries };
73
+ }
74
+
75
+ function keyOf(symbol: string, system: string, file: string | undefined): string {
76
+ return JSON.stringify([symbol, system, file ?? null]);
77
+ }
78
+
79
+ /** The entries, looked up by call-site row. */
80
+ export interface ImpactIndex {
81
+ readonly entries: readonly ImpactEntry[];
82
+ /** The row's assessment: the entry for its file, else the one for its system, else none. */
83
+ forRow(symbol: string, system: string, file: string): Assessment | null;
84
+ /** The system-wide entry for a symbol, which is what a summarised symbol's row shows. */
85
+ forSystem(symbol: string, system: string): Assessment | null;
86
+ }
87
+
88
+ export function impactIndex(entries: readonly ImpactEntry[]): ImpactIndex {
89
+ const by = new Map(entries.map((e) => [keyOf(e.symbol, e.system, e.file), e] as const));
90
+ const get = (k: string) => {
91
+ const e = by.get(k);
92
+ return e === undefined ? null : { impact: e.impact, dataFlow: e.dataFlow };
93
+ };
94
+ return {
95
+ entries,
96
+ forRow: (symbol, system, file) => get(keyOf(symbol, system, file)) ?? get(keyOf(symbol, system, undefined)),
97
+ forSystem: (symbol, system) => get(keyOf(symbol, system, undefined)),
98
+ };
99
+ }
100
+
101
+ /** The entries that cover no call-site row at all: a typo, or a symbol this head no longer has. */
102
+ export function unmatchedEntries(index: ImpactIndex, rows: readonly SystemRow[]): ImpactEntry[] {
103
+ const present = new Set<string>();
104
+ for (const r of rows) {
105
+ present.add(keyOf(r.symbol, r.site.system, r.site.file));
106
+ present.add(keyOf(r.symbol, r.site.system, undefined));
107
+ }
108
+ return index.entries.filter((e) => !present.has(keyOf(e.symbol, e.system, e.file)));
109
+ }