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/control-homes.json b/conformance/control-homes.json new file mode 100644 index 00000000..db7ed7d1 --- /dev/null +++ b/conformance/control-homes.json @@ -0,0 +1,75 @@ +{ + "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"] } + } + ] +} diff --git a/packages/cli/src/control/daemon.ts b/packages/cli/src/control/daemon.ts index 046090ba..2e7adcaa 100644 --- a/packages/cli/src/control/daemon.ts +++ b/packages/cli/src/control/daemon.ts @@ -2845,7 +2845,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..4ef8b109 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,27 @@ 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("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..6517ddd4 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"; @@ -639,12 +639,47 @@ export function resolveHome(session: string, dirs: readonly string[]): HomeChoic 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 linked = oneThroughLinks(session, live); + if (linked) return { transcript: linked }; return { ambiguous: [...new Set(all.map(homeName))].sort(), live: [...new Set(live.map(homeName))].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 linkedFolder = (dir: string, name: string): boolean => { + try { + return lstatSync(path.join(dir, name)).isSymbolicLink(); + } catch { + /* v8 ignore next -- the folder was just read through; gone since, treat as unlinked */ + return false; + } +}; + +/** 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(session: string, live: readonly Transcript[]): Transcript | null { + if (live.length < 2) return null; + if (new Set(live.map((t) => realOf(t.file))).size !== 1) return null; + const rows = new Set(live.flatMap((t) => liveRecords(session, t.configDir).map((r) => realOf(r.file)))); + if (rows.size !== 1) return null; + const own = live.find((t) => !linkedFolder(t.configDir, "projects") && !linkedFolder(t.configDir, "sessions")); + return own ?? (live[0] as Transcript); +} + 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 +805,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 +830,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 +844,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..a84a42e1 100644 --- a/packages/core/test/claude-live-record.test.ts +++ b/packages/core/test/claude-live-record.test.ts @@ -2,12 +2,15 @@ // 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 tmp = mkdtempSync(path.join(os.tmpdir(), "sp-live-record-")); afterAll(() => rmSync(tmp, { recursive: true, force: true })); @@ -151,4 +154,138 @@ 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)); + 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(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("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, + }, + }); + }); +}); + +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")); + if (a.link_sessions) + symlinkSync(path.join(byName.get(a.link_sessions) as string, "sessions"), path.join(dir, "sessions")); + } + 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 c28dc792..75be5081 100644 --- a/spec/CONTROL.md +++ b/spec/CONTROL.md @@ -563,6 +563,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