@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,615 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // The P2PExtension `p2p` loads (packages/p2p/src/extensions.ts): `receive`
4
+ // renders inbound x:ix.* kinds, and `commands` become `p2p ix …`.
5
+ //
6
+ // Consent and safety (SPEC.md §2):
7
+ // - receiving only validates, sanitizes and renders: no Ix call, no write;
8
+ // - `import` (a note into the local graph) and `resolve` (a subgraph in the
9
+ // local graph) run only when the user starts them, and ask first (or take
10
+ // --yes; with --json and no --yes they refuse);
11
+ // - everything sent is size-capped and has absolute paths made relative or
12
+ // dropped.
13
+ //
14
+ // The types are the seam's (import type only: no runtime dependency on p2p).
15
+ import { createHash } from "node:crypto";
16
+ import { homedir, hostname } from "node:os";
17
+ import { readFile } from "node:fs/promises";
18
+ import { realpathSync } from "node:fs";
19
+ import { isAbsolute, relative, resolve as resolvePath } from "node:path";
20
+ import { ixNeighbourhood, semanticConflicts } from "./conflicts.js";
21
+ import { audienceOf } from "./overlap-command.js";
22
+ import { FOOTPRINT_KIND, FOOTPRINT_TTL, parseFootprintBody } from "./footprint.js";
23
+ import { footprintCommands } from "./footprint-command.js";
24
+ import { buildImpact, IMPACT_KIND, impactFallback, parseImpactBody, renderImpact } from "./impact.js";
25
+ import { callPaths, checkedTarget, guardRunner, refuseForTarget, ixAvailable, ixJson, ixRunner, IX_NOTE_ID_RE, localTarget, memoryRefusal, memorySupport } from "./ix.js";
26
+ import { ixMemory, recordOf } from "./memory.js";
27
+ import { checkLoopbackListener } from "./listener.js";
28
+ import { buildNote, NOTE_KIND, parseNoteBody, renderNote } from "./note.js";
29
+ import { compareRepo, localRepo, normalizeRemote } from "./repo.js";
30
+ import { buildSubgraph, describeSelector, parseSubgraphBody, renderSubgraph, resolveArgv, SUBGRAPH_KIND } from "./subgraph.js";
31
+ import { frame, InvalidBody, IxExtError, line, NOTE_TAGS, SPEC_VERSION, toRepoRelative } from "./text.js";
32
+ export const VERSION = "0.1.1";
33
+ export const KINDS = [NOTE_KIND, SUBGRAPH_KIND, IMPACT_KIND];
34
+ /** Cap on local Ix output a command hands back (resolve). */
35
+ export const MAX_RESOLVE_OUTPUT = 32 * 1024;
36
+ // ---------------------------------------------------------------------------
37
+ // Receiving
38
+ /** Validates and renders one inbound kind. Never runs Ix, never writes. */
39
+ export function receiveIx(input) {
40
+ if (input.v > SPEC_VERSION)
41
+ return { ok: false, reason: `${input.kind} v${input.v} is newer than this ext-ix (v${SPEC_VERSION}): update @peer2peer/ext-ix` };
42
+ if (input.v < 1)
43
+ return { ok: false, reason: `${input.kind} v${input.v} is not a known version` };
44
+ const from = { address: input.from.address };
45
+ try {
46
+ switch (input.kind) {
47
+ case NOTE_KIND: {
48
+ const b = parseNoteBody(input.body);
49
+ return { ok: true, rendered: renderNote(b, from), keep: b };
50
+ }
51
+ case SUBGRAPH_KIND: {
52
+ const b = parseSubgraphBody(input.body);
53
+ return { ok: true, rendered: renderSubgraph(b, from), keep: b };
54
+ }
55
+ case IMPACT_KIND: {
56
+ const b = parseImpactBody(input.body);
57
+ return { ok: true, rendered: renderImpact(b, from), keep: b };
58
+ }
59
+ case FOOTPRINT_KIND: {
60
+ // A state kind (SPEC §8.5): validated strictly and kept; nothing rendered, so nothing a
61
+ // person or a model reads comes from it (p2p never logs a state value as an event).
62
+ const b = parseFootprintBody(input.body);
63
+ return { ok: true, rendered: { type: "footprint" }, keep: b };
64
+ }
65
+ default:
66
+ return { ok: false, reason: `${input.kind} is not an Ix kind this version knows` };
67
+ }
68
+ }
69
+ catch (e) {
70
+ if (e instanceof InvalidBody)
71
+ return { ok: false, reason: `invalid ${input.kind}: ${e.message}` };
72
+ throw e;
73
+ }
74
+ }
75
+ // ---------------------------------------------------------------------------
76
+ // Commands
77
+ /** A received note in full, framed as data from the named peer (L4): what `show` prints and `import` asks about. */
78
+ export function noteFull(b, address) {
79
+ const head = frame(address, `Ix ${b.tag} note, full text, ${[...b.text].length} characters`, "");
80
+ return `${head.trimEnd()}\n${b.title ? `Title: ${line(b.title, 120)}\n` : ""}\n${b.text}`;
81
+ }
82
+ const SHOWN_KEY = "shown";
83
+ const MAX_SHOWN = 100;
84
+ const bodyHash = (body) => createHash("sha256").update(JSON.stringify(body) ?? "").digest("hex").slice(0, 32);
85
+ const noteHash = (b) => createHash("sha256").update(JSON.stringify([b.title ?? "", b.text])).digest("hex").slice(0, 32);
86
+ /** Records that a person read this note in full at a terminal. */
87
+ async function markShown(ctx, id, b) {
88
+ const cur = ((await ctx.kv.get(SHOWN_KEY)) ?? {});
89
+ const next = Object.entries({ ...cur, [id]: noteHash(b) }).slice(-MAX_SHOWN);
90
+ await ctx.kv.set(SHOWN_KEY, Object.fromEntries(next));
91
+ }
92
+ async function wasShown(ctx, id, b) {
93
+ const cur = (await ctx.kv.get(SHOWN_KEY));
94
+ return cur?.[id] === noteHash(b);
95
+ }
96
+ const usage = (m) => new IxExtError("usage", m);
97
+ const asUsage = (f) => {
98
+ try {
99
+ return f();
100
+ }
101
+ catch (e) {
102
+ if (e instanceof InvalidBody)
103
+ throw usage(e.message);
104
+ throw e;
105
+ }
106
+ };
107
+ const sendOpts = [
108
+ { flags: "--from-session <sid>", description: "Your session id (required)" },
109
+ { flags: "--to <address>", description: 'The peer: name@fingerprint, userId or petname, optionally "[ref]" or /sid (required)' },
110
+ ];
111
+ function need(opts, k, flag) {
112
+ const v = opts[k];
113
+ if (typeof v !== "string" || v.trim() === "")
114
+ throw usage(`${flag} is required`);
115
+ return v;
116
+ }
117
+ /**
118
+ * The graph target of a call (packages/p2p/src/projects.ts graphTarget, through ExtContext): the
119
+ * only place an `ix` endpoint comes from. A p2p from before graph targets has none to give: local.
120
+ * Any failure is local too.
121
+ */
122
+ export function targetOf(ctx, sid, extra = []) {
123
+ const memo = new Map();
124
+ const more = extra.filter((p) => typeof p === "string" && p !== "").map((p) => (isAbsolute(p) ? p : resolvePath(ctx.cwd, p)));
125
+ return (call) => {
126
+ const paths = [...new Set([...more, ...callPaths(call)])];
127
+ const key = JSON.stringify(paths);
128
+ let p = memo.get(key);
129
+ if (!p) {
130
+ p = (async () => {
131
+ if (!ctx.graphTarget)
132
+ return localTarget();
133
+ try {
134
+ return checkedTarget(await ctx.graphTarget({ ...(sid ? { sid } : {}), paths }));
135
+ }
136
+ catch {
137
+ return localTarget();
138
+ }
139
+ })();
140
+ memo.set(key, p);
141
+ }
142
+ return p;
143
+ };
144
+ }
145
+ /**
146
+ * The `ix` a command runs: each call pinned to the graph target of session `sid` (when the command
147
+ * has one), its folders, the paths the call names (callPaths) and `extra` (the command's own path
148
+ * arguments: --changed, --file), and limited to the commands that target allows.
149
+ */
150
+ export function runner(ctx, deps, sid, extra = []) {
151
+ const target = targetOf(ctx, sid, extra);
152
+ return guardRunner(deps.ix ? deps.ix(ctx) : ixRunner({ env: ctx.env, cwd: ctx.cwd, target }), target, ctx.cwd, deps.listener ? { listener: deps.listener } : {});
153
+ }
154
+ export async function repoOf(ctx) {
155
+ const r = await localRepo(ctx.cwd, { ...process.env, ...ctx.env });
156
+ const roots = new Set();
157
+ const real = (p) => {
158
+ try {
159
+ return realpathSync(p);
160
+ }
161
+ catch {
162
+ return p;
163
+ }
164
+ };
165
+ if (r.root) {
166
+ roots.add(r.root);
167
+ roots.add(real(r.root));
168
+ // The cwd's own spellings of the root (the shell's logical $PWD keeps symlinks): minus the path below the root.
169
+ const pwd = process.env.PWD;
170
+ for (const cwd of [ctx.cwd, ...(pwd && real(pwd) === real(ctx.cwd) ? [pwd] : [])]) {
171
+ const below = relative(real(r.root), real(cwd));
172
+ if (below.startsWith("..") || isAbsolute(below))
173
+ continue;
174
+ const up = below === "" ? cwd : cwd.slice(0, Math.max(0, cwd.length - below.length - 1));
175
+ if (up)
176
+ roots.add(up);
177
+ }
178
+ }
179
+ return { ...r, roots: [...roots] };
180
+ }
181
+ async function findEvent(ctx, idArg, kind) {
182
+ const all = await ctx.events(kind ? { kind } : {});
183
+ const hits = all.filter((e) => e.id === idArg || (idArg.length >= 6 && e.id.endsWith(idArg)) || (idArg.length >= 8 && e.id.includes(idArg)));
184
+ if (hits.length === 0)
185
+ throw new IxExtError("not_found", `no received ${kind ?? "x:ix.*"} event ${line(idArg, 80)} (see \`p2p ix inbox\`)`);
186
+ if (hits.length > 1)
187
+ throw new IxExtError("ambiguous", `${hits.length} events match ${line(idArg, 80)}: give the full id`);
188
+ return hits[0];
189
+ }
190
+ function keptBody(e, parse) {
191
+ if (!e.kept)
192
+ throw new IxExtError("unavailable", "this event's content wasn't kept (it arrived before ext-ix was installed, or was invalid or too large)");
193
+ try {
194
+ return parse(e.kept.body);
195
+ }
196
+ catch (err) {
197
+ if (err instanceof InvalidBody)
198
+ throw new IxExtError("invalid", `the kept content no longer validates: ${err.message}`);
199
+ throw err;
200
+ }
201
+ }
202
+ async function readTextArg(ctx, words, stdin) {
203
+ const arr = Array.isArray(words) ? words.map(String) : [];
204
+ const fromStdin = stdin || (arr.length === 1 && arr[0] === "-");
205
+ if (fromStdin || arr.length === 0)
206
+ return ctx.io.readStdin ? (await ctx.io.readStdin()).replace(/\n$/, "") : "";
207
+ return arr.join(" ");
208
+ }
209
+ function sentHuman(kind, r) {
210
+ const where = r.to.own === r.to.userId ? `${r.to.address} [${r.to.ref}]` : `${r.to.address} (in your session ${r.to.sid})`;
211
+ return `Sent ${kind} to ${where} via ${r.relays} relay${r.relays === 1 ? "" : "s"}.`;
212
+ }
213
+ export function ixCommands(deps = {}) {
214
+ return [
215
+ {
216
+ name: "note",
217
+ args: "[text...]",
218
+ description: "Share an Ix session note with a peer session (x:ix.note); text from args, stdin, or --ix-note ID",
219
+ options: [
220
+ ...sendOpts,
221
+ { flags: "--tag <tag>", description: `${NOTE_TAGS.join("|")} (default: note, or the Ix note's tag)` },
222
+ { flags: "--title <title>", description: "A short title" },
223
+ { flags: "--session <name>", description: "The Ix session it belongs to (a label for the reader)" },
224
+ { flags: "--ix-note <id>", description: "Share an existing Ix note (read with `ix note show <id> --json`)" },
225
+ { flags: "--ref <path>", description: "A repo-relative file the note is about (repeatable)", repeatable: true },
226
+ { flags: "--stdin", description: "Read the text from stdin" },
227
+ { flags: "--without-repo", description: "Don't name the repo and revision" },
228
+ ],
229
+ run: async (ctx, args, opts) => {
230
+ const fromSession = need(opts, "fromSession", "--from-session");
231
+ const to = need(opts, "to", "--to");
232
+ const here = await repoOf(ctx);
233
+ const repo = opts.withoutRepo ? { roots: here.roots } : here;
234
+ let text;
235
+ let tag = opts.tag;
236
+ let at;
237
+ if (typeof opts.ixNote === "string") {
238
+ if (!IX_NOTE_ID_RE.test(opts.ixNote))
239
+ throw usage("--ix-note must be a note id");
240
+ const n = (await ixJson(runner(ctx, deps, fromSession), ["note", "--json", "show", opts.ixNote]));
241
+ if (typeof n?.text !== "string")
242
+ throw new IxExtError("ix_failed", "ix note show returned no text");
243
+ // Graph memory's own records (memory.ts) hold a session's context: they go out only from that
244
+ // session, or from one whose reach is no wider than its (both shared, and p2p says so). A
245
+ // private project's record, one whose session can't be told, or an older p2p: refused.
246
+ const rec = await recordOf(ctx, n);
247
+ if (rec && rec.sid !== fromSession) {
248
+ const ok = rec.sid !== undefined && typeof ctx.mayShareSessionContext === "function" && (await ctx.mayShareSessionContext(rec.sid, fromSession).catch(() => false)) === true;
249
+ if (!ok)
250
+ throw new IxExtError("not_shared", "that Ix note is a Peer2Peer record of another session's context, which this session may not pass on (share it from that session, or write your own note)");
251
+ }
252
+ text = n.text;
253
+ tag ??= typeof n.tag === "string" && NOTE_TAGS.includes(n.tag) ? n.tag : undefined;
254
+ at = typeof n.at === "string" ? n.at : undefined;
255
+ }
256
+ else {
257
+ text = await readTextArg(ctx, args[0], Boolean(opts.stdin));
258
+ }
259
+ if (text.trim() === "")
260
+ throw usage("nothing to share: give the note text, pipe it on stdin, or --ix-note ID");
261
+ const { body, fallback } = asUsage(() => buildNote({
262
+ text,
263
+ tag,
264
+ title: opts.title,
265
+ session: opts.session,
266
+ refs: opts.ref?.map((r) => (isAbsolute(r) ? r : resolvePath(ctx.cwd, r))),
267
+ repo: repo.ref,
268
+ at,
269
+ root: repo.roots,
270
+ home: homedir(),
271
+ hostname: hostname(),
272
+ }));
273
+ const r = await ctx.send({ fromSession, to, kind: NOTE_KIND, v: SPEC_VERSION, body, fallback });
274
+ return { json: { ...r, body }, human: sentHuman("an Ix note", r) };
275
+ },
276
+ },
277
+ {
278
+ name: "subgraph",
279
+ args: "[pattern]",
280
+ description: 'Point a peer at part of your graph (x:ix.subgraph): a path like "auth/*", or --symbol / --region. Sends a reference, no graph content',
281
+ options: [
282
+ ...sendOpts,
283
+ { flags: "--symbol <name>", description: "A symbol instead of a path" },
284
+ { flags: "--kind <kind>", description: "With --symbol: its entity kind (function, class, …)" },
285
+ { flags: "--path <path>", description: "With --symbol: a repo-relative path it lives under" },
286
+ { flags: "--region <name>", description: "An architecture region (ix subsystems) instead of a path" },
287
+ { flags: "--title <title>", description: "A short title" },
288
+ { flags: "--why <text>", description: "Why they should look" },
289
+ { flags: "--remote <remote>", description: "The repo's remote (default: this checkout's origin)" },
290
+ { flags: "--rev <commit>", description: "The revision (default: this checkout's HEAD)" },
291
+ ],
292
+ run: async (ctx, args, opts) => {
293
+ const fromSession = need(opts, "fromSession", "--from-session");
294
+ const to = need(opts, "to", "--to");
295
+ const pattern = typeof args[0] === "string" ? args[0] : undefined;
296
+ const picks = [pattern, opts.symbol, opts.region].filter((x) => typeof x === "string").length;
297
+ if (picks !== 1)
298
+ throw usage("give exactly one of: a path pattern, --symbol <name>, --region <name>");
299
+ const local = await repoOf(ctx);
300
+ let repo = local.ref;
301
+ if (typeof opts.remote === "string") {
302
+ const remote = normalizeRemote(opts.remote) ?? (/^[a-z0-9.-]+(\/[a-z0-9._~-]+)+$/.test(opts.remote) ? opts.remote : undefined);
303
+ if (!remote)
304
+ throw usage("--remote must be a git remote URL or host/owner/name");
305
+ repo = { remote, ...(repo?.remote === remote && repo.rev ? { rev: repo.rev } : {}) };
306
+ }
307
+ if (typeof opts.rev === "string" && repo)
308
+ repo = { ...repo, rev: opts.rev.toLowerCase() };
309
+ let selector;
310
+ if (pattern !== undefined) {
311
+ // A path given as absolute or ./relative becomes repo-relative; others stay as typed.
312
+ const glob = /\/(\*\*?)$/.exec(pattern)?.[0] ?? "";
313
+ const bare = glob ? pattern.slice(0, -glob.length) : pattern;
314
+ const rel = isAbsolute(bare) ? toRepoRelative(bare, local.roots) : bare.replace(/^\.\//, "");
315
+ if (rel === undefined)
316
+ throw usage("the path must be inside this repository");
317
+ selector = { type: "path", pattern: rel + glob };
318
+ }
319
+ else if (typeof opts.symbol === "string") {
320
+ selector = { type: "symbol", name: opts.symbol, ...(typeof opts.kind === "string" ? { kind: opts.kind } : {}), ...(typeof opts.path === "string" ? { path: opts.path } : {}) };
321
+ }
322
+ else
323
+ selector = { type: "region", name: opts.region };
324
+ const { body, fallback } = asUsage(() => buildSubgraph({ repo, selector, title: opts.title, why: opts.why, root: local.roots, home: homedir(), hostname: hostname() }));
325
+ const r = await ctx.send({ fromSession, to, kind: SUBGRAPH_KIND, v: SPEC_VERSION, body, fallback });
326
+ return { json: { ...r, body }, human: sentHuman(`a reference to ${describeSelector(selector)}`, r) };
327
+ },
328
+ },
329
+ {
330
+ name: "impact",
331
+ args: "<target>",
332
+ description: "Share a blast-radius report of a change (x:ix.impact), made by your Ix (`ix impact TARGET --format json`)",
333
+ options: [
334
+ ...sendOpts,
335
+ { flags: "--kind <kind>", description: "Ix: filter the target by kind" },
336
+ { flags: "--path <path>", description: "Ix: restrict to symbols under this path" },
337
+ { flags: "--depth <n>", description: "Ix: expansion depth 1-3" },
338
+ { flags: "--changed <file>", description: "A file your change touches (repeatable)", repeatable: true },
339
+ { flags: "--ix-json <file>", description: "Use this saved `ix impact --format json` output (- for stdin) instead of running Ix" },
340
+ { flags: "--without-repo", description: "Don't name the repo and revision" },
341
+ { flags: "--dry-run", description: "Build the report and print it (`body`) without sending: for a client to show its user first" },
342
+ { flags: "--body <file>", description: "Send this already-built report body (- for stdin; e.g. a --dry-run's, as shown to the user) instead of running Ix" },
343
+ ],
344
+ run: async (ctx, args, opts) => {
345
+ // A body built earlier (a client's dry run, shown to its user): validated again, sent as is.
346
+ if (typeof opts.body === "string") {
347
+ const fromSession = need(opts, "fromSession", "--from-session");
348
+ const to = need(opts, "to", "--to");
349
+ const raw = opts.body === "-" ? ((await ctx.io.readStdin?.()) ?? "") : await readFile(resolvePath(ctx.cwd, opts.body), "utf8");
350
+ let parsed;
351
+ try {
352
+ parsed = JSON.parse(raw);
353
+ }
354
+ catch {
355
+ throw usage("--body is not JSON");
356
+ }
357
+ const body = asUsage(() => parseImpactBody(parsed));
358
+ const r = await ctx.send({ fromSession, to, kind: IMPACT_KIND, v: SPEC_VERSION, body, fallback: impactFallback(body) });
359
+ return { json: { ...r, body }, human: sentHuman(`an Ix blast-radius report (${body.riskLevel} risk)`, r) };
360
+ }
361
+ const dryRun = Boolean(opts.dryRun);
362
+ const fromSession = dryRun ? "" : need(opts, "fromSession", "--from-session");
363
+ const to = dryRun ? "" : need(opts, "to", "--to");
364
+ const here = await repoOf(ctx);
365
+ let target = String(args[0] ?? "");
366
+ // L3: an absolute target becomes repo-relative, or is refused: it would reach the report.
367
+ if (isAbsolute(target) || /^[A-Za-z]:[\\/]/.test(target)) {
368
+ const rel = toRepoRelative(target, here.roots.length ? here.roots : [ctx.cwd]);
369
+ if (!rel)
370
+ throw usage("<target> is an absolute path outside this repository: give a symbol or a repo-relative path");
371
+ target = rel;
372
+ }
373
+ if (!/^[A-Za-z0-9_$.:#/@+-]{1,300}$/.test(target) || target.startsWith("-"))
374
+ throw usage("<target> must be a symbol or a path");
375
+ let ixOut;
376
+ if (typeof opts.ixJson === "string") {
377
+ const raw = opts.ixJson === "-" ? ((await ctx.io.readStdin?.()) ?? "") : await readFile(resolvePath(ctx.cwd, opts.ixJson), "utf8");
378
+ try {
379
+ ixOut = JSON.parse(raw);
380
+ }
381
+ catch {
382
+ throw usage("--ix-json is not JSON");
383
+ }
384
+ }
385
+ else {
386
+ const argv = ["impact", target, "--format", "json", "--limit", "20"];
387
+ if (typeof opts.kind === "string") {
388
+ if (!/^[a-z][a-z_]{0,31}$/.test(opts.kind))
389
+ throw usage("--kind must be an entity kind");
390
+ argv.push("--kind", opts.kind);
391
+ }
392
+ if (typeof opts.path === "string") {
393
+ if (opts.path.startsWith("-"))
394
+ throw usage("--path must be a path");
395
+ argv.push("--path", opts.path);
396
+ }
397
+ if (opts.depth !== undefined) {
398
+ const d = Number(opts.depth);
399
+ if (!Number.isInteger(d) || d < 1 || d > 3)
400
+ throw usage("--depth must be 1, 2 or 3");
401
+ argv.push("--depth", String(d));
402
+ }
403
+ ixOut = await ixJson(runner(ctx, deps, fromSession || undefined, opts.changed ?? []), argv);
404
+ }
405
+ const repo = opts.withoutRepo ? { roots: here.roots } : here;
406
+ const changed = opts.changed?.map((r) => (isAbsolute(r) ? r : resolvePath(ctx.cwd, r)));
407
+ const { body, fallback } = asUsage(() => buildImpact({ ix: ixOut, repo: repo.ref, changed, root: repo.roots.length ? repo.roots : [ctx.cwd], home: homedir(), hostname: hostname() }));
408
+ if (dryRun)
409
+ return { json: { dryRun: true, body, fallback }, human: JSON.stringify(body, null, 2) };
410
+ const r = await ctx.send({ fromSession, to, kind: IMPACT_KIND, v: SPEC_VERSION, body, fallback });
411
+ return { json: { ...r, body }, human: sentHuman(`an Ix blast-radius report (${body.riskLevel} risk)`, r) };
412
+ },
413
+ },
414
+ {
415
+ name: "inbox",
416
+ description: "Ix notes, subgraph references and impact reports peers sent you",
417
+ options: [{ flags: "--kind <kind>", description: "note, subgraph or impact" }],
418
+ offline: true,
419
+ run: async (ctx, _args, opts) => {
420
+ const kind = typeof opts.kind === "string" ? `x:ix.${opts.kind}` : undefined;
421
+ if (kind && !KINDS.includes(kind))
422
+ throw usage("--kind must be note, subgraph or impact");
423
+ const events = await ctx.events(kind ? { kind } : {});
424
+ const rows = events.map((e) => ({
425
+ id: e.id,
426
+ at: e.at,
427
+ kind: e.kind,
428
+ from: e.from,
429
+ ...(e.ref ? { ref: e.ref } : {}),
430
+ digest: typeof e.rendered?.digest === "string" ? e.rendered.digest : e.fallback,
431
+ ...(e.extError ? { extError: e.extError } : {}),
432
+ kept: e.kept !== undefined,
433
+ }));
434
+ const human = rows.length ? rows.map((r) => `${r.id} ${r.kind.slice(5)} ${r.from.address}: ${r.digest}`).join("\n") : "Nothing from peers yet.";
435
+ return { json: { events: rows }, human };
436
+ },
437
+ },
438
+ {
439
+ name: "show",
440
+ args: "<event>",
441
+ description: "Show a received x:ix.* item in full (read-only)",
442
+ offline: true,
443
+ run: async (ctx, args) => {
444
+ const e = await findEvent(ctx, String(args[0]));
445
+ const event = { id: e.id, at: e.at, kind: e.kind, from: e.from, fallback: e.fallback, rendered: e.rendered, ...(e.extError ? { extError: e.extError } : {}) };
446
+ // L4: everything shown is framed as data from the named peer, in --json too.
447
+ if (e.kind === NOTE_KIND && e.kept) {
448
+ const b = keptBody(e, parseNoteBody);
449
+ const text = noteFull(b, e.from.address);
450
+ // M1: a person read the whole note at a terminal; `import --yes` may rely on that.
451
+ if (ctx.interactive)
452
+ await markShown(ctx, e.id, b);
453
+ const { text: _t, ...rest } = b;
454
+ // `textHash` names exactly this title and text: a client that displayed them in full to its
455
+ // user passes it back as `import --yes --shown=<textHash>`.
456
+ return { json: { event, text, textHash: noteHash(b), body: rest }, human: text };
457
+ }
458
+ const framing = frame(e.from.address, e.kind, "(the body below)").replace(/: \(the body below\)$/, "");
459
+ // `bodyHash` names exactly this body: a client shows it, then passes it back (`resolve --yes --shown=`).
460
+ return { json: { event, framing, body: e.kept?.body, ...(e.kept ? { bodyHash: bodyHash(e.kept.body) } : {}) }, human: String(e.rendered?.digest ?? e.fallback) };
461
+ },
462
+ },
463
+ {
464
+ name: "import",
465
+ args: "<event>",
466
+ description: "Write a received Ix note into your local Ix graph (asks first; the user's decision, never the agent's). Needs an Ix with the OSS `ix note`",
467
+ options: [
468
+ { flags: "--tag <tag>", description: "Override the note's tag" },
469
+ { flags: "--session <name>", description: "Attach it to one of your Ix sessions" },
470
+ { flags: "-y, --yes", description: "Don't ask (the user already agreed)" },
471
+ { flags: "--shown <hash>", description: "With --yes: the textHash `ix show --json` gave for what your client displayed to the user in full" },
472
+ ],
473
+ run: async (ctx, args, opts) => {
474
+ const e = await findEvent(ctx, String(args[0]), NOTE_KIND);
475
+ const b = keptBody(e, parseNoteBody);
476
+ const tag = opts.tag ?? b.tag;
477
+ if (!NOTE_TAGS.includes(tag))
478
+ throw usage(`--tag must be one of ${NOTE_TAGS.join(", ")}`);
479
+ const session = opts.session;
480
+ if (session !== undefined && !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/.test(session))
481
+ throw usage("--session must be an Ix session name or id");
482
+ const address = line(e.from.address, 80);
483
+ const actor = /^[A-Za-z0-9._@-]{1,80}$/.test(address) ? [`--actor=p2p:${address}`] : [];
484
+ const argv = ["note", `--tag=${tag}`, ...(session ? [`--session=${session}`] : []), ...actor, "--json"];
485
+ // Before anything is asked: the graph target must allow this exact call (local, never shared),
486
+ // and the `ix` that answers must have the OSS `ix note` (the local backend), not Ix Pro's (the
487
+ // cloud org) or none (an Ix from before #916: upgrade). The guarded runner checks both again.
488
+ const target = await targetOf(ctx)({ argv, cwd: ctx.cwd });
489
+ const refused = refuseForTarget(argv, target);
490
+ if (refused)
491
+ throw refused;
492
+ const ix = runner(ctx, deps);
493
+ if (!(await ixAvailable(ix)))
494
+ throw new IxExtError("ix_missing", "Ix isn't installed: https://github.com/ix-infrastructure/Ix");
495
+ const support = await memorySupport(ix);
496
+ if (support !== "oss")
497
+ throw memoryRefusal(support, target);
498
+ // And the local endpoint's port must be this user's (listener.ts): checked again by the guard.
499
+ const held = await (deps.listener ?? ((e, o) => checkLoopbackListener(e, { trustRoot: o?.trustRoot === true })))(target.endpoint, { trustRoot: target.kind === "local" && target.trustRootListener === true }).catch(() => ({ ok: false, why: "couldn't tell who listens on its port" }));
500
+ if (!held.ok)
501
+ throw new IxExtError("ix_listener", `the local Ix endpoint ${target.endpoint} isn't one Peer2Peer can trust: ${held.why}`);
502
+ const text = `Shared by ${address} over Peer2Peer${b.title ? `: ${b.title}` : ""}\n\n${b.text}`;
503
+ // M1: consent covers exactly what is written. Either the full title and text are shown here
504
+ // and the user agrees, or --yes after the user read this very note with `p2p ix show` at a terminal.
505
+ if (opts.yes) {
506
+ // A client UI (the Claude mod's typed /peers ix import) shows the full note itself and vouches with
507
+ // the hash of what it showed; a stale or different hash doesn't count.
508
+ const vouched = typeof opts.shown === "string" && opts.shown === noteHash(b);
509
+ if (!vouched && !(await wasShown(ctx, e.id, b))) {
510
+ throw new IxExtError("consent_required", `not imported: the user hasn't read this note in full: run \`p2p ix show ${e.id}\` in a terminal first (or import without --yes there)`);
511
+ }
512
+ }
513
+ else {
514
+ const ok = await ctx.confirm(`${noteFull(b, address)}\n\nWrite all of this ${tag} note (${[...b.text].length} characters, shown in full above) from ${address} into your Ix graph?`);
515
+ if (!ok)
516
+ throw new IxExtError("consent_required", "not imported: the user didn't agree (run it in a terminal, or `p2p ix show` it there and then import with --yes)");
517
+ }
518
+ const r = await ix.run(argv, { stdin: text });
519
+ if (r.code !== 0)
520
+ throw new IxExtError("ix_failed", `ix note failed (exit ${r.code})${r.stderr ? `: ${line(r.stderr, 300)}` : ""}`);
521
+ let created = {};
522
+ try {
523
+ created = JSON.parse(r.stdout);
524
+ }
525
+ catch {
526
+ // older Ix: no JSON
527
+ }
528
+ const id = typeof created.id === "string" ? created.id : undefined;
529
+ return { json: { imported: true, event: e.id, ...(id ? { noteId: id } : {}), tag }, human: `Imported into your Ix graph${id ? ` as note ${id}` : ""}.` };
530
+ },
531
+ },
532
+ {
533
+ name: "resolve",
534
+ args: "<event>",
535
+ description: "Open a received subgraph reference in your own Ix graph (asks first; runs your `ix`, read-only)",
536
+ options: [
537
+ { flags: "--any-repo", description: "Resolve even when this checkout isn't the referenced repo" },
538
+ { flags: "-y, --yes", description: "Don't ask (the user already agreed)" },
539
+ { flags: "--shown <hash>", description: "The bodyHash `ix show --json` gave for what your client displayed; refused if the reference differs" },
540
+ ],
541
+ run: async (ctx, args, opts) => {
542
+ const e = await findEvent(ctx, String(args[0]), SUBGRAPH_KIND);
543
+ const b = keptBody(e, parseSubgraphBody);
544
+ // Bound like import: a client's confirm covers exactly the reference it showed.
545
+ if (typeof opts.shown === "string" && opts.shown !== bodyHash(e.kept.body)) {
546
+ throw new IxExtError("consent_required", "not resolved: the reference isn't the one that was shown (show it again)");
547
+ }
548
+ const local = await repoOf(ctx);
549
+ const cmp = compareRepo(b.repo, local.ref);
550
+ if (!cmp.sameRepo && !opts.anyRepo) {
551
+ throw new IxExtError("other_repo", `the reference is to ${b.repo.remote}, but this checkout is ${local.ref?.remote ?? "not a git repo with an origin"}: run it there, or pass --any-repo`);
552
+ }
553
+ const argv = resolveArgv(b.selector);
554
+ const ok = await ctx.confirm(`Run \`ix ${argv.join(" ")}\` on your graph for ${line(e.from.address, 80)}?`, Boolean(opts.yes));
555
+ if (!ok)
556
+ throw new IxExtError("consent_required", "not resolved: the user didn't agree (run it in a terminal, or with --yes once they have)");
557
+ const ix = runner(ctx, deps);
558
+ const r = await ix.run(argv);
559
+ if (r.code !== 0)
560
+ throw new IxExtError("ix_failed", `ix ${argv[0]} failed (exit ${r.code})${r.stderr ? `: ${line(r.stderr, 300)}` : ""}`);
561
+ const out = r.stdout.length > MAX_RESOLVE_OUTPUT ? `${r.stdout.slice(0, MAX_RESOLVE_OUTPUT)}\n… (truncated)` : r.stdout;
562
+ const warn = cmp.sameRev === false ? `note: they referenced ${b.repo.rev?.slice(0, 12)}, this checkout is at ${local.ref?.rev?.slice(0, 12)}` : undefined;
563
+ return {
564
+ json: { event: e.id, selector: b.selector, repo: b.repo, sameRepo: cmp.sameRepo, ...(cmp.sameRev !== undefined ? { sameRev: cmp.sameRev } : {}), command: ["ix", ...argv], output: out },
565
+ human: [warn, out.trimEnd()].filter(Boolean).join("\n"),
566
+ };
567
+ },
568
+ },
569
+ {
570
+ name: "conflicts",
571
+ description: "Possible semantic conflicts: live peer sessions changing files connected (in your Ix graph) to the ones you're changing",
572
+ options: [
573
+ { flags: "--session <sid>", description: "Your session (its last status gives your files and repo)" },
574
+ { flags: "--file <path>", description: "A repo-relative file you're changing (repeatable; instead of the status)", repeatable: true },
575
+ { flags: "--repo <repo>", description: "Your repo as statuses name it (default: the session's status)" },
576
+ ],
577
+ run: async (ctx, _args, opts) => {
578
+ const own = typeof opts.session === "string" ? await ctx.ownStatus(opts.session) : undefined;
579
+ const mine = opts.file ?? own?.files ?? [];
580
+ const repo = opts.repo ?? own?.repo;
581
+ if (mine.length === 0)
582
+ return { json: { conflicts: [], errors: [], checked: 0 }, human: "No files of yours to check (give --file, or --session with a posted status)." };
583
+ const ix = runner(ctx, deps, typeof opts.session === "string" ? opts.session : undefined, mine);
584
+ if (!(await ixAvailable(ix)))
585
+ throw new IxExtError("ix_missing", "Ix isn't installed: https://github.com/ix-infrastructure/Ix");
586
+ // For a session: only sessions its status reaches (project boundaries), and this user's own.
587
+ const reach = typeof opts.session === "string" ? await audienceOf(ctx, opts.session, (await ctx.self()).userId) : undefined;
588
+ const peers = (await ctx.peers()).filter((p) => p.live && !p.thisDevice && !(p.self && p.sid === opts.session) && (!reach || reach.has(p.own)));
589
+ const r = await semanticConflicts({ mine, peers, repo, neighbourhood: ixNeighbourhood(ix) });
590
+ const human = r.conflicts.length ? r.conflicts.map((c) => c.message).join("\n") : `No semantic conflicts with ${peers.length} live session${peers.length === 1 ? "" : "s"}.`;
591
+ return { json: { ...r, checked: peers.length }, human };
592
+ },
593
+ },
594
+ ...footprintCommands(deps, { runner, repoOf }),
595
+ ];
596
+ }
597
+ export function createIxExtension(deps = {}) {
598
+ return {
599
+ api: 1,
600
+ // Every Ix call takes its endpoint from ExtContext.graphTarget (p2p refuses an ext-ix without this).
601
+ graphTargets: 1,
602
+ ns: "ix",
603
+ name: "@peer2peer/ext-ix",
604
+ version: VERSION,
605
+ description: "Ix: share notes, subgraph references and blast-radius reports; semantic conflicts; session footprints",
606
+ receive: receiveIx,
607
+ commands: ixCommands(deps),
608
+ // x:ix.footprint is a state kind: published to the session's status audience, kept latest-wins.
609
+ state: { [FOOTPRINT_KIND]: { ttl: FOOTPRINT_TTL } },
610
+ // Graph memory (SPEC §10): this device's own sessions' context, into the local graph only.
611
+ memory: ixMemory((ctx, sid) => runner(ctx, deps, sid), deps.listener),
612
+ };
613
+ }
614
+ /** What `p2p` loads. */
615
+ export const extension = createIxExtension();