@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.
@@ -0,0 +1,57 @@
1
+ import type { ExtAudience, ExtCommand, ExtContext } from "@peer2peer/cli";
2
+ import type { Deps, Here } from "./extension.js";
3
+ import { type FootprintBody, type FpNames } from "./footprint.js";
4
+ import { type NameKey } from "./hmac.js";
5
+ import { type IxRunner } from "./ix.js";
6
+ import { type RepoRef } from "./repo.js";
7
+ /** At most one computation per session this often (SPEC §8.4). */
8
+ export declare const FOOTPRINT_MIN_INTERVAL_MS = 30000;
9
+ /** An unchanged footprint is republished this often, so it stays live at the receivers. */
10
+ export declare const FOOTPRINT_KEEPALIVE_MS: number;
11
+ export interface FootprintConfig {
12
+ /** The default for every session (otherwise decided by the audience). */
13
+ names?: FpNames;
14
+ /** Per circle (cid). */
15
+ circles?: Record<string, FpNames>;
16
+ }
17
+ /**
18
+ * Plain or hashed names (SPEC §8.6). Hashed is the default for every audience. Plain only by the
19
+ * person's explicit choice, most specific first: --names, P2P_IX_FOOTPRINT_NAMES, then
20
+ * `p2p ix config --circle <cid> names=…` for the session's circle, then `p2p ix config names=…`.
21
+ * An open circle takes plain only from its own circle setting (or --names / the variable), never
22
+ * from the global one. An audience that can't be read (no roster yet, a circle that can't be
23
+ * loaded, an older p2p) gets no circle setting and no global plain: hashed (fail closed).
24
+ */
25
+ export declare function footprintNames(o: {
26
+ flag?: unknown;
27
+ env?: string;
28
+ config?: FootprintConfig;
29
+ audience: ExtAudience | undefined | null;
30
+ }): {
31
+ names: FpNames;
32
+ why: string;
33
+ };
34
+ /**
35
+ * The person's footprint settings. A setting that makes names plain counts only when the store
36
+ * carries a MAC over the settings keyed by this device's secret (ExtContext.localMac), which
37
+ * `p2p ix config` writes: an edit of the store by file tools, or settings copied from another
38
+ * device or circle, can't opt into plain names. Not a boundary against something that runs
39
+ * `p2p ix config` as the user (SPEC §8.6). Hashed settings need no MAC (they only narrow what is
40
+ * shared).
41
+ */
42
+ export declare function readConfig(ctx: ExtContext): Promise<FootprintConfig & {
43
+ unverified?: true;
44
+ }>;
45
+ /** This session's readable body; sessions no longer live on this device (`live`) are pruned. */
46
+ export declare function readMine(ctx: ExtContext, sid: string, live?: readonly string[]): Promise<FootprintBody | undefined>;
47
+ /** The repository's name key, or why there is none (SPEC §8.6): no root commit, or a shallow clone. */
48
+ export declare function repoNameKey(root: string, ref: RepoRef, env: NodeJS.ProcessEnv): Promise<{
49
+ key: NameKey;
50
+ } | {
51
+ why: string;
52
+ }>;
53
+ export interface FootprintHelpers {
54
+ runner(ctx: ExtContext, deps: Deps, sid?: string): IxRunner;
55
+ repoOf(ctx: ExtContext): Promise<Here>;
56
+ }
57
+ export declare function footprintCommands(deps: Deps, h: FootprintHelpers): ExtCommand[];
@@ -0,0 +1,398 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // `p2p ix footprint` and `p2p ix config` (SPEC.md §8): computing this
4
+ // session's footprint from the local Ix and publishing it as the session's
5
+ // x:ix.footprint state, to the session's status audience only.
6
+ import { createHash, timingSafeEqual } from "node:crypto";
7
+ import { stat } from "node:fs/promises";
8
+ import { homedir, hostname } from "node:os";
9
+ import { assembleFootprint, footprintDigest, FOOTPRINT_KIND, FP_NAMES } from "./footprint.js";
10
+ import { computeFootprint } from "./footprint-compute.js";
11
+ import { deriveNameKey, pickRootCommit } from "./hmac.js";
12
+ import { ixAvailable } from "./ix.js";
13
+ import { conflictPeersWithoutFootprint, overlapsFor } from "./overlap-command.js";
14
+ import { gitOut } from "./repo.js";
15
+ import { IxExtError, jsonBytes, SPEC_VERSION } from "./text.js";
16
+ /** At most one computation per session this often (SPEC §8.4). */
17
+ export const FOOTPRINT_MIN_INTERVAL_MS = 30_000;
18
+ /** An unchanged footprint is republished this often, so it stays live at the receivers. */
19
+ export const FOOTPRINT_KEEPALIVE_MS = 5 * 60_000;
20
+ const STATE_KEY = "footprint";
21
+ const CONFIG_KEY = "config";
22
+ /** The per-file cache; `fpcache` (v1, before names were scrubbed) is dropped on the next save. */
23
+ const CACHE_KEY = "fpcache2";
24
+ const OLD_CACHE_KEYS = ["fpcache"];
25
+ const MAX_SESSIONS = 16;
26
+ const MAX_CACHE = 60;
27
+ const MAX_CACHE_BYTES = 16 * 1024;
28
+ /** This device's own footprints with plain names, by session (for the person's `detail` lines). */
29
+ const MINE_KEY = "mine2";
30
+ const OLD_MINE_KEYS = ["mine"];
31
+ /** At most this many sessions' readable bodies (bounded: the store is 64 KiB). */
32
+ const MAX_MINE = 2;
33
+ const MAX_CIRCLES = 50;
34
+ const CID_RE = /^[A-Za-z0-9_-]{1,80}$/;
35
+ const usage = (m) => new IxExtError("usage", m);
36
+ /**
37
+ * Plain or hashed names (SPEC §8.6). Hashed is the default for every audience. Plain only by the
38
+ * person's explicit choice, most specific first: --names, P2P_IX_FOOTPRINT_NAMES, then
39
+ * `p2p ix config --circle <cid> names=…` for the session's circle, then `p2p ix config names=…`.
40
+ * An open circle takes plain only from its own circle setting (or --names / the variable), never
41
+ * from the global one. An audience that can't be read (no roster yet, a circle that can't be
42
+ * loaded, an older p2p) gets no circle setting and no global plain: hashed (fail closed).
43
+ */
44
+ export function footprintNames(o) {
45
+ const pick = (v) => (FP_NAMES.includes(v) ? v : undefined);
46
+ const flag = pick(o.flag);
47
+ if (flag)
48
+ return { names: flag, why: "--names" };
49
+ const env = pick(o.env?.trim());
50
+ if (env)
51
+ return { names: env, why: "P2P_IX_FOOTPRINT_NAMES" };
52
+ const a = o.audience;
53
+ if (!a)
54
+ return { names: "hmac", why: "hashed by default (who the session reaches can't be read)" };
55
+ const circle = a.circle ? pick(o.config?.circles?.[a.circle]) : undefined;
56
+ if (circle)
57
+ return { names: circle, why: `p2p ix config --circle ${a.circle}` };
58
+ const def = pick(o.config?.names);
59
+ if (def && !a.open)
60
+ return { names: def, why: "p2p ix config" };
61
+ return { names: "hmac", why: a.open ? "hashed by default (an open circle: plain only with its own --circle setting)" : "hashed by default" };
62
+ }
63
+ /** The settings as the MAC covers them: the names choices only, in a fixed order. */
64
+ function canonicalConfig(c) {
65
+ const circles = Object.entries(c.circles ?? {})
66
+ .filter(([, v]) => FP_NAMES.includes(v))
67
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
68
+ return JSON.stringify(["ix-footprint-config/v1", c.names ?? null, circles]);
69
+ }
70
+ function macOk(ctx, c) {
71
+ if (!ctx.localMac || typeof c.mac !== "string")
72
+ return false;
73
+ let want;
74
+ try {
75
+ want = ctx.localMac(canonicalConfig(c));
76
+ }
77
+ catch {
78
+ return false;
79
+ }
80
+ const a = Buffer.from(c.mac);
81
+ const b = Buffer.from(want);
82
+ return a.length === b.length && timingSafeEqual(a, b);
83
+ }
84
+ /**
85
+ * The person's footprint settings. A setting that makes names plain counts only when the store
86
+ * carries a MAC over the settings keyed by this device's secret (ExtContext.localMac), which
87
+ * `p2p ix config` writes: an edit of the store by file tools, or settings copied from another
88
+ * device or circle, can't opt into plain names. Not a boundary against something that runs
89
+ * `p2p ix config` as the user (SPEC §8.6). Hashed settings need no MAC (they only narrow what is
90
+ * shared).
91
+ */
92
+ export async function readConfig(ctx) {
93
+ const raw = await ctx.kv.get(CONFIG_KEY);
94
+ const c = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
95
+ const cfg = {
96
+ ...(FP_NAMES.includes(c.names) ? { names: c.names } : {}),
97
+ circles: Object.fromEntries(Object.entries(c.circles && typeof c.circles === "object" ? c.circles : {}).filter(([k, v]) => CID_RE.test(k) && FP_NAMES.includes(v))),
98
+ };
99
+ if (macOk(ctx, { ...cfg, mac: c.mac }))
100
+ return cfg;
101
+ const plain = cfg.names === "plain" || Object.values(cfg.circles ?? {}).includes("plain");
102
+ if (!plain)
103
+ return cfg;
104
+ return {
105
+ ...(cfg.names === "hmac" ? { names: "hmac" } : {}),
106
+ circles: Object.fromEntries(Object.entries(cfg.circles ?? {}).filter(([, v]) => v === "hmac")),
107
+ unverified: true,
108
+ };
109
+ }
110
+ async function writeConfig(ctx, cfg) {
111
+ if (!ctx.localMac) {
112
+ const plain = cfg.names === "plain" || Object.values(cfg.circles ?? {}).includes("plain");
113
+ if (plain)
114
+ throw new IxExtError("unsupported", "this p2p can't sign settings (ExtContext.localMac): update @peer2peer/cli to set names=plain");
115
+ await ctx.kv.set(CONFIG_KEY, cfg);
116
+ return;
117
+ }
118
+ await ctx.kv.set(CONFIG_KEY, { ...cfg, mac: ctx.localMac(canonicalConfig(cfg)) });
119
+ }
120
+ /** The per-file result cache, kept in the extension's store (bounded). */
121
+ async function loadCache(ctx) {
122
+ const raw = await ctx.kv.get(CACHE_KEY).catch(() => undefined);
123
+ const map = new Map(raw && typeof raw === "object" && !Array.isArray(raw) ? Object.entries(raw) : []);
124
+ const h = (k) => createHash("sha256").update(k).digest("base64url").slice(0, 24);
125
+ let dirty = false;
126
+ let t = 0;
127
+ return {
128
+ cache: {
129
+ get: (k) => {
130
+ const e = map.get(h(k));
131
+ return e && typeof e === "object" && e.r && typeof e.r === "object" ? e.r : undefined;
132
+ },
133
+ set: (k, r) => {
134
+ map.set(h(k), { t: Date.now() + t++, r });
135
+ dirty = true;
136
+ },
137
+ },
138
+ save: async () => {
139
+ if (!dirty)
140
+ return;
141
+ let entries = [...map.entries()].sort((a, b) => b[1].t - a[1].t).slice(0, MAX_CACHE);
142
+ while (entries.length && jsonBytes(Object.fromEntries(entries)) > MAX_CACHE_BYTES)
143
+ entries = entries.slice(0, -1);
144
+ for (const old of OLD_CACHE_KEYS)
145
+ if ((await ctx.kv.get(old).catch(() => undefined)) !== undefined)
146
+ await ctx.kv.set(old, undefined).catch(() => undefined);
147
+ await ctx.kv.set(CACHE_KEY, Object.fromEntries(entries)).catch(() => undefined);
148
+ },
149
+ };
150
+ }
151
+ async function sessionStates(ctx) {
152
+ const v = await ctx.kv.get(STATE_KEY);
153
+ return v && typeof v === "object" && !Array.isArray(v) ? v : {};
154
+ }
155
+ async function saveSessionState(ctx, sid, st) {
156
+ const all = { ...(await sessionStates(ctx)), [sid]: st };
157
+ const kept = Object.entries(all)
158
+ .sort((a, b) => (b[1].computedAt ?? 0) - (a[1].computedAt ?? 0))
159
+ .slice(0, MAX_SESSIONS);
160
+ await ctx.kv.set(STATE_KEY, Object.fromEntries(kept));
161
+ }
162
+ async function mineStore(ctx) {
163
+ const v = await ctx.kv.get(MINE_KEY).catch(() => undefined);
164
+ return v && typeof v === "object" && !Array.isArray(v) ? v : {};
165
+ }
166
+ /** Keeps this session's latest plain-names footprint (local only, never sent): newest MAX_MINE sessions. */
167
+ async function saveMine(ctx, sid, body) {
168
+ if (jsonBytes(body) > 16 * 1024)
169
+ return;
170
+ const all = { ...(await mineStore(ctx)), [sid]: { at: body.at, body } };
171
+ const kept = Object.entries(all)
172
+ .sort((a, b) => (b[1].at ?? 0) - (a[1].at ?? 0))
173
+ .slice(0, MAX_MINE);
174
+ for (const old of OLD_MINE_KEYS)
175
+ if ((await ctx.kv.get(old).catch(() => undefined)) !== undefined)
176
+ await ctx.kv.set(old, undefined).catch(() => undefined);
177
+ await ctx.kv.set(MINE_KEY, Object.fromEntries(kept)).catch(() => undefined);
178
+ }
179
+ /** This session's readable body; sessions no longer live on this device (`live`) are pruned. */
180
+ export async function readMine(ctx, sid, live) {
181
+ const all = await mineStore(ctx);
182
+ if (live) {
183
+ const gone = Object.keys(all).filter((s) => !live.includes(s));
184
+ if (gone.length) {
185
+ for (const s of gone)
186
+ delete all[s];
187
+ await ctx.kv.set(MINE_KEY, all).catch(() => undefined);
188
+ }
189
+ }
190
+ const e = all[sid];
191
+ return e && e.body && typeof e.body === "object" ? e.body : undefined;
192
+ }
193
+ /** The repository's name key, or why there is none (SPEC §8.6): no root commit, or a shallow clone. */
194
+ export async function repoNameKey(root, ref, env) {
195
+ const shallow = await gitOut(root, ["rev-parse", "--is-shallow-repository"], env, { timeoutMs: 10_000 });
196
+ if (shallow === "true")
197
+ return { why: "shallow clone (its root commit isn't the repository's, so hashed names wouldn't match peers'): `git fetch --unshallow`" };
198
+ const rc = pickRootCommit((await gitOut(root, ["rev-list", "--max-parents=0", "HEAD"], env, { maxBuffer: 1 << 16, timeoutMs: 10_000 })) ?? "");
199
+ if (!rc)
200
+ return { why: "git didn't give the repository's root commit (in time)" };
201
+ return { key: deriveNameKey(ref.remote, rc) };
202
+ }
203
+ function summary(b) {
204
+ const head = `Footprint (${b.names} names${b.truncated ? ", truncated" : ""}): ${b.merged.counts.changedSymbols} changed symbol(s), ${b.merged.counts.ring1Files} file(s) one hop downstream${b.merged.counts.ring2Files ? `, ${b.merged.counts.ring2Files} two hops` : ""}, risk ${b.merged.risk}`;
205
+ const actors = b.actors.map((a) => ` ${a.a}: graph ${a.graph}${a.wt ? " (worktree)" : ""}, ${a.changed.files.length} file(s), ${a.changed.symbols.length} symbol(s)${a.changed.new?.length ? ` + ${a.changed.new.length} new` : ""}, ring 1 ${a.ring1.files.length}${a.coarse ? ", coarse" : ""}${a.stale ? ", stale" : ""}${a.partial ? ", partial" : ""}`);
206
+ return [head, ...actors].join("\n");
207
+ }
208
+ export function footprintCommands(deps, h) {
209
+ const now = () => (deps.now ? deps.now() : Date.now());
210
+ return [
211
+ {
212
+ name: "overlaps",
213
+ description: "Overlaps between this session's Ix footprint and live peer sessions' (same symbol, depends, same file, same area, transitive), both ways",
214
+ options: [
215
+ { flags: "--session <sid>", description: "Your session (default: the one live session of yours on this device)" },
216
+ { flags: "--fallback", description: "For peers without a footprint, also ask your Ix about their status files (`ix around`, as `p2p ix conflicts`)" },
217
+ ],
218
+ run: async (ctx, _args, opts) => {
219
+ let sid = typeof opts.session === "string" ? opts.session : undefined;
220
+ if (!sid) {
221
+ const mine = (await ctx.peers()).filter((p) => p.self && p.thisDevice && p.live);
222
+ if (mine.length !== 1)
223
+ throw usage(mine.length ? "several live sessions of yours on this device: give --session" : "no live session of yours on this device: give --session");
224
+ sid = mine[0].sid;
225
+ }
226
+ const r = await overlapsFor(ctx, sid, {
227
+ readMine: (live) => readMine(ctx, sid, live),
228
+ repo: () => h.repoOf(ctx),
229
+ nameKey: repoNameKey,
230
+ });
231
+ let fallback = [];
232
+ if (opts.fallback && r.withoutFootprint.length)
233
+ fallback = await conflictPeersWithoutFootprint(ctx, sid, r.withoutFootprint, h.runner(ctx, deps, sid));
234
+ // Readable names (`detail`) only for a person at a terminal; --json (what a client, or a
235
+ // model's shell, reads) carries the model-safe line only.
236
+ const lines = r.overlaps.map((o) => (ctx.interactive ? o.detail : o.message));
237
+ const human = r.overlaps.length || fallback.length ? [...lines, ...fallback.map((c) => String(c.message))].join("\n") : r.note ?? `No overlaps with ${r.checked} live session${r.checked === 1 ? "" : "s"} with a footprint.`;
238
+ const overlaps = r.overlaps.map(({ detail: _d, ...o }) => o);
239
+ return { json: { overlaps, fallback, skipped: r.skipped, checked: r.checked, withoutFootprint: r.withoutFootprint.length, ...(r.note ? { note: r.note } : {}) }, human };
240
+ },
241
+ },
242
+ {
243
+ name: "footprint",
244
+ description: "This session's Ix footprint (x:ix.footprint): changed symbols, their blast radius and regions, per agent; --publish shares it with the session's status audience",
245
+ options: [
246
+ { flags: "--session <sid>", description: "Your session (default: the one live session of yours on this device)" },
247
+ { flags: "--publish", description: "Publish it as the session's footprint state (at most every 30 s; only when it changed, or every 5 min)" },
248
+ { flags: "--names <mode>", description: "plain or hmac (default: hmac; plain is opt-in, see `p2p ix config`)" },
249
+ { flags: "--depth <n>", description: "1 (default), or 2 for a second ring (P2P_IX_FOOTPRINT_DEPTH)" },
250
+ { flags: "--force", description: "Ignore the 30 s spacing and publish even when unchanged" },
251
+ ],
252
+ run: async (ctx, _args, opts) => {
253
+ const t0 = now();
254
+ let sid = typeof opts.session === "string" ? opts.session : undefined;
255
+ if (!sid) {
256
+ const mine = (await ctx.peers()).filter((p) => p.self && p.thisDevice && p.live);
257
+ if (mine.length !== 1)
258
+ throw usage(mine.length ? "several live sessions of yours on this device: give --session" : "no live session of yours on this device: give --session");
259
+ sid = mine[0].sid;
260
+ }
261
+ if (opts.names !== undefined && !FP_NAMES.includes(opts.names))
262
+ throw usage("--names must be plain or hmac");
263
+ const depthRaw = opts.depth ?? ctx.env.P2P_IX_FOOTPRINT_DEPTH;
264
+ const depth = depthRaw === undefined || depthRaw === "" ? 1 : Number(depthRaw);
265
+ if (depth !== 1 && depth !== 2)
266
+ throw usage("--depth must be 1 or 2");
267
+ const publish = Boolean(opts.publish);
268
+ // Publishing follows the same switches as the session's status, whoever runs it.
269
+ const off = ctx.env.P2P_SHARE_STATUS === "0" || ctx.env.IX_PEERS_SHARE_STATUS === "0" ? "P2P_SHARE_STATUS=0" : ctx.env.P2P_IX_FOOTPRINT === "0" ? "P2P_IX_FOOTPRINT=0" : undefined;
270
+ if (publish && off)
271
+ return { json: { published: false, skipped: "disabled", why: off }, human: `Not published: ${off}.` };
272
+ const states = await sessionStates(ctx);
273
+ const prev = states[sid];
274
+ if (publish && !opts.force && prev && t0 - prev.computedAt < FOOTPRINT_MIN_INTERVAL_MS && prev.computedAt <= t0) {
275
+ const retryAfterMs = FOOTPRINT_MIN_INTERVAL_MS - (t0 - prev.computedAt);
276
+ return { json: { published: false, skipped: "too_soon", retryAfterMs }, human: `Computed less than 30 s ago; next in ${Math.ceil(retryAfterMs / 1000)} s.` };
277
+ }
278
+ const own = await ctx.ownStatus(sid);
279
+ if (!own)
280
+ throw new IxExtError("no_status", `session ${sid} has posted no status on this device yet`);
281
+ const here = await h.repoOf(ctx);
282
+ if (!here.root)
283
+ throw new IxExtError("not_a_repo", "not in a git repository: a footprint needs the session's repo (P2P_WORKDIR)");
284
+ if (!here.ref)
285
+ throw new IxExtError("no_remote", "this repository has no origin remote: a footprint names its repo by its remote");
286
+ const ix = h.runner(ctx, deps, sid);
287
+ // No Ix: no footprint, one clear error (a client stops asking for this run).
288
+ if (!(await ixAvailable(ix)))
289
+ throw new IxExtError("ix_missing", "Ix isn't installed: https://github.com/ix-infrastructure/Ix");
290
+ const env = { ...process.env, ...ctx.env };
291
+ const { cache, save } = await loadCache(ctx);
292
+ const computed = await computeFootprint({ root: here.root, roots: here.roots, home: homedir(), hostname: hostname(), own: { files: own.files, ...(own.agents ? { agents: own.agents } : {}) }, depth: depth, cache }, {
293
+ ix,
294
+ git: (cwd, args, o) => gitOut(cwd, args, env, o),
295
+ stat: async (p) => {
296
+ try {
297
+ const s = await stat(p);
298
+ return { mtimeMs: Math.floor(s.mtimeMs), size: s.size };
299
+ }
300
+ catch {
301
+ return undefined;
302
+ }
303
+ },
304
+ now,
305
+ });
306
+ await save();
307
+ const nextState = { seq: prev?.seq ?? 0, computedAt: t0, ...(prev?.digest ? { digest: prev.digest } : {}), ...(prev?.publishedAt ? { publishedAt: prev.publishedAt } : {}) };
308
+ const usable = computed.actors.filter((a) => a.graph !== "none");
309
+ if (computed.actors.length === 0 || usable.length === 0) {
310
+ if (publish)
311
+ await saveSessionState(ctx, sid, nextState);
312
+ const skipped = computed.actors.length === 0 ? "nothing_changed" : "not_mapped";
313
+ return {
314
+ json: { published: false, skipped, calls: computed.calls },
315
+ human: skipped === "nothing_changed" ? "No changed files in this session's status: no footprint." : "This repository isn't mapped by Ix (`ix map`): no footprint.",
316
+ };
317
+ }
318
+ const audience = ctx.audience ? await ctx.audience(sid).catch(() => null) : null;
319
+ const mode = footprintNames({ flag: opts.names, env: ctx.env.P2P_IX_FOOTPRINT_NAMES, config: await readConfig(ctx), audience });
320
+ let key;
321
+ if (mode.names === "hmac") {
322
+ // Fail closed: hashed names were called for, and plain ones never go out instead.
323
+ const k = await repoNameKey(here.root, here.ref, env);
324
+ if ("why" in k)
325
+ throw new IxExtError("no_hmac_key", `no_hmac_key: ${k.why}; nothing published${/shallow/.test(k.why) ? "" : "; the next try computes again"}`);
326
+ key = k.key;
327
+ }
328
+ const seq = (prev?.seq ?? 0) + 1;
329
+ const { body, fallback } = assembleFootprint({ repo: here.ref, at: t0, seq, actors: computed.actors, ...(key ? { key } : {}) });
330
+ // This side's own names, kept locally (never sent): overlap messages name things with them.
331
+ await saveMine(ctx, sid, key ? assembleFootprint({ repo: here.ref, at: t0, seq, actors: computed.actors }).body : body);
332
+ const digest = footprintDigest(body);
333
+ const out = { names: mode.names, namesWhy: mode.why, calls: computed.calls, ...(computed.partial ? { partial: true } : {}), footprint: body, fallback };
334
+ if (!publish)
335
+ return { json: { published: false, ...out }, human: summary(body) };
336
+ const fresh = prev?.publishedAt !== undefined && digest === prev.digest && t0 - prev.publishedAt < FOOTPRINT_KEEPALIVE_MS && prev.publishedAt <= t0;
337
+ if (fresh && !opts.force) {
338
+ await saveSessionState(ctx, sid, nextState);
339
+ return { json: { published: false, skipped: "unchanged", ...out }, human: `${summary(body)}\nUnchanged since the last publish: not sent.` };
340
+ }
341
+ let r;
342
+ try {
343
+ r = await ctx.publish({ fromSession: sid, kind: FOOTPRINT_KIND, v: SPEC_VERSION, body, fallback });
344
+ }
345
+ catch (e) {
346
+ await saveSessionState(ctx, sid, nextState);
347
+ const code = e.code;
348
+ if (code === "rate_limited")
349
+ return { json: { published: false, skipped: "rate_limited", ...out }, human: "Published less than 5 s ago: not sent." };
350
+ throw e;
351
+ }
352
+ await saveSessionState(ctx, sid, { seq, computedAt: t0, digest, publishedAt: t0 });
353
+ const n = r.delivered.length;
354
+ return { json: { published: true, delivered: r.delivered, skipped: r.skipped, failed: r.failed, ...out }, human: `${summary(body)}\nPublished to ${n} ${n === 1 ? "person" : "people"}${r.skipped.length ? ` (${r.skipped.length} skipped: their clients don't keep footprints)` : ""}.` };
355
+ },
356
+ },
357
+ {
358
+ name: "config",
359
+ args: "[settings...]",
360
+ description: "Footprint settings: names=plain|hmac|auto, for every session or one circle (--circle)",
361
+ options: [{ flags: "--circle <cid>", description: "Set it for sessions shared with this circle" }],
362
+ offline: true,
363
+ run: async (ctx, args, opts) => {
364
+ const settings = Array.isArray(args[0]) ? args[0].map(String) : [];
365
+ const { unverified, ...cfg } = await readConfig(ctx);
366
+ const circle = typeof opts.circle === "string" ? opts.circle : undefined;
367
+ if (circle !== undefined && !CID_RE.test(circle))
368
+ throw usage("--circle must be a circle id");
369
+ for (const s of settings) {
370
+ const m = /^names=(plain|hmac|auto)$/.exec(s);
371
+ if (!m)
372
+ throw usage(`unknown setting ${JSON.stringify(s.slice(0, 40))}: names=plain|hmac|auto`);
373
+ const v = m[1] === "auto" ? undefined : m[1];
374
+ if (circle) {
375
+ const circles = { ...(cfg.circles ?? {}) };
376
+ if (v)
377
+ circles[circle] = v;
378
+ else
379
+ delete circles[circle];
380
+ if (Object.keys(circles).length > MAX_CIRCLES)
381
+ throw usage(`at most ${MAX_CIRCLES} circles have their own setting`);
382
+ cfg.circles = circles;
383
+ }
384
+ else if (v)
385
+ cfg.names = v;
386
+ else
387
+ delete cfg.names;
388
+ }
389
+ if (settings.length)
390
+ await writeConfig(ctx, cfg);
391
+ const lines = [`names: ${cfg.names ?? "auto (hashed; plain only where you set names=plain)"}`, ...Object.entries(cfg.circles ?? {}).map(([c, v]) => `circle ${c}: names=${v}`)];
392
+ if (unverified && !settings.length)
393
+ lines.push("ignored: a names=plain setting in the store that this device didn't sign (set it again with `p2p ix config`)");
394
+ return { json: { config: cfg, ...(unverified && !settings.length ? { ignoredUnsigned: true } : {}) }, human: lines.join("\n") };
395
+ },
396
+ },
397
+ ];
398
+ }
@@ -0,0 +1,106 @@
1
+ import type { IxRunner } from "./ix.js";
2
+ import { type FpComponent, type FpRel, type FpSymbolRel, type RawActor } from "./footprint.js";
3
+ import { type RiskLevel } from "./text.js";
4
+ export declare const FOOTPRINT_BUDGET_MS = 40000;
5
+ export declare const FOOTPRINT_MAX_CALLS = 80;
6
+ /** Agents count while running or waiting, or for this long after their last activity. */
7
+ export declare const AGENT_RECENT_MS: number;
8
+ export interface Range {
9
+ start: number;
10
+ end: number;
11
+ }
12
+ export interface AgentLike {
13
+ id: string;
14
+ state: string;
15
+ files?: string[];
16
+ wt?: true | boolean;
17
+ branch?: string;
18
+ at: number;
19
+ }
20
+ export interface ComputeDeps {
21
+ ix: IxRunner;
22
+ /** git's stdout, or undefined on failure. */
23
+ git(cwd: string, args: string[], opts?: {
24
+ maxBuffer?: number;
25
+ trim?: boolean;
26
+ timeoutMs?: number;
27
+ }): Promise<string | undefined>;
28
+ stat(abs: string): Promise<{
29
+ mtimeMs: number;
30
+ size: number;
31
+ } | undefined>;
32
+ now(): number;
33
+ }
34
+ /** One file's measured result, plain names (what the cache holds). */
35
+ export interface FileResult {
36
+ inGraph: boolean;
37
+ risk: RiskLevel;
38
+ symbols: {
39
+ k: string;
40
+ kind: string;
41
+ }[];
42
+ coarse?: boolean;
43
+ partial?: boolean;
44
+ ring1Files: {
45
+ f: string;
46
+ rel: FpRel;
47
+ }[];
48
+ ring1Symbols: {
49
+ k: string;
50
+ rel: FpSymbolRel;
51
+ }[];
52
+ components: FpComponent[];
53
+ newSymbols?: string[];
54
+ }
55
+ export interface FileCache {
56
+ get(key: string): FileResult | undefined;
57
+ set(key: string, value: FileResult): void;
58
+ }
59
+ export interface ComputeInput {
60
+ /** The session's checkout (absolute; local only, never sent). */
61
+ root: string;
62
+ /** Every spelling of `root` (symlinks), for making Ix's paths repo-relative. */
63
+ roots?: string[];
64
+ own: {
65
+ files: string[];
66
+ agents?: AgentLike[];
67
+ };
68
+ depth?: 1 | 2;
69
+ /** This machine's home directory and host name: scrubbed from every name Ix gives (region and symbol names). */
70
+ home?: string;
71
+ hostname?: string;
72
+ budgetMs?: number;
73
+ maxCalls?: number;
74
+ cache?: FileCache;
75
+ }
76
+ export interface ComputeResult {
77
+ actors: RawActor[];
78
+ /** `ix` invocations made. */
79
+ calls: number;
80
+ /** Whether the session's own checkout is mapped by Ix. */
81
+ mapped: boolean;
82
+ partial: boolean;
83
+ }
84
+ export interface FileDiff {
85
+ /** Ranges on the old (merge-base / HEAD) side. */
86
+ old: Range[];
87
+ /** Ranges on the new (working tree) side. */
88
+ new: Range[];
89
+ /** Added lines (for naming symbols that exist only on the new side). */
90
+ added: string[];
91
+ }
92
+ /** Reads `git diff -U0` output (core.quotePath=false) into per-file hunks. Quoted (unusual) paths are skipped. */
93
+ export declare function parseUnifiedDiff(text: string): Map<string, FileDiff>;
94
+ /** At most `max` ranges: neighbours within `gap` lines merge, then the closest pairs until few enough. */
95
+ export declare function groupRanges(ranges: Range[], max?: number, gap?: number): Range[];
96
+ /** Names declared on added lines: symbols that may exist only on the new side. */
97
+ export declare function declaredNames(added: string[]): string[];
98
+ /** A name from Ix as it may leave this machine: local paths, the home directory, e-mail and host name scrubbed, one sanitized line. */
99
+ export type Scrub = (name: string, max: number) => string | undefined;
100
+ export declare function nameScrubber(roots: string[], home?: string, hostname?: string): Scrub;
101
+ /** Bumped whenever what a cached FileResult holds changes (v2: names scrubbed, rows outside the repo dropped). */
102
+ export declare const FILE_CACHE_VERSION = 2;
103
+ /** `git worktree list --porcelain`: worktree path by branch (refs/heads/ stripped). */
104
+ export declare function parseWorktrees(text: string): Map<string, string>;
105
+ /** Measures every actor (SPEC.md §8.2). Never throws for an Ix or git failure: what fails is coarse or partial. */
106
+ export declare function computeFootprint(input: ComputeInput, deps: ComputeDeps): Promise<ComputeResult>;