@peer2peer/cli 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.
package/dist/config.js CHANGED
@@ -22,6 +22,57 @@ import { join } from "node:path";
22
22
  import { fileURLToPath } from "node:url";
23
23
  import { canonicalRelayUrl, MAX_RELAYS, relayHttpsBase } from "@peer2peer/core/v3";
24
24
  import { CliError } from "./errors.js";
25
+ /**
26
+ * Whether `p2p watch` writes this device's sessions' context into the local Ix graph (graph-memory.ts):
27
+ * on by default (it needs the Ix extension and an Ix with the OSS `ix note`). `"ixMemory": false` in
28
+ * config.json turns it off, and so does P2P_IX_MEMORY=0 (or `false`). The environment can only turn it
29
+ * off: it never overrides the person's `false`.
30
+ */
31
+ export function graphMemoryEnabled(env, home) {
32
+ const v = env.P2P_IX_MEMORY?.trim().toLowerCase();
33
+ if (v === "0" || v === "false")
34
+ return false;
35
+ try {
36
+ return readFileConfig(home).ixMemory !== false;
37
+ }
38
+ catch {
39
+ return true;
40
+ }
41
+ }
42
+ /** Whether your own agent sessions' messages skip the hold (FileConfig.ownAgentsDeliver). */
43
+ export function ownAgentsDeliver(home) {
44
+ try {
45
+ return readFileConfig(home).ownAgentsDeliver === true;
46
+ }
47
+ catch {
48
+ return false;
49
+ }
50
+ }
51
+ /** The other devices whose sessions skip the hold (FileConfig.ownDevicesDeliver): none, a list, or every other one. */
52
+ export function ownDevicesDeliver(home) {
53
+ try {
54
+ const v = readFileConfig(home).ownDevicesDeliver;
55
+ if (v === "all-other")
56
+ return v;
57
+ return Array.isArray(v) ? v.filter((d) => typeof d === "string") : [];
58
+ }
59
+ catch {
60
+ return [];
61
+ }
62
+ }
63
+ /**
64
+ * Whether a message from one of your own agent sessions on device `did` skips the hold now (read at
65
+ * delivery time, never stamped on an event): `own-agents deliver`, or `--devices` naming that device
66
+ * (another device than this one).
67
+ */
68
+ export function ownAgentsDeliverFrom(home, did, thisDevice) {
69
+ if (ownAgentsDeliver(home))
70
+ return true;
71
+ if (did === thisDevice)
72
+ return false;
73
+ const devices = ownDevicesDeliver(home);
74
+ return devices === "all-other" || devices.includes(did);
75
+ }
25
76
  /**
26
77
  * Whether this device puts its caps and client version in the identity document (`dinfo`).
27
78
  * Off by default in this release: pre-release clients from before protocol 3.1 refuse
package/dist/doctor.d.ts CHANGED
@@ -64,6 +64,7 @@ export interface HttpProbe {
64
64
  /** One bounded GET (the relay's document API), with its latency and the server's Date header. */
65
65
  export declare function httpProbe(url: string, timeoutMs: number, opts?: {
66
66
  maxBody?: number;
67
+ noRedirect?: boolean;
67
68
  }): Promise<HttpProbe>;
68
69
  export interface WsProbe {
69
70
  /** Dial + hello (+ auth) took this long. */
@@ -83,6 +84,10 @@ export declare function modVersions(root: string): Promise<{
83
84
  plugin?: string;
84
85
  bundled?: string;
85
86
  }>;
87
+ declare class Checks {
88
+ readonly list: Check[];
89
+ add(id: string, status: CheckStatus, title: string, detail: string, fix?: string): Check;
90
+ }
86
91
  /**
87
92
  * The clock check from each relay's skew (seconds, + when this device is ahead): ✓ under
88
93
  * SKEW_OK_SEC, ? (a warning) up to the protocol's limit (SKEW_FAIL_SEC, 300 s), ✗ only past it.
@@ -91,9 +96,18 @@ export declare function clockVerdict(skews: readonly {
91
96
  relay: string;
92
97
  sec: number;
93
98
  }[]): Check;
99
+ /**
100
+ * The Ix section: the binary and its version, the local backend (reachable at the local endpoint),
101
+ * whether the project here is mapped, and the graph target of the project here and of each project
102
+ * with a policy ("local only" today). Without Ix nothing is a failure: Peer2Peer works without it.
103
+ * `ix` runs as ext-ix runs it (ix-local.ts): absolute path, allowlisted environment, the local
104
+ * endpoint pinned, read-only commands, bounded.
105
+ */
106
+ export declare function ixChecks(c: Checks, app: App, ms: number): Promise<void>;
94
107
  export declare function summarize(checks: readonly Check[]): DoctorResult["summary"];
95
108
  /** The doctor's per-step bound: P2P_DOCTOR_TIMEOUT_MS (default 5 s), never more than the connect timeout. */
96
109
  export declare function doctorTimeoutMs(app: App, override?: number): number;
97
110
  export declare function doctor(app: App, o: DoctorOptions): Promise<DoctorResult>;
98
111
  /** Human output: one line per check (✓ ✗ ?), with its fix indented below. */
99
112
  export declare function formatDoctor(r: DoctorResult): string;
113
+ export {};
package/dist/doctor.js CHANGED
@@ -33,6 +33,11 @@ import { defaultRelays } from "./config.js";
33
33
  import { CliError } from "./errors.js";
34
34
  import { readCapped, RelayConnection } from "./relay-client.js";
35
35
  import { rosterAudience, sessionRef } from "./sessions.js";
36
+ import { enabledNamespaces } from "./extensions.js";
37
+ import { extIxInstalled, ixBinary, IX_INSTALL_URL, ixMemorySupport, ixVersion, runIx } from "./ix-local.js";
38
+ import { graphMemoryReport } from "./graph-memory.js";
39
+ import { graphMemoryEnabled } from "./config.js";
40
+ import { describeGraphTarget, listProjects, localGraphEndpoint, projectOf, projectsDoc, projectGraphTarget, sessionWorkdir } from "./projects.js";
36
41
  /**
37
42
  * Clock skew. Signed objects (device certificates, documents, caps, invites, statements) are
38
43
  * refused when their `iat` is more than DEFAULT_SKEW_SEC (300 s) ahead of the verifier's clock,
@@ -95,7 +100,7 @@ export async function httpProbe(url, timeoutMs, opts = {}) {
95
100
  t.unref?.();
96
101
  const t0 = Date.now();
97
102
  try {
98
- const res = await fetch(url, { signal: ctl.signal, headers: { accept: "application/json" } });
103
+ const res = await fetch(url, { signal: ctl.signal, headers: { accept: "application/json" }, ...(opts.noRedirect ? { redirect: "error" } : {}) });
99
104
  const t1 = Date.now();
100
105
  const date = res.headers.get("date");
101
106
  const serverMs = date ? Date.parse(date) : NaN;
@@ -495,9 +500,117 @@ async function deviceChecks(c, app, o, ms, reports) {
495
500
  if (dropped > 0) {
496
501
  c.add("inbound", "unknown", "incoming envelopes", `${dropped} couldn't be applied and ${dropped === 1 ? "was" : "were"} dropped after failing for good (or every attempt)`, "if messages from someone seem missing, ask them to send again; P2P_DEBUG=1 on `p2p ls` shows why one fails");
497
502
  }
503
+ await ixChecks(c, app, ms);
498
504
  await versionCheck(c, app, o, ms);
499
505
  }
500
506
  // ---------------------------------------------------------------------------
507
+ // Ix (epic #41): the local CLI, its backend, this checkout's map, and each project's graph target
508
+ /** At most this many projects' graph targets are listed. */
509
+ const MAX_GRAPH_ROWS = 10;
510
+ /**
511
+ * The Ix section: the binary and its version, the local backend (reachable at the local endpoint),
512
+ * whether the project here is mapped, and the graph target of the project here and of each project
513
+ * with a policy ("local only" today). Without Ix nothing is a failure: Peer2Peer works without it.
514
+ * `ix` runs as ext-ix runs it (ix-local.ts): absolute path, allowlisted environment, the local
515
+ * endpoint pinned, read-only commands, bounded.
516
+ */
517
+ export async function ixChecks(c, app, ms) {
518
+ const local = localGraphEndpoint(app.env, app.file);
519
+ const target = { endpoint: local };
520
+ const bin = ixBinary(app.env);
521
+ const on = enabledNamespaces(app.env, app.file).enabled.includes("ix");
522
+ if (!bin) {
523
+ c.add("ix", "unknown", "Ix", "the Ix CLI isn't installed (Peer2Peer works without it; peers' Ix items show as plain text)", `install Ix (${IX_INSTALL_URL}), then \`p2p extensions enable ix\``);
524
+ }
525
+ else {
526
+ const v = (await bounded(ixVersion(bin, app.env, target, ms), ms + 500)).value;
527
+ if (v)
528
+ c.add("ix", "ok", "Ix", `ix ${v} (${bin})`);
529
+ else
530
+ c.add("ix", "unknown", "Ix", `${bin} didn't answer \`ix --version\` in time`, "run `ix --version` in a terminal");
531
+ if (on)
532
+ c.add("ix-extension", "ok", "Ix extension", "enabled: sessions can share Ix context");
533
+ else
534
+ c.add("ix-extension", "unknown", "Ix extension", "not enabled", extIxInstalled(app.env) ? "`p2p extensions enable ix`" : "`npm i -g @peer2peer/ext-ix`, then `p2p extensions enable ix`");
535
+ if (on)
536
+ await graphMemoryChecks(c, app, bin, target, ms);
537
+ // Never followed elsewhere: a loopback listener that redirects is not the local backend.
538
+ const h = await httpProbe(`${local}/v1/health`, ms, { noRedirect: true });
539
+ if (h.ok && h.status !== undefined && h.status < 500)
540
+ c.add("ix-backend", "ok", "Ix backend", `reachable at ${local} (${h.ms} ms)`);
541
+ else
542
+ c.add("ix-backend", "fail", "Ix backend", `nothing answers at ${local}${h.error ? `: ${h.error}` : h.status ? ` (HTTP ${h.status})` : ""}`, "start it with `ix docker start` (or set `ixEndpoint` in config.json to your local backend)");
543
+ const here = projectOf(sessionWorkdir(app.env));
544
+ if (here.kind === "git" && h.ok) {
545
+ const st = (await bounded(runIx(bin, ["status", "--format", "json", "--root", here.root], { env: app.env, target, cwd: here.root, timeoutMs: ms }), ms + 500)).value;
546
+ let mapped;
547
+ try {
548
+ const j = st && st.code === 0 ? JSON.parse(st.stdout) : undefined;
549
+ mapped = j ? j.graphCompleted === true : undefined;
550
+ }
551
+ catch {
552
+ mapped = undefined;
553
+ }
554
+ if (mapped === true)
555
+ c.add("ix-workspace", "ok", "Ix workspace", `${here.name} is mapped`);
556
+ else if (mapped === false)
557
+ c.add("ix-workspace", "unknown", "Ix workspace", `${here.name} isn't mapped yet`, `run \`ix map\` in ${here.root}`);
558
+ else
559
+ c.add("ix-workspace", "unknown", "Ix workspace", `couldn't tell whether ${here.name} is mapped`, "run `ix status` in it");
560
+ }
561
+ }
562
+ // Graph targets: the project here first, then each project with a policy.
563
+ const doc = (await bounded(projectsDoc(app), ms)).value ?? { v: 1, projects: {} };
564
+ const here = projectOf(sessionWorkdir(app.env));
565
+ const rows = [{ id: here.id, name: here.name, ...(here.repoPrivate ? { repoPrivate: true } : {}) }];
566
+ const all = (await bounded(listProjects(app), ms)).value ?? [];
567
+ for (const p of all)
568
+ if (!rows.some((r) => r.id === p.id))
569
+ rows.push({ id: p.id, name: p.name });
570
+ for (const r of rows.slice(0, MAX_GRAPH_ROWS)) {
571
+ const t = projectGraphTarget(app, r, doc);
572
+ c.add(`graph:${r.id}`, "ok", `graph of project ${peer(r.name)}${r.id === here.id ? " (here)" : ""}`, `${describeGraphTarget(t)}${t.kind === "local" ? `: ${t.why}` : ""}`);
573
+ }
574
+ if (rows.length > MAX_GRAPH_ROWS)
575
+ c.add("graph:more", "ok", "graphs of other projects", `${rows.length - MAX_GRAPH_ROWS} more not listed (run \`p2p project show\` in each)`);
576
+ }
577
+ /**
578
+ * Graph memory (graph-memory.ts): whether this Ix has the OSS `ix note` (local) or Ix Pro's (cloud,
579
+ * so memory stays off), and what `p2p watch` wrote, queued and dropped. Never a failure: Peer2Peer
580
+ * works without it.
581
+ */
582
+ async function graphMemoryChecks(c, app, bin, target, ms) {
583
+ if (!graphMemoryEnabled(app.env, app.home)) {
584
+ c.add("ix-memory", "ok", "Ix graph memory", 'off ("ixMemory": false in config.json, or P2P_IX_MEMORY=0)');
585
+ return;
586
+ }
587
+ const support = (await bounded(ixMemorySupport(bin, app.env, target, ms), ms + 500)).value;
588
+ const doc = (await bounded(graphMemoryReport(app), ms)).value;
589
+ const counts = doc ? `${doc.written} written, ${doc.queue.length} queued` : "nothing written yet";
590
+ const dropped = doc ? Object.entries(doc.dropped).filter(([, n]) => n > 0) : [];
591
+ if (support === "oss")
592
+ c.add("ix-memory", "ok", "Ix graph memory", `on: sessions' records, statuses and edited files go to the local graph only (${target.endpoint}); ${counts}`);
593
+ else if (support === "pro")
594
+ c.add("ix-memory", "unknown", "Ix graph memory", "off: Ix Pro is installed, and its `ix note` writes to your cloud org; Peer2Peer keeps graph writes local", "use an Ix without Pro for local notes (or leave it off)");
595
+ else if (support === "none")
596
+ c.add("ix-memory", "unknown", "Ix graph memory", "off: this Ix has no local `ix note` (it came after Ix 0.13.0)", "upgrade Ix (`ix upgrade`)");
597
+ else
598
+ c.add("ix-memory", "unknown", "Ix graph memory", `couldn't tell whether this Ix has a local \`ix note\`; ${counts}`, "run `ix --help` in a terminal");
599
+ if (dropped.length > 0) {
600
+ const total = dropped.reduce((a, [, n]) => a + n, 0);
601
+ c.add("ix-memory-dropped", "unknown", "Ix graph memory dropped", `${total} item${total === 1 ? "" : "s"} not written (${dropped.map(([r, n]) => `${peer(r)}: ${n}`).join(", ")})`, "best effort: each reason is counted; the queue holds 64 items");
602
+ }
603
+ if (doc?.unavailable && support === "oss") {
604
+ // Who holds the local endpoint's port wasn't this user (ext-ix listener.ts): say what to do.
605
+ const fix = doc.unavailable.reason === "ix_listener"
606
+ ? `start your Ix backend (\`ix docker start\`); if another user's process holds the port, use a port of yours (\`ixEndpoint\` in config.json). On Linux, Docker's port proxy runs as root: if this machine's Docker is only yours, set "ixTrustRootListener": true in config.json (by hand)`
607
+ : undefined;
608
+ c.add("ix-memory-last", "unknown", "Ix graph memory", `last stopped: ${peer(doc.unavailable.message, 300)}`, fix);
609
+ }
610
+ if (app.file.ixTrustRootListener === true)
611
+ c.add("ix-memory-root", "ok", "Ix graph memory", 'a root-owned listener on the local port counts as yours ("ixTrustRootListener": true in config.json)');
612
+ }
613
+ // ---------------------------------------------------------------------------
501
614
  // About another user
502
615
  /**
503
616
  * Refreshes `userId`'s document from at most 5 relays, whatever its held (possibly forked) view
@@ -3,6 +3,12 @@ import type { App, Io } from "./app.js";
3
3
  import { type ExtContext, type ExtensionRegistry, type P2PExtension } from "./extensions.js";
4
4
  export declare const IX_INSTALL_HINT = "https://github.com/ix-infrastructure/Ix";
5
5
  export declare function extContext(app: App, ext: P2PExtension, io: Io, json: boolean, confirm: (q: string, yes?: boolean) => Promise<boolean>): ExtContext;
6
+ /**
7
+ * ExtContext.mayShareSessionContext: context recorded for `ofSid` may go out from `fromSid` only when
8
+ * they're the same session, or both ceilings are shared, everyone `fromSid` reaches is also reached
9
+ * by `ofSid`, and their graph targets are the same. Fails closed: anything private, unbound or unknown is no.
10
+ */
11
+ export declare function mayShareSessionContext(app: App, ofSid: string, fromSid: string): Promise<boolean>;
6
12
  /** ExtContext.kv: <home>/ext/<ns>.json, written atomically, 0600. */
7
13
  export declare const MAX_EXT_STORE_BYTES: number;
8
14
  /**
package/dist/ext-host.js CHANGED
@@ -12,7 +12,7 @@ import { join } from "node:path";
12
12
  import { displayStatus, sanitizePeerText } from "@peer2peer/core/v3";
13
13
  import { CliError } from "./errors.js";
14
14
  import { enabledNamespaces, extensionPackageName, kindNamespace, KNOWN_EXTENSIONS, setExtensionEnabled, } from "./extensions.js";
15
- import { sessionWorkdir } from "./projects.js";
15
+ import { ceilingAudience, graphPinnedEnv, graphTarget, localGraphEndpoint, PERSON_SESSION, sessionCeiling, sessionDirs, sessionWorkdir } from "./projects.js";
16
16
  import { listPeers, sendExtension, sessionAudience, sessionRef } from "./sessions.js";
17
17
  import { sessKey } from "./state.js";
18
18
  import { declaredState, expiresAt, keptCopy, liveStates, publishExtensionState } from "./xstate.js";
@@ -46,9 +46,18 @@ function toExtEvent(e) {
46
46
  };
47
47
  }
48
48
  export function extContext(app, ext, io, json, confirm) {
49
+ // Pinned to the local graph: no IX_* cloud setting of the caller's reaches an extension's `ix` (projects.ts).
50
+ const pinned = graphPinnedEnv(app.env, { kind: "local", endpoint: localGraphEndpoint(app.env, app.file), why: "" });
49
51
  return {
50
- env: app.env,
52
+ env: pinned,
51
53
  cwd: extWorkdir(app.env),
54
+ graphTarget: async (o = {}) => {
55
+ const { dirs, over } = sessionDirs(app.env);
56
+ const paths = Array.isArray(o.paths) ? [...o.paths] : [];
57
+ const t = await graphTarget(app, { ...(typeof o.sid === "string" && o.sid !== "" ? { sid: o.sid } : {}), dirs, paths, over });
58
+ // From config.json only (the person's file), never the environment.
59
+ return t.kind === "local" && app.file.ixTrustRootListener === true ? { ...t, trustRootListener: true } : t;
60
+ },
52
61
  io: { err: (s) => io.err(s), ...(io.readStdin ? { readStdin: io.readStdin } : {}) },
53
62
  json,
54
63
  interactive: !json && io.prompt !== undefined,
@@ -116,6 +125,7 @@ export function extContext(app, ext, io, json, confirm) {
116
125
  });
117
126
  },
118
127
  audience: (sid) => sessionAudience(app, sid),
128
+ mayShareSessionContext: (ofSid, fromSid) => mayShareSessionContext(app, ofSid, fromSid),
119
129
  localMac: (data) => localMac(app, ext.ns, data),
120
130
  ownStatus: async (sid) => {
121
131
  const rec = (await app.state.get("peers"))?.[sessKey(app.userId, sid)];
@@ -127,6 +137,30 @@ export function extContext(app, ext, io, json, confirm) {
127
137
  },
128
138
  };
129
139
  }
140
+ /**
141
+ * ExtContext.mayShareSessionContext: context recorded for `ofSid` may go out from `fromSid` only when
142
+ * they're the same session, or both ceilings are shared, everyone `fromSid` reaches is also reached
143
+ * by `ofSid`, and their graph targets are the same. Fails closed: anything private, unbound or unknown is no.
144
+ */
145
+ export async function mayShareSessionContext(app, ofSid, fromSid) {
146
+ if (typeof ofSid !== "string" || typeof fromSid !== "string" || ofSid === "" || fromSid === "")
147
+ return false;
148
+ if (ofSid === fromSid)
149
+ return true;
150
+ if (ofSid === PERSON_SESSION || fromSid === PERSON_SESSION)
151
+ return false;
152
+ const [of, from] = await Promise.all([sessionCeiling(app, ofSid), sessionCeiling(app, fromSid)]);
153
+ if (of.kind !== "shared" || from.kind !== "shared")
154
+ return false;
155
+ const [ofAud, fromAud] = await Promise.all([ceilingAudience(app, of), ceilingAudience(app, from)]);
156
+ if (!ofAud || !fromAud)
157
+ return false;
158
+ for (const u of fromAud)
159
+ if (!ofAud.has(u))
160
+ return false;
161
+ const [a, b] = await Promise.all([graphTarget(app, { sid: ofSid }), graphTarget(app, { sid: fromSid })]);
162
+ return a.kind === b.kind && a.endpoint === b.endpoint && (a.kind !== "shared" || (b.kind === "shared" && a.circle === b.circle));
163
+ }
130
164
  /** ExtContext.kv: <home>/ext/<ns>.json, written atomically, 0600. */
131
165
  export const MAX_EXT_STORE_BYTES = 64 * 1024;
132
166
  function extStore(home, ns) {
@@ -72,6 +72,12 @@ export interface ExtCommand {
72
72
  }
73
73
  export interface P2PExtension {
74
74
  api: number;
75
+ /**
76
+ * The graph-target contract this extension implements (1: every Ix call takes its endpoint only from
77
+ * ExtContext.graphTarget). Required of the `ix` namespace (REQUIRED_GRAPH_TARGETS): an ext-ix from
78
+ * before it would run Ix with the caller's environment and config, which Ix Pro routes to the cloud.
79
+ */
80
+ graphTargets?: number;
75
81
  /** Its §8.1 namespace: the package must be `@peer2peer/ext-<ns>`. */
76
82
  ns: string;
77
83
  name: string;
@@ -87,7 +93,65 @@ export interface P2PExtension {
87
93
  * advertises `<kind>.v1` for each.
88
94
  */
89
95
  state?: Record<string, ExtStateKind>;
96
+ /**
97
+ * Graph memory (epic #41 piece 2): writes this device's own sessions' context (their record, status
98
+ * one-liners, the files they edit) into the person's local graph. `p2p watch` gathers it from the
99
+ * statuses this device posted, queues it (bounded) and hands it over in batches, off the hook path.
100
+ * Optional: an extension without it (an older ext-ix) is simply never asked. Each batch is for one
101
+ * session and has already been checked local by graphTarget; the extension checks again.
102
+ */
103
+ memory?: ExtMemory;
104
+ }
105
+ /** One thing to remember about a session (graph-memory.ts). Every string is local, the person's own. */
106
+ export interface ExtMemoryItem {
107
+ kind: "start" | "status" | "files" | "end";
108
+ /** When it happened (ms). */
109
+ at: number;
110
+ /** start: the session's label, repository and branch. */
111
+ label?: string;
112
+ repo?: string;
113
+ branch?: string;
114
+ /** status: the one-line status. */
115
+ summary?: string;
116
+ /** files: repo-relative files edited since the last batch. */
117
+ files?: string[];
118
+ }
119
+ /** Why memory can't be written now; `message` says what the person can do. */
120
+ export interface ExtMemoryUnavailable {
121
+ ok: false;
122
+ /** e.g. `ix_missing`, `ix_upgrade` (no local `ix note`), `ix_pro` (Ix Pro answers: cloud). */
123
+ reason: string;
124
+ message: string;
125
+ }
126
+ export interface ExtMemoryResult {
127
+ written: number;
128
+ /** Items not written, by reason (counted as dropped). */
129
+ failed?: {
130
+ reason: string;
131
+ n: number;
132
+ message?: string;
133
+ }[];
134
+ /** Stop asking for now (the same as available() turning false). */
135
+ unavailable?: ExtMemoryUnavailable;
90
136
  }
137
+ export interface ExtMemory {
138
+ v: 1;
139
+ /** Whether the writes can go to the local graph at all (asked before anything is gathered). */
140
+ available(ctx: ExtContext): Promise<{
141
+ ok: true;
142
+ } | ExtMemoryUnavailable>;
143
+ /**
144
+ * Writes one session's items. `signal` aborts when the host's time for the batch is up: the writer
145
+ * must check it before every write and write nothing after it fires (the host waits for it to settle).
146
+ */
147
+ write(ctx: ExtContext, batch: {
148
+ sid: string;
149
+ items: ExtMemoryItem[];
150
+ signal?: AbortSignal;
151
+ }): Promise<ExtMemoryResult>;
152
+ }
153
+ /** `ext.memory` when it is a usable v1 memory writer; undefined otherwise (absent or malformed: never asked). */
154
+ export declare function memoryOf(ext: P2PExtension | undefined): ExtMemory | undefined;
91
155
  export interface ExtStateKind {
92
156
  /** Seconds a value stays valid (EXT_STATE_TTL_MIN-MAX); default EXT_STATE_TTL_DEFAULT. */
93
157
  ttl?: number;
@@ -227,11 +291,39 @@ export interface ExtAudience {
227
291
  /** Distinct verified organisations among them (a trust provider's labels); absent when unknown. */
228
292
  orgs?: number;
229
293
  }
294
+ /**
295
+ * Which Ix graph a call may reach (projects.ts graphTarget, the chokepoint): this machine's backend,
296
+ * or one circle's shared graph. An extension that runs Ix takes the endpoint (and any token) only
297
+ * from here, never from its environment.
298
+ */
299
+ export type ExtGraphTarget =
300
+ /** `trustRootListener`: the person set `ixTrustRootListener: true` in config.json (a root-owned listener on the port, Docker's proxy on Linux, is theirs). */
301
+ {
302
+ kind: "local";
303
+ endpoint: string;
304
+ why: string;
305
+ trustRootListener?: true;
306
+ } | {
307
+ kind: "shared";
308
+ circle: string;
309
+ endpoint: string;
310
+ token?: string;
311
+ };
230
312
  /** What a command gets from `p2p`: no keys, no store, only these. */
231
313
  export interface ExtContext {
232
314
  env: Env;
233
315
  /** The user's working directory: P2P_WORKDIR (an existing absolute directory), else the process's. */
234
316
  cwd: string;
317
+ /**
318
+ * The graph target for a call made for session `sid` (when given), working in this context's folders
319
+ * (P2P_WORKDIR, P2P_PROJECT_DIRS and the process's cwd) and naming `paths` (absolute: the call's
320
+ * targets, `--path`, `--changed`, the child's cwd; every one is intersected in): projects.ts
321
+ * graphTarget. Absent on clients from before graph targets: an extension then treats every call as local.
322
+ */
323
+ graphTarget?(opts?: {
324
+ sid?: string;
325
+ paths?: readonly string[];
326
+ }): Promise<ExtGraphTarget>;
235
327
  /** stdout lines are for `--json`-less output only; use the returned `human`. */
236
328
  io: {
237
329
  err(s: string): void;
@@ -287,6 +379,13 @@ export interface ExtContext {
287
379
  * file tools): store the MAC with the setting and honour the setting only when it verifies.
288
380
  */
289
381
  localMac?(data: string): string;
382
+ /**
383
+ * Whether session `fromSid` may pass on context recorded for session `ofSid` (graph memory's
384
+ * records, ExtMemory): the same session, or both bound to projects whose ceilings are shared, with
385
+ * `fromSid`'s audience within `ofSid`'s and the same graph target. Absent on older clients: a
386
+ * caller then refuses anything but the same session.
387
+ */
388
+ mayShareSessionContext?(ofSid: string, fromSid: string): Promise<boolean>;
290
389
  /** Own sessions' last posted statuses on this device. */
291
390
  ownStatus(sid: string): Promise<{
292
391
  repo?: string;
@@ -322,6 +421,8 @@ export interface LoadOptions {
322
421
  /** Overrides where this CLI is installed (tests). */
323
422
  selfUrl?: string;
324
423
  }
424
+ /** Namespaces that run Ix, and the graph-target contract version each must declare to load. */
425
+ export declare const REQUIRED_GRAPH_TARGETS: Readonly<Record<string, number>>;
325
426
  /** Validates what a module exports; undefined (with a reason) when it isn't a usable extension. */
326
427
  export declare function checkExtension(mod: unknown, ns: string): {
327
428
  ext?: P2PExtension;
@@ -58,6 +58,11 @@ export function extensionPackageName(ns) {
58
58
  export function kindNamespace(kind) {
59
59
  return isExtensionKind(kind) ? kind.slice(2, kind.indexOf(".")) : undefined;
60
60
  }
61
+ /** `ext.memory` when it is a usable v1 memory writer; undefined otherwise (absent or malformed: never asked). */
62
+ export function memoryOf(ext) {
63
+ const m = ext?.memory;
64
+ return m && typeof m === "object" && m.v === 1 && typeof m.available === "function" && typeof m.write === "function" ? m : undefined;
65
+ }
61
66
  export class ExtensionRegistry {
62
67
  byNs = new Map();
63
68
  constructor(list = []) {
@@ -76,6 +81,8 @@ export class ExtensionRegistry {
76
81
  return [...this.byNs.values()];
77
82
  }
78
83
  }
84
+ /** Namespaces that run Ix, and the graph-target contract version each must declare to load. */
85
+ export const REQUIRED_GRAPH_TARGETS = { ix: 1 };
79
86
  /** Validates what a module exports; undefined (with a reason) when it isn't a usable extension. */
80
87
  export function checkExtension(mod, ns) {
81
88
  const m = mod;
@@ -86,6 +93,10 @@ export function checkExtension(mod, ns) {
86
93
  return { why: `built for extension API ${String(ext.api)}, this p2p has ${EXTENSION_API}` };
87
94
  if (ext.ns !== ns)
88
95
  return { why: `declares namespace ${String(ext.ns)}, expected ${ns}` };
96
+ const need = REQUIRED_GRAPH_TARGETS[ns];
97
+ if (need !== undefined && !(typeof ext.graphTargets === "number" && ext.graphTargets >= need)) {
98
+ return { why: `it predates graph targets (it would run Ix with your environment and config, which Ix Pro can route to the cloud): update ${extensionPackageName(ns)} (npm i -g ${extensionPackageName(ns)}@latest; the Claude Code mod ships a current copy)` };
99
+ }
89
100
  if (ext.receive !== undefined && typeof ext.receive !== "function")
90
101
  return { why: "receive is not a function" };
91
102
  if (ext.state !== undefined) {
@@ -0,0 +1,107 @@
1
+ import type { App } from "./app.js";
2
+ import { type ExtMemory, type ExtMemoryItem, type ExtMemoryUnavailable, type P2PExtension } from "./extensions.js";
3
+ import { type GraphTarget } from "./projects.js";
4
+ import type { PeerStatusRec } from "./state.js";
5
+ /** How often `p2p watch` gathers and drains (P2P_IX_MEMORY_TICK_MS, 1-60 s, for tests). */
6
+ export declare const GRAPH_MEMORY_TICK_MS = 5000;
7
+ /** At most this many items wait; past it, new ones are dropped (counted as `queue_full`). */
8
+ export declare const GRAPH_MEMORY_QUEUE_MAX = 64;
9
+ /** At most this many items are handed over in one drain. */
10
+ export declare const GRAPH_MEMORY_BATCH = 16;
11
+ /** At most this many sessions are tracked (the oldest ended ones go first). */
12
+ export declare const GRAPH_MEMORY_SESSIONS_MAX = 64;
13
+ /** At most this many files are remembered as recorded per session. */
14
+ export declare const GRAPH_MEMORY_FILES_MAX = 200;
15
+ /** A session first seen with no status newer than this isn't recorded (one from before an upgrade). */
16
+ export declare const GRAPH_MEMORY_FRESH_MS: number;
17
+ /** While memory is unavailable, it is asked again this often (Ix installed or upgraded meanwhile). */
18
+ export declare const GRAPH_MEMORY_RECHECK_MS: number;
19
+ /** One drain gives up waiting on the extension after this long (its `ix` calls are bounded too). */
20
+ export declare const GRAPH_MEMORY_DRAIN_MS = 120000;
21
+ export type GraphMemoryItem = ExtMemoryItem & {
22
+ sid: string;
23
+ };
24
+ export interface GraphMemorySession {
25
+ /** When the session's start was queued (ms). */
26
+ start: number;
27
+ /** The last status one-liner queued. */
28
+ summary?: string;
29
+ /** Files already queued (capped). */
30
+ files: string[];
31
+ /** When its end was queued. */
32
+ ended?: number;
33
+ }
34
+ export interface GraphMemoryDoc {
35
+ v: 1;
36
+ sessions: Record<string, GraphMemorySession>;
37
+ queue: GraphMemoryItem[];
38
+ /** Items written to the local graph. */
39
+ written: number;
40
+ /** Items dropped, by reason (queue_full, not_local, ix_failed, ix_timeout, graph_target, ix_unconfirmed, …). */
41
+ dropped: Record<string, number>;
42
+ lastWriteAt?: number;
43
+ lastDropAt?: number;
44
+ /** Why memory is off now (no Ix, an Ix without local notes, Ix Pro), as the extension said it. */
45
+ unavailable?: {
46
+ reason: string;
47
+ message: string;
48
+ at: number;
49
+ };
50
+ /**
51
+ * Sessions a drain is writing now, until when (ms): one writer per session at a time, across
52
+ * every process (take() skips them), so a session's record is never created twice.
53
+ */
54
+ leases?: Record<string, number>;
55
+ }
56
+ /**
57
+ * What changed in this device's own sessions since the last look, as items, queued (pure, for
58
+ * tests: `ended` says whether a session's watch is gone). Returns the next doc and how many were
59
+ * queued and dropped. Only sessions `recordable` says yes to are gathered: a session whose project
60
+ * ceiling isn't shared (a private or unmapped project, `.p2p-private`, not bound yet) is never
61
+ * recorded, and one that becomes so stops being recorded (fail closed: its context never reaches a
62
+ * graph that a shared session's agent could read and pass on).
63
+ */
64
+ export declare function gather(doc: GraphMemoryDoc, recs: readonly PeerStatusRec[], ended: (sid: string) => boolean, now?: number, recordable?: (sid: string) => boolean): {
65
+ doc: GraphMemoryDoc;
66
+ queued: number;
67
+ dropped: number;
68
+ };
69
+ /** Gathers and queues what changed (under the state lock). */
70
+ export declare function gatherGraphMemory(app: App, now?: number): Promise<{
71
+ queued: number;
72
+ dropped: number;
73
+ }>;
74
+ export interface DrainDeps {
75
+ /** The graph target of a session's batch (default: the chokepoint, projects.ts graphTarget). */
76
+ target?: (sid: string) => Promise<GraphTarget>;
77
+ log?: (msg: string) => void;
78
+ /** One session's time to write (tests); default GRAPH_MEMORY_DRAIN_MS. */
79
+ deadlineMs?: number;
80
+ /** After the abort, how long to wait for the writer to settle (tests); default GRAPH_MEMORY_SETTLE_MS. */
81
+ settleMs?: number;
82
+ }
83
+ /** After a timed-out batch is aborted, how long the drain waits for the writer to settle before giving up on it. */
84
+ export declare const GRAPH_MEMORY_SETTLE_MS = 30000;
85
+ /** How long a session's lease lasts: past every drain's own bound, then free again (a crashed writer). */
86
+ export declare const GRAPH_MEMORY_LEASE_MS: number;
87
+ /**
88
+ * Hands the next batch to the extension, a session at a time. A session whose graph target isn't
89
+ * local is never handed over: its items are dropped as `not_local`. Returns what happened.
90
+ */
91
+ export declare function drainGraphMemory(app: App, ext: P2PExtension, mem: ExtMemory, deps?: DrainDeps): Promise<{
92
+ written: number;
93
+ dropped: number;
94
+ unavailable?: ExtMemoryUnavailable;
95
+ }>;
96
+ /** The tick interval (P2P_IX_MEMORY_TICK_MS, 1-60 s). */
97
+ export declare function graphMemoryTickMs(env: Record<string, string | undefined>): number;
98
+ /**
99
+ * The loop `p2p watch` runs: `tick()` gathers and drains when memory is on and available (asked of
100
+ * the extension at most every GRAPH_MEMORY_RECHECK_MS while it isn't). Never throws; one tick at a
101
+ * time.
102
+ */
103
+ export declare function graphMemoryLoop(app: App, deps?: DrainDeps): {
104
+ tick(): Promise<void>;
105
+ };
106
+ /** What `p2p doctor` says about graph memory (undefined: nothing recorded yet). */
107
+ export declare function graphMemoryReport(app: App): Promise<GraphMemoryDoc | undefined>;