@peer2peer/ext-ix 0.1.0 → 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,50 @@
1
+ import type { ExtContext, ExtMemory, ExtMemoryItem } from "@peer2peer/cli";
2
+ import { type IxRunner } from "./ix.js";
3
+ import { type ListenerCheck } from "./listener.js";
4
+ /** How long Ix keeps a session record: 30 days. */
5
+ export declare const MEMORY_TTL_HOURS = 720;
6
+ /** At most this many sessions' Ix ids are remembered (ExtContext.kv is 64 KiB). */
7
+ export declare const MAX_MEMORY_SESSIONS = 50;
8
+ /** Longest one-line text written per item (characters). */
9
+ export declare const MAX_MEMORY_LINE = 300;
10
+ /** At most this many files named per note. */
11
+ export declare const MAX_MEMORY_FILES = 50;
12
+ /** Longest file name written (characters). */
13
+ export declare const MAX_MEMORY_PATH = 200;
14
+ /** Bound on one `ix` call made for memory. */
15
+ export declare const MEMORY_IX_TIMEOUT_MS = 15000;
16
+ /** The tag of every record (the person's own notes are usually `note`). */
17
+ export declare const MEMORY_TAG = "finding";
18
+ /** The first line of every record: what it is, and that it isn't instructions. */
19
+ export declare const MEMORY_PREFIX = "Recorded by Peer2Peer (agent-generated, untrusted)";
20
+ /** One line: control and format characters dropped, whitespace collapsed, capped. */
21
+ export declare function oneLine(s: unknown, max?: number): string;
22
+ /** The Ix session name of Peer2Peer session `sid`: `p2p-<sid>`, or `p2p-` and its hash when the id doesn't fit. */
23
+ export declare function memorySessionName(sid: string): string;
24
+ /** `--actor=`: `p2p:<address>` when the address is a plain one, else `p2p`. */
25
+ export declare function memoryActor(address: string | undefined): string;
26
+ /** The session record's purpose (one line, at most MAX_PURPOSE characters). */
27
+ export declare function memoryPurpose(i: Pick<ExtMemoryItem, "label" | "repo" | "branch">): string;
28
+ /** A file name a record may carry: repo-relative, no `.`/`..`, no whitespace or control character, capped. */
29
+ export declare function memoryPath(f: unknown): f is string;
30
+ /** The note text of one item; undefined when there is nothing to write (an empty status, no valid file). */
31
+ export declare function memoryText(i: ExtMemoryItem): string | undefined;
32
+ /**
33
+ * The Peer2Peer session a note was recorded for, when it is one of graph memory's records: its
34
+ * Ix session is one this extension created (by id), or is named `p2p-<sid>`, or its text starts
35
+ * with MEMORY_PREFIX. `{sid: undefined}` for a record whose session can't be told (a hashed name,
36
+ * no session): the caller must refuse it. Undefined for any other note.
37
+ */
38
+ export declare function recordOf(ctx: ExtContext, note: {
39
+ sessionId?: unknown;
40
+ sessionName?: unknown;
41
+ text?: unknown;
42
+ }): Promise<{
43
+ sid: string | undefined;
44
+ } | undefined>;
45
+ /**
46
+ * The memory writer. `runner(ctx, sid)` is the guarded runner of a call made for session `sid`
47
+ * (extension.ts runner: pinned to that session's graph target, OSS-only for note and session, the
48
+ * port's listener checked). `listener` is the same check, for available().
49
+ */
50
+ export declare function ixMemory(runner: (ctx: ExtContext, sid?: string) => IxRunner, listener?: ListenerCheck): ExtMemory;
package/dist/memory.js ADDED
@@ -0,0 +1,315 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // Local graph as memory (epic #41 piece 2; SPEC.md §10): the context of this device's own sessions,
4
+ // written into the person's local Ix graph as it happens. `p2p watch` gathers it from the statuses
5
+ // the session posted (packages/p2p/src/graph-memory.ts; only sessions whose project ceiling is
6
+ // shared: a private project's sessions are never recorded), queues it, and hands it here in
7
+ // batches, off the hook path. Per session:
8
+ //
9
+ // ix session --json create p2p-<sid> --purpose=<label, repo, branch> --actor=p2p:<address> --ttl=720
10
+ // ix note --tag=finding --session=<its id> --actor=p2p:<address> --json
11
+ // < "Recorded by Peer2Peer (agent-generated, untrusted)\nSession started …" (and Status, Edited, Session ended)
12
+ //
13
+ // Every call goes through the guarded runner (ix.ts guardRunner): the graph target of the session
14
+ // (p2p's chokepoint) must be local, the port must be held by this user (listener.ts), the `ix` that
15
+ // answers must have the OSS `ix note` / `ix session` (never Ix Pro's, which write to the cloud org),
16
+ // and each write must say on stderr that it reached the local endpoint. Text goes on stdin only.
17
+ // Records are framed as untrusted (agent-generated) and tagged `finding`, so a reader can tell them
18
+ // from the person's own notes.
19
+ import { createHash } from "node:crypto";
20
+ import { isSafeRelativePath } from "@peer2peer/core/v3";
21
+ import { checkedTarget, IX_ACTOR_RE, IX_SESSION_NAME_RE, IX_SESSION_REF_RE, ixAvailable, MAX_PURPOSE, memoryRefusal, memorySupport } from "./ix.js";
22
+ import { checkLoopbackListener } from "./listener.js";
23
+ import { IxExtError } from "./text.js";
24
+ /** How long Ix keeps a session record: 30 days. */
25
+ export const MEMORY_TTL_HOURS = 720;
26
+ /** At most this many sessions' Ix ids are remembered (ExtContext.kv is 64 KiB). */
27
+ export const MAX_MEMORY_SESSIONS = 50;
28
+ /** Longest one-line text written per item (characters). */
29
+ export const MAX_MEMORY_LINE = 300;
30
+ /** At most this many files named per note. */
31
+ export const MAX_MEMORY_FILES = 50;
32
+ /** Longest file name written (characters). */
33
+ export const MAX_MEMORY_PATH = 200;
34
+ /** Bound on one `ix` call made for memory. */
35
+ export const MEMORY_IX_TIMEOUT_MS = 15_000;
36
+ /** The tag of every record (the person's own notes are usually `note`). */
37
+ export const MEMORY_TAG = "finding";
38
+ /** The first line of every record: what it is, and that it isn't instructions. */
39
+ export const MEMORY_PREFIX = "Recorded by Peer2Peer (agent-generated, untrusted)";
40
+ const KV_KEY = "memory";
41
+ /** One line: control and format characters dropped, whitespace collapsed, capped. */
42
+ export function oneLine(s, max = MAX_MEMORY_LINE) {
43
+ if (typeof s !== "string")
44
+ return "";
45
+ const t = s
46
+ .replace(/[\p{Cc}\p{Cf}\u2028\u2029]+/gu, " ")
47
+ .replace(/\s+/g, " ")
48
+ .trim();
49
+ const cps = [...t];
50
+ return cps.length > max ? `${cps.slice(0, max - 1).join("")}…` : t;
51
+ }
52
+ /** The Ix session name of Peer2Peer session `sid`: `p2p-<sid>`, or `p2p-` and its hash when the id doesn't fit. */
53
+ export function memorySessionName(sid) {
54
+ const name = `p2p-${sid}`;
55
+ return IX_SESSION_NAME_RE.test(name) ? name : `p2p-${createHash("sha256").update(sid).digest("hex").slice(0, 32)}`;
56
+ }
57
+ /** `--actor=`: `p2p:<address>` when the address is a plain one, else `p2p`. */
58
+ export function memoryActor(address) {
59
+ const a = `p2p:${address ?? ""}`;
60
+ return IX_ACTOR_RE.test(a) ? a : "p2p";
61
+ }
62
+ const iso = (ms) => (Number.isFinite(ms) && ms > 0 ? new Date(ms).toISOString() : new Date().toISOString());
63
+ /** Where a session runs, in words: `label (repo widgets, branch main)`. */
64
+ function where(i) {
65
+ const label = oneLine(i.label, 64) || "session";
66
+ const bits = [i.repo ? `repo ${oneLine(i.repo, 100)}` : "", i.branch ? `branch ${oneLine(i.branch, 100)}` : ""].filter(Boolean);
67
+ return bits.length ? `${label} (${bits.join(", ")})` : label;
68
+ }
69
+ /** The session record's purpose (one line, at most MAX_PURPOSE characters). */
70
+ export function memoryPurpose(i) {
71
+ return oneLine(`Peer2Peer session ${where(i)}`, MAX_PURPOSE);
72
+ }
73
+ /** A file name a record may carry: repo-relative, no `.`/`..`, no whitespace or control character, capped. */
74
+ export function memoryPath(f) {
75
+ return typeof f === "string" && f.length > 0 && [...f].length <= MAX_MEMORY_PATH && isSafeRelativePath(f) && !/[\s\p{Cc}\p{Cf}\u2028\u2029]/u.test(f);
76
+ }
77
+ /** The note text of one item; undefined when there is nothing to write (an empty status, no valid file). */
78
+ export function memoryText(i) {
79
+ let body;
80
+ switch (i.kind) {
81
+ case "start":
82
+ body = `Session started ${iso(i.at)}: ${where(i)}.`;
83
+ break;
84
+ case "status": {
85
+ const s = oneLine(i.summary);
86
+ body = s ? `Status (${iso(i.at)}): ${s}` : undefined;
87
+ break;
88
+ }
89
+ case "files": {
90
+ const files = [...new Set((i.files ?? []).filter(memoryPath))];
91
+ if (files.length === 0)
92
+ return undefined;
93
+ const shown = files.slice(0, MAX_MEMORY_FILES);
94
+ body = `Edited (${iso(i.at)}): ${shown.join(", ")}${files.length > shown.length ? ` and ${files.length - shown.length} more` : ""}`;
95
+ break;
96
+ }
97
+ case "end":
98
+ body = `Session ended ${iso(i.at)}.`;
99
+ break;
100
+ default:
101
+ return undefined;
102
+ }
103
+ return body === undefined ? undefined : `${MEMORY_PREFIX}\n${body}`;
104
+ }
105
+ /** The store's sessions in one canonical form, for its MAC. */
106
+ function canon(sessions) {
107
+ return JSON.stringify(Object.keys(sessions)
108
+ .sort()
109
+ .map((k) => [k, sessions[k].id, sessions[k].endpoint, sessions[k].at]));
110
+ }
111
+ /**
112
+ * The store (`<home>/ext/ix.json`, key `memory`), MACed with the device's key when the host offers
113
+ * one (ExtContext.localMac): anything that can write files in P2P_HOME without the keys (a model's
114
+ * file tools) can't plant a mapping from a session to another Ix session. A MAC that doesn't verify
115
+ * means no record at all: sessions are made again, and recordOf traces nothing through it.
116
+ */
117
+ async function loadKv(ctx) {
118
+ const v = (await ctx.kv.get(KV_KEY));
119
+ const sessions = {};
120
+ if (v && typeof v.sessions === "object" && v.sessions !== null) {
121
+ for (const [sid, s] of Object.entries(v.sessions)) {
122
+ if (s && typeof s.id === "string" && IX_SESSION_REF_RE.test(s.id) && typeof s.endpoint === "string" && typeof s.at === "number")
123
+ sessions[sid] = { id: s.id, endpoint: s.endpoint, at: s.at };
124
+ }
125
+ }
126
+ if (typeof ctx.localMac === "function") {
127
+ let ok;
128
+ try {
129
+ ok = typeof v?.mac === "string" && v.mac === ctx.localMac(canon(sessions));
130
+ }
131
+ catch {
132
+ ok = false;
133
+ }
134
+ if (!ok)
135
+ return { sessions: {} };
136
+ }
137
+ return { sessions };
138
+ }
139
+ async function saveKv(ctx, kv) {
140
+ const kept = Object.entries(kv.sessions)
141
+ .sort((a, b) => a[1].at - b[1].at)
142
+ .slice(-MAX_MEMORY_SESSIONS);
143
+ const sessions = Object.fromEntries(kept);
144
+ let mac;
145
+ try {
146
+ mac = typeof ctx.localMac === "function" ? ctx.localMac(canon(sessions)) : undefined;
147
+ }
148
+ catch {
149
+ mac = undefined;
150
+ }
151
+ await ctx.kv.set(KV_KEY, { sessions, ...(mac ? { mac } : {}) });
152
+ }
153
+ /**
154
+ * The Peer2Peer session a note was recorded for, when it is one of graph memory's records: its
155
+ * Ix session is one this extension created (by id), or is named `p2p-<sid>`, or its text starts
156
+ * with MEMORY_PREFIX. `{sid: undefined}` for a record whose session can't be told (a hashed name,
157
+ * no session): the caller must refuse it. Undefined for any other note.
158
+ */
159
+ export async function recordOf(ctx, note) {
160
+ const kv = await loadKv(ctx);
161
+ if (typeof note.sessionId === "string") {
162
+ const hit = Object.entries(kv.sessions).find(([, s]) => s.id === note.sessionId);
163
+ if (hit)
164
+ return { sid: hit[0] };
165
+ }
166
+ if (typeof note.sessionName === "string" && note.sessionName.startsWith("p2p-")) {
167
+ const rest = note.sessionName.slice(4);
168
+ // A hashed name (an id that didn't fit) can't be traced back.
169
+ return { sid: /^[0-9a-f]{32}$/.test(rest) ? undefined : rest };
170
+ }
171
+ if (typeof note.text === "string" && note.text.startsWith(MEMORY_PREFIX))
172
+ return { sid: undefined };
173
+ return undefined;
174
+ }
175
+ /** An error's reason code (IxExtError's, else ix_failed). */
176
+ const reasonOf = (e) => (e instanceof IxExtError ? e.code : "ix_failed");
177
+ /** Reasons that stop a batch and turn memory off until available() says otherwise. */
178
+ const STOPS = new Set(["graph_target", "ix_unconfirmed", "ix_missing", "ix_listener", "aborted"]);
179
+ /** What available() reports for a support answer that isn't "oss". */
180
+ function unavailable(support, installed) {
181
+ if (!installed)
182
+ return { ok: false, reason: "ix_missing", message: "Ix isn't installed: graph memory is off (https://github.com/ix-infrastructure/Ix)" };
183
+ const e = memoryRefusal(support, { kind: "local", endpoint: "" });
184
+ return { ok: false, reason: support === "pro" ? "ix_pro" : "ix_upgrade", message: e.message };
185
+ }
186
+ /** The local target of `sid` (checked again here), or undefined when it isn't local. */
187
+ async function localOf(ctx, sid) {
188
+ let t;
189
+ try {
190
+ t = ctx.graphTarget ? checkedTarget(await ctx.graphTarget(sid ? { sid } : {})) : checkedTarget(undefined);
191
+ }
192
+ catch {
193
+ t = checkedTarget(undefined);
194
+ }
195
+ return t.kind === "local" ? t : undefined;
196
+ }
197
+ /**
198
+ * The memory writer. `runner(ctx, sid)` is the guarded runner of a call made for session `sid`
199
+ * (extension.ts runner: pinned to that session's graph target, OSS-only for note and session, the
200
+ * port's listener checked). `listener` is the same check, for available().
201
+ */
202
+ export function ixMemory(runner, listener = (e, o) => checkLoopbackListener(e, { trustRoot: o?.trustRoot === true })) {
203
+ return {
204
+ v: 1,
205
+ available: async (ctx) => {
206
+ const ix = runner(ctx);
207
+ if (!(await ixAvailable(ix)))
208
+ return unavailable("none", false);
209
+ const s = await memorySupport(ix);
210
+ if (s !== "oss")
211
+ return unavailable(s, true);
212
+ const t = await localOf(ctx);
213
+ if (!t)
214
+ return { ok: false, reason: "not_local", message: "graph memory goes to the local graph only" };
215
+ const v = await listener(t.endpoint, { trustRoot: t.trustRootListener === true }).catch(() => ({ ok: false, why: "couldn't tell who listens on its port" }));
216
+ return v.ok ? { ok: true } : { ok: false, reason: "ix_listener", message: `the local Ix endpoint ${t.endpoint} isn't one Peer2Peer can trust: ${v.why}` };
217
+ },
218
+ write: async (ctx, batch) => {
219
+ const items = Array.isArray(batch?.items) ? batch.items : [];
220
+ const sid = typeof batch?.sid === "string" ? batch.sid : "";
221
+ const signal = batch?.signal;
222
+ if (items.length === 0 || sid === "")
223
+ return { written: 0 };
224
+ // The chokepoint first, for the whole batch: anything but local is refused, before any `ix` runs.
225
+ const target = await localOf(ctx, sid);
226
+ if (!target) {
227
+ return { written: 0, failed: [{ reason: "not_local", n: items.length, message: "graph memory goes to the local graph only, and this session's target isn't local" }] };
228
+ }
229
+ const ix = runner(ctx, sid);
230
+ const actor = memoryActor((await ctx.self().catch(() => undefined))?.address);
231
+ const kv = await loadKv(ctx);
232
+ let written = 0;
233
+ const failed = new Map();
234
+ const fail = (reason, n, message) => {
235
+ const f = failed.get(reason) ?? { n: 0 };
236
+ failed.set(reason, { n: f.n + n, message: message ?? f.message });
237
+ };
238
+ const aborted = () => {
239
+ if (signal?.aborted)
240
+ throw new IxExtError("aborted", "the batch ran out of time");
241
+ };
242
+ let checked = false;
243
+ const sessionId = async (first) => {
244
+ const known = kv.sessions[sid];
245
+ // Remembered for this endpoint, and still there (checked once per batch): used. Gone (the
246
+ // backend was reset), or created at another endpoint: made again.
247
+ if (known && known.endpoint === target.endpoint) {
248
+ if (checked)
249
+ return known.id;
250
+ aborted();
251
+ const r = await ix.run(["session", "--json", "show", known.id], { timeoutMs: MEMORY_IX_TIMEOUT_MS });
252
+ let same;
253
+ try {
254
+ same = r.code === 0 && JSON.parse(r.stdout).sessionId === known.id;
255
+ }
256
+ catch {
257
+ same = false;
258
+ }
259
+ checked = true;
260
+ if (same)
261
+ return known.id;
262
+ }
263
+ delete kv.sessions[sid];
264
+ aborted();
265
+ const argv = ["session", "--json", "create", memorySessionName(sid), `--purpose=${memoryPurpose(first)}`, `--actor=${actor}`, `--ttl=${MEMORY_TTL_HOURS}`];
266
+ const r = await ix.run(argv, { timeoutMs: MEMORY_IX_TIMEOUT_MS });
267
+ if (r.code !== 0)
268
+ throw new IxExtError("ix_failed", `ix session create failed (exit ${r.code})`);
269
+ let id;
270
+ try {
271
+ id = JSON.parse(r.stdout).sessionId;
272
+ }
273
+ catch {
274
+ id = undefined;
275
+ }
276
+ if (typeof id !== "string" || !IX_SESSION_REF_RE.test(id))
277
+ throw new IxExtError("ix_failed", "ix session create printed no session id");
278
+ kv.sessions[sid] = { id, endpoint: target.endpoint, at: Date.now() };
279
+ checked = true;
280
+ await saveKv(ctx, kv);
281
+ return id;
282
+ };
283
+ for (let i = 0; i < items.length; i++) {
284
+ const item = items[i];
285
+ const text = memoryText(item);
286
+ if (text === undefined)
287
+ continue;
288
+ try {
289
+ aborted();
290
+ const ixSession = await sessionId(item);
291
+ aborted();
292
+ const r = await ix.run(["note", `--tag=${MEMORY_TAG}`, `--session=${ixSession}`, `--actor=${actor}`, "--json"], { stdin: text, timeoutMs: MEMORY_IX_TIMEOUT_MS });
293
+ if (r.code !== 0)
294
+ throw new IxExtError("ix_failed", `ix note failed (exit ${r.code})`);
295
+ written++;
296
+ }
297
+ catch (e) {
298
+ const reason = reasonOf(e);
299
+ const message = e instanceof Error ? e.message : undefined;
300
+ if (STOPS.has(reason)) {
301
+ fail(reason, items.length - i, message);
302
+ const support = e.extra?.ix;
303
+ return {
304
+ written,
305
+ failed: [...failed].map(([r, f]) => ({ reason: r, ...f })),
306
+ ...(reason === "aborted" ? {} : { unavailable: { ok: false, reason: support === "pro" ? "ix_pro" : support === "upgrade" ? "ix_upgrade" : reason, message: message ?? reason } }),
307
+ };
308
+ }
309
+ fail(reason, 1, message);
310
+ }
311
+ }
312
+ return { written, ...(failed.size ? { failed: [...failed].map(([reason, f]) => ({ reason, ...f })) } : {}) };
313
+ },
314
+ };
315
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peer2peer/ext-ix",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "The Ix extension for Peer2Peer v3: share Ix session notes, subgraph references and blast-radius reports between agent sessions (x:ix.note, x:ix.subgraph, x:ix.impact), and flag semantic conflicts. Needs only a local Ix install.",
5
5
  "keywords": [
6
6
  "peer2peer",
@@ -50,10 +50,10 @@
50
50
  "registry": "https://registry.npmjs.org/"
51
51
  },
52
52
  "dependencies": {
53
- "@peer2peer/core": "0.1.0"
53
+ "@peer2peer/core": "0.1.1"
54
54
  },
55
55
  "peerDependencies": {
56
- "@peer2peer/cli": "^0.1.0"
56
+ "@peer2peer/cli": "^0.1.1"
57
57
  },
58
58
  "peerDependenciesMeta": {
59
59
  "@peer2peer/cli": {