From c91576bcffeaf781db5a11386b2a5d94d5b5cef1 Mon Sep 17 00:00:00 2001 From: Ilya Fomin <2030645+fominfo@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:35:20 -0800 Subject: [PATCH 1/4] Take one session when Claude accounts share their folders by symlink Accounts that link projects/ and sessions/ to one config dir each find the same transcript and the same live record, so resolveHome counted every one of them live and refused ambiguous_home. Where every live copy is one file on disk and every live record one registry file, take that session, filed under the account whose own folders hold it. Two files, two processes, or nothing live still refuses (spec/CONTROL.md section 6.1). Fixes #350 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Ilya Fomin <2030645+fominfo@users.noreply.github.com> --- .changeset/linked-homes-one-session.md | 5 +++ .../core/src/adapters/claude-code-control.ts | 35 ++++++++++++++- packages/core/test/claude-live-record.test.ts | 45 ++++++++++++++++++- spec/CONTROL.md | 7 +++ 4 files changed, 90 insertions(+), 2 deletions(-) create mode 100644 .changeset/linked-homes-one-session.md diff --git a/.changeset/linked-homes-one-session.md b/.changeset/linked-homes-one-session.md new file mode 100644 index 00000000..57570412 --- /dev/null +++ b/.changeset/linked-homes-one-session.md @@ -0,0 +1,5 @@ +--- +"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/packages/core/src/adapters/claude-code-control.ts b/packages/core/src/adapters/claude-code-control.ts index a0f02cf9..d7e31229 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,45 @@ 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 { + return p; + } +}; +const linkedFolder = (dir: string, name: string): boolean => { + try { + return lstatSync(path.join(dir, name)).isSymbolicLink(); + } catch { + 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 diff --git a/packages/core/test/claude-live-record.test.ts b/packages/core/test/claude-live-record.test.ts index 70281bb3..e8bc352e 100644 --- a/packages/core/test/claude-live-record.test.ts +++ b/packages/core/test/claude-live-record.test.ts @@ -2,7 +2,7 @@ // 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, rmSync, symlinkSync, writeFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; import { afterAll, describe, expect, it } from "vitest"; @@ -151,4 +151,47 @@ 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("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"], + }); + }); }); diff --git a/spec/CONTROL.md b/spec/CONTROL.md index 53b6ee73..f72b41fc 100644 --- a/spec/CONTROL.md +++ b/spec/CONTROL.md @@ -581,6 +581,13 @@ 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`. + ### 6.2 The session's mode Some decisions below need the permission mode a live session is actually running in. A From 6151e8d418bbfe7ff683658db34178d4dac8a807 Mon Sep 17 00:00:00 2001 From: Ilya Fomin <2030645+fominfo@users.noreply.github.com> Date: Sun, 29 Nov 2026 20:53:55 -0800 Subject: [PATCH 2/4] Count a registry row seen through linked accounts once, in the inbox lane too The inbox lane looks the live record up across every account, and with sessions/ linked each account read the same registry file, so liveRecord found one row per account and returned null: no_record, and the message went to a fork instead of the live window. liveRecords now keeps one row per real registry file, named for the account the session was resolved to, so a second process in another account still refuses and other_home still compares the right accounts. A daemon test writes through linked homes into the inbox; spec section 6.1 covers the all-links case. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Ilya Fomin <2030645+fominfo@users.noreply.github.com> --- packages/cli/src/control/daemon.ts | 4 +++- packages/cli/test/control-inbox.test.ts | 22 +++++++++++++++++ .../core/src/adapters/claude-code-control.ts | 24 ++++++++++++++----- packages/core/test/claude-live-record.test.ts | 11 +++++++++ spec/CONTROL.md | 6 ++++- 5 files changed, 59 insertions(+), 8 deletions(-) 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..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 d7e31229..ee07fc92 100644 --- a/packages/core/src/adapters/claude-code-control.ts +++ b/packages/core/src/adapters/claude-code-control.ts @@ -803,9 +803,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 { @@ -823,7 +828,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 && dir === prefer) out[seen] = row; } } return out; @@ -831,9 +842,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 e8bc352e..6927d674 100644 --- a/packages/core/test/claude-live-record.test.ts +++ b/packages/core/test/claude-live-record.test.ts @@ -174,6 +174,17 @@ describe("resolveHome", () => { }); }); + 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 }); diff --git a/spec/CONTROL.md b/spec/CONTROL.md index f72b41fc..e124789c 100644 --- a/spec/CONTROL.md +++ b/spec/CONTROL.md @@ -586,7 +586,11 @@ Accounts can share one tree by symlink (several logins on one machine that link 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`. +(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 From 671226fe233fbb4b8753f5d98da0dd4884258204 Mon Sep 17 00:00:00 2001 From: kombuchapunk <35040017+kombuchapunk@users.noreply.github.com> Date: Tue, 1 Dec 2026 11:49:25 -0800 Subject: [PATCH 3/4] conformance, test: add control-homes.json fixture and cover all-links branch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add conformance/control-homes.json covering CONTROL.md §6.1 Homes (single, missing, one-live, ambiguous, linked-to-owner, all-links fallback, cold linked, and linked projects with two live registries), driven by packages/core/test/claude-live-record.test.ts. - Cover the all-links fallback branch in oneThroughLinks and mark the two TOCTOU catch fallbacks in realOf/linkedFolder with v8 ignore so 100% coverage holds. - Compare prefer with path.resolve in liveRecords to match vetInbox, and list sessionpipe alongside sessionpipe-core in the changeset. Signed-off-by: kombuchapunk <35040017+kombuchapunk@users.noreply.github.com> --- .changeset/linked-homes-one-session.md | 1 + conformance/control-homes.json | 75 ++++++++++++++++ .../core/src/adapters/claude-code-control.ts | 4 +- packages/core/test/claude-live-record.test.ts | 85 ++++++++++++++++++- 4 files changed, 163 insertions(+), 2 deletions(-) create mode 100644 conformance/control-homes.json diff --git a/.changeset/linked-homes-one-session.md b/.changeset/linked-homes-one-session.md index 57570412..e5e9e3fd 100644 --- a/.changeset/linked-homes-one-session.md +++ b/.changeset/linked-homes-one-session.md @@ -1,4 +1,5 @@ --- +"sessionpipe": patch "sessionpipe-core": patch --- 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/core/src/adapters/claude-code-control.ts b/packages/core/src/adapters/claude-code-control.ts index ee07fc92..6517ddd4 100644 --- a/packages/core/src/adapters/claude-code-control.ts +++ b/packages/core/src/adapters/claude-code-control.ts @@ -651,6 +651,7 @@ 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; } }; @@ -658,6 +659,7 @@ 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; } }; @@ -834,7 +836,7 @@ export function liveRecords(session: string, dirs: string | readonly string[], p if (seen === undefined) { at.set(real, out.length); out.push(row); - } else if (prefer !== undefined && dir === prefer) out[seen] = row; + } else if (prefer !== undefined && path.resolve(dir) === path.resolve(prefer)) out[seen] = row; } } return out; diff --git a/packages/core/test/claude-live-record.test.ts b/packages/core/test/claude-live-record.test.ts index 6927d674..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, symlinkSync, 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 })); @@ -205,4 +208,84 @@ describe("resolveHome", () => { 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); + }); + } }); From 87c37bc135266e7a8c208dfc5d2a47685785dd26 Mon Sep 17 00:00:00 2001 From: kombuchapunk <35040017+kombuchapunk@users.noreply.github.com> Date: Thu, 3 Dec 2026 15:51:19 -0800 Subject: [PATCH 4/4] fix(control): harden linked-home resolution, Windows symlink tests, and edge-case coverage - Capture liveRecords once in resolveHome and pass the snapshot into oneThroughLinks to avoid double disk scans and eliminate the TOCTOU race where a second account's registry row vanishes between the two reads. - Check lstatSync(path.resolve(p)) on configDir itself (not only projects/ and sessions/) so a whole-config-dir symlink prefers the real owner, and treat lstatSync errors as non-owning rather than owning. - Use NTFS junctions on win32 in packages/core/test/claude-live-record.test.ts so linked-home and conformance tests run cross-platform without elevation; guard Unix-only file-symlink and ELOOP cycle tests with it.runIf(unix). - Expand conformance/control-homes.json (and document it in conformance/README.md) plus unit/daemon tests covering dangling symlinks, ELOOP cycles, split-ownership and whole-dir links, two real transcripts with linked sessions/, two live processes in shared sessions/, all-links daemon inbox delivery, no_record / other_home refusals, and cancel() with linked homes. Signed-off-by: kombuchapunk <35040017+kombuchapunk@users.noreply.github.com> --- conformance/README.md | 5 + conformance/control-homes.json | 25 ++++ packages/cli/test/control-inbox.test.ts | 59 +++++++++ .../core/src/adapters/claude-code-control.ts | 31 +++-- packages/core/test/claude-live-record.test.ts | 118 +++++++++++++++++- 5 files changed, 222 insertions(+), 16 deletions(-) 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 index db7ed7d1..d4586e1f 100644 --- a/conformance/control-homes.json +++ b/conformance/control-homes.json @@ -70,6 +70,31 @@ { "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/test/control-inbox.test.ts b/packages/cli/test/control-inbox.test.ts index 4ef8b109..7fe9f97b 100644 --- a/packages/cli/test/control-inbox.test.ts +++ b/packages/cli/test/control-inbox.test.ts @@ -314,6 +314,65 @@ describe.runIf(unix)("a message into a live session's own 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 6517ddd4..ef17894d 100644 --- a/packages/core/src/adapters/claude-code-control.ts +++ b/packages/core/src/adapters/claude-code-control.ts @@ -637,13 +637,13 @@ 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 linked = oneThroughLinks(session, live); + 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(), }; } @@ -655,12 +655,12 @@ const realOf = (p: string): string => { return p; } }; -const linkedFolder = (dir: string, name: string): boolean => { +const isLink = (p: string): boolean => { try { - return lstatSync(path.join(dir, name)).isSymbolicLink(); + return lstatSync(path.resolve(p)).isSymbolicLink(); } catch { - /* v8 ignore next -- the folder was just read through; gone since, treat as unlinked */ - return false; + /* v8 ignore next -- the folder was just read through; gone since, treat as not owning */ + return true; } }; @@ -671,13 +671,18 @@ const linkedFolder = (dir: string, name: string): boolean => { * 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 { +function oneThroughLinks(live: readonly { t: Transcript; rows: LiveRecord[] }[]): 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 (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) => !linkedFolder(t.configDir, "projects") && !linkedFolder(t.configDir, "sessions")); - return own ?? (live[0] as Transcript); + 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, "-"); diff --git a/packages/core/test/claude-live-record.test.ts b/packages/core/test/claude-live-record.test.ts index a84a42e1..3c42a967 100644 --- a/packages/core/test/claude-live-record.test.ts +++ b/packages/core/test/claude-live-record.test.ts @@ -10,6 +10,9 @@ 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 })); @@ -159,7 +162,7 @@ describe("resolveHome", () => { 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)); + for (const f of folders) symlinkSync(path.join(owner, f), path.join(dir, f), dirLink); return dir; }; @@ -182,6 +185,7 @@ describe("resolveHome", () => { 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 }] }); @@ -209,6 +213,31 @@ describe("resolveHome", () => { }); }); + 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); @@ -221,6 +250,81 @@ describe("resolveHome", () => { }, }); }); + + 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)", () => { @@ -269,9 +373,17 @@ describe("homes (conformance/control-homes.json)", () => { 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")); + 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")); + 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);