@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/projects.js CHANGED
@@ -4,7 +4,9 @@
4
4
  //
5
5
  // - A project is a git repository, keyed by its normalised remote URL (if any) and its git
6
6
  // common dir, so every worktree and subfolder of one clone is the same project. Outside git,
7
- // the real path of the folder.
7
+ // the real path of the folder, or of the nearest folder above it whose share covers its
8
+ // subfolders (opt-in: `p2p project share --subfolders`), never past a repository, a
9
+ // `.p2p-private`, a folder with its own policy or a folder that is gone.
8
10
  // - Its policy lives only in this user's state (`<home>/cli/projects`): shared with circles and
9
11
  // named people, or private. A project with no policy is private: only this user's own devices
10
12
  // see its sessions. Nothing in a repository can widen that; a committed `.p2p-private` file at
@@ -20,8 +22,9 @@
20
22
  // session: never bound, no ceiling.
21
23
  import { agentAncestor, isAgentProcess } from "./ancestry.js";
22
24
  import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
23
- import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
24
- import { basename, delimiter, dirname, isAbsolute, join, resolve } from "node:path";
25
+ import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
26
+ import { homedir, tmpdir } from "node:os";
27
+ import { basename, delimiter, dirname, isAbsolute, join, resolve, sep } from "node:path";
25
28
  import { circlePolicy, liveFriendshipsV3, loadCircle, sanitizePeerText, standsLookup } from "@peer2peer/core/v3";
26
29
  import { CliError } from "./errors.js";
27
30
  /** The person's own terminal session (`p2p tui`, `p2p send` with no --from-session). */
@@ -54,8 +57,20 @@ export function sessionWorkdir(env) {
54
57
  export function sessionDirs(env) {
55
58
  const extra = (env.P2P_PROJECT_DIRS ?? "").split(delimiter).filter((x) => x.trim() !== "" && isAbsolute(x.trim()));
56
59
  // Past the cap (or when the front end says it dropped some): private, never "the first N".
57
- const over = extra.length > MAX_SESSION_DIRS || env.P2P_PROJECT_DIRS_OVER === "1";
58
- return { dirs: [sessionWorkdir(env), ...extra.slice(0, MAX_SESSION_DIRS)], over };
60
+ const why = extra.length > MAX_SESSION_DIRS ? ["folders"] : [];
61
+ const said = env.P2P_PROJECT_DIRS_OVER?.trim() ?? "";
62
+ if (said !== "" && said !== "0")
63
+ why.push(...overWhys(said));
64
+ return { dirs: [sessionWorkdir(env), ...extra.slice(0, MAX_SESSION_DIRS)], over: why.length > 0, why: [...new Set(why)] };
65
+ }
66
+ const OVER_WHYS = new Set(["projects", "folders", "unresolved", "front", "constraints"]);
67
+ /** A front end's over reasons (`unresolved,folders`, an array, or `1`/`true` from an older one): an unknown word counts as `front`, never as nothing. */
68
+ export function overWhys(v) {
69
+ const words = Array.isArray(v) ? v.map(String) : typeof v === "string" ? v.split(/[\s,]+/) : v === true ? ["front"] : [];
70
+ const out = new Set();
71
+ for (const w of words.map((x) => x.trim().toLowerCase()).filter((x) => x !== ""))
72
+ out.add(OVER_WHYS.has(w) ? w : "front");
73
+ return [...out];
59
74
  }
60
75
  /** At most this many folders a front end passes per call; past it the session is private. */
61
76
  export const MAX_SESSION_DIRS = 512;
@@ -67,6 +82,10 @@ export const SESSION_BINDING_TTL_MS = 30 * 24 * 3600 * 1000;
67
82
  export const MAX_PROJECT_SHARES = 32;
68
83
  /** At most this many constraints a session keeps; past it, private. */
69
84
  export const MAX_SESSION_CONSTRAINTS = 16;
85
+ /** At most this many covered subfolders a bound folder project remembers; past it, every policy below it counts. */
86
+ export const MAX_UNDER = 64;
87
+ /** Causes no share can lift: the session stays private until it ends. */
88
+ const STICKY = new Set(["projects", "folders", "unresolved", "front", "constraints", "legacy-over", "repo-private", "sent-private"]);
70
89
  // ---------------------------------------------------------------------------
71
90
  // Project identity
72
91
  const sha = (s) => createHash("sha256").update(s, "utf8").digest("hex");
@@ -101,6 +120,87 @@ function existingDir(p) {
101
120
  }
102
121
  return cur;
103
122
  }
123
+ /** Device and pseudo-file roots: what is under them is never a project (POSIX). */
124
+ const PSEUDO_ROOTS = ["/dev", "/proc", "/sys"];
125
+ /**
126
+ * Whether `p` is a device or pseudo file (`/dev/null`, `/dev/tty`, `/proc/self/status`), never a
127
+ * project: it exists, isn't a folder, and its real path stays under /dev (and isn't a regular
128
+ * file there, like one in /dev/shm), /proc or /sys. A path through /proc to a real file
129
+ * (`/proc/self/cwd/x`, `/proc/<pid>/root/…`) resolves out of it and binds as usual; one that
130
+ * doesn't exist binds its nearest existing parent as every path does.
131
+ */
132
+ export function pseudoPath(p) {
133
+ if (process.platform === "win32" || typeof p !== "string" || !isAbsolute(p))
134
+ return false;
135
+ // Named there, too: a link elsewhere (a repository's file that points at /dev/null) binds as its folder.
136
+ const at = resolve(p);
137
+ if (!PSEUDO_ROOTS.some((root) => at === root || at.startsWith(`${root}/`)))
138
+ return false;
139
+ let st;
140
+ try {
141
+ st = statSync(p);
142
+ }
143
+ catch {
144
+ return false;
145
+ }
146
+ if (st.isDirectory())
147
+ return false;
148
+ const r = real(p);
149
+ const under = (root) => r === root || r.startsWith(`${root}/`);
150
+ if (under("/dev"))
151
+ return !st.isFile();
152
+ return PSEUDO_ROOTS.slice(1).some(under);
153
+ }
154
+ /**
155
+ * Whether a path component holds a brace expansion with a choice: a `{`, then `,` or `..` with no
156
+ * brace between, then `}` (`{.git,x}`, `{a..z}`). One pass, so it stays linear on any input.
157
+ */
158
+ export function braceChoice(c) {
159
+ let open = false;
160
+ let choice = false;
161
+ for (let i = 0; i < c.length; i++) {
162
+ const ch = c[i];
163
+ if (ch === "{") {
164
+ open = true;
165
+ choice = false;
166
+ }
167
+ else if (ch === "}") {
168
+ if (open && choice)
169
+ return true;
170
+ open = false;
171
+ }
172
+ else if (open && (ch === "," || (ch === "." && c[i + 1] === ".")))
173
+ choice = true;
174
+ }
175
+ return false;
176
+ }
177
+ /**
178
+ * The folder holding the first path component that names a repository's marker (`.git`,
179
+ * PRIVATE_MARKER) or could match one (a glob or brace pattern a dotfile can match: `.g*`,
180
+ * `[.]git`, `{.git,x}`): a command naming it may remove it, so a shared folder above never
181
+ * covers that folder (projectOf). Lexical, on the path as given.
182
+ */
183
+ function namedStop(p) {
184
+ const parts = p.split(/[\\/]/);
185
+ for (let i = 1; i < parts.length; i++) {
186
+ const c = parts[i];
187
+ const glob = ((c.startsWith(".") || c.startsWith("[")) && /[*?[]/.test(c)) || braceChoice(c);
188
+ if (c === ".git" || c === PRIVATE_MARKER || glob)
189
+ return parts.slice(0, i).join(sep) || sep;
190
+ }
191
+ return undefined;
192
+ }
193
+ /** Whether `p` is `dir` or below it (real paths, this platform's separator). */
194
+ function within(p, dir) {
195
+ if (p === dir)
196
+ return true;
197
+ const d = dir.endsWith(sep) ? dir : `${dir}${sep}`;
198
+ return p.startsWith(d);
199
+ }
200
+ /** A folder project's id: its real path, hashed. */
201
+ export function dirProjectId(root) {
202
+ return `pj_${sha(`dir\n${root}`).slice(0, 24)}`;
203
+ }
104
204
  /**
105
205
  * A remote URL as one canonical string: scheme, credentials, port-less ssh form, trailing `.git`
106
206
  * and slashes dropped, host lower-cased. `https://u:t@GitHub.com/a/b.git` and `git@github.com:a/b`
@@ -170,27 +270,97 @@ function readSmall(file) {
170
270
  return undefined;
171
271
  }
172
272
  }
273
+ /**
274
+ * Whether `d` is a bare git repository: `HEAD`, `objects/` and `refs/` in it, or a `config` that
275
+ * says `bare = true` (a folder named `.git` is a working tree's, found from its parent instead).
276
+ */
277
+ function isBareRepo(d) {
278
+ if (basename(d) === ".git")
279
+ return false;
280
+ const st = (p) => {
281
+ try {
282
+ return statSync(p);
283
+ }
284
+ catch {
285
+ return undefined;
286
+ }
287
+ };
288
+ if (st(join(d, "HEAD"))?.isFile() && st(join(d, "objects"))?.isDirectory() && st(join(d, "refs"))?.isDirectory())
289
+ return true;
290
+ return /^\s*bare\s*=\s*true\s*$/im.test(readSmall(join(d, "config")) ?? "");
291
+ }
292
+ /** The git project whose git dir is `gitDir`, found at the folder `root`. */
293
+ function gitRef(gitDir, root) {
294
+ let common = gitDir;
295
+ const cd = readSmall(join(gitDir, "commondir"))?.trim();
296
+ if (cd)
297
+ common = resolve(gitDir, cd);
298
+ common = real(common);
299
+ const urls = remotesOf(readSmall(join(common, "config")) ?? "");
300
+ const remote = urls.map(normalizeRemote).find((x) => x !== undefined);
301
+ const main = basename(common) === ".git" ? dirname(common) : common;
302
+ const name = clean(remote ? (remote.split("/").pop() ?? "") : basename(main)) || clean(basename(root)) || "project";
303
+ return {
304
+ id: `pj_${sha(`git\n${remote ?? ""}\n${common}`).slice(0, 24)}`,
305
+ name,
306
+ kind: "git",
307
+ root,
308
+ ...(remote ? { remote } : {}),
309
+ ...(existsSync(join(root, PRIVATE_MARKER)) ? { repoPrivate: true } : {}),
310
+ };
311
+ }
312
+ /** Whether `p` names something that is there, its trailing pattern parts (`*.log`, `{a,b}`) left out. */
313
+ function present(p) {
314
+ let q = resolve(p);
315
+ while (/[*?[\]{}]/.test(basename(q)) && dirname(q) !== q)
316
+ q = dirname(q);
317
+ try {
318
+ statSync(q);
319
+ return true;
320
+ }
321
+ catch {
322
+ return false;
323
+ }
324
+ }
173
325
  /**
174
326
  * The project `dir` belongs to, read from the files alone (git is never run: no hook, fsmonitor
175
327
  * or config of the repository's can execute). A `.git` directory or `gitdir:` file up the tree
176
328
  * marks a working tree; its common dir (`commondir` for a linked worktree) identifies the clone.
329
+ * A bare repository (isBareRepo) is a git project too, and a `.git` that can't be read as one is
330
+ * a folder project of its own.
331
+ *
332
+ * Outside git, a folder project. With `doc` (the policies), the nearest folder at or above `dir`
333
+ * that has a policy of its own is the project when that is `dir`'s own folder, or when its share
334
+ * covers subfolders (`covers`, given with `p2p project share --subfolders`; a policy without it
335
+ * is for that folder alone, as before). The walk stops at the first folder with a policy (the
336
+ * nearest one wins, so a private subfolder stays private; one that doesn't cover leaves `dir`'s
337
+ * own folder as the project), and it never crosses:
338
+ * - a git repository (found first: a nested repository is always its own project);
339
+ * - a `.p2p-private` (at or above `dir`: the folder project is private, whatever covers it);
340
+ * - a folder whose `.git` or `.p2p-private` the path itself names (namedStop: a command that may
341
+ * have just removed it);
342
+ * - the nearest existing folder, when `dir` itself isn't there (deleted or moved since the
343
+ * session named it, or not made yet): that folder is the project unless it has a policy, so a
344
+ * repository removed after a session read it is never covered from above.
345
+ * Without `doc` (sharing, `project show`): the folder itself.
177
346
  */
178
- export function projectOf(dir) {
179
- const start = existingDir(isAbsolute(dir) ? dir : resolve(dir));
347
+ export function projectOf(dir, doc) {
348
+ const given = resolve(dir);
349
+ const start = existingDir(given);
180
350
  let cur = start;
181
351
  for (let i = 0; i < 4096; i++) {
182
352
  const dotgit = join(cur, ".git");
183
353
  // Anything named .git here (a folder, a file, a symlink, even a broken or unreadable one) ends
184
354
  // the walk: this folder is its own project, never the parent repository's.
185
- let present;
355
+ let isThere;
186
356
  try {
187
357
  lstatSync(dotgit);
188
- present = true;
358
+ isThere = true;
189
359
  }
190
360
  catch {
191
- present = false;
361
+ isThere = false;
192
362
  }
193
- if (present) {
363
+ if (isThere) {
194
364
  let st;
195
365
  try {
196
366
  st = statSync(dotgit);
@@ -208,34 +378,51 @@ export function projectOf(dir) {
208
378
  }
209
379
  if (!gitDir || !existsSync(gitDir)) {
210
380
  // A .git that can't be read as one: a folder project at this level (private until shared).
211
- return { id: `pj_${sha(`dir\n${cur}`).slice(0, 24)}`, name: clean(basename(cur)) || "folder", kind: "dir", root: cur };
212
- }
213
- {
214
- let common = gitDir;
215
- const cd = readSmall(join(gitDir, "commondir"))?.trim();
216
- if (cd)
217
- common = resolve(gitDir, cd);
218
- common = real(common);
219
- const urls = remotesOf(readSmall(join(common, "config")) ?? "");
220
- const remote = urls.map(normalizeRemote).find((x) => x !== undefined);
221
- const main = basename(common) === ".git" ? dirname(common) : common;
222
- const name = clean(remote ? (remote.split("/").pop() ?? "") : basename(main)) || clean(basename(cur)) || "project";
223
- return {
224
- id: `pj_${sha(`git\n${remote ?? ""}\n${common}`).slice(0, 24)}`,
225
- name,
226
- kind: "git",
227
- root: cur,
228
- ...(remote ? { remote } : {}),
229
- ...(existsSync(join(cur, PRIVATE_MARKER)) ? { repoPrivate: true } : {}),
230
- };
381
+ return { id: dirProjectId(cur), name: clean(basename(cur)) || "folder", kind: "dir", root: cur };
231
382
  }
383
+ return gitRef(gitDir, cur);
232
384
  }
385
+ // A bare repository (a clone with no working tree): a git project, never a shared folder's.
386
+ if (isBareRepo(cur))
387
+ return gitRef(cur, cur);
233
388
  const up = dirname(cur);
234
389
  if (up === cur)
235
390
  break;
236
391
  cur = up;
237
392
  }
238
- return { id: `pj_${sha(`dir\n${start}`).slice(0, 24)}`, name: clean(basename(start)) || "folder", kind: "dir", root: start };
393
+ const dirRef = (root, repoPrivate) => ({ id: dirProjectId(root), name: clean(basename(root)) || "folder", kind: "dir", root, ...(repoPrivate ? { repoPrivate: true } : {}) });
394
+ // A .p2p-private at or above the folder (no repository in between, or the walk above found it):
395
+ // the folder is private, whatever a policy above says.
396
+ let marked = false;
397
+ for (let c = start, i = 0; i < 4096; i++) {
398
+ if (existsSync(join(c, PRIVATE_MARKER))) {
399
+ marked = true;
400
+ break;
401
+ }
402
+ const up = dirname(c);
403
+ if (up === c)
404
+ break;
405
+ c = up;
406
+ }
407
+ if (!doc || marked)
408
+ return dirRef(start, marked);
409
+ // The walk stops at a folder the path names a marker in (it may be gone now: never covered from
410
+ // above), and at `start` itself when the path isn't there (only its nearest parent is).
411
+ const named = namedStop(given);
412
+ const ns = named === undefined ? undefined : existingDir(named);
413
+ const stop = !present(given) ? start : ns === undefined ? undefined : within(start, ns) ? ns : start;
414
+ for (let c = start, i = 0; i < 4096; i++) {
415
+ const rec = doc.projects[dirProjectId(c)];
416
+ if (rec)
417
+ return c === start || rec.covers === true ? dirRef(c, false) : dirRef(start, false);
418
+ if (c === stop)
419
+ break;
420
+ const up = dirname(c);
421
+ if (up === c)
422
+ break;
423
+ c = up;
424
+ }
425
+ return dirRef(start, false);
239
426
  }
240
427
  const clean = (s) => sanitizePeerText(s, 64).replace(/[^\w.@+-]/g, "").slice(0, 64);
241
428
  // ---------------------------------------------------------------------------
@@ -280,8 +467,110 @@ export async function projectView(app, ref, doc) {
280
467
  people,
281
468
  ...(why ? { why } : {}),
282
469
  ...(ref.repoPrivate ? { repoPrivate: true } : {}),
470
+ ...(d.projects[ref.id]?.covers === true && ref.kind === "dir" ? { covers: true } : {}),
471
+ graph: projectGraphTarget(app, ref, d),
283
472
  };
284
473
  }
474
+ /**
475
+ * Why `root` may not cover its subfolders (a share for it alone is still allowed), or undefined:
476
+ * the file system's root, a home folder or a folder above one (`$HOME`, `/Users`, `/home/<u>`),
477
+ * the temporary folders (`/tmp`, `/private/tmp`, `/var/folders/…`, os.tmpdir() and above it), and
478
+ * the system's top folders. Everything below them would be one project.
479
+ */
480
+ export function broadRoot(root, env = {}) {
481
+ const norm = (p) => {
482
+ const r = resolve(p);
483
+ return process.platform === "win32" ? r.toLowerCase() : r;
484
+ };
485
+ const forms = (p) => [...new Set([norm(p), norm(real(p))])];
486
+ const at = forms(root);
487
+ const isOrAbove = (dir) => !!dir && isAbsolute(dir) && forms(dir).some((d) => at.some((r) => within(d, r)));
488
+ if (at.some((r) => dirname(r) === r))
489
+ return "the file system's root";
490
+ const homes = [homedir(), env.HOME, env.USERPROFILE].filter((x) => typeof x === "string" && x !== "");
491
+ if (homes.some(isOrAbove))
492
+ return "a home folder (or a folder that holds one)";
493
+ if (isOrAbove(tmpdir()) || isOrAbove(env.TMPDIR))
494
+ return "the temporary folder (or a folder that holds it)";
495
+ for (const r of at) {
496
+ const parts = r.split(/[\\/]+/).filter(Boolean);
497
+ const top = (parts[0] ?? "").toLowerCase();
498
+ if (!/^[a-z]:$/i.test(top) && parts.length === 1)
499
+ return "a top-level system folder";
500
+ if (/^[a-z]:$/i.test(parts[0] ?? "") && parts.length <= 2 && (parts.length === 1 || (parts[1] ?? "").toLowerCase() === "users"))
501
+ return "a drive's root or its Users folder";
502
+ if (/^[a-z]:$/i.test(parts[0] ?? "") && parts.length === 3 && (parts[1] ?? "").toLowerCase() === "users")
503
+ return "a home folder";
504
+ if (["home", "users"].includes(top) && parts.length <= 2)
505
+ return "a home folder (or the folder that holds them)";
506
+ if (top === "tmp" && parts.length === 1)
507
+ return "the temporary folder";
508
+ if (top === "private" && parts.length <= 2)
509
+ return "a system folder";
510
+ if (top === "private" && (parts[1] === "tmp" || parts[1] === "var") && parts.length === 2)
511
+ return "the temporary folder";
512
+ const vf = top === "var" ? 1 : top === "private" && parts[1] === "var" ? 2 : -1;
513
+ if (vf > 0 && parts[vf] === "folders" && parts.length <= vf + 4)
514
+ return "the temporary folder (or a folder that holds it)";
515
+ if (vf > 0 && parts.length <= vf + 1)
516
+ return "a system folder";
517
+ if (top === "run" && parts.length <= 3)
518
+ return "a system folder";
519
+ if (["volumes", "mnt", "media"].includes(top) && parts.length <= 2)
520
+ return "a volume's root";
521
+ }
522
+ return undefined;
523
+ }
524
+ /** At most this deep and this many entries `nestedBoundaries` looks through below a covering share. */
525
+ export const NESTED_SCAN_DEPTH = 4;
526
+ export const NESTED_SCAN_ENTRIES = 2000;
527
+ /**
528
+ * The nested git repositories (a `.git`, or a bare repository) and `.p2p-private` folders below
529
+ * `root`, for the warning a covering share prints: each stays its own project, but only while its
530
+ * marker is there. Bounded (NESTED_SCAN_DEPTH, NESTED_SCAN_ENTRIES: `capped` past it); symlinks
531
+ * are never followed.
532
+ */
533
+ export function nestedBoundaries(root) {
534
+ const repos = [];
535
+ const priv = [];
536
+ let seen = 0;
537
+ let capped = false;
538
+ let level = [root];
539
+ for (let depth = 1; depth <= NESTED_SCAN_DEPTH && level.length > 0 && !capped; depth++) {
540
+ const next = [];
541
+ for (const d of level) {
542
+ let entries;
543
+ try {
544
+ entries = readdirSync(d, { withFileTypes: true });
545
+ }
546
+ catch {
547
+ continue;
548
+ }
549
+ for (const e of entries) {
550
+ if (++seen > NESTED_SCAN_ENTRIES) {
551
+ capped = true;
552
+ break;
553
+ }
554
+ if (!e.isDirectory() || e.isSymbolicLink())
555
+ continue;
556
+ const p = join(d, e.name);
557
+ if (e.name === ".git")
558
+ continue;
559
+ if (existsSync(join(p, ".git")) || isBareRepo(p)) {
560
+ repos.push(p);
561
+ continue;
562
+ }
563
+ if (existsSync(join(p, PRIVATE_MARKER)))
564
+ priv.push(p);
565
+ next.push(p);
566
+ }
567
+ if (capped)
568
+ break;
569
+ }
570
+ level = next;
571
+ }
572
+ return { repos, private: priv, capped };
573
+ }
285
574
  /**
286
575
  * `p2p project share`: share the project at `dir` with circles you joined and friends. Replaces the
287
576
  * project's shares with exactly these (`add` keeps the ones it has). Only ever the person's
@@ -293,9 +582,28 @@ export async function shareProject(app, dir, targets) {
293
582
  if (ref.repoPrivate) {
294
583
  throw new CliError("repo_private", `${ref.name} asks to stay private: its repository has ${PRIVATE_MARKER} at the top level. Peer2Peer never shares it; remove that file from your copy first if you mean to`);
295
584
  }
585
+ const warnings = [];
586
+ // Subfolders are covered only when asked, and never below a root that holds everything.
587
+ let subfolders = targets.subfolders === true;
588
+ if (subfolders && ref.kind === "git") {
589
+ warnings.push(`${ref.name} is a git repository: its subfolders are part of it already (--subfolders is for folders outside git)`);
590
+ subfolders = false;
591
+ }
592
+ if (subfolders) {
593
+ const broad = broadRoot(ref.root, app.env);
594
+ if (broad)
595
+ throw new CliError("usage", `${ref.root} is ${broad}: a share there can't cover its subfolders (share it without --subfolders, or share the folders below it you mean)`);
596
+ const n = nestedBoundaries(ref.root);
597
+ const list = (xs) => `${xs.slice(0, 10).join(", ")}${xs.length > 10 ? ` and ${xs.length - 10} more` : ""}`;
598
+ if (n.repos.length > 0)
599
+ warnings.push(`git repositories below ${ref.root} stay their own projects (private until you share each one), only while their .git is there: ${list(n.repos)}`);
600
+ if (n.private.length > 0)
601
+ warnings.push(`folders below ${ref.root} with ${PRIVATE_MARKER} stay private: ${list(n.private)}`);
602
+ if (n.capped)
603
+ warnings.push(`stopped looking for repositories below ${ref.root} after ${NESTED_SCAN_ENTRIES} entries (${NESTED_SCAN_DEPTH} levels deep): there may be more than listed`);
604
+ }
296
605
  const { resolveCircle } = await import("./circle-ops.js");
297
606
  const circles = [];
298
- const warnings = [];
299
607
  for (const c of targets.circles ?? []) {
300
608
  const r = await resolveCircle(app, c);
301
609
  if (!r.record.joinedByMe)
@@ -330,7 +638,9 @@ export async function shareProject(app, dir, targets) {
330
638
  const share = { circles: [...new Set([...keep.circles, ...circles])], people: [...new Set([...keep.people, ...people])] };
331
639
  if (share.circles.length + share.people.length > MAX_PROJECT_SHARES)
332
640
  throw new CliError("usage", `a project is shared with at most ${MAX_PROJECT_SHARES} circles and people`);
333
- const next = { ...d, projects: { ...d.projects, [ref.id]: { name: ref.name, root: ref.root, ...(ref.remote ? { remote: ref.remote } : {}), share, at: Date.now() } } };
641
+ // --add keeps whether it covers its subfolders; a share made afresh covers them only when asked.
642
+ const covers = subfolders || (targets.add === true && targets.subfolders === undefined && d.projects[ref.id]?.covers === true);
643
+ const next = { ...d, projects: { ...d.projects, [ref.id]: { name: ref.name, root: ref.root, ...(ref.remote ? { remote: ref.remote } : {}), share, ...(covers ? { covers: true } : {}), at: Date.now() } } };
334
644
  return { next: next, result: next };
335
645
  });
336
646
  return { project: await projectView(app, ref, doc), warnings };
@@ -354,9 +664,10 @@ export async function listProjects(app) {
354
664
  }
355
665
  return out.sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
356
666
  }
357
- /** `p2p project show`: the project at `dir`, its policy and why. */
667
+ /** `p2p project show`: the project at `dir` (a shared folder above it covers it), its policy and why. */
358
668
  export async function showProject(app, dir) {
359
- return projectView(app, projectOf(dir));
669
+ const doc = await projectsDoc(app);
670
+ return projectView(app, projectOf(dir, doc), doc);
360
671
  }
361
672
  // ---------------------------------------------------------------------------
362
673
  // Sessions
@@ -372,12 +683,24 @@ export async function bindSession(app, sid, dirs, o = {}) {
372
683
  return undefined;
373
684
  throw new CliError("usage", `session ${PERSON_SESSION} is your own terminal's (p2p tui, or p2p send typed with no --from-session); an agent sends from its own session`);
374
685
  }
686
+ // Folder projects follow the policies (a shared folder covers its subfolders): read once, before the lock.
687
+ const doc = dirs.length > 0 ? await projectsDoc(app) : undefined;
375
688
  const refs = new Map();
376
689
  for (const d of dirs) {
377
690
  if (typeof d !== "string" || d.trim() === "")
378
691
  continue;
379
- const r = projectOf(d);
380
- refs.set(r.id, r);
692
+ // A device or pseudo file (2>/dev/null) is no project; a path that isn't there yet still binds its parent's.
693
+ if (pseudoPath(d))
694
+ continue;
695
+ const r = projectOf(d, doc);
696
+ const one = refs.get(r.id) ?? { ref: r, under: new Set() };
697
+ // A folder a shared folder above covered: remembered, so a policy it gets later still narrows this session.
698
+ if (r.kind === "dir") {
699
+ const at = existingDir(d);
700
+ if (at !== r.root && within(at, r.root))
701
+ one.under.add(at);
702
+ }
703
+ refs.set(r.id, one);
381
704
  }
382
705
  // Who may speak for a session (statuses, sends): its front end (the person token), or, for a session
383
706
  // no front end registered, a caller outside any agent's session. An agent's own shell never may.
@@ -404,20 +727,38 @@ export async function bindSession(app, sid, dirs, o = {}) {
404
727
  throw new CliError("refused", `session ${sid} belongs to a front end of yours (the Claude mod or the Codex bridge): only it speaks for that session`);
405
728
  }
406
729
  const projects = { ...(have?.projects ?? {}) };
407
- let over = have?.over === true || o.over === true;
408
- for (const r of refs.values()) {
730
+ const why = new Set(have?.overWhy ?? []);
731
+ if (o.over === true)
732
+ why.add("front");
733
+ else if (Array.isArray(o.over))
734
+ for (const w of overWhys(o.over))
735
+ why.add(w);
736
+ // A binding from before overWhy kept only `over`: it stays over (said as such: legacy-over).
737
+ let over = have?.over === true || why.size > 0;
738
+ for (const { ref: r, under } of refs.values()) {
409
739
  const prev = projects[r.id];
410
740
  if (!prev && Object.keys(projects).length >= MAX_SESSION_PROJECTS) {
411
741
  over = true;
742
+ why.add("projects");
412
743
  continue;
413
744
  }
414
- // Once a repository asked for privacy, it stays asked for this session.
415
- projects[r.id] = { name: r.name, ...(r.repoPrivate || prev?.repoPrivate ? { repoPrivate: true } : {}) };
745
+ // Once a repository asked for privacy, it stays asked for this session; covered folders only add up.
746
+ const all = new Set([...(prev?.under ?? []), ...under]);
747
+ const underOver = prev?.underOver === true || all.size > MAX_UNDER;
748
+ projects[r.id] = {
749
+ name: r.name,
750
+ root: prev?.root ?? r.root,
751
+ ...(r.repoPrivate || prev?.repoPrivate ? { repoPrivate: true } : {}),
752
+ ...(!underOver && all.size > 0 ? { under: [...all].sort() } : {}),
753
+ ...(underOver ? { underOver: true } : {}),
754
+ };
416
755
  }
417
756
  const constraints = [...(have?.constraints ?? [])];
418
757
  if (o.constraint !== undefined && !constraints.some((c) => JSON.stringify(c) === JSON.stringify(o.constraint))) {
419
- if (constraints.length >= MAX_SESSION_CONSTRAINTS)
758
+ if (constraints.length >= MAX_SESSION_CONSTRAINTS) {
420
759
  over = true;
760
+ why.add("constraints");
761
+ }
421
762
  else
422
763
  constraints.push(o.constraint);
423
764
  }
@@ -426,9 +767,11 @@ export async function bindSession(app, sid, dirs, o = {}) {
426
767
  const next = {
427
768
  projects,
428
769
  ...(over ? { over: true } : {}),
770
+ ...(why.size > 0 ? { overWhy: [...why] } : {}),
429
771
  ...(constraints.length ? { constraints } : {}),
430
772
  ...(unregistered ? { unregistered: true } : {}),
431
773
  ...(registered ? { registered: true } : {}),
774
+ since: typeof have?.since === "number" ? have.since : now,
432
775
  at: now,
433
776
  };
434
777
  return { next: { ...all, [sid]: next }, result: next };
@@ -529,16 +872,32 @@ export function takePersonToken(env, home) {
529
872
  * Lets a command that widens who reaches this user (sharing a project, a session, a default
530
873
  * circle, invites, joins, trust, friends) run only for the person: their front end's token; or,
531
874
  * outside any agent's session, their "yes" typed on the controlling terminal (never stdin, never a
532
- * flag: a process detached from every terminal can't give it). Reads are never asked.
875
+ * flag: a process detached from every terminal can't give it). Reads are never asked, except for
876
+ * the person's own messages (history.ts), which pass their own `why`.
533
877
  */
534
- export async function assertPersonForWidening(app, what, confirm) {
878
+ export async function assertPersonForWidening(app, what, confirm, why = "changes who reaches you") {
535
879
  if (app.front === true)
536
880
  return;
537
881
  if (agentContext(app.env)) {
538
- throw new CliError("refused", `\`p2p ${what}\` changes who reaches you, so only you run it: in your own terminal (not inside Claude Code or Codex), or with /peers in Claude Code. It was refused here because it runs inside an agent's session`);
882
+ throw new CliError("refused", `\`p2p ${what}\` ${why}, so only you run it: in your own terminal (not inside Claude Code or Codex), or with /peers in Claude Code. It was refused here because it runs inside an agent's session`);
539
883
  }
540
- if (!(await confirm(`p2p ${what} changes who reaches you.`))) {
541
- throw new CliError("refused", `\`p2p ${what}\` changes who reaches you: confirm it with "yes" on your own terminal (it is read from the terminal itself, so a script or a process without one can't)`);
884
+ if (!(await confirm(`p2p ${what} ${why}.`))) {
885
+ throw new CliError("refused", `\`p2p ${what}\` ${why}: confirm it with "yes" on your own terminal (it is read from the terminal itself, so a script or a process without one can't)`);
886
+ }
887
+ }
888
+ /**
889
+ * For an act on a session that binds nothing (a delivery receipt): the session's front end (its
890
+ * token); or, outside any agent's session, a caller acting for a session no front end registered.
891
+ * An agent's own shell never may, as for statuses and sends (bindSession).
892
+ */
893
+ export async function assertSpeaksFor(app, sid) {
894
+ if (app.front === true)
895
+ return;
896
+ if (agentContext(app.env)) {
897
+ throw new CliError("refused", `session ${sid}: inside an agent's session only its front end speaks for a session (the Claude mod, the Codex bridge), never the shell`);
898
+ }
899
+ if ((await sessionBinding(app, sid))?.registered) {
900
+ throw new CliError("refused", `session ${sid} belongs to a front end of yours (the Claude mod or the Codex bridge): only it speaks for that session`);
542
901
  }
543
902
  }
544
903
  /** Whether a person-only path (session `tui`) may run here: the person's front end, or no agent in sight (then a terminal "yes" too). */
@@ -548,6 +907,99 @@ export function personHere(app) {
548
907
  export async function sessionBinding(app, sid) {
549
908
  return (await app.state.get("sessionProjects"))?.[sid];
550
909
  }
910
+ const OVER_TEXT = {
911
+ projects: `it worked in more than ${MAX_SESSION_PROJECTS} projects`,
912
+ folders: "it worked in more folders than Peer2Peer keeps track of for one session",
913
+ unresolved: "a command it ran named a path Peer2Peer couldn't resolve (one that starts with a variable or a command substitution its front end doesn't know the value of, like $X/… or $(…)/…), so which project that path is in can't be told",
914
+ front: "its front end couldn't keep track of every folder it worked in (a forked conversation, or a record it couldn't read)",
915
+ constraints: `more than ${MAX_SESSION_CONSTRAINTS} sessions of yours sent it messages`,
916
+ "legacy-over": "it worked in more projects or folders than Peer2Peer keeps track of, or named a path Peer2Peer couldn't resolve",
917
+ };
918
+ /**
919
+ * Every policy a bound project answers to: its own, and, for a folder project a shared folder
920
+ * covered, each policy a covered subfolder (or a folder between it and the root) has since been
921
+ * given. Past MAX_UNDER covered subfolders, every folder policy below the root.
922
+ */
923
+ function boundShares(doc, id, p) {
924
+ const out = [{ share: shareOf(doc, id), mapped: doc.projects[id] !== undefined, name: p.name }];
925
+ const root = p.root;
926
+ if (typeof root !== "string" || root === "")
927
+ return out;
928
+ const seen = new Set([id]);
929
+ const add = (pid) => {
930
+ const r = doc.projects[pid];
931
+ if (seen.has(pid) || !r)
932
+ return;
933
+ seen.add(pid);
934
+ out.push({ share: shareOf(doc, pid), mapped: true, name: clean(String(r.name ?? "")) || p.name });
935
+ };
936
+ // Subfolders it covered, and its share no longer covers them (shared again without --subfolders): private.
937
+ if ((p.underOver || (p.under?.length ?? 0) > 0) && doc.projects[id]?.covers !== true)
938
+ out.push({ share: "private", mapped: true, name: p.name });
939
+ if (p.underOver) {
940
+ for (const [pid, r] of Object.entries(doc.projects))
941
+ if (typeof r?.root === "string" && r.root !== root && within(r.root, root) && pid === dirProjectId(r.root))
942
+ add(pid);
943
+ return out;
944
+ }
945
+ for (const f of p.under ?? []) {
946
+ if (typeof f !== "string")
947
+ continue;
948
+ for (let c = f, i = 0; i < 4096 && c !== root && within(c, root); i++) {
949
+ add(dirProjectId(c));
950
+ const up = dirname(c);
951
+ if (up === c)
952
+ break;
953
+ c = up;
954
+ }
955
+ }
956
+ return out;
957
+ }
958
+ /** Why a binding is private, every cause (no network: `disjoint` needs the store, see sessionCeiling). */
959
+ export function privateReasons(doc, b) {
960
+ const out = [];
961
+ if (b.over)
962
+ for (const w of b.overWhy?.length ? overWhys(b.overWhy) : ["legacy-over"])
963
+ out.push({ cause: w, why: OVER_TEXT[w] });
964
+ if (b.unregistered)
965
+ out.push({ cause: "unregistered", why: "an agent named it, and no front end of yours has registered it" });
966
+ for (const [id, p] of Object.entries(b.projects)) {
967
+ if (p.repoPrivate) {
968
+ out.push({ cause: "repo-private", why: `${p.name} asks to stay private (${PRIVATE_MARKER})`, project: p.name });
969
+ continue;
970
+ }
971
+ for (const s of boundShares(doc, id, p)) {
972
+ if (s.share !== "private")
973
+ continue;
974
+ out.push(s.mapped ? { cause: "private", why: `${s.name} is private`, project: s.name } : { cause: "unshared", why: `${s.name} isn't shared (projects are private until you share them)`, project: s.name });
975
+ break;
976
+ }
977
+ }
978
+ if ((b.constraints ?? []).includes("private"))
979
+ out.push({ cause: "sent-private", why: "a private session of yours sent it a message" });
980
+ return out;
981
+ }
982
+ /**
983
+ * What the person can do about a private session, for an error a model may read: a share only
984
+ * when a share can lift it, never the "share each project" hint for a cause that lasts until the
985
+ * session ends (a cap, an unresolved path, a dropped front end, `.p2p-private`, a private
986
+ * session's message).
987
+ */
988
+ export function privateRemedy(causes, names) {
989
+ if (causes.some((c) => STICKY.has(c))) {
990
+ return "sharing a project can't change that, and it lasts until the session ends: start a new session for the work you want to share (`p2p session show <session>` in your own terminal, or /peers session in Claude Code, lists what it is bound to and why)";
991
+ }
992
+ const parts = [];
993
+ if (causes.includes("unregistered"))
994
+ parts.push("send from the session's own front end (SendMessage in Claude Code, p2p_send in Codex), which registers it");
995
+ if (causes.some((c) => c === "private" || c === "unshared" || c === "disjoint") || parts.length === 0)
996
+ parts.push(shareHint(names));
997
+ return parts.join("; and ");
998
+ }
999
+ /** Whether a ceiling's privacy can only end with the session (privateRemedy says to start a new one). */
1000
+ export function stickyPrivate(c) {
1001
+ return c.kind === "private" && c.causes.some((x) => STICKY.has(x));
1002
+ }
551
1003
  /**
552
1004
  * The most a session may reach: the intersection of every bound project's policy. Unmapped,
553
1005
  * private and repository-private projects make it private, and so does an empty intersection.
@@ -558,27 +1010,18 @@ export async function sessionCeiling(app, sid, binding) {
558
1010
  const b = binding === null ? undefined : (binding ?? (await sessionBinding(app, sid)));
559
1011
  if (!b || (Object.keys(b.projects).length === 0 && !b.constraints?.length && !b.unregistered && !b.over))
560
1012
  return { kind: "none" };
561
- if (b.over)
562
- return { kind: "private", why: `it worked in more than ${MAX_SESSION_PROJECTS} projects (or ${MAX_SESSION_DIRS} folders)` };
563
- if (b.unregistered)
564
- return { kind: "private", why: "an agent named it, and no front end of yours has registered it" };
565
1013
  const doc = await projectsDoc(app);
1014
+ const reasons = privateReasons(doc, b);
1015
+ if (reasons.length > 0)
1016
+ return privateOf(reasons);
566
1017
  let circles;
567
1018
  let people;
568
1019
  const shares = [];
569
- for (const [id, p] of Object.entries(b.projects)) {
570
- if (p.repoPrivate)
571
- return { kind: "private", why: `${p.name} asks to stay private (${PRIVATE_MARKER})` };
572
- const share = shareOf(doc, id);
573
- if (share === "private")
574
- return { kind: "private", why: doc.projects[id] ? `${p.name} is private` : `${p.name} isn't shared (projects are private until you share them)` };
575
- shares.push({ name: p.name, share });
576
- }
577
- for (const c of b.constraints ?? []) {
578
- if (c === "private")
579
- return { kind: "private", why: "a private session of yours sent it a message" };
1020
+ for (const [id, p] of Object.entries(b.projects))
1021
+ for (const s of boundShares(doc, id, p))
1022
+ shares.push({ name: s.name, share: s.share });
1023
+ for (const c of b.constraints ?? [])
580
1024
  shares.push({ name: "a session of yours that sent it a message", share: c });
581
- }
582
1025
  for (const { share } of shares) {
583
1026
  if (share === "private")
584
1027
  continue;
@@ -594,11 +1037,22 @@ export async function sessionCeiling(app, sid, binding) {
594
1037
  const friends = (people?.size ?? 0) > 0 ? await friendIds(app) : new Set();
595
1038
  const ppl = [...(people ?? [])].filter((u) => !blocks.has(u) && u !== app.userId && friends.has(u));
596
1039
  if (joined.length + ppl.length === 0) {
597
- const names = shares.map((x) => x.name);
598
- return { kind: "private", why: names.length > 1 ? `its projects (${names.join(", ")}) share nobody in common` : `${names[0]} shares nobody you can reach` };
1040
+ const names = [...new Set(shares.map((x) => x.name))];
1041
+ return privateOf([{ cause: "disjoint", why: names.length > 1 ? `its projects (${names.join(", ")}) share nobody in common` : `${names[0]} shares nobody you can reach` }], names);
599
1042
  }
600
1043
  return { kind: "shared", circles: joined.sort(), people: ppl.sort() };
601
1044
  }
1045
+ /** A private ceiling from its reasons: the first said in full, the count of the rest (`p2p session show` lists them all). */
1046
+ function privateOf(reasons, names) {
1047
+ const more = reasons.length - 1;
1048
+ const blocking = names ?? [...new Set(reasons.map((r) => r.project).filter((x) => x !== undefined))];
1049
+ return {
1050
+ kind: "private",
1051
+ why: `${reasons[0].why}${more > 0 ? ` (and ${more} more reason${more === 1 ? "" : "s"})` : ""}`,
1052
+ causes: [...new Set(reasons.map((r) => r.cause))],
1053
+ ...(blocking.length ? { blocking } : {}),
1054
+ };
1055
+ }
602
1056
  /** Everyone a ceiling lets in (besides this user): members of its circles who stand in them, and its people. */
603
1057
  export async function ceilingAudience(app, c) {
604
1058
  if (c.kind === "none")
@@ -645,9 +1099,10 @@ export async function assertMayReach(app, sid, userId, o = {}) {
645
1099
  const names = Object.values(b?.projects ?? {}).map((p) => p.name);
646
1100
  const who = o.address ?? (await app.addressOf(userId));
647
1101
  const why = c.kind === "private" ? c.why : `${who} isn't in the circles or people ${names.length > 1 ? "all its projects share" : "its project shares"}`;
648
- throw new CliError("not_shared", `session ${sid} works in ${names.join(", ") || "a project"}, and Peer2Peer won't carry anything from it to ${who}: ${why}. ${shareHint(names).replace(/^o/, "O")}`, {
1102
+ const remedy = c.kind === "private" ? privateRemedy(c.causes, c.blocking?.length ? c.blocking : names) : shareHint(names);
1103
+ throw new CliError("not_shared", `session ${sid} works in ${names.join(", ") || "a project"}, and Peer2Peer won't carry anything from it to ${who}: ${why}. ${remedy.charAt(0).toUpperCase()}${remedy.slice(1)}`, {
649
1104
  delivered: false,
650
- project: { names, policy: c.kind },
1105
+ project: { names, policy: c.kind, ...(c.kind === "private" ? { causes: c.causes, ...(stickyPrivate(c) ? { sticky: true } : {}) } : {}) },
651
1106
  });
652
1107
  }
653
1108
  /** Friends of this user (live friendships), for the roster's named parts. */
@@ -662,11 +1117,45 @@ export async function sessionProjectView(app, sid) {
662
1117
  const c = await sessionCeiling(app, sid, b ?? null);
663
1118
  const projects = Object.entries(b?.projects ?? {}).map(([id, p]) => ({ id, name: p.name, ...(p.repoPrivate ? { repoPrivate: true } : {}) }));
664
1119
  if (c.kind === "private")
665
- return { projects, policy: "private", why: c.why };
1120
+ return { projects, policy: "private", why: c.why, causes: c.causes };
666
1121
  if (c.kind === "shared")
667
1122
  return { projects, policy: "shared", circles: c.circles, people: c.people };
668
1123
  return { projects, policy: "none" };
669
1124
  }
1125
+ /**
1126
+ * `p2p session show <sid>`: read only, and the person's: their front end (the person token) or
1127
+ * their own terminal outside any agent's session. An agent's shell is refused, so no session reads
1128
+ * another's bindings (or its own: the model has the not_shared reason already).
1129
+ */
1130
+ export async function showSession(app, sid) {
1131
+ if (app.front !== true && agentContext(app.env)) {
1132
+ throw new CliError("refused", "`p2p session show` lists a session's projects and why it is private, which is for you to read: run it in your own terminal (not inside Claude Code or Codex), or type /peers session in Claude Code");
1133
+ }
1134
+ if (sid === PERSON_SESSION)
1135
+ return { sid, policy: "none", reasons: [], projects: [], constraints: 0 };
1136
+ const b = await sessionBinding(app, sid);
1137
+ const c = await sessionCeiling(app, sid, b ?? null);
1138
+ const doc = await projectsDoc(app);
1139
+ const reasons = b ? privateReasons(doc, b) : [];
1140
+ if (c.kind === "private" && reasons.length === 0)
1141
+ reasons.push({ cause: c.causes[0] ?? "disjoint", why: c.why });
1142
+ const projects = [];
1143
+ for (const [id, p] of Object.entries(b?.projects ?? {})) {
1144
+ const root = typeof p.root === "string" && p.root !== "" ? p.root : (doc.projects[id]?.root ?? "");
1145
+ const kind = root !== "" && dirProjectId(root) === id ? "dir" : "git";
1146
+ const v = await projectView(app, { id, name: p.name, kind, root, ...(doc.projects[id]?.remote ? { remote: doc.projects[id].remote } : {}), ...(p.repoPrivate ? { repoPrivate: true } : {}) }, doc);
1147
+ projects.push({ ...v, ...(p.under?.length ? { under: [...p.under] } : {}), ...(p.underOver ? { underOver: true } : {}) });
1148
+ }
1149
+ return {
1150
+ sid,
1151
+ policy: c.kind,
1152
+ reasons,
1153
+ ...(c.kind === "private" ? { remedy: privateRemedy(c.causes, c.blocking?.length ? c.blocking : projects.map((x) => x.name)) } : {}),
1154
+ ...(c.kind === "shared" ? { circles: c.circles, people: c.people } : {}),
1155
+ projects,
1156
+ constraints: b?.constraints?.length ?? 0,
1157
+ };
1158
+ }
670
1159
  /**
671
1160
  * The one-time notice for a user who relied on the default circle: shown once per device, the
672
1161
  * first time a session of theirs is private only because its project was never shared.
@@ -697,3 +1186,198 @@ export async function defaultCircleNotice(app, sid) {
697
1186
  }
698
1187
  /** The text of the one-time notice starts so (the mod and the Codex bridge match it). */
699
1188
  export const PROJECT_NOTICE_PREFIX = "project boundaries:";
1189
+ /** `s` without trailing slashes (a loop, not a regex: linear on any input). */
1190
+ function trimSlashes(s) {
1191
+ let n = s.length;
1192
+ while (n > 0 && s.charCodeAt(n - 1) === 47)
1193
+ n--;
1194
+ return s.slice(0, n);
1195
+ }
1196
+ /** What `p2p doctor` and `p2p project show` print for a local target. */
1197
+ export const GRAPH_LOCAL_ONLY = "local only";
1198
+ /** Ix's own default backend (ix-cli config.ts DEFAULT_ENDPOINT): `ix docker` runs it on this machine. */
1199
+ export const DEFAULT_IX_ENDPOINT = "http://localhost:8090";
1200
+ /**
1201
+ * Whether `url` is an Ix backend on this machine: http(s) to localhost, 127.0.0.0/8 or ::1, with no
1202
+ * credentials, query or fragment. Anything else (a cloud URL, a LAN host, `localhost.example.com`,
1203
+ * `http://127.0.0.1@evil.example`) is not.
1204
+ */
1205
+ export function isLoopbackEndpoint(url) {
1206
+ if (typeof url !== "string" || url.length > 512 || /[\s\0]/.test(url))
1207
+ return false;
1208
+ let u;
1209
+ try {
1210
+ u = new URL(url);
1211
+ }
1212
+ catch {
1213
+ return false;
1214
+ }
1215
+ if ((u.protocol !== "http:" && u.protocol !== "https:") || u.username || u.password || u.search || u.hash)
1216
+ return false;
1217
+ const h = u.hostname.toLowerCase();
1218
+ return h === "localhost" || h === "[::1]" || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(h);
1219
+ }
1220
+ /** A loopback endpoint as one canonical string: `origin + pathname`, trailing slashes dropped. Undefined when it isn't one. */
1221
+ export function normalizeLoopbackEndpoint(url) {
1222
+ if (!isLoopbackEndpoint(url))
1223
+ return undefined;
1224
+ const u = new URL(url.trim());
1225
+ return trimSlashes(u.origin + u.pathname);
1226
+ }
1227
+ /**
1228
+ * The local Ix endpoint every `local` target names: `ixEndpoint` in config.json (the person's own
1229
+ * file) when it is a loopback URL, else Ix's default. Never from the environment (an agent or a
1230
+ * project config can set that), and never a non-loopback URL. On a shared machine another user can
1231
+ * listen on a loopback port first (threat model, "Graph targets").
1232
+ */
1233
+ export function localGraphEndpoint(_env, file) {
1234
+ return normalizeLoopbackEndpoint(typeof file?.ixEndpoint === "string" ? file.ixEndpoint.trim() : undefined) ?? DEFAULT_IX_ENDPOINT;
1235
+ }
1236
+ /**
1237
+ * The circles that have a shared graph, and its endpoint. None yet: the shared cloud graph (epic #41
1238
+ * piece 3) comes in a later PR, which fills this from settled, person-made state. Nothing in the
1239
+ * environment, config.json, a repository or a peer's message can add to it.
1240
+ */
1241
+ export const SHARED_GRAPHS = new Map();
1242
+ /**
1243
+ * The graph target of a set of projects (pure: graphTarget gathers the inputs). Intersection, like
1244
+ * the session ceiling: any private, repository-private or unmapped project makes it local, and so
1245
+ * does an empty set. A shared target needs every input shared with the same circle, and exactly one
1246
+ * such circle with a shared graph (an https endpoint); people-only shares, no common circle, or a
1247
+ * choice of several circles all stay local.
1248
+ */
1249
+ export function graphTargetOf(inputs, o) {
1250
+ const local = (why) => ({ kind: "local", endpoint: o.local, why });
1251
+ if (inputs.length === 0)
1252
+ return local("no project: nothing is shared");
1253
+ let circles;
1254
+ for (const i of inputs) {
1255
+ if (i.repoPrivate)
1256
+ return local(`${i.name} asks to stay private (${PRIVATE_MARKER})`);
1257
+ if (i.share === "private" || typeof i.share !== "object")
1258
+ return local(`${i.name} is private`);
1259
+ const cs = Array.isArray(i.share.circles) ? i.share.circles.filter((c) => typeof c === "string") : [];
1260
+ circles = circles ? new Set(cs.filter((c) => circles.has(c))) : new Set(cs);
1261
+ }
1262
+ if (!circles || circles.size === 0)
1263
+ return local(inputs.length > 1 ? "its projects share no circle in common" : `${inputs[0].name} isn't shared with a circle`);
1264
+ const graphs = o.sharedGraphs ?? SHARED_GRAPHS;
1265
+ const withGraph = [...circles].filter((c) => {
1266
+ const ep = graphs.get(c);
1267
+ return normalizeSharedEndpoint(ep) !== undefined;
1268
+ });
1269
+ if (withGraph.length === 0)
1270
+ return local("no shared graph for its circle yet: Ix stays on this machine");
1271
+ if (withGraph.length > 1)
1272
+ return local("it is shared with more than one circle that has a shared graph: Ix stays on this machine");
1273
+ return { kind: "shared", circle: withGraph[0], endpoint: normalizeSharedEndpoint(graphs.get(withGraph[0])) };
1274
+ }
1275
+ /** A shared graph's endpoint as `origin + pathname` (https, off this machine, no credentials, query or fragment), else undefined. */
1276
+ export function normalizeSharedEndpoint(url) {
1277
+ if (typeof url !== "string" || url.length > 512 || /[\s\0]/.test(url))
1278
+ return undefined;
1279
+ let u;
1280
+ try {
1281
+ u = new URL(url);
1282
+ }
1283
+ catch {
1284
+ return undefined;
1285
+ }
1286
+ if (u.protocol !== "https:" || u.username || u.password || u.search || u.hash || isLoopbackEndpoint(url))
1287
+ return undefined;
1288
+ return trimSlashes(u.origin + u.pathname);
1289
+ }
1290
+ /**
1291
+ * The chokepoint for every Ix call Peer2Peer makes or lets an extension make (ext-ix takes its
1292
+ * endpoint only from here, ExtContext.graphTarget): the graph a session, the folders it works in,
1293
+ * or both may reach. A session bound to a private project, or one whose ceiling is private for any
1294
+ * reason (an unregistered agent session, too many projects, a private session's message), is local.
1295
+ * The folders' own projects are intersected in, so a session can't name a shared sibling to widen
1296
+ * a private repository it works in. The process's own cwd and every path the call names (`paths`:
1297
+ * its targets, `--path`, `--changed`, the child's cwd) are intersected in as well. A named session
1298
+ * that isn't bound yet is local, and a `shared` result needs a session a front end registered (its
1299
+ * person token). Read only: binds nothing.
1300
+ */
1301
+ export async function graphTarget(app, o = {}, sharedGraphs = SHARED_GRAPHS) {
1302
+ const lo = localGraphEndpoint(app.env, app.file);
1303
+ const local = (why) => ({ kind: "local", endpoint: lo, why });
1304
+ if (o.over)
1305
+ return local(`it works in more than ${MAX_SESSION_DIRS} folders`);
1306
+ // The paths a call names (its targets, --path, --changed, the child's cwd): absolute only, capped.
1307
+ const paths = o.paths ?? [];
1308
+ if (paths.length > MAX_GRAPH_PATHS)
1309
+ return local(`a call named more than ${MAX_GRAPH_PATHS} paths`);
1310
+ if (paths.some((p) => typeof p !== "string" || !isAbsolute(p)))
1311
+ return local("a call named a path that isn't absolute");
1312
+ const doc = await projectsDoc(app);
1313
+ const inputs = [];
1314
+ let registered = false;
1315
+ if (o.sid !== undefined && o.sid !== PERSON_SESSION) {
1316
+ const b = await sessionBinding(app, o.sid);
1317
+ registered = b?.registered === true;
1318
+ const c = await sessionCeiling(app, o.sid, b ?? null);
1319
+ if (c.kind === "private")
1320
+ return local(`session ${o.sid} is private: ${c.why}`);
1321
+ // A session no front end has bound yet has no ceiling to intersect: fail closed.
1322
+ if (c.kind === "none")
1323
+ return local(`session ${o.sid} isn't bound to a project yet`);
1324
+ if (c.kind === "shared")
1325
+ inputs.push({ name: `session ${o.sid}`, share: { circles: c.circles, people: c.people } });
1326
+ }
1327
+ const seen = new Set();
1328
+ // The process's real cwd always counts too: P2P_WORKDIR replaces it for display, never for the boundary.
1329
+ for (const d of [...(o.dirs ?? []), process.cwd(), ...paths]) {
1330
+ if (typeof d !== "string" || d.trim() === "")
1331
+ continue;
1332
+ const r = projectOf(d);
1333
+ if (seen.has(r.id))
1334
+ continue;
1335
+ seen.add(r.id);
1336
+ if (seen.size > MAX_SESSION_PROJECTS)
1337
+ return local(`it works in more than ${MAX_SESSION_PROJECTS} projects`);
1338
+ inputs.push({ name: r.name, share: shareOf(doc, r.id), ...(r.repoPrivate ? { repoPrivate: true } : {}) });
1339
+ }
1340
+ const t = graphTargetOf(inputs, { local: lo, sharedGraphs });
1341
+ // A shared graph only for a session a front end of this user registered (its token), never a bare call.
1342
+ if (t.kind === "shared" && !registered)
1343
+ return local(o.sid ? `session ${o.sid} isn't registered by a front end of yours` : "no session: only a session your front end registered may reach a shared graph");
1344
+ return t;
1345
+ }
1346
+ /** At most this many paths one Ix call may name for its graph target; past it, local. */
1347
+ export const MAX_GRAPH_PATHS = 64;
1348
+ /** One project's graph target (`p2p project show`, `p2p doctor`). */
1349
+ export function projectGraphTarget(app, ref, doc) {
1350
+ const lo = localGraphEndpoint(app.env, app.file);
1351
+ return graphTargetOf([{ name: ref.name, share: shareOf(doc, ref.id), ...(ref.repoPrivate ? { repoPrivate: true } : {}) }], { local: lo });
1352
+ }
1353
+ /** How a target reads in one line: `local only (http://localhost:8090)`, or the circle's shared graph. */
1354
+ export function describeGraphTarget(t) {
1355
+ return t.kind === "local" ? `${GRAPH_LOCAL_ONLY} (${t.endpoint})` : `the shared graph of circle ${t.circle} (${t.endpoint})`;
1356
+ }
1357
+ /**
1358
+ * The Ix variables that could send an `ix` call somewhere other than its graph target, or carry a
1359
+ * cloud credential: Ix Pro's PAT mode (IX_PAT, IX_ORG, its endpoint override), the cloud push and
1360
+ * ingestion knobs, the OAuth secret, auto-map routing to the cloud. Every IX_* variable outside
1361
+ * IX_KEEP is dropped as well; these are named so tests and docs can point at them.
1362
+ */
1363
+ export const IX_CLOUD_ENV = ["IX_ENDPOINT", "IX_PAT", "IX_ORG", "IX_ORG_ID", "IX_PUSH_ENDPOINT", "IX_PUSH_TOKEN", "IX_OAUTH_CLIENT_SECRET", "IX_AUTO_MAP_CLOUD", "IX_AUTO_MAP", "IX_KARTR_UI_URL", "IX_VIEW_BACKEND_URL", "IX_VIEW_BACKEND_TOKEN"];
1364
+ /** IX_* variables an `ix` call keeps: which binary (read by ext-ix, not ix), where Ix keeps its local state, and the local backend's token (Ix sends it to a loopback endpoint only). */
1365
+ export const IX_KEEP = ["IX_BIN", "IX_HOME", "IX_TOKEN"];
1366
+ /**
1367
+ * The environment an extension gets (ExtContext.env), with the target pinned: every IX_* variable
1368
+ * outside IX_KEEP set to undefined (so a `{...process.env, ...ctx.env}` merge drops it too: an older
1369
+ * ext-ix spreads it), IX_ENDPOINT set to the target's endpoint, and readers kept from starting a
1370
+ * background `ix map` (Ix Pro routes a map to the cloud when an org session is active, whatever
1371
+ * IX_ENDPOINT says). Defence in depth: ext-ix builds its own allowlisted env from the target.
1372
+ */
1373
+ export function graphPinnedEnv(env, target, base = process.env) {
1374
+ const out = { ...env };
1375
+ const keep = new Set(IX_KEEP);
1376
+ for (const k of new Set([...Object.keys(base), ...Object.keys(env)]))
1377
+ if (/^IX_/i.test(k) && !keep.has(k.toUpperCase()))
1378
+ out[k] = undefined;
1379
+ out.IX_ENDPOINT = target.endpoint;
1380
+ out.IX_MAP_BACKGROUND_REFRESH = "0";
1381
+ out.IX_NO_UPDATE_CHECK = "1";
1382
+ return out;
1383
+ }