diff --git a/.changeset/linked-homes-one-session.md b/.changeset/linked-homes-one-session.md new file mode 100644 index 00000000..e5e9e3fd --- /dev/null +++ b/.changeset/linked-homes-one-session.md @@ -0,0 +1,6 @@ +--- +"sessionpipe": patch +"sessionpipe-core": patch +--- + +Control: a message for a Claude Code session is no longer refused `ambiguous_home` when several accounts share one `projects/` tree and live-session registry by symlink. Each finds the same transcript and the same live record, so the machine takes that one session (spec/CONTROL.md §6.1). Two transcripts, two processes, or nothing live is still refused. diff --git a/conformance/README.md b/conformance/README.md index 5aa55df1..fa5f6d90 100644 --- a/conformance/README.md +++ b/conformance/README.md @@ -77,6 +77,11 @@ written, when a run of it is known to have ended, when its own hooks last spoke of a turn running in it, and when a run that was asked to copy it and may have run in it ended. Run by `packages/cli/test/control-daemon.test.ts`. +- `control-homes.json` — which Claude Code account a session id belongs to when a machine has + more than one config dir, including accounts that share `projects/` and `sessions/` by symlink + (spec/CONTROL.md §6.1): `{ stores?, accounts, expect }`, the backing folders and config dirs + with transcripts, live rows and symlinks, and `{ home }`, `{ ambiguous, live }`, or null. Run + by `packages/core/test/claude-live-record.test.ts`. - `control-session-ids.json` — which Claude Code session an id names (spec/CONTROL.md §6): `{ filed, asked, found, taken }`, the transcripts in a project folder, the id a command names, the file that is that session's (its exact name, or none), and whether the id is diff --git a/conformance/control-homes.json b/conformance/control-homes.json new file mode 100644 index 00000000..d4586e1f --- /dev/null +++ b/conformance/control-homes.json @@ -0,0 +1,100 @@ +{ + "spec": "CONTROL.md §6.1 Homes", + "note": "Which Claude Code account a session id belongs to when a machine has more than one config dir. `stores` names backing folders outside `accounts` (for the all-links case); each entry in `accounts` is a config dir in the order the machine lists them, with `transcript` (holds the session's transcript), `live` (live registry rows, named `self` or `parent` so two processes are distinct), and `link_projects` / `link_sessions` (symlinked to another named store or account). `expect` is `{ \"home\": }`, `{ \"ambiguous\": [...], \"live\": [...] }` (directory names only, sorted), or null when no account has the session.", + "cases": [ + { + "name": "one account has the transcript, no live process needed", + "accounts": [{ "name": "only", "transcript": true }], + "expect": { "home": "only" } + }, + { + "name": "no account has the transcript", + "accounts": [{ "name": "empty" }], + "expect": null + }, + { + "name": "two accounts, one holds it open", + "accounts": [ + { "name": "cold", "transcript": true }, + { "name": "live", "transcript": true, "live": ["self"] } + ], + "expect": { "home": "live" } + }, + { + "name": "two accounts, neither live: ambiguous", + "accounts": [ + { "name": "b", "transcript": true }, + { "name": "a", "transcript": true } + ], + "expect": { "ambiguous": ["a", "b"], "live": [] } + }, + { + "name": "three accounts, two live and one cold: ambiguous, naming the two live", + "accounts": [ + { "name": "a", "transcript": true, "live": ["self"] }, + { "name": "b", "transcript": true, "live": ["parent"] }, + { "name": "c", "transcript": true } + ], + "expect": { "ambiguous": ["a", "b", "c"], "live": ["a", "b"] } + }, + { + "name": "linked accounts sharing projects/ and sessions/, one live process: chosen under the owner", + "accounts": [ + { "name": "linked-a", "link_projects": "own", "link_sessions": "own" }, + { "name": "own", "transcript": true, "live": ["self"] }, + { "name": "linked-b", "link_projects": "own", "link_sessions": "own" } + ], + "expect": { "home": "own" } + }, + { + "name": "all accounts link to a shared folder none of them owns, one live process: first account in dirs", + "stores": [{ "name": "shared", "transcript": true, "live": ["self"] }], + "accounts": [ + { "name": "first", "link_projects": "shared", "link_sessions": "shared" }, + { "name": "second", "link_projects": "shared", "link_sessions": "shared" } + ], + "expect": { "home": "first" } + }, + { + "name": "linked accounts, nothing live: still ambiguous", + "accounts": [ + { "name": "own", "transcript": true, "live": [] }, + { "name": "linked", "link_projects": "own", "link_sessions": "own" } + ], + "expect": { "ambiguous": ["linked", "own"], "live": [] } + }, + { + "name": "linked projects/ but separate registries with two live processes: still ambiguous", + "accounts": [ + { "name": "own", "transcript": true, "live": ["self"] }, + { "name": "other", "link_projects": "own", "live": ["parent"] } + ], + "expect": { "ambiguous": ["other", "own"], "live": ["other", "own"] } + }, + { + "name": "separate projects/ (two real transcripts) with linked sessions/: still ambiguous", + "accounts": [ + { "name": "own", "transcript": true, "live": ["self"] }, + { "name": "other", "transcript": true, "link_sessions": "own" } + ], + "expect": { "ambiguous": ["other", "own"], "live": ["other", "own"] } + }, + { + "name": "linked projects/ and sessions/ with two live processes in the shared registry: still ambiguous", + "accounts": [ + { "name": "own", "transcript": true, "live": ["self", "parent"] }, + { "name": "linked", "link_projects": "own", "link_sessions": "own" } + ], + "expect": { "ambiguous": ["linked", "own"], "live": ["linked", "own"] } + }, + { + "name": "linked accounts sharing one live session plus a third cold account with its own transcript: chosen under the owner", + "accounts": [ + { "name": "cold", "transcript": true }, + { "name": "linked", "link_projects": "own", "link_sessions": "own" }, + { "name": "own", "transcript": true, "live": ["self"] } + ], + "expect": { "home": "own" } + } + ] +} diff --git a/packages/cli/src/control/daemon.ts b/packages/cli/src/control/daemon.ts index 8f215d60..4ad4a11b 100644 --- a/packages/cli/src/control/daemon.ts +++ b/packages/cli/src/control/daemon.ts @@ -2923,7 +2923,9 @@ export class ControlDaemon { code: "stale", detail: `a message written into a live session must arrive within ${INBOX_FRESH_MS / 1000} s of being signed, and this one is dated ${Math.round(age / 1000)} s from now`, }; - const rec = liveRecord(target, this.deps.claudeDirs()); + // Every account, so a second process in another one still refuses; a row two + // accounts see through linked folders is one row, named for the account resolved. + const rec = liveRecord(target, this.deps.claudeDirs(), place.transcript.configDir); const cls = peerClass(this.modeOf(key)); const why = inbox.vetInbox(rec, { sessionClass: cls, diff --git a/packages/cli/test/control-inbox.test.ts b/packages/cli/test/control-inbox.test.ts index ee0860de..7fe9f97b 100644 --- a/packages/cli/test/control-inbox.test.ts +++ b/packages/cli/test/control-inbox.test.ts @@ -11,6 +11,7 @@ import { mkdtempSync, readFileSync, rmSync, + symlinkSync, utimesSync, writeFileSync, } from "node:fs"; @@ -292,6 +293,86 @@ describe.runIf(unix)("a message into a live session's own inbox", () => { expect(rx.hellos.at(-1)?.modes).toContain("inbox"); }); + it("accounts that share their folders by symlink: written in place, in the account that owns them", async () => { + // A second login whose `projects/` and `sessions/` are links to the first: both + // accounts find the one transcript and the one registry row. Listed first, so a + // lookup that took the first account it found would vet against the wrong one (its + // own settings say nothing of bypass) and fork instead. + row(); + const linked = path.join(tmp, "home-linked"); + mkdirSync(linked, { recursive: true }); + symlinkSync(path.join(configDir, "projects"), path.join(linked, "projects")); + symlinkSync(path.join(configDir, "sessions"), path.join(linked, "sessions")); + await startDaemon({ extra: { claudeDirs: () => [linked, configDir] } }); + await sawMode("bypassPermissions"); + const q = await rx.send({ session: SESSION, kind: "prompt", text: "through the links?" }); + await wrote(1); + expect(frameIn()).toContain(markOf(q.id)); + answered(markOf(q.id)); + await ask(sock, { op: "event", session: SESSION, event: "UserPromptSubmit", mode: "bypassPermissions" }, 500); + expect(await rx.waitAck(q.id)).toMatchObject({ outcome: "delivered", mode: "inbox" }); + expect(() => readFileSync(claudeLog, "utf8")).toThrow(); + }); + + it("all accounts linked to an external shared store: takes the first account and uses its settings", async () => { + row(); + const first = path.join(tmp, "home-ext-1"); + const second = path.join(tmp, "home-ext-2"); + for (const dir of [first, second]) { + mkdirSync(dir, { recursive: true }); + symlinkSync(path.join(configDir, "projects"), path.join(dir, "projects")); + symlinkSync(path.join(configDir, "sessions"), path.join(dir, "sessions")); + } + homeDefault("bypassPermissions", {}, first); + await startDaemon({ extra: { claudeDirs: () => [first, second] } }); + await sawMode("bypassPermissions"); + const q = await rx.send({ session: SESSION, kind: "prompt", text: "all links?" }); + await wrote(1); + expect(frameIn()).toContain(markOf(q.id)); + answered(markOf(q.id)); + await ask(sock, { op: "event", session: SESSION, event: "UserPromptSubmit", mode: "bypassPermissions" }, 500); + expect(await rx.waitAck(q.id)).toMatchObject({ outcome: "delivered", mode: "inbox" }); + expect(() => readFileSync(claudeLog, "utf8")).toThrow(); + }); + + it("linked accounts plus a second live process in an unlinked account: refuses the inbox lane (no_record)", async () => { + row(); + const linked = path.join(tmp, "home-linked-2"); + mkdirSync(linked, { recursive: true }); + symlinkSync(path.join(configDir, "projects"), path.join(linked, "projects")); + symlinkSync(path.join(configDir, "sessions"), path.join(linked, "sessions")); + const other = path.join(tmp, "home-other"); + row({ pid: process.ppid }, other); + await startDaemon({ extra: { claudeDirs: () => [linked, configDir, other] } }); + await sawMode("bypassPermissions"); + const q = await rx.send({ session: SESSION, kind: "prompt", text: "two processes?" }); + expect(await rx.waitAck(q.id, 15_000)).toMatchObject({ outcome: "delivered", mode: "fork" }); + expect(written).toEqual([]); + expect(log.some((l) => l.includes("no_record"))).toBe(true); + }); + + it("unlinked live process in another account: refuses the inbox lane (other_home)", async () => { + const other = path.join(tmp, "home-other-live"); + row({}, other); + await startDaemon({ extra: { claudeDirs: () => [configDir, other] } }); + await sawMode("bypassPermissions"); + const q = await rx.send({ session: SESSION, kind: "prompt", text: "wrong account?" }); + expect(await rx.waitAck(q.id, 15_000)).toMatchObject({ outcome: "delivered", mode: "resume" }); + expect(written).toEqual([]); + expect(log.some((l) => l.includes("other_home"))).toBe(true); + }); + + it("cancel with linked accounts still sees the open interactive session and refuses to signal it", async () => { + row(); + const linked = path.join(tmp, "home-linked-cancel"); + mkdirSync(linked, { recursive: true }); + symlinkSync(path.join(configDir, "projects"), path.join(linked, "projects")); + symlinkSync(path.join(configDir, "sessions"), path.join(linked, "sessions")); + await startDaemon({ extra: { claudeDirs: () => [linked, configDir] } }); + const stop = await rx.send({ kind: "cancel", session: SESSION, text: undefined }); + expect(await rx.waitAck(stop.id, 15_000)).toMatchObject({ outcome: "unsupported" }); + }); + it("says nothing about the platform when nobody asked it to: this computer's own", async () => { row(); // Whatever this computer is, the row is one the mode can use there: a Mac vets the diff --git a/packages/core/src/adapters/claude-code-control.ts b/packages/core/src/adapters/claude-code-control.ts index a0f02cf9..ef17894d 100644 --- a/packages/core/src/adapters/claude-code-control.ts +++ b/packages/core/src/adapters/claude-code-control.ts @@ -7,7 +7,7 @@ // spacesheep CLI's machine listener (lib/machine.js, 1.22), which ran it in // production first. import { execFile, execFileSync } from "node:child_process"; -import { closeSync, openSync, readdirSync, readFileSync, readSync, statSync } from "node:fs"; +import { closeSync, lstatSync, openSync, readdirSync, readFileSync, readSync, realpathSync, statSync } from "node:fs"; import os from "node:os"; import path from "node:path"; import { PICTURE_TYPES, type Picture, type PictureLimits, picturesFor } from "../control/pictures.js"; @@ -637,14 +637,54 @@ export function resolveHome(session: string, dirs: readonly string[]): HomeChoic const all = findTranscripts(session, dirs); if (!all.length) return null; if (all.length === 1) return { transcript: all[0] as Transcript }; - const live = all.filter((t) => liveRecords(session, t.configDir).length > 0); - if (live.length === 1) return { transcript: live[0] as Transcript }; + const live = all.map((t) => ({ t, rows: liveRecords(session, t.configDir) })).filter((x) => x.rows.length > 0); + if (live.length === 1) return { transcript: (live[0] as { t: Transcript }).t }; + const linked = oneThroughLinks(live); + if (linked) return { transcript: linked }; return { ambiguous: [...new Set(all.map(homeName))].sort(), - live: [...new Set(live.map(homeName))].sort(), + live: [...new Set(live.map((x) => homeName(x.t)))].sort(), }; } +const realOf = (p: string): string => { + try { + return realpathSync(p); + } catch { + /* v8 ignore next -- the file was just read; gone since, keep its path */ + return p; + } +}; +const isLink = (p: string): boolean => { + try { + return lstatSync(path.resolve(p)).isSymbolicLink(); + } catch { + /* v8 ignore next -- the folder was just read through; gone since, treat as not owning */ + return true; + } +}; + +/** Accounts that share one `projects/` and one `sessions/` folder by symlink (several + * logins on one machine, one history) each find the same transcript and the same live + * row. That is one session held by one process, not a choice between accounts: a message + * goes into that process, whichever directory names it. Collapsed only when every live + * copy is one file on disk and every live row one registry file, so a real choice (two + * files, or two processes) still refuses, and with nothing live it still refuses, since a + * copy would need an account. The one kept is the account whose folders are its own. */ +function oneThroughLinks(live: readonly { t: Transcript; rows: LiveRecord[] }[]): Transcript | null { + if (live.length < 2) return null; + if (new Set(live.map((x) => realOf(x.t.file))).size !== 1) return null; + const rows = new Set(live.flatMap((x) => x.rows.map((r) => realOf(r.file)))); + if (rows.size !== 1) return null; + const own = live.find( + ({ t }) => + !isLink(t.configDir) && + !isLink(path.join(t.configDir, "projects")) && + !isLink(path.join(t.configDir, "sessions")), + ); + return (own ?? (live[0] as { t: Transcript })).t; +} + const projectName = (cwd: string) => cwd.replace(/[^a-zA-Z0-9]/g, "-"); /** The folder a session runs in, from its transcript's own records (never from a @@ -770,9 +810,14 @@ const registryRow = (file: string, configDir: string, j: Record }; /** Every live registry row for this session, across the config dirs given. A row whose - * pid is gone is not one: the file outlives the process. */ -export function liveRecords(session: string, dirs: string | readonly string[]): LiveRecord[] { + * pid is gone is not one: the file outlives the process. One registry file seen through + * several dirs (accounts that link `sessions/` to one folder) is one row, not one per + * account: kept as `prefer`'s copy when that dir is among them, so the row names the + * account the caller resolved the session to (the `other_home` check compares the two), + * else as the first dir's. */ +export function liveRecords(session: string, dirs: string | readonly string[], prefer?: string): LiveRecord[] { const out: LiveRecord[] = []; + const at = new Map(); for (const dir of typeof dirs === "string" ? [dirs] : dirs) { let names: string[] = []; try { @@ -790,7 +835,13 @@ export function liveRecords(session: string, dirs: string | readonly string[]): } if (String(j.sessionId) !== session) continue; const row = registryRow(file, dir, j); - if (pidAlive(row.pid)) out.push(row); + if (!pidAlive(row.pid)) continue; + const real = realOf(file); + const seen = at.get(real); + if (seen === undefined) { + at.set(real, out.length); + out.push(row); + } else if (prefer !== undefined && path.resolve(dir) === path.resolve(prefer)) out[seen] = row; } } return out; @@ -798,9 +849,10 @@ export function liveRecords(session: string, dirs: string | readonly string[]): /** The ONE live process that holds this session, or null. Two rows — two accounts, or * two processes in one — is a refusal rather than a guess: a lane that writes into a - * live session has to know which process it is writing to (spec/CONTROL.md §6.3). */ -export function liveRecord(session: string, dirs: string | readonly string[]): LiveRecord | null { - const all = liveRecords(session, dirs); + * live session has to know which process it is writing to (spec/CONTROL.md §6.3). + * `prefer` is the account the session was resolved to (`liveRecords`). */ +export function liveRecord(session: string, dirs: string | readonly string[], prefer?: string): LiveRecord | null { + const all = liveRecords(session, dirs, prefer); return all.length === 1 ? (all[0] as LiveRecord) : null; } diff --git a/packages/core/test/claude-live-record.test.ts b/packages/core/test/claude-live-record.test.ts index 70281bb3..3c42a967 100644 --- a/packages/core/test/claude-live-record.test.ts +++ b/packages/core/test/claude-live-record.test.ts @@ -2,12 +2,18 @@ // Which one process holds a Claude Code session, and which account it belongs to when // more than one has its transcript (spec/CONTROL.md §6, Homes; §6.3 `inbox`). Registry // rows are files in a temp dir; the live pid is this test process's own. -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; +import { fileURLToPath } from "node:url"; import { afterAll, describe, expect, it } from "vitest"; import { findTranscripts, liveRecord, liveRecords, resolveHome } from "../src/adapters/claude-code-control.js"; +const here = path.dirname(fileURLToPath(import.meta.url)); +const unix = process.platform !== "win32"; +/** Directory symlinks use NTFS junctions on Windows so tests need no elevation. */ +const dirLink: "junction" | "dir" = unix ? "dir" : "junction"; + const tmp = mkdtempSync(path.join(os.tmpdir(), "sp-live-record-")); afterAll(() => rmSync(tmp, { recursive: true, force: true })); @@ -151,4 +157,247 @@ describe("resolveHome", () => { }); expect([a, b].every((d) => path.isAbsolute(d))).toBe(true); }); + + /** A second login that links its `projects/` (and `sessions/`) to `owner`'s. */ + const linkedTo = (name: string, owner: string, folders = ["projects", "sessions"]) => { + const dir = path.join(tmp, name); + mkdirSync(dir, { recursive: true }); + for (const f of folders) symlinkSync(path.join(owner, f), path.join(dir, f), dirLink); + return dir; + }; + + it("accounts sharing their folders by symlink, one process live: that session, in the account owning the folders", () => { + const owner = home("link-own", { session: SESSION, rows: [{ pid: process.pid, sessionId: SESSION }] }); + const a = linkedTo("link-a", owner); + const b = linkedTo("link-b", owner); + expect(findTranscripts(SESSION, [a, owner, b])).toHaveLength(3); + expect(resolveHome(SESSION, [a, owner, b])).toEqual({ + transcript: { + file: path.join(owner, "projects", PROJECT, `${SESSION}.jsonl`), + configDir: owner, + project: PROJECT, + }, + }); + }); + + it("one registry file seen through linked accounts is one live row, named for the account preferred", () => { + const owner = home("row-own", { session: SESSION, rows: [{ pid: process.pid, sessionId: SESSION }] }); + const a = linkedTo("row-a", owner); + expect(liveRecords(SESSION, [a, owner]).map((r) => r.configDir)).toEqual([a]); + expect(liveRecords(SESSION, [a, owner], owner).map((r) => r.configDir)).toEqual([owner]); + expect(liveRecords(SESSION, [a, owner], `${owner}${path.sep}`).map((r) => r.configDir)).toEqual([owner]); + expect(liveRecord(SESSION, [a, owner], owner)?.configDir).toBe(owner); + // A second process in an account of its own is still a second row. + const other = home("row-other", { session: SESSION, rows: [{ pid: process.ppid, sessionId: SESSION }] }); + expect(liveRecord(SESSION, [a, owner, other], owner)).toBeNull(); + }); + + it("shared folders and nothing live: still ambiguous, since a copy would need an account", () => { + const owner = home("cold-own", { session: SESSION }); + mkdirSync(path.join(owner, "sessions"), { recursive: true }); + const a = linkedTo("cold-a", owner); + expect(resolveHome(SESSION, [owner, a])).toEqual({ ambiguous: ["cold-a", "cold-own"], live: [] }); + }); + + it("one transcript by symlink but two processes, each in its own registry: still ambiguous", () => { + const owner = home("pair-own", { session: SESSION, rows: [{ pid: process.pid, sessionId: SESSION }] }); + const other = linkedTo("pair-b", owner, ["projects"]); + mkdirSync(path.join(other, "sessions"), { recursive: true }); + writeFileSync( + path.join(other, "sessions", `${process.ppid}.json`), + JSON.stringify({ pid: process.ppid, sessionId: SESSION }), + ); + expect(resolveHome(SESSION, [owner, other])).toEqual({ + ambiguous: ["pair-b", "pair-own"], + live: ["pair-b", "pair-own"], + }); + }); + + it("two distinct real transcripts with a shared sessions/ symlink: still ambiguous", () => { + const owner = home("split-t-own", { session: SESSION, rows: [{ pid: process.pid, sessionId: SESSION }] }); + const other = home("split-t-other", { session: SESSION }); + symlinkSync(path.join(owner, "sessions"), path.join(other, "sessions"), dirLink); + expect(resolveHome(SESSION, [owner, other])).toEqual({ + ambiguous: ["split-t-other", "split-t-own"], + live: ["split-t-other", "split-t-own"], + }); + }); + + it("shared projects/ and sessions/ with two live processes: still ambiguous", () => { + const owner = home("two-live-own", { + session: SESSION, + rows: [ + { pid: process.pid, sessionId: SESSION }, + { pid: process.ppid, sessionId: SESSION }, + ], + }); + const a = linkedTo("two-live-a", owner); + expect(resolveHome(SESSION, [owner, a])).toEqual({ + ambiguous: ["two-live-a", "two-live-own"], + live: ["two-live-a", "two-live-own"], + }); + }); + + it("all accounts linked to a shared store outside dirs: picks the first account in dirs", () => { + const shared = home("ext-shared", { session: SESSION, rows: [{ pid: process.pid, sessionId: SESSION }] }); + const first = linkedTo("ext-first", shared); + const second = linkedTo("ext-second", shared); + expect(resolveHome(SESSION, [first, second])).toEqual({ + transcript: { + file: path.join(first, "projects", PROJECT, `${SESSION}.jsonl`), + configDir: first, + project: PROJECT, + }, + }); + }); + + it("whole config dir symlinked to owner: prefers the real config dir", () => { + const owner = home("dirlink-own", { session: SESSION, rows: [{ pid: process.pid, sessionId: SESSION }] }); + const alias = path.join(tmp, "dirlink-alias"); + symlinkSync(owner, alias, dirLink); + expect(resolveHome(SESSION, [alias, owner])).toEqual({ + transcript: { + file: path.join(owner, "projects", PROJECT, `${SESSION}.jsonl`), + configDir: owner, + project: PROJECT, + }, + }); + }); + + it("split ownership (one owns projects/, the other owns sessions/): falls back to first account in dirs", () => { + const a = home("split-a", { session: SESSION }); + const b = home("split-b", { rows: [{ pid: process.pid, sessionId: SESSION }] }); + symlinkSync(path.join(b, "sessions"), path.join(a, "sessions"), dirLink); + symlinkSync(path.join(a, "projects"), path.join(b, "projects"), dirLink); + expect(resolveHome(SESSION, [a, b])).toEqual({ + transcript: { + file: path.join(a, "projects", PROJECT, `${SESSION}.jsonl`), + configDir: a, + project: PROJECT, + }, + }); + }); + + it("broken/dangling projects/ or sessions/ symlinks are ignored without throwing", () => { + const owner = home("dangling-own", { session: SESSION, rows: [{ pid: process.pid, sessionId: SESSION }] }); + const brokenProj = path.join(tmp, "dangling-proj"); + mkdirSync(brokenProj, { recursive: true }); + symlinkSync(path.join(tmp, "no-such-projects"), path.join(brokenProj, "projects"), dirLink); + symlinkSync(path.join(tmp, "no-such-sessions"), path.join(brokenProj, "sessions"), dirLink); + const brokenSess = linkedTo("dangling-sess", owner, ["projects"]); + symlinkSync(path.join(tmp, "no-such-sessions-2"), path.join(brokenSess, "sessions"), dirLink); + expect(liveRecords(SESSION, [brokenProj, brokenSess])).toEqual([]); + expect(resolveHome(SESSION, [brokenProj, brokenSess, owner])).toEqual({ + transcript: { + file: path.join(owner, "projects", PROJECT, `${SESSION}.jsonl`), + configDir: owner, + project: PROJECT, + }, + }); + }); + + it.runIf(unix)( + "symlink cycles (ELOOP) and dangling file symlinks in projects/ or sessions/ are ignored cleanly", + () => { + const owner = home("loop-own", { session: SESSION, rows: [{ pid: process.pid, sessionId: SESSION }] }); + const loopDir = path.join(tmp, "loop-dir"); + mkdirSync(loopDir, { recursive: true }); + // Self-referential folder symlinks → ELOOP on readdirSync / realpathSync. + symlinkSync(path.join(loopDir, "projects"), path.join(loopDir, "projects")); + symlinkSync(path.join(loopDir, "sessions"), path.join(loopDir, "sessions")); + // Account with dangling and cyclic file symlinks inside real folders. + const badFiles = path.join(tmp, "bad-files"); + mkdirSync(path.join(badFiles, "projects", PROJECT), { recursive: true }); + mkdirSync(path.join(badFiles, "sessions"), { recursive: true }); + symlinkSync(path.join(tmp, "gone.jsonl"), path.join(badFiles, "projects", PROJECT, `${SESSION}.jsonl`)); + symlinkSync(path.join(tmp, "gone.json"), path.join(badFiles, "sessions", `${process.pid}.json`)); + symlinkSync( + path.join(badFiles, "sessions", `${process.ppid}.json`), + path.join(badFiles, "sessions", `${process.ppid}.json`), + ); + expect(liveRecords(SESSION, [loopDir, badFiles])).toEqual([]); + expect(resolveHome(SESSION, [loopDir, badFiles, owner])).toEqual({ + transcript: { + file: path.join(owner, "projects", PROJECT, `${SESSION}.jsonl`), + configDir: owner, + project: PROJECT, + }, + }); + }, + ); +}); + +describe("homes (conformance/control-homes.json)", () => { + type SpecDir = { + name: string; + transcript?: boolean; + live?: ("self" | "parent")[]; + link_projects?: string; + link_sessions?: string; + }; + type HomesVector = { + cases: { + name: string; + stores?: SpecDir[]; + accounts: SpecDir[]; + expect: { home: string } | { ambiguous: string[]; live: string[] } | null; + }[]; + }; + const vectors = JSON.parse( + readFileSync(path.resolve(here, "../../../conformance/control-homes.json"), "utf8"), + ) as HomesVector; + const pidOf = (k: "self" | "parent") => (k === "self" ? process.pid : process.ppid); + + for (const [i, c] of vectors.cases.entries()) { + it(c.name, () => { + const root = path.join(tmp, `vec-${i}`); + mkdirSync(root, { recursive: true }); + const all = [...(c.stores ?? []), ...c.accounts]; + const byName = new Map(); + for (const a of all) { + const dir = path.join(root, a.name); + mkdirSync(dir, { recursive: true }); + byName.set(a.name, dir); + if (a.transcript) { + mkdirSync(path.join(dir, "projects", PROJECT), { recursive: true }); + writeFileSync(path.join(dir, "projects", PROJECT, `${SESSION}.jsonl`), ""); + } + if (a.live !== undefined) { + mkdirSync(path.join(dir, "sessions"), { recursive: true }); + for (const k of a.live) { + const pid = pidOf(k); + writeFileSync(path.join(dir, "sessions", `${pid}.json`), JSON.stringify({ pid, sessionId: SESSION })); + } + } + } + for (const a of all) { + const dir = byName.get(a.name) as string; + if (a.link_projects) + symlinkSync( + path.join(byName.get(a.link_projects) as string, "projects"), + path.join(dir, "projects"), + dirLink, + ); + if (a.link_sessions) + symlinkSync( + path.join(byName.get(a.link_sessions) as string, "sessions"), + path.join(dir, "sessions"), + dirLink, + ); + } + const dirs = c.accounts.map((a) => byName.get(a.name) as string); + const got = resolveHome(SESSION, dirs); + if (c.expect === null) expect(got).toBeNull(); + else if ("home" in c.expect) { + const expectedDir = byName.get(c.expect.home) as string; + expect(got).toEqual({ + transcript: { + file: path.join(expectedDir, "projects", PROJECT, `${SESSION}.jsonl`), + configDir: expectedDir, + project: PROJECT, + }, + }); + } else expect(got).toEqual(c.expect); + }); + } }); diff --git a/spec/CONTROL.md b/spec/CONTROL.md index 53b6ee73..e124789c 100644 --- a/spec/CONTROL.md +++ b/spec/CONTROL.md @@ -581,6 +581,17 @@ Nothing live, or more than one live, is acked `refused` with code `ambiguous_hom where more than one is live, which ones — all by their directory name and never by path. A guess there put a message into an account that was signed out. +Accounts can share one tree by symlink (several logins on one machine that link their +`projects/` and live-session registry to one config dir's). Each then finds the same +transcript and the same live record, which is one session in one process, not a choice: +where every live copy resolves to one file on disk and every live record to one registry +file, the machine takes that session, filed under the account whose own folders hold it +(not links). Two files, two processes, or nothing live is still `ambiguous_home`. Where +every account is a link (to a folder none of them owns), it is the first account in the +machine's list of config dirs, and that account's own `settings.json`, which links do not +share, is the one that sets the machine's class (§6.3). A lane that looks the live record +up across accounts counts that shared registry file once, under the account chosen here. + ### 6.2 The session's mode Some decisions below need the permission mode a live session is actually running in. A