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