@peer2peer/ext-ix 0.0.0-stage → 0.1.1
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/LICENSE +201 -0
- package/README.md +79 -2
- package/SPEC.md +785 -0
- package/dist/conflicts.d.ts +64 -0
- package/dist/conflicts.js +188 -0
- package/dist/extension.d.ts +45 -0
- package/dist/extension.js +615 -0
- package/dist/footprint-command.d.ts +57 -0
- package/dist/footprint-command.js +398 -0
- package/dist/footprint-compute.d.ts +106 -0
- package/dist/footprint-compute.js +559 -0
- package/dist/footprint.d.ts +162 -0
- package/dist/footprint.js +451 -0
- package/dist/hmac.d.ts +18 -0
- package/dist/hmac.js +42 -0
- package/dist/impact.d.ts +66 -0
- package/dist/impact.js +208 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +21 -0
- package/dist/ix.d.ts +158 -0
- package/dist/ix.js +420 -0
- package/dist/listener.d.ts +48 -0
- package/dist/listener.js +203 -0
- package/dist/memory.d.ts +50 -0
- package/dist/memory.js +315 -0
- package/dist/note.d.ts +40 -0
- package/dist/note.js +82 -0
- package/dist/overlap-command.d.ts +37 -0
- package/dist/overlap-command.js +81 -0
- package/dist/overlap.d.ts +83 -0
- package/dist/overlap.js +227 -0
- package/dist/repo.d.ts +36 -0
- package/dist/repo.js +116 -0
- package/dist/subgraph.d.ts +59 -0
- package/dist/subgraph.js +140 -0
- package/dist/text.d.ts +83 -0
- package/dist/text.js +187 -0
- package/dist/which.d.ts +1 -0
- package/dist/which.js +45 -0
- package/package.json +61 -4
|
@@ -0,0 +1,559 @@
|
|
|
1
|
+
// Copyright 2026 Ix Infrastructure Inc.
|
|
2
|
+
//
|
|
3
|
+
// Measuring a session's footprint with the local Ix (SPEC.md §8.2), per
|
|
4
|
+
// actor: the main loop, then each subagent in the session's status.
|
|
5
|
+
//
|
|
6
|
+
// 1. Checkout and graph. The main loop and agents editing the session's own
|
|
7
|
+
// checkout use its graph ("base"). An agent in its own git worktree uses
|
|
8
|
+
// that worktree's graph when Ix has mapped it ("worktree"), otherwise the
|
|
9
|
+
// main checkout's graph with the worktree's repo-relative paths ("base"),
|
|
10
|
+
// and its hunks on the merge base's side, which is what that graph holds.
|
|
11
|
+
// An unmapped checkout gives a file-level actor ("none").
|
|
12
|
+
// 2. Changed files: the actor's files from the status, plus (worktree
|
|
13
|
+
// agents) `git diff --name-only <merge-base>`, which catches Bash edits.
|
|
14
|
+
// 3. Changed symbols: `git diff -U0` hunks, then per file
|
|
15
|
+
// `ix impact <file> --format json --limit 50` (risk, regions, and member
|
|
16
|
+
// spans) and `ix around <file>:<start>-<end> --format json` for up to 3
|
|
17
|
+
// hunk groups (the definitions the edit touched, innermost first). A file
|
|
18
|
+
// whose edits name no symbol falls back to `ix overview`'s key items
|
|
19
|
+
// (coarse).
|
|
20
|
+
// 4. Ring 1: the callers, users, tests and importers `ix around` reports.
|
|
21
|
+
// 5. Ring 2 (depth 2): `ix around` of the first ring-1 files.
|
|
22
|
+
//
|
|
23
|
+
// Every `ix` call is bounded: at most `maxCalls` per computation, each with a
|
|
24
|
+
// timeout, all within one budget (40 s, inside p2p's 60 s command deadline);
|
|
25
|
+
// what doesn't fit is marked `partial`. Results are cached per (checkout,
|
|
26
|
+
// file, mtime, size, hunks), so an unchanged file costs no Ix call.
|
|
27
|
+
import { join } from "node:path";
|
|
28
|
+
import { FP_LIMITS, symbolKey } from "./footprint.js";
|
|
29
|
+
import { isSafeRelativePath } from "@peer2peer/core/v3";
|
|
30
|
+
import { cps, isObj, LIMITS, line, RISK_LEVELS, scrubPaths, toRepoRelative } from "./text.js";
|
|
31
|
+
export const FOOTPRINT_BUDGET_MS = 40_000;
|
|
32
|
+
export const FOOTPRINT_MAX_CALLS = 80;
|
|
33
|
+
const PER_CALL_MS = 12_000;
|
|
34
|
+
/** Files measured at once (each runs up to 4 `ix` processes together). */
|
|
35
|
+
const CONCURRENCY = 2;
|
|
36
|
+
/** Agents count while running or waiting, or for this long after their last activity. */
|
|
37
|
+
export const AGENT_RECENT_MS = 10 * 60_000;
|
|
38
|
+
const MAX_AGENTS = FP_LIMITS.actors - 1;
|
|
39
|
+
const RING2_FROM = 5;
|
|
40
|
+
const HUNK_GROUPS = 3;
|
|
41
|
+
const HUNK_GAP = 30;
|
|
42
|
+
/** Reads `git diff -U0` output (core.quotePath=false) into per-file hunks. Quoted (unusual) paths are skipped. */
|
|
43
|
+
export function parseUnifiedDiff(text) {
|
|
44
|
+
const out = new Map();
|
|
45
|
+
let cur;
|
|
46
|
+
let oldPath;
|
|
47
|
+
for (const l of text.split("\n")) {
|
|
48
|
+
if (l.startsWith("diff --git ")) {
|
|
49
|
+
cur = undefined;
|
|
50
|
+
oldPath = undefined;
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
if (l.startsWith("--- ")) {
|
|
54
|
+
oldPath = l.startsWith("--- a/") ? l.slice(6) : undefined;
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
if (l.startsWith("+++ ")) {
|
|
58
|
+
const p = l.startsWith("+++ b/") ? l.slice(6) : oldPath;
|
|
59
|
+
cur = p ? (out.get(p) ?? { old: [], new: [], added: [] }) : undefined;
|
|
60
|
+
if (p && cur)
|
|
61
|
+
out.set(p, cur);
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
const h = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/.exec(l);
|
|
65
|
+
if (h && cur) {
|
|
66
|
+
const os = Number(h[1]);
|
|
67
|
+
const oc = h[2] === undefined ? 1 : Number(h[2]);
|
|
68
|
+
const ns = Number(h[3]);
|
|
69
|
+
const nc = h[4] === undefined ? 1 : Number(h[4]);
|
|
70
|
+
// A side with no lines is the point the change sits after (at least line 1).
|
|
71
|
+
cur.old.push(oc === 0 ? { start: Math.max(1, os), end: Math.max(1, os) } : { start: os, end: os + oc - 1 });
|
|
72
|
+
cur.new.push(nc === 0 ? { start: Math.max(1, ns), end: Math.max(1, ns) } : { start: ns, end: ns + nc - 1 });
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
if (cur && l.startsWith("+") && !l.startsWith("+++") && cur.added.length < 400)
|
|
76
|
+
cur.added.push(l.slice(1));
|
|
77
|
+
}
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
80
|
+
/** At most `max` ranges: neighbours within `gap` lines merge, then the closest pairs until few enough. */
|
|
81
|
+
export function groupRanges(ranges, max = HUNK_GROUPS, gap = HUNK_GAP) {
|
|
82
|
+
const sorted = [...ranges].sort((a, b) => a.start - b.start || a.end - b.end);
|
|
83
|
+
const out = [];
|
|
84
|
+
for (const r of sorted) {
|
|
85
|
+
const last = out[out.length - 1];
|
|
86
|
+
if (last && r.start - last.end <= gap)
|
|
87
|
+
last.end = Math.max(last.end, r.end);
|
|
88
|
+
else
|
|
89
|
+
out.push({ ...r });
|
|
90
|
+
}
|
|
91
|
+
while (out.length > max) {
|
|
92
|
+
let j = 0;
|
|
93
|
+
for (let i = 1; i < out.length - 1; i++)
|
|
94
|
+
if (out[i + 1].start - out[i].end < out[j + 1].start - out[j].end)
|
|
95
|
+
j = i;
|
|
96
|
+
out.splice(j, 2, { start: out[j].start, end: Math.max(out[j].end, out[j + 1].end) });
|
|
97
|
+
}
|
|
98
|
+
return out;
|
|
99
|
+
}
|
|
100
|
+
const DIFF_ARGS = ["-c", "core.quotePath=false", "diff", "--no-color", "--no-ext-diff", "--no-textconv", "--no-renames", "-U0"];
|
|
101
|
+
class Budget {
|
|
102
|
+
ix;
|
|
103
|
+
deadline;
|
|
104
|
+
maxCalls;
|
|
105
|
+
now;
|
|
106
|
+
calls = 0;
|
|
107
|
+
partial = false;
|
|
108
|
+
constructor(ix, deadline, maxCalls, now) {
|
|
109
|
+
this.ix = ix;
|
|
110
|
+
this.deadline = deadline;
|
|
111
|
+
this.maxCalls = maxCalls;
|
|
112
|
+
this.now = now;
|
|
113
|
+
}
|
|
114
|
+
async json(argv, cwd) {
|
|
115
|
+
const left = this.deadline - this.now();
|
|
116
|
+
if (this.calls >= this.maxCalls || left < 500) {
|
|
117
|
+
this.partial = true;
|
|
118
|
+
return { ok: false, skipped: true };
|
|
119
|
+
}
|
|
120
|
+
this.calls++;
|
|
121
|
+
let r;
|
|
122
|
+
try {
|
|
123
|
+
r = await this.ix.run(argv, { cwd, timeoutMs: Math.min(PER_CALL_MS, left) });
|
|
124
|
+
}
|
|
125
|
+
catch {
|
|
126
|
+
// A timeout, or Ix vanished mid-run: this file is partial.
|
|
127
|
+
this.partial = true;
|
|
128
|
+
return { ok: false, skipped: true };
|
|
129
|
+
}
|
|
130
|
+
let parsed;
|
|
131
|
+
try {
|
|
132
|
+
parsed = JSON.parse(r.stdout);
|
|
133
|
+
}
|
|
134
|
+
catch {
|
|
135
|
+
return { ok: false };
|
|
136
|
+
}
|
|
137
|
+
if (!isObj(parsed))
|
|
138
|
+
return { ok: false };
|
|
139
|
+
if (r.code !== 0 || typeof parsed.error === "string")
|
|
140
|
+
return { ok: false, json: parsed };
|
|
141
|
+
return { ok: true, json: parsed };
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* git inside the same budget: each call's timeout is what is left of it (at most its own), and
|
|
146
|
+
* none starts once the budget is spent. A timed-out git is killed (SIGKILL), like a timed-out ix.
|
|
147
|
+
*/
|
|
148
|
+
function budgetedGit(deps, b) {
|
|
149
|
+
return async (cwd, args, o = {}) => {
|
|
150
|
+
const left = b.deadline - deps.now();
|
|
151
|
+
if (left < 500) {
|
|
152
|
+
b.partial = true;
|
|
153
|
+
return undefined;
|
|
154
|
+
}
|
|
155
|
+
return deps.git(cwd, args, { ...o, timeoutMs: Math.min(o.timeoutMs ?? 5_000, left) });
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
async function pool(items, n, f) {
|
|
159
|
+
const out = new Array(items.length);
|
|
160
|
+
let next = 0;
|
|
161
|
+
const worker = async () => {
|
|
162
|
+
while (next < items.length) {
|
|
163
|
+
const i = next++;
|
|
164
|
+
out[i] = await f(items[i], i);
|
|
165
|
+
}
|
|
166
|
+
};
|
|
167
|
+
await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker));
|
|
168
|
+
return out;
|
|
169
|
+
}
|
|
170
|
+
// ---------------------------------------------------------------------------
|
|
171
|
+
// One file
|
|
172
|
+
const rows = (sec) => (isObj(sec) && Array.isArray(sec.rows) ? sec.rows.filter(isObj) : []);
|
|
173
|
+
const num = (v) => (typeof v === "number" && Number.isSafeInteger(v) && v > 0 ? v : undefined);
|
|
174
|
+
const str = (v) => (typeof v === "string" && v.trim() !== "" ? v.trim() : undefined);
|
|
175
|
+
const kindOf = (v) => {
|
|
176
|
+
const s = str(v)?.toLowerCase().replace(/[^a-z0-9_-]/g, "_").slice(0, 32);
|
|
177
|
+
return s && /^[a-z]/.test(s) ? s : "unknown";
|
|
178
|
+
};
|
|
179
|
+
/** `name` qualified by the innermost other definition whose span holds it (Ix's `container.name`), when there is one. */
|
|
180
|
+
function qualify(d, defs) {
|
|
181
|
+
if (d.name.includes("."))
|
|
182
|
+
return d.name;
|
|
183
|
+
let best;
|
|
184
|
+
for (const o of defs) {
|
|
185
|
+
if (o === d || o.name === d.name)
|
|
186
|
+
continue;
|
|
187
|
+
const holds = o.start <= d.start && o.end >= d.end && o.end - o.start > d.end - d.start;
|
|
188
|
+
if (holds && (!best || o.end - o.start < best.end - best.start))
|
|
189
|
+
best = o;
|
|
190
|
+
}
|
|
191
|
+
return best ? `${best.name.split(".").pop()}.${d.name}` : d.name;
|
|
192
|
+
}
|
|
193
|
+
const overlaps = (d, ranges) => ranges.some((r) => d.start <= r.end && d.end >= r.start);
|
|
194
|
+
const DECL_RES = [
|
|
195
|
+
/^\s*(?:export\s+)?(?:default\s+)?(?:abstract\s+)?(?:async\s+)?(?:function\*?|class|interface|enum|type|struct|trait|def|fn|func|object|record)\s+([A-Za-z_$][\w$]*)/,
|
|
196
|
+
/^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?(?:\(|function\b)/,
|
|
197
|
+
/^\s*func\s+\([^)]*\)\s*([A-Za-z_]\w*)/,
|
|
198
|
+
/^\s*(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?fn\s+([A-Za-z_]\w*)/,
|
|
199
|
+
];
|
|
200
|
+
/** Names declared on added lines: symbols that may exist only on the new side. */
|
|
201
|
+
export function declaredNames(added) {
|
|
202
|
+
const out = [];
|
|
203
|
+
for (const l of added) {
|
|
204
|
+
for (const re of DECL_RES) {
|
|
205
|
+
const m = re.exec(l);
|
|
206
|
+
if (m) {
|
|
207
|
+
if (!out.includes(m[1]))
|
|
208
|
+
out.push(m[1]);
|
|
209
|
+
break;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
return out;
|
|
214
|
+
}
|
|
215
|
+
export function nameScrubber(roots, home, hostname) {
|
|
216
|
+
return (name, max) => {
|
|
217
|
+
const s = line(scrubPaths(name, { root: roots, home, hostname }), max).trim();
|
|
218
|
+
return s === "" ? undefined : s;
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
async function fileFootprint(b, cwd, roots, file, ranges, scrub) {
|
|
222
|
+
const rel = (p) => (typeof p === "string" ? toRepoRelative(p, roots) : undefined);
|
|
223
|
+
const res = { inGraph: false, risk: "unknown", symbols: [], ring1Files: [], ring1Symbols: [], components: [] };
|
|
224
|
+
// A path Ix would read as an option is measured at file level only.
|
|
225
|
+
if (file.startsWith("-"))
|
|
226
|
+
return { ...res, coarse: true };
|
|
227
|
+
const groups = ranges && ranges.length ? groupRanges(ranges) : [];
|
|
228
|
+
const [impact, ...arounds] = await Promise.all([
|
|
229
|
+
b.json(["impact", file, "--format", "json", "--limit", "50"], cwd),
|
|
230
|
+
...(groups.length ? groups.map((g) => b.json(["around", `${file}:${g.start}-${g.end}`, "--format", "json", "--limit", "20"], cwd)) : [b.json(["around", file, "--format", "json", "--limit", "20"], cwd)]),
|
|
231
|
+
]);
|
|
232
|
+
if ([impact, ...arounds].some((a) => !a.ok && a.skipped))
|
|
233
|
+
res.partial = true;
|
|
234
|
+
const defs = [];
|
|
235
|
+
const changed = [];
|
|
236
|
+
const addDef = (list, d) => {
|
|
237
|
+
if (!list.some((x) => x.name === d.name && x.start === d.start))
|
|
238
|
+
list.push(d);
|
|
239
|
+
};
|
|
240
|
+
if (impact.ok) {
|
|
241
|
+
res.inGraph = true;
|
|
242
|
+
const j = impact.json;
|
|
243
|
+
if (RISK_LEVELS.includes(String(j.riskLevel)))
|
|
244
|
+
res.risk = j.riskLevel;
|
|
245
|
+
for (const bkt of Array.isArray(j.propagationBuckets) ? j.propagationBuckets : []) {
|
|
246
|
+
if (!isObj(bkt))
|
|
247
|
+
continue;
|
|
248
|
+
// Region names come from the graph: scrubbed like any free text that leaves (impact.ts buildImpact).
|
|
249
|
+
const raw = str(bkt.region);
|
|
250
|
+
const n = raw ? scrub(raw, LIMITS.region) : undefined;
|
|
251
|
+
if (!n)
|
|
252
|
+
continue;
|
|
253
|
+
const kind = str(bkt.regionKind) ? kindOf(bkt.regionKind) : undefined;
|
|
254
|
+
res.components.push({ n, ...(kind ? { kind } : {}), count: Math.min(FP_LIMITS.counts, num(bkt.count) ?? 0) });
|
|
255
|
+
}
|
|
256
|
+
for (const m of Array.isArray(j.topImpactedMembers) ? j.topImpactedMembers : []) {
|
|
257
|
+
if (!isObj(m) || rel(m.path) !== file)
|
|
258
|
+
continue;
|
|
259
|
+
const raw = str(m.name);
|
|
260
|
+
const name = raw ? scrub(raw, LIMITS.symbol) : undefined;
|
|
261
|
+
const start = num(m.lineStart);
|
|
262
|
+
if (!name || name === "(unnamed)" || !start)
|
|
263
|
+
continue;
|
|
264
|
+
const d = { name, kind: kindOf(m.kind), start, end: num(m.lineEnd) ?? start };
|
|
265
|
+
addDef(defs, d);
|
|
266
|
+
if (groups.length && overlaps(d, ranges))
|
|
267
|
+
addDef(changed, d);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
for (const a of arounds) {
|
|
271
|
+
if (!a.ok)
|
|
272
|
+
continue;
|
|
273
|
+
res.inGraph = true;
|
|
274
|
+
const j = a.json;
|
|
275
|
+
for (const s of Array.isArray(j.symbols) ? j.symbols : []) {
|
|
276
|
+
if (!isObj(s))
|
|
277
|
+
continue;
|
|
278
|
+
// Only the file asked about (a row elsewhere, or outside the repo, is dropped), its name scrubbed.
|
|
279
|
+
if (s.path !== undefined && rel(s.path) !== file)
|
|
280
|
+
continue;
|
|
281
|
+
const rawName = str(s.name);
|
|
282
|
+
const name = rawName ? scrub(rawName, LIMITS.symbol) : undefined;
|
|
283
|
+
const start = num(s.lineStart);
|
|
284
|
+
if (name && start) {
|
|
285
|
+
const d = { name, kind: kindOf(s.kind), start, end: num(s.lineEnd) ?? start };
|
|
286
|
+
addDef(defs, d);
|
|
287
|
+
// With a line range, `ix around` names exactly the definitions the edit touched.
|
|
288
|
+
if (groups.length)
|
|
289
|
+
addDef(changed, d);
|
|
290
|
+
}
|
|
291
|
+
// Without hunks, only the file's importers count (the symbols it picks weren't necessarily touched).
|
|
292
|
+
if (!groups.length)
|
|
293
|
+
continue;
|
|
294
|
+
const ring = (sec, r) => {
|
|
295
|
+
for (const row of rows(sec)) {
|
|
296
|
+
const p = rel(row.path);
|
|
297
|
+
if (!p)
|
|
298
|
+
continue;
|
|
299
|
+
if (p !== file)
|
|
300
|
+
res.ring1Files.push({ f: p, rel: r });
|
|
301
|
+
const rawNm = str(row.name);
|
|
302
|
+
const nm = rawNm ? scrub(rawNm, LIMITS.symbol) : undefined;
|
|
303
|
+
if (nm && (r === "call" || r === "use")) {
|
|
304
|
+
const k = symbolKey(p, nm);
|
|
305
|
+
if (k)
|
|
306
|
+
res.ring1Symbols.push({ k, rel: r });
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
};
|
|
310
|
+
ring(s.callers, "call");
|
|
311
|
+
ring(s.users, "use");
|
|
312
|
+
ring(s.tests, "test");
|
|
313
|
+
}
|
|
314
|
+
for (const row of rows(j.importers)) {
|
|
315
|
+
const p = rel(row.path);
|
|
316
|
+
if (p && p !== file)
|
|
317
|
+
res.ring1Files.push({ f: p, rel: "import" });
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
// Innermost first, as `ix around` does: a definition around another changed one (a class around
|
|
321
|
+
// the method whose body changed) isn't itself a change to every user of it.
|
|
322
|
+
const inner = changed.filter((d) => !changed.some((o) => o !== d && d.start <= o.start && d.end >= o.end && d.end - d.start > o.end - o.start));
|
|
323
|
+
inner.sort((x, y) => x.start - y.start || (x.name < y.name ? -1 : 1));
|
|
324
|
+
for (const d of inner) {
|
|
325
|
+
const k = symbolKey(file, qualify(d, defs));
|
|
326
|
+
if (k && !res.symbols.some((s) => s.k === k))
|
|
327
|
+
res.symbols.push({ k, kind: d.kind });
|
|
328
|
+
}
|
|
329
|
+
if (res.inGraph && res.symbols.length === 0 && groups.length) {
|
|
330
|
+
// Edits that name no definition Ix knows: the file's key items, marked coarse.
|
|
331
|
+
res.coarse = true;
|
|
332
|
+
const ov = await b.json(["overview", file, "--format", "json"], cwd);
|
|
333
|
+
if (!ov.ok && ov.skipped)
|
|
334
|
+
res.partial = true;
|
|
335
|
+
if (ov.ok) {
|
|
336
|
+
for (const it of Array.isArray(ov.json.keyItems) ? ov.json.keyItems.slice(0, 10) : []) {
|
|
337
|
+
if (!isObj(it))
|
|
338
|
+
continue;
|
|
339
|
+
const rawName = str(it.name);
|
|
340
|
+
const name = rawName ? scrub(rawName, LIMITS.symbol) : undefined;
|
|
341
|
+
const k = name ? symbolKey(file, name) : undefined;
|
|
342
|
+
if (k && !res.symbols.some((s) => s.k === k))
|
|
343
|
+
res.symbols.push({ k, kind: kindOf(it.kind) });
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
if (!groups.length)
|
|
348
|
+
res.coarse = true;
|
|
349
|
+
return res;
|
|
350
|
+
}
|
|
351
|
+
const ingestTime = (j) => {
|
|
352
|
+
const t = typeof j?.lastIngestAt === "string" ? Date.parse(j.lastIngestAt) : NaN;
|
|
353
|
+
return Number.isFinite(t) ? t : undefined;
|
|
354
|
+
};
|
|
355
|
+
function diffsToRanges(diffs, files, side) {
|
|
356
|
+
const ranges = new Map();
|
|
357
|
+
const added = new Map();
|
|
358
|
+
for (const f of files) {
|
|
359
|
+
const d = diffs?.get(f);
|
|
360
|
+
if (!d)
|
|
361
|
+
continue;
|
|
362
|
+
ranges.set(f, d[side]);
|
|
363
|
+
added.set(f, d.added);
|
|
364
|
+
}
|
|
365
|
+
return { ranges, added };
|
|
366
|
+
}
|
|
367
|
+
/** Bumped whenever what a cached FileResult holds changes (v2: names scrubbed, rows outside the repo dropped). */
|
|
368
|
+
export const FILE_CACHE_VERSION = 2;
|
|
369
|
+
const cacheKey = (graph, cwd, ingest, file, st, ranges) => JSON.stringify([FILE_CACHE_VERSION, graph, cwd, ingest ?? 0, file, st?.mtimeMs ?? 0, st?.size ?? 0, ranges ?? null]);
|
|
370
|
+
async function measureActor(b, deps, spec, roots, scrub, cache) {
|
|
371
|
+
const actor = {
|
|
372
|
+
a: spec.a,
|
|
373
|
+
graph: spec.graph,
|
|
374
|
+
...(spec.wt ? { wt: true } : {}),
|
|
375
|
+
...(spec.branch ? { branch: spec.branch } : {}),
|
|
376
|
+
...(spec.base ? { base: spec.base } : {}),
|
|
377
|
+
...(spec.done ? { done: true } : {}),
|
|
378
|
+
risk: "unknown",
|
|
379
|
+
files: spec.files,
|
|
380
|
+
symbols: [],
|
|
381
|
+
ring1Files: [],
|
|
382
|
+
ring1Symbols: [],
|
|
383
|
+
components: [],
|
|
384
|
+
};
|
|
385
|
+
if (spec.graph === "none")
|
|
386
|
+
return { ...actor, coarse: true };
|
|
387
|
+
const results = await pool(spec.files, CONCURRENCY, async (file) => {
|
|
388
|
+
const st = await deps.stat(join(spec.checkout, file));
|
|
389
|
+
const ranges = spec.ranges.get(file);
|
|
390
|
+
const key = cacheKey(spec.graph, spec.ixCwd, spec.graphIngest, file, st, ranges);
|
|
391
|
+
let r = cache?.get(key);
|
|
392
|
+
if (!r) {
|
|
393
|
+
r = await fileFootprint(b, spec.ixCwd, roots, file, ranges, scrub);
|
|
394
|
+
if (!r.partial)
|
|
395
|
+
cache?.set(key, r);
|
|
396
|
+
}
|
|
397
|
+
const stale = spec.lastIngestAt !== undefined && st !== undefined && st.mtimeMs > spec.lastIngestAt;
|
|
398
|
+
return { file, r, stale };
|
|
399
|
+
});
|
|
400
|
+
const risks = [];
|
|
401
|
+
const newSyms = [];
|
|
402
|
+
for (const { file, r, stale } of results) {
|
|
403
|
+
risks.push(r.risk);
|
|
404
|
+
actor.symbols.push(...r.symbols);
|
|
405
|
+
actor.ring1Files.push(...r.ring1Files);
|
|
406
|
+
actor.ring1Symbols.push(...r.ring1Symbols);
|
|
407
|
+
actor.components.push(...r.components);
|
|
408
|
+
if (r.coarse)
|
|
409
|
+
actor.coarse = true;
|
|
410
|
+
if (r.partial)
|
|
411
|
+
actor.partial = true;
|
|
412
|
+
if (stale)
|
|
413
|
+
actor.stale = true;
|
|
414
|
+
// A symbol declared on the new side that the graph doesn't name.
|
|
415
|
+
if (spec.wantNew || !r.inGraph) {
|
|
416
|
+
const known = new Set(r.symbols.map((s) => s.k.slice(s.k.indexOf("#") + 1).split(".").pop()));
|
|
417
|
+
for (const n of declaredNames(spec.added.get(file) ?? [])) {
|
|
418
|
+
const k = known.has(n) ? undefined : symbolKey(file, n);
|
|
419
|
+
if (k && !newSyms.includes(k))
|
|
420
|
+
newSyms.push(k);
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
if (newSyms.length)
|
|
425
|
+
actor.newSymbols = newSyms.slice(0, FP_LIMITS.newSymbols);
|
|
426
|
+
const order = ["unknown", "low", "medium", "high", "critical"];
|
|
427
|
+
actor.risk = risks.reduce((m, r) => (order.indexOf(r) > order.indexOf(m) ? r : m), "unknown");
|
|
428
|
+
return actor;
|
|
429
|
+
}
|
|
430
|
+
/** Ring 2: `ix around` of the first ring-1 files (not tests): who calls, uses or imports them. */
|
|
431
|
+
async function ring2(b, spec, actor, roots) {
|
|
432
|
+
const seen = new Set([...spec.files, ...actor.ring1Files.map((x) => x.f)]);
|
|
433
|
+
const from = [...new Set(actor.ring1Files.filter((x) => x.rel !== "test").map((x) => x.f))].filter((f) => !f.startsWith("-")).slice(0, RING2_FROM);
|
|
434
|
+
const out = [];
|
|
435
|
+
const answers = await pool(from, CONCURRENCY, (f) => b.json(["around", f, "--format", "json", "--limit", "20"], spec.ixCwd));
|
|
436
|
+
for (const a of answers) {
|
|
437
|
+
if (!a.ok) {
|
|
438
|
+
if (a.skipped)
|
|
439
|
+
actor.partial = true;
|
|
440
|
+
continue;
|
|
441
|
+
}
|
|
442
|
+
const add = (p) => {
|
|
443
|
+
const r = typeof p === "string" ? toRepoRelative(p, roots) : undefined;
|
|
444
|
+
if (r && !seen.has(r)) {
|
|
445
|
+
seen.add(r);
|
|
446
|
+
out.push(r);
|
|
447
|
+
}
|
|
448
|
+
};
|
|
449
|
+
for (const s of Array.isArray(a.json.symbols) ? a.json.symbols : []) {
|
|
450
|
+
if (!isObj(s))
|
|
451
|
+
continue;
|
|
452
|
+
for (const row of [...rows(s.callers), ...rows(s.users)])
|
|
453
|
+
add(row.path);
|
|
454
|
+
}
|
|
455
|
+
for (const row of rows(a.json.importers))
|
|
456
|
+
add(row.path);
|
|
457
|
+
}
|
|
458
|
+
return out.slice(0, FP_LIMITS.ring2Files);
|
|
459
|
+
}
|
|
460
|
+
/** `git worktree list --porcelain`: worktree path by branch (refs/heads/ stripped). */
|
|
461
|
+
export function parseWorktrees(text) {
|
|
462
|
+
const out = new Map();
|
|
463
|
+
let path;
|
|
464
|
+
for (const l of text.split("\n")) {
|
|
465
|
+
if (l.startsWith("worktree "))
|
|
466
|
+
path = l.slice(9);
|
|
467
|
+
else if (l.startsWith("branch ") && path)
|
|
468
|
+
out.set(l.slice(7).replace(/^refs\/heads\//, ""), path);
|
|
469
|
+
else if (l === "")
|
|
470
|
+
path = undefined;
|
|
471
|
+
}
|
|
472
|
+
return out;
|
|
473
|
+
}
|
|
474
|
+
/** Repo-relative paths only: no control or bidi characters, no git-quoted names (`"…"`), nothing core's `files` rule refuses. */
|
|
475
|
+
const safeFiles = (fs) => [...new Set(fs.filter((f) => typeof f === "string" && !f.startsWith('"') && isSafeRelativePath(f) && cps(f) <= LIMITS.path && line(f, LIMITS.path) === f && !/[\p{Cc}\p{Cf}]/u.test(f)))];
|
|
476
|
+
/** Measures every actor (SPEC.md §8.2). Never throws for an Ix or git failure: what fails is coarse or partial. */
|
|
477
|
+
export async function computeFootprint(input, deps) {
|
|
478
|
+
const now = deps.now();
|
|
479
|
+
const b = new Budget(deps.ix, now + (input.budgetMs ?? FOOTPRINT_BUDGET_MS), input.maxCalls ?? FOOTPRINT_MAX_CALLS, deps.now);
|
|
480
|
+
const roots = [...new Set([input.root, ...(input.roots ?? [])])];
|
|
481
|
+
const root = input.root;
|
|
482
|
+
const scrub = nameScrubber(roots, input.home, input.hostname);
|
|
483
|
+
deps = { ...deps, git: budgetedGit(deps, b) };
|
|
484
|
+
const st = await b.json(["status", "--format", "json", "--root", root], root);
|
|
485
|
+
const mapped = st.ok && st.json.graphCompleted === true;
|
|
486
|
+
const rootIngest = mapped ? ingestTime(st.ok ? st.json : undefined) : undefined;
|
|
487
|
+
const specs = [];
|
|
488
|
+
const headDiff = async (files) => {
|
|
489
|
+
if (files.length === 0)
|
|
490
|
+
return undefined;
|
|
491
|
+
const out = await deps.git(root, [...DIFF_ARGS, "HEAD", "--", ...files], { maxBuffer: 4 << 20, trim: false, timeoutMs: 10_000 });
|
|
492
|
+
return out === undefined ? undefined : parseUnifiedDiff(out);
|
|
493
|
+
};
|
|
494
|
+
const mainFiles = safeFiles(input.own.files).slice(0, FP_LIMITS.files);
|
|
495
|
+
if (mainFiles.length) {
|
|
496
|
+
const { ranges, added } = diffsToRanges(await headDiff(mainFiles), mainFiles, "new");
|
|
497
|
+
specs.push({ a: "main", graph: mapped ? "base" : "none", ixCwd: root, checkout: root, files: mainFiles, ranges, added, wantNew: false, lastIngestAt: rootIngest, graphIngest: rootIngest });
|
|
498
|
+
}
|
|
499
|
+
const agents = (input.own.agents ?? [])
|
|
500
|
+
.filter((x) => /^a[1-9][0-9]{0,3}$/.test(x.id))
|
|
501
|
+
.filter((x) => x.state === "running" || x.state === "waiting" || now - x.at < AGENT_RECENT_MS)
|
|
502
|
+
.filter((x) => (x.files?.length ?? 0) > 0 || x.wt)
|
|
503
|
+
.slice(0, MAX_AGENTS);
|
|
504
|
+
let worktrees;
|
|
505
|
+
let rootHead;
|
|
506
|
+
for (const ag of agents) {
|
|
507
|
+
const done = ag.state === "done" || ag.state === "failed";
|
|
508
|
+
const files0 = safeFiles(ag.files ?? []);
|
|
509
|
+
if (!ag.wt) {
|
|
510
|
+
const files = files0.slice(0, FP_LIMITS.files);
|
|
511
|
+
const { ranges, added } = diffsToRanges(await headDiff(files), files, "new");
|
|
512
|
+
specs.push({ a: ag.id, graph: mapped ? "base" : "none", ixCwd: root, checkout: root, files, ranges, added, done, wantNew: false, lastIngestAt: rootIngest, graphIngest: rootIngest });
|
|
513
|
+
continue;
|
|
514
|
+
}
|
|
515
|
+
worktrees ??= parseWorktrees((await deps.git(root, ["worktree", "list", "--porcelain"])) ?? "");
|
|
516
|
+
rootHead ??= await deps.git(root, ["rev-parse", "HEAD"]);
|
|
517
|
+
const wtPath = ag.branch ? worktrees.get(ag.branch) : undefined;
|
|
518
|
+
if (!wtPath || !rootHead) {
|
|
519
|
+
// Its worktree isn't found here (removed, or another machine's): file level, against the base graph.
|
|
520
|
+
const files = files0.slice(0, FP_LIMITS.files);
|
|
521
|
+
specs.push({ a: ag.id, graph: mapped ? "base" : "none", ixCwd: root, checkout: root, files, ranges: new Map(), added: new Map(), wt: true, branch: ag.branch, done, wantNew: false, graphIngest: rootIngest });
|
|
522
|
+
continue;
|
|
523
|
+
}
|
|
524
|
+
const wst = await b.json(["status", "--format", "json", "--root", wtPath], wtPath);
|
|
525
|
+
const own = wst.ok && wst.json.graphCompleted === true;
|
|
526
|
+
const graph = own ? "worktree" : mapped ? "base" : "none";
|
|
527
|
+
const mb = await deps.git(wtPath, ["merge-base", "HEAD", rootHead]);
|
|
528
|
+
const base = mb && /^[0-9a-f]{7,64}$/.test(mb) ? mb : undefined;
|
|
529
|
+
const names = base ? ((await deps.git(wtPath, ["-c", "core.quotePath=false", "diff", "--name-only", "--no-renames", base])) ?? "").split("\n").filter(Boolean) : [];
|
|
530
|
+
const files = safeFiles([...files0, ...names]).slice(0, FP_LIMITS.files);
|
|
531
|
+
const raw = base && files.length ? await deps.git(wtPath, [...DIFF_ARGS, base, "--", ...files], { maxBuffer: 4 << 20, trim: false, timeoutMs: 10_000 }) : undefined;
|
|
532
|
+
// The base graph holds the merge base's lines, so its side of each hunk; the worktree's own graph, the new side.
|
|
533
|
+
const { ranges, added } = diffsToRanges(raw === undefined ? undefined : parseUnifiedDiff(raw), files, own ? "new" : "old");
|
|
534
|
+
specs.push({
|
|
535
|
+
a: ag.id,
|
|
536
|
+
graph,
|
|
537
|
+
ixCwd: own ? wtPath : root,
|
|
538
|
+
checkout: wtPath,
|
|
539
|
+
files,
|
|
540
|
+
ranges,
|
|
541
|
+
added,
|
|
542
|
+
wt: true,
|
|
543
|
+
branch: ag.branch,
|
|
544
|
+
...(base ? { base: base.slice(0, 12) } : {}),
|
|
545
|
+
done,
|
|
546
|
+
wantNew: !own,
|
|
547
|
+
lastIngestAt: own ? ingestTime(wst.ok ? wst.json : undefined) : undefined,
|
|
548
|
+
graphIngest: own ? ingestTime(wst.ok ? wst.json : undefined) : rootIngest,
|
|
549
|
+
});
|
|
550
|
+
}
|
|
551
|
+
const actors = [];
|
|
552
|
+
for (const spec of specs) {
|
|
553
|
+
const actor = await measureActor(b, deps, spec, spec.ixCwd === root ? roots : [spec.ixCwd], scrub, input.cache);
|
|
554
|
+
if (input.depth === 2 && spec.graph !== "none" && actor.ring1Files.length)
|
|
555
|
+
actor.ring2Files = await ring2(b, spec, actor, spec.ixCwd === root ? roots : [spec.ixCwd]);
|
|
556
|
+
actors.push(actor);
|
|
557
|
+
}
|
|
558
|
+
return { actors, calls: b.calls, mapped, partial: b.partial };
|
|
559
|
+
}
|