From fa6c4aafffb26cb8593ec57b1fa92dbd84f1c879 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 21 Nov 2026 19:41:49 +0100 Subject: [PATCH 01/22] fix(remote): give each session its own saved-connection file A saved connection was stored under a file whose name sanitized the session, replacing every character a filename cannot hold. Two names that differ only in case produce the same name, so on a case-insensitive filesystem both sessions opened one file and one session read and overwrote another session's record. A session name that is a filename on its own keeps it. Any other name is stored under its SHA-256. A record at the old path is used only when its contents name that session, and a record that names another session is refused with the typed reason connection_session_mismatch instead of being read, overwritten, or removed. The active-session pointer is never a session record. --- ...-connection-state-session-identity.test.ts | 178 ++++++++++++++++++ .../remote/src/remote-connection-state.ts | 86 +++++++-- 2 files changed, 245 insertions(+), 19 deletions(-) create mode 100644 packages/remote/src/remote-connection-state-session-identity.test.ts diff --git a/packages/remote/src/remote-connection-state-session-identity.test.ts b/packages/remote/src/remote-connection-state-session-identity.test.ts new file mode 100644 index 0000000000..2f26d3c7b2 --- /dev/null +++ b/packages/remote/src/remote-connection-state-session-identity.test.ts @@ -0,0 +1,178 @@ +import { test } from 'vitest'; +import assert from 'node:assert/strict'; +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import path from 'node:path'; +import { AppError } from '@agent-device/kernel/errors'; +import { mkdtempForTestSync } from '@agent-device/test-kit'; +import { + readRemoteConnectionState, + removeRemoteConnectionState, + writeRemoteConnectionState, + type RemoteConnectionState, +} from './remote-connection-state.ts'; + +// A saved connection is stored in a file named after its session. Sanitizing a name that cannot be a +// filename, instead of hashing it, let two names that differ only in case open the same file on a +// case-insensitive filesystem, so one session read and then overwrote another session's record. + +const RECORDS_DIR = 'remote-connections'; +const ACTIVE_SESSION_FILE = '.active-session.json'; + +function recordFor(session: string): RemoteConnectionState { + const now = new Date().toISOString(); + return { + version: 1, + session, + remoteConfigPath: '/profiles/remote.json', + remoteConfigHash: 'hash', + tenant: 'acme', + runId: `run-${session}`, + connectedAt: now, + updatedAt: now, + }; +} + +/** Writes a record straight to `fileName`, as a previous build or another session would have left it. */ +function writeRecordFile(stateDir: string, fileName: string, session: string): string { + const recordsDir = path.join(stateDir, RECORDS_DIR); + fs.mkdirSync(recordsDir, { recursive: true }); + const statePath = path.join(recordsDir, fileName); + fs.writeFileSync(statePath, `${JSON.stringify(recordFor(session), null, 2)}\n`, 'utf8'); + return statePath; +} + +function sha256(value: string): string { + return crypto.createHash('sha256').update(value).digest('hex'); +} + +/** Where a session whose name cannot be a filename is stored: under its own hash. */ +function hashedFileName(session: string): string { + return `~${sha256(session)}.json`; +} + +/** The file name a build that sanitized names wrote for `session`. */ +function sanitizedFileName(session: string): string { + const safe = session.replaceAll(/[^a-zA-Z0-9._-]/g, '_'); + return safe === session ? `${safe}.json` : `${safe}-${sha256(session).slice(0, 8)}.json`; +} + +function captureRefusal(run: () => unknown): AppError { + try { + run(); + } catch (error) { + assert.ok(error instanceof AppError, `expected an AppError, got ${String(error)}`); + return error; + } + return assert.fail('expected a refusal'); +} + +test('sessions named Demo and demo keep separate records', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-case-'); + writeRemoteConnectionState({ stateDir, state: recordFor('Demo') }); + writeRemoteConnectionState({ stateDir, state: recordFor('demo') }); + + assert.equal( + readRemoteConnectionState({ stateDir, session: 'Demo' })?.runId, + 'run-Demo', + 'reading one session must not return the record the case-variant session wrote', + ); + assert.equal(readRemoteConnectionState({ stateDir, session: 'demo' })?.runId, 'run-demo'); + assert.deepEqual( + fs.readdirSync(path.join(stateDir, RECORDS_DIR)).sort(), + [ACTIVE_SESSION_FILE, 'demo.json', hashedFileName('Demo')].sort(), + 'a name that cannot be a filename gets its own hashed file, never one two names share', + ); +}); + +test('disconnecting one of two case-variant sessions leaves the other record', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-remove-'); + writeRemoteConnectionState({ stateDir, state: recordFor('Demo') }); + writeRemoteConnectionState({ stateDir, state: recordFor('demo') }); + + removeRemoteConnectionState({ stateDir, session: 'Demo' }); + + assert.equal(readRemoteConnectionState({ stateDir, session: 'Demo' }), null); + assert.equal( + readRemoteConnectionState({ stateDir, session: 'demo' })?.runId, + 'run-demo', + 'removing a session must not reach through to the file another session owns', + ); +}); + +test('a session name that cannot be a filename is stored under its hash', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-hashed-'); + const session = 'team/dev#1'; + + writeRemoteConnectionState({ stateDir, state: recordFor(session) }); + + assert.deepEqual( + fs.readdirSync(path.join(stateDir, RECORDS_DIR)).sort(), + [hashedFileName(session), ACTIVE_SESSION_FILE].sort(), + ); + assert.equal(readRemoteConnectionState({ stateDir, session })?.runId, `run-${session}`); +}); + +test('a record at the sanitized path is used only when its contents name this session', () => { + const reusedDir = mkdtempForTestSync('agent-device-remote-identity-legacy-match-'); + const session = 'team/dev#1'; + writeRecordFile(reusedDir, sanitizedFileName(session), session); + + assert.equal( + readRemoteConnectionState({ stateDir: reusedDir, session })?.runId, + `run-${session}`, + 'a record written before hashed paths still serves the session it names', + ); + + // One file whose contents name another session: that is what a session finds when an older build + // wrote two sessions to the same name, so the file name proves nothing and only contents decide. + const aliasedDir = mkdtempForTestSync('agent-device-remote-identity-legacy-alias-'); + writeRecordFile(aliasedDir, sanitizedFileName(session), 'team:dev#1'); + + assert.equal( + readRemoteConnectionState({ stateDir: aliasedDir, session }), + null, + 'a record naming another session is not this session record, so nothing is read from it', + ); + assert.equal( + fs.existsSync(path.join(aliasedDir, RECORDS_DIR, hashedFileName(session))), + false, + 'and reading it does not give this session a record of its own', + ); +}); + +test('a record left on the active-session pointer path is not read as a session record', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-pointer-'); + // A build that sanitized names wrote the session `.active-session` to exactly the path its + // active-session pointer uses, so that file holds a full connection record for it. + const session = '.active-session'; + writeRecordFile(stateDir, ACTIVE_SESSION_FILE, session); + + assert.equal( + readRemoteConnectionState({ stateDir, session }), + null, + 'the pointer path is never a session record, so the session reads as unconnected', + ); +}); + +test('a saved connection naming another session is refused rather than reused', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-mismatch-'); + const statePath = writeRecordFile(stateDir, 'demo.json', 'Demo'); + + const read = captureRefusal(() => readRemoteConnectionState({ stateDir, session: 'demo' })); + assert.equal(read.code, 'COMMAND_FAILED'); + assert.equal(read.details?.reason, 'connection_session_mismatch'); + + const write = captureRefusal(() => + writeRemoteConnectionState({ stateDir, state: recordFor('demo') }), + ); + assert.equal(write.details?.reason, 'connection_session_mismatch'); + + const remove = captureRefusal(() => removeRemoteConnectionState({ stateDir, session: 'demo' })); + assert.equal(remove.details?.reason, 'connection_session_mismatch'); + assert.equal( + fs.existsSync(statePath), + true, + 'a refused disconnect must not delete the record it would have overwritten', + ); +}); diff --git a/packages/remote/src/remote-connection-state.ts b/packages/remote/src/remote-connection-state.ts index 59426dfda5..b2ffe11299 100644 --- a/packages/remote/src/remote-connection-state.ts +++ b/packages/remote/src/remote-connection-state.ts @@ -222,6 +222,12 @@ type RemoteConnectionDefaults = { connection?: RemoteConnectionRequestMetadata; }; +const REMOTE_CONNECTION_STATE_REASONS = { + // A command named one session and the saved connection it reached names another, so nothing about + // that connection was read, replaced, or removed. + sessionMismatch: { reason: 'connection_session_mismatch' }, +} as const satisfies ReasonTable<'remote connections'>; + export function readRemoteConnectionState(options: { stateDir: string; session: string; @@ -239,6 +245,11 @@ export function readRemoteConnectionState(options: { removeInvalidRemoteConnectionState(options); return null; } + if (parsed.session !== options.session) { + throw new AppError('COMMAND_FAILED', 'The saved connection belongs to a different session.', { + reason: REMOTE_CONNECTION_STATE_REASONS.sessionMismatch.reason, + }); + } return parsed; } @@ -252,10 +263,9 @@ export function writeRemoteConnectionState(options: { */ onSessionRecordCommitted?: () => void; }): void { - const statePath = remoteConnectionStatePath({ - stateDir: options.stateDir, - session: options.state.session, - }); + const location = { stateDir: options.stateDir, session: options.state.session }; + readRemoteConnectionState(location); + const statePath = remoteConnectionStatePath(location); fs.mkdirSync(path.dirname(statePath), { recursive: true }); writeJsonFile(statePath, options.state); options.onSessionRecordCommitted?.(); @@ -276,6 +286,11 @@ export function buildRemoteConnectionDaemonState( } export function removeRemoteConnectionState(options: { stateDir: string; session: string }): void { + readRemoteConnectionState(options); + removeRemoteConnectionStateFile(options); +} + +function removeRemoteConnectionStateFile(options: { stateDir: string; session: string }): void { fs.rmSync(remoteConnectionStatePath(options), { force: true }); const activePath = activeConnectionStatePath(options.stateDir); const activeSession = readActiveConnectionSession(options.stateDir); @@ -514,16 +529,57 @@ export function hashRemoteConfigFile(configPath: string): string { } } +/** The pointer to the machine-wide active session. It is not a session record and never names one. */ +const ACTIVE_SESSION_FILE_NAME = '.active-session.json'; + function remoteConnectionStatePath(options: { stateDir: string; session: string }): string { - return path.join( - options.stateDir, - 'remote-connections', - `${safeStateName(options.session)}.json`, - ); + const dir = path.join(options.stateDir, 'remote-connections'); + // A name that cannot be a filename on its own — anything starting with `.`, or holding a + // separator — is stored by hash, so it can never take the active-session pointer's file either. + if (/^[a-z0-9_-][a-z0-9._-]*$/.test(options.session)) { + return path.join(dir, `${options.session}.json`); + } + + const canonical = path.join(dir, `~${connectionSessionIdentity(options.session)}.json`); + if (fs.existsSync(canonical)) return canonical; + + // Older records were named by sanitizing the session, so two names that differ only in case could + // share one file on a case-insensitive filesystem. Trust such a file only when its contents prove + // they name this session; otherwise this session's record belongs to the hashed path. + const legacy = legacyRemoteConnectionStatePath({ recordsDir: dir, session: options.session }); + if (!legacy) return canonical; + try { + const state: unknown = JSON.parse(fs.readFileSync(legacy, 'utf8')); + return isRemoteConnectionState(state) && state.session === options.session ? legacy : canonical; + } catch { + return canonical; + } +} + +/** + * The SHA-256 of a session name, hex. It is the file identity for a session whose name cannot be a + * filename on its own, so two names that differ only in case never share one record. + */ +export function connectionSessionIdentity(session: string): string { + return crypto.createHash('sha256').update(session).digest('hex'); +} + +/** Where a record written before per-session paths lived, or `undefined` when it aliased the pointer. */ +function legacyRemoteConnectionStatePath(options: { + recordsDir: string; + session: string; +}): string | undefined { + const safe = options.session.replaceAll(/[^a-zA-Z0-9._-]/g, '_'); + const name = + safe === options.session + ? safe + : `${safe}-${connectionSessionIdentity(options.session).slice(0, 8)}`; + if (!name || `${name}.json` === ACTIVE_SESSION_FILE_NAME) return undefined; + return path.join(options.recordsDir, `${name}.json`); } function activeConnectionStatePath(stateDir: string): string { - return path.join(stateDir, 'remote-connections', '.active-session.json'); + return path.join(stateDir, 'remote-connections', ACTIVE_SESSION_FILE_NAME); } export function readActiveConnectionState(options: { @@ -610,15 +666,7 @@ function removeInvalidRemoteConnectionState( cause: error instanceof Error ? error.message : error ? String(error) : undefined, }, }); - removeRemoteConnectionState(options); -} - -function safeStateName(value: string): string { - const safe = value.replaceAll(/[^a-zA-Z0-9._-]/g, '_'); - if (!safe) return 'default'; - if (safe === value) return safe; - const suffix = crypto.createHash('sha256').update(value).digest('hex').slice(0, 8); - return `${safe}-${suffix}`; + removeRemoteConnectionStateFile(options); } function isRemoteConnectionState(value: unknown): value is RemoteConnectionState { From 050cf0d47f597c8b4b612a1794e8599a3fc6573d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 21 Nov 2026 19:41:53 +0100 Subject: [PATCH 02/22] test(daemon-client): publish the startup phase gate atomically The child polls the gate file and reads it whole. A plain write left a window where the file existed with no contents yet, so the child reported an empty phase and the test lost a receipt. Publishing it means the child sees a phase name or no file at all. --- .../src/__tests__/daemon-client-startup-budget.test.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/daemon-client/src/__tests__/daemon-client-startup-budget.test.ts b/packages/daemon-client/src/__tests__/daemon-client-startup-budget.test.ts index 7d8d388652..3b05f48edd 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-startup-budget.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-startup-budget.test.ts @@ -19,6 +19,7 @@ import { startHttpDaemonFixture, skipWhenLoopbackUnavailable, } from '@agent-device/test-kit'; +import { publishFileSync } from '@agent-device/host-kit/file'; import { isProcessAlive } from '@agent-device/host-kit/process'; import { readVersion } from '@agent-device/host-kit/version'; import { @@ -187,7 +188,8 @@ test('a daemon slower than the retired 15 s budget starts successfully while it if (spawned.child && now.value - spawned.at < 80_000) { now.value += 20_000; if (nextPhase < phases.length) { - fs.writeFileSync(gate, phases[nextPhase]!); + // Published atomically: the child polls this file, and a partial read would lose a phase. + publishFileSync({ destination: gate, contents: phases[nextPhase]! }); nextPhase += 1; // Wait for the child's real channel message before advancing the clock again, so each // receipt lands on the virtual time this pause just set. @@ -486,7 +488,7 @@ test('a repeated phase message keeps the first receipt time', async () => { now.value += 1_000; const elapsed = now.value - started; if (elapsed === 1_000 || elapsed === 10_000) { - fs.writeFileSync(gate, 'lock-acquired'); + publishFileSync({ destination: gate, contents: 'lock-acquired' }); sent += 1; for (let attempt = 0; reported.length < sent && attempt < 400; attempt += 1) await realPause(5); From 1e24b0bd4893ed1acc4a11ef35b2bd7e2f4243bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 21 Nov 2026 19:51:33 +0100 Subject: [PATCH 03/22] chore(gates): exempt the session file identity export from unused-export audit connectionSessionIdentity is the published name for the hash a session maps to in its saved-connection file name. Production derives it inside the module, and the package test reads it, which the production export audit cannot see. --- .fallowrc.json | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.fallowrc.json b/.fallowrc.json index 10904eb4da..b8fa753135 100644 --- a/.fallowrc.json +++ b/.fallowrc.json @@ -280,6 +280,14 @@ "file": "packages/maestro/src/internal/program-ir-command-parser.ts", "exports": ["SUPPORTED_MAESTRO_COMMAND_NAMES"] }, + { + // The hash a session's saved-connection file name is built from. Production derives it inside + // remote-connection-state.ts when it resolves that file path and reaches no in-repo consumer of + // the export; it is published so a caller can name a session's record path. The package test + // recomputes it on purpose, so an accidental change to the identity breaks the test. + "file": "packages/remote/src/remote-connection-state.ts", + "exports": ["connectionSessionIdentity"] + }, { // Linux package façade loader is a named external seam. Its dynamic property read is not visible to --production analysis. "file": "packages/platform-linux/src/index.ts", From 33d652b0163b0749ba745c630d0c7183ebf94c76 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 21 Nov 2026 21:39:38 +0100 Subject: [PATCH 04/22] fix(remote): never resolve a session onto another session's record On a case-insensitive filesystem, the record an older build wrote for `Demo` opens when `demo` asks for its own plain name, so every remote command for `demo` answered `connection_session_mismatch` and the only way out was deleting the file by hand. Path resolution trusted a name; contents decide ownership. A session now resolves to the next path its own name answers for when a record there proves it belongs to another session: the case-variant reads no state, writes its own hashed record, and the other session's file is left alone. `connection status` and `disconnect --session demo` answer that demo has no connection instead of failing. The contents check stays as the last guard for a record that still disagrees after resolution, and it now names the refused path and how to clear it. --- ...-connection-state-session-identity.test.ts | 89 ++++++++++++++- .../remote/src/remote-connection-state.ts | 60 ++++++++-- .../connection-case-variant-session.test.ts | 103 ++++++++++++++++++ 3 files changed, 237 insertions(+), 15 deletions(-) create mode 100644 src/cli/commands/connection-case-variant-session.test.ts diff --git a/packages/remote/src/remote-connection-state-session-identity.test.ts b/packages/remote/src/remote-connection-state-session-identity.test.ts index 2f26d3c7b2..0c22dc338d 100644 --- a/packages/remote/src/remote-connection-state-session-identity.test.ts +++ b/packages/remote/src/remote-connection-state-session-identity.test.ts @@ -57,6 +57,32 @@ function sanitizedFileName(session: string): string { return safe === session ? `${safe}.json` : `${safe}-${sha256(session).slice(0, 8)}.json`; } +/** + * Leaves one legacy record reachable under the names of both `session` and its case-variant, which is + * what a case-insensitive filesystem does by itself. On such a volume the name an older build wrote + * for `Demo` already IS the name `demo` opens; on a case-sensitive one, a hard link stands in for that + * fold so both names open the same bytes. + */ +function plantRecordSharedByCaseVariants(stateDir: string, session: string): string { + const recordsDir = path.join(stateDir, RECORDS_DIR); + fs.mkdirSync(recordsDir, { recursive: true }); + const written = path.join(recordsDir, `${session}.json`); + fs.writeFileSync(written, `${JSON.stringify(recordFor(session), null, 2)}\n`, 'utf8'); + const aliased = path.join(recordsDir, `${session.toLowerCase()}.json`); + try { + fs.linkSync(written, aliased); + } catch (error) { + // EEXIST: the volume folds the two names onto the file that is already there. + if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error; + assert.equal( + fs.readFileSync(aliased, 'utf8'), + fs.readFileSync(written, 'utf8'), + 'the case-variant name must open the record it shares', + ); + } + return written; +} + function captureRefusal(run: () => unknown): AppError { try { run(); @@ -155,20 +181,73 @@ test('a record left on the active-session pointer path is not read as a session ); }); -test('a saved connection naming another session is refused rather than reused', () => { +test('a record an older build shared with a case-variant session does not lock that session out', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-upgrade-'); + const sharedPath = plantRecordSharedByCaseVariants(stateDir, 'Demo'); + const planted = fs.readFileSync(sharedPath, 'utf8'); + + assert.equal( + readRemoteConnectionState({ stateDir, session: 'demo' }), + null, + 'the record an older build named for Demo proves it is not the demo session connection', + ); + assert.equal(fs.readFileSync(sharedPath, 'utf8'), planted); + + writeRemoteConnectionState({ stateDir, state: recordFor('demo') }); + + assert.equal(readRemoteConnectionState({ stateDir, session: 'demo' })?.runId, 'run-demo'); + assert.equal( + fs.existsSync(path.join(stateDir, RECORDS_DIR, hashedFileName('demo'))), + true, + 'a session whose plain name is taken by another session writes under its hash', + ); + assert.equal( + readRemoteConnectionState({ stateDir, session: 'Demo' })?.runId, + 'run-Demo', + 'the aliased record still serves the session it names', + ); + assert.equal( + fs.readFileSync(sharedPath, 'utf8'), + planted, + 'writing this session record never rewrites the file the other session owns', + ); + + removeRemoteConnectionState({ stateDir, session: 'demo' }); + + assert.equal(readRemoteConnectionState({ stateDir, session: 'demo' }), null); + assert.equal( + readRemoteConnectionState({ stateDir, session: 'Demo' })?.runId, + 'run-Demo', + 'removing one session still must not reach the record the other one owns', + ); + assert.equal(fs.existsSync(sharedPath), true); +}); + +test('the last guard names the record it refused and how to clear it', () => { const stateDir = mkdtempForTestSync('agent-device-remote-identity-mismatch-'); - const statePath = writeRecordFile(stateDir, 'demo.json', 'Demo'); + // A record that reached a session's own path while naming another session — a foreign record someone + // planted there, or one that changed under a command in flight. Resolution takes the path the hash + // answers for, so only the contents check can refuse it. + const session = 'team/dev#1'; + const statePath = writeRecordFile(stateDir, hashedFileName(session), 'team:dev#1'); - const read = captureRefusal(() => readRemoteConnectionState({ stateDir, session: 'demo' })); + const read = captureRefusal(() => readRemoteConnectionState({ stateDir, session })); assert.equal(read.code, 'COMMAND_FAILED'); assert.equal(read.details?.reason, 'connection_session_mismatch'); + assert.equal(read.details?.session, session); + assert.equal(read.details?.recordPath, statePath); + assert.match(String(read.details?.hint), /disconnect --session team:dev#1/); + assert.ok( + String(read.details?.hint).includes(statePath), + 'the recovery names the file it wants removed', + ); const write = captureRefusal(() => - writeRemoteConnectionState({ stateDir, state: recordFor('demo') }), + writeRemoteConnectionState({ stateDir, state: recordFor(session) }), ); assert.equal(write.details?.reason, 'connection_session_mismatch'); - const remove = captureRefusal(() => removeRemoteConnectionState({ stateDir, session: 'demo' })); + const remove = captureRefusal(() => removeRemoteConnectionState({ stateDir, session })); assert.equal(remove.details?.reason, 'connection_session_mismatch'); assert.equal( fs.existsSync(statePath), diff --git a/packages/remote/src/remote-connection-state.ts b/packages/remote/src/remote-connection-state.ts index b2ffe11299..d79de869fd 100644 --- a/packages/remote/src/remote-connection-state.ts +++ b/packages/remote/src/remote-connection-state.ts @@ -246,8 +246,15 @@ export function readRemoteConnectionState(options: { return null; } if (parsed.session !== options.session) { + // Path resolution already sends a session whose name is taken by another session's record to its + // own hashed path, so reaching here means the record changed between resolving and reading it. + // Nothing is read, written, or removed under a name another session owns; the file is named so a + // caller can see what it is standing on. throw new AppError('COMMAND_FAILED', 'The saved connection belongs to a different session.', { reason: REMOTE_CONNECTION_STATE_REASONS.sessionMismatch.reason, + session: options.session, + recordPath: statePath, + hint: `Run disconnect --session ${parsed.session} to release that connection, or remove ${statePath}.`, }); } return parsed; @@ -532,28 +539,61 @@ export function hashRemoteConfigFile(configPath: string): string { /** The pointer to the machine-wide active session. It is not a session record and never names one. */ const ACTIVE_SESSION_FILE_NAME = '.active-session.json'; +/** + * Where a session's saved connection lives. + * + * Contents decide who owns a record; its file name never does. On a case-insensitive filesystem the + * file an older build wrote for `Demo` opens when `demo` asks for its own name, and trusting it would + * have `demo` read, overwrite, or delete a connection it does not own. So a session never resolves to + * a record that proves it belongs to another session: it resolves to the next path its own name + * answers for, finds no record there, and writes its own. The other session's file is left alone. + * + * A name that is a filename on its own belongs to that name, and to its hashed path when a record + * there names another session. Any other name belongs to its hashed path, and to the sanitized path + * older builds used only while a record there names this session. + */ function remoteConnectionStatePath(options: { stateDir: string; session: string }): string { - const dir = path.join(options.stateDir, 'remote-connections'); + const recordsDir = path.join(options.stateDir, 'remote-connections'); + // A name that cannot be a filename on its own — anything starting with `.`, or holding a // separator — is stored by hash, so it can never take the active-session pointer's file either. if (/^[a-z0-9_-][a-z0-9._-]*$/.test(options.session)) { - return path.join(dir, `${options.session}.json`); + const plain = path.join(recordsDir, `${options.session}.json`); + const recorded = sessionNamedBy(plain); + return recorded !== undefined && recorded !== options.session + ? hashedRemoteConnectionStatePath(recordsDir, options.session) + : plain; } - const canonical = path.join(dir, `~${connectionSessionIdentity(options.session)}.json`); + const canonical = hashedRemoteConnectionStatePath(recordsDir, options.session); if (fs.existsSync(canonical)) return canonical; // Older records were named by sanitizing the session, so two names that differ only in case could - // share one file on a case-insensitive filesystem. Trust such a file only when its contents prove - // they name this session; otherwise this session's record belongs to the hashed path. - const legacy = legacyRemoteConnectionStatePath({ recordsDir: dir, session: options.session }); - if (!legacy) return canonical; + // share one file. Trust such a file only when its contents prove they name this session. + const legacy = legacyRemoteConnectionStatePath({ recordsDir, session: options.session }); + return legacy !== undefined && sessionNamedBy(legacy) === options.session ? legacy : canonical; +} + +function hashedRemoteConnectionStatePath(recordsDir: string, session: string): string { + return path.join(recordsDir, `~${connectionSessionIdentity(session)}.json`); +} + +/** + * The session the record at `statePath` names, or `undefined` when it is absent, unreadable, does not + * parse, or names none. Absence and an unreadable file answer alike: neither proves the record belongs + * to another session, so neither moves a session off the path its own name answers for. + */ +function sessionNamedBy(statePath: string | undefined): string | undefined { + if (statePath === undefined) return undefined; + let parsed: unknown; try { - const state: unknown = JSON.parse(fs.readFileSync(legacy, 'utf8')); - return isRemoteConnectionState(state) && state.session === options.session ? legacy : canonical; + parsed = JSON.parse(fs.readFileSync(statePath, 'utf8')); } catch { - return canonical; + return undefined; } + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return undefined; + const session = (parsed as { session?: unknown }).session; + return typeof session === 'string' ? session : undefined; } /** diff --git a/src/cli/commands/connection-case-variant-session.test.ts b/src/cli/commands/connection-case-variant-session.test.ts new file mode 100644 index 0000000000..ad46aa0bd4 --- /dev/null +++ b/src/cli/commands/connection-case-variant-session.test.ts @@ -0,0 +1,103 @@ +import { test } from 'vitest'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { withCapturedStdoutAsync } from '@agent-device/test-kit'; +import { hashRemoteConfigFile } from '@agent-device/remote/remote-connection-state'; +import { + connectionWorkspace, + createTestClient, +} from '../../__tests__/remote-connection.fixtures.ts'; +import { + connectionCommand, + disconnectCommand, +} from '../../__tests__/test-utils/host-bound-commands.ts'; + +// Upgrading on a case-insensitive filesystem left the record an older build wrote for `Demo` at the +// name `demo` opens. `connection status --session demo` and `disconnect --session demo` both answered +// `connection_session_mismatch`, so the session could neither report nor drop its own connection. + +const RECORDS_DIR = 'remote-connections'; + +/** + * Leaves a saved connection for `session` reachable under the name its case-variant opens too, which is + * what a case-insensitive filesystem does by itself. On such a volume the name `Demo` was written under + * already IS the name `demo` opens; on a case-sensitive one, a hard link stands in for that fold. + */ +function plantRecordSharedByCaseVariants(options: { + stateDir: string; + remoteConfigPath: string; + session: string; +}): string { + const recordsDir = path.join(options.stateDir, RECORDS_DIR); + fs.mkdirSync(recordsDir, { recursive: true }); + const now = new Date().toISOString(); + const written = path.join(recordsDir, `${options.session}.json`); + fs.writeFileSync( + written, + `${JSON.stringify( + { + version: 1, + session: options.session, + remoteConfigPath: options.remoteConfigPath, + remoteConfigHash: hashRemoteConfigFile(options.remoteConfigPath), + tenant: 'acme', + runId: `run-${options.session}`, + connectedAt: now, + updatedAt: now, + }, + null, + 2, + )}\n`, + 'utf8', + ); + const aliased = path.join(recordsDir, `${options.session.toLowerCase()}.json`); + try { + fs.linkSync(written, aliased); + } catch (error) { + // EEXIST: the volume folds the two names onto the file that is already there. + if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error; + assert.equal( + fs.readFileSync(aliased, 'utf8'), + fs.readFileSync(written, 'utf8'), + 'the case-variant name must open the record it shares', + ); + } + return written; +} + +for (const [name, run] of [ + ['connection status', connectionCommand], + ['disconnect', disconnectCommand], +] as const) { + test(`${name} for a session whose saved-connection name an older build shared reports no connection`, async () => { + const { tempRoot, stateDir, remoteConfigPath } = connectionWorkspace( + 'agent-device-connection-case-variant-', + ); + fs.writeFileSync(remoteConfigPath, '{}'); + const sharedPath = plantRecordSharedByCaseVariants({ + stateDir, + remoteConfigPath, + session: 'Demo', + }); + + const stdout = await withCapturedStdoutAsync(async () => { + // Every call this client answers throws: neither command may reach the daemon. + await run({ + positionals: name === 'connection status' ? ['status'] : [], + flags: { json: true, help: false, version: false, stateDir, session: 'demo' }, + client: createTestClient(), + }); + }); + + const payload = JSON.parse(stdout).data; + assert.equal(payload.connected, false); + assert.equal(payload.session, 'demo'); + assert.deepEqual( + JSON.parse(fs.readFileSync(sharedPath, 'utf8')).session, + 'Demo', + 'answering for one session leaves the record the other one owns in place', + ); + fs.rmSync(tempRoot, { recursive: true, force: true }); + }); +} From c5cdd7b5386b1ec18e5be9379a1d9a2558d8b534 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 22 Nov 2026 08:18:20 +0100 Subject: [PATCH 05/22] fix(remote): keep finding a session's hashed record after the shared file is removed --- ...ote-connection-state-session-identity.test.ts | 16 ++++++++++++++++ packages/remote/src/remote-connection-state.ts | 8 +++++--- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/packages/remote/src/remote-connection-state-session-identity.test.ts b/packages/remote/src/remote-connection-state-session-identity.test.ts index 0c22dc338d..eecb545e71 100644 --- a/packages/remote/src/remote-connection-state-session-identity.test.ts +++ b/packages/remote/src/remote-connection-state-session-identity.test.ts @@ -126,6 +126,22 @@ test('disconnecting one of two case-variant sessions leaves the other record', ( ); }); +test('a session that wrote under its hash keeps its record after the shared file is removed', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-alias-gone-'); + const shared = plantRecordSharedByCaseVariants(stateDir, 'Demo'); + writeRemoteConnectionState({ stateDir, state: recordFor('demo') }); + + for (const name of [shared, path.join(path.dirname(shared), 'demo.json')]) { + fs.rmSync(name, { force: true }); + } + + assert.equal( + readRemoteConnectionState({ stateDir, session: 'demo' })?.runId, + 'run-demo', + 'a session must keep finding the record it wrote under its hash', + ); +}); + test('a session name that cannot be a filename is stored under its hash', () => { const stateDir = mkdtempForTestSync('agent-device-remote-identity-hashed-'); const session = 'team/dev#1'; diff --git a/packages/remote/src/remote-connection-state.ts b/packages/remote/src/remote-connection-state.ts index d79de869fd..fbba2db431 100644 --- a/packages/remote/src/remote-connection-state.ts +++ b/packages/remote/src/remote-connection-state.ts @@ -559,10 +559,12 @@ function remoteConnectionStatePath(options: { stateDir: string; session: string // separator — is stored by hash, so it can never take the active-session pointer's file either. if (/^[a-z0-9_-][a-z0-9._-]*$/.test(options.session)) { const plain = path.join(recordsDir, `${options.session}.json`); + const hashed = hashedRemoteConnectionStatePath(recordsDir, options.session); + // A session that once found another session's record on its plain path wrote under its hash. + // Keep finding that record after the other session's file is gone. + if (sessionNamedBy(hashed) === options.session) return hashed; const recorded = sessionNamedBy(plain); - return recorded !== undefined && recorded !== options.session - ? hashedRemoteConnectionStatePath(recordsDir, options.session) - : plain; + return recorded !== undefined && recorded !== options.session ? hashed : plain; } const canonical = hashedRemoteConnectionStatePath(recordsDir, options.session); From 850e14c1fa91be8dbcf3b35ecdc3e52db1b18510 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 22 Nov 2026 09:19:40 +0100 Subject: [PATCH 06/22] fix(remote): resolve a session's saved connection by name and migrate legacy records once A plain session name maps to .json and every other name to the SHA-256 of its UTF-16 code units, so lone surrogates and case variants never share a file. Records older builds left under sanitized names, at a case alias, or on the active-session pointer path move once to their verified owner's path; an occupied target keeps the source and refuses. Only ENOENT means absent, and a file is removed as invalid only after its parsed session matches the caller. --- ...-connection-state-session-identity.test.ts | 301 ++++++++++++------ .../remote/src/remote-connection-state.ts | 255 ++++++++++----- src/__tests__/cli-config.test.ts | 10 +- .../connection-case-variant-session.test.ts | 15 +- 4 files changed, 381 insertions(+), 200 deletions(-) diff --git a/packages/remote/src/remote-connection-state-session-identity.test.ts b/packages/remote/src/remote-connection-state-session-identity.test.ts index eecb545e71..8a38884c46 100644 --- a/packages/remote/src/remote-connection-state-session-identity.test.ts +++ b/packages/remote/src/remote-connection-state-session-identity.test.ts @@ -33,52 +33,57 @@ function recordFor(session: string): RemoteConnectionState { }; } -/** Writes a record straight to `fileName`, as a previous build or another session would have left it. */ -function writeRecordFile(stateDir: string, fileName: string, session: string): string { +/** Writes `contents` straight to `fileName`, as a previous build or another session would have left it. */ +function writeRecordFile( + stateDir: string, + fileName: string, + contents: string | Record, +): string { const recordsDir = path.join(stateDir, RECORDS_DIR); fs.mkdirSync(recordsDir, { recursive: true }); const statePath = path.join(recordsDir, fileName); - fs.writeFileSync(statePath, `${JSON.stringify(recordFor(session), null, 2)}\n`, 'utf8'); + const text = typeof contents === 'string' ? contents : `${JSON.stringify(contents, null, 2)}\n`; + fs.writeFileSync(statePath, text, 'utf8'); return statePath; } -function sha256(value: string): string { - return crypto.createHash('sha256').update(value).digest('hex'); -} - -/** Where a session whose name cannot be a filename is stored: under its own hash. */ +/** Where a session whose name cannot be a filename is stored: under the hash of its UTF-16 code units. */ function hashedFileName(session: string): string { - return `~${sha256(session)}.json`; + const identity = crypto + .createHash('sha256') + .update(Buffer.from(session, 'utf16le')) + .digest('hex'); + return `~${identity}.json`; } /** The file name a build that sanitized names wrote for `session`. */ function sanitizedFileName(session: string): string { const safe = session.replaceAll(/[^a-zA-Z0-9._-]/g, '_'); - return safe === session ? `${safe}.json` : `${safe}-${sha256(session).slice(0, 8)}.json`; + if (safe === session) return `${safe}.json`; + return `${safe}-${crypto.createHash('sha256').update(session).digest('hex').slice(0, 8)}.json`; +} + +function recordsIn(stateDir: string): string[] { + return fs.readdirSync(path.join(stateDir, RECORDS_DIR)).sort(); } /** - * Leaves one legacy record reachable under the names of both `session` and its case-variant, which is - * what a case-insensitive filesystem does by itself. On such a volume the name an older build wrote - * for `Demo` already IS the name `demo` opens; on a case-sensitive one, a hard link stands in for that - * fold so both names open the same bytes. + * Leaves one legacy file reachable under the names of both `session` and its lower-case variant, which + * is what a case-insensitive filesystem does by itself. On a case-sensitive one, a hard link stands in + * for that fold so both names open the same bytes. */ -function plantRecordSharedByCaseVariants(stateDir: string, session: string): string { - const recordsDir = path.join(stateDir, RECORDS_DIR); - fs.mkdirSync(recordsDir, { recursive: true }); - const written = path.join(recordsDir, `${session}.json`); - fs.writeFileSync(written, `${JSON.stringify(recordFor(session), null, 2)}\n`, 'utf8'); - const aliased = path.join(recordsDir, `${session.toLowerCase()}.json`); +function plantFileSharedByCaseVariants( + stateDir: string, + session: string, + contents: string | Record = recordFor(session), +): string { + const written = writeRecordFile(stateDir, `${session}.json`, contents); + const aliased = path.join(path.dirname(written), `${session.toLowerCase()}.json`); try { fs.linkSync(written, aliased); } catch (error) { // EEXIST: the volume folds the two names onto the file that is already there. if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error; - assert.equal( - fs.readFileSync(aliased, 'utf8'), - fs.readFileSync(written, 'utf8'), - 'the case-variant name must open the record it shares', - ); } return written; } @@ -93,6 +98,8 @@ function captureRefusal(run: () => unknown): AppError { return assert.fail('expected a refusal'); } +const runsAsRoot = process.getuid?.() === 0; + test('sessions named Demo and demo keep separate records', () => { const stateDir = mkdtempForTestSync('agent-device-remote-identity-case-'); writeRemoteConnectionState({ stateDir, state: recordFor('Demo') }); @@ -105,12 +112,26 @@ test('sessions named Demo and demo keep separate records', () => { ); assert.equal(readRemoteConnectionState({ stateDir, session: 'demo' })?.runId, 'run-demo'); assert.deepEqual( - fs.readdirSync(path.join(stateDir, RECORDS_DIR)).sort(), + recordsIn(stateDir), [ACTIVE_SESSION_FILE, 'demo.json', hashedFileName('Demo')].sort(), 'a name that cannot be a filename gets its own hashed file, never one two names share', ); }); +test('sessions named by the lone surrogates U+D800 and U+D801 keep separate records', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-surrogate-'); + writeRemoteConnectionState({ stateDir, state: recordFor('\uD800') }); + writeRemoteConnectionState({ stateDir, state: recordFor('\uD801') }); + + assert.equal(readRemoteConnectionState({ stateDir, session: '\uD800' })?.runId, 'run-\uD800'); + assert.equal(readRemoteConnectionState({ stateDir, session: '\uD801' })?.runId, 'run-\uD801'); + assert.deepEqual( + recordsIn(stateDir), + [ACTIVE_SESSION_FILE, hashedFileName('\uD800'), hashedFileName('\uD801')].sort(), + 'names that UTF-8 encodes alike must still get different files', + ); +}); + test('disconnecting one of two case-variant sessions leaves the other record', () => { const stateDir = mkdtempForTestSync('agent-device-remote-identity-remove-'); writeRemoteConnectionState({ stateDir, state: recordFor('Demo') }); @@ -126,133 +147,209 @@ test('disconnecting one of two case-variant sessions leaves the other record', ( ); }); -test('a session that wrote under its hash keeps its record after the shared file is removed', () => { - const stateDir = mkdtempForTestSync('agent-device-remote-identity-alias-gone-'); - const shared = plantRecordSharedByCaseVariants(stateDir, 'Demo'); - writeRemoteConnectionState({ stateDir, state: recordFor('demo') }); - - for (const name of [shared, path.join(path.dirname(shared), 'demo.json')]) { - fs.rmSync(name, { force: true }); - } - - assert.equal( - readRemoteConnectionState({ stateDir, session: 'demo' })?.runId, - 'run-demo', - 'a session must keep finding the record it wrote under its hash', - ); -}); - test('a session name that cannot be a filename is stored under its hash', () => { const stateDir = mkdtempForTestSync('agent-device-remote-identity-hashed-'); const session = 'team/dev#1'; writeRemoteConnectionState({ stateDir, state: recordFor(session) }); - assert.deepEqual( - fs.readdirSync(path.join(stateDir, RECORDS_DIR)).sort(), - [hashedFileName(session), ACTIVE_SESSION_FILE].sort(), - ); + assert.deepEqual(recordsIn(stateDir), [hashedFileName(session), ACTIVE_SESSION_FILE].sort()); assert.equal(readRemoteConnectionState({ stateDir, session })?.runId, `run-${session}`); }); -test('a record at the sanitized path is used only when its contents name this session', () => { - const reusedDir = mkdtempForTestSync('agent-device-remote-identity-legacy-match-'); +test('a record at the sanitized path that names this session moves to its hashed path', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-legacy-match-'); const session = 'team/dev#1'; - writeRecordFile(reusedDir, sanitizedFileName(session), session); + writeRecordFile(stateDir, sanitizedFileName(session), recordFor(session)); assert.equal( - readRemoteConnectionState({ stateDir: reusedDir, session })?.runId, + readRemoteConnectionState({ stateDir, session })?.runId, `run-${session}`, 'a record written before hashed paths still serves the session it names', ); + assert.deepEqual( + recordsIn(stateDir), + [hashedFileName(session)], + 'the record now lives only at the hashed path, and the sanitized name is gone', + ); +}); - // One file whose contents name another session: that is what a session finds when an older build - // wrote two sessions to the same name, so the file name proves nothing and only contents decide. - const aliasedDir = mkdtempForTestSync('agent-device-remote-identity-legacy-alias-'); - writeRecordFile(aliasedDir, sanitizedFileName(session), 'team:dev#1'); +test('a record at the sanitized path that names another session is left in place', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-legacy-alias-'); + const session = 'team/dev#1'; + // An older build wrote two sessions to the same name, so the file name proves nothing. + const legacyPath = writeRecordFile(stateDir, sanitizedFileName(session), recordFor('team:dev#1')); - assert.equal( - readRemoteConnectionState({ stateDir: aliasedDir, session }), - null, - 'a record naming another session is not this session record, so nothing is read from it', - ); - assert.equal( - fs.existsSync(path.join(aliasedDir, RECORDS_DIR, hashedFileName(session))), - false, - 'and reading it does not give this session a record of its own', - ); + assert.equal(readRemoteConnectionState({ stateDir, session }), null); + writeRemoteConnectionState({ stateDir, state: recordFor(session) }); + + assert.equal(JSON.parse(fs.readFileSync(legacyPath, 'utf8')).session, 'team:dev#1'); + assert.equal(readRemoteConnectionState({ stateDir, session })?.runId, `run-${session}`); }); -test('a record left on the active-session pointer path is not read as a session record', () => { - const stateDir = mkdtempForTestSync('agent-device-remote-identity-pointer-'); - // A build that sanitized names wrote the session `.active-session` to exactly the path its - // active-session pointer uses, so that file holds a full connection record for it. - const session = '.active-session'; - writeRecordFile(stateDir, ACTIVE_SESSION_FILE, session); +test('a sanitized record whose hashed path is already taken is kept and refused', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-legacy-occupied-'); + const session = 'team/dev#1'; + const legacyPath = writeRecordFile(stateDir, sanitizedFileName(session), recordFor(session)); + writeRecordFile(stateDir, hashedFileName(session), recordFor(session)); - assert.equal( - readRemoteConnectionState({ stateDir, session }), - null, - 'the pointer path is never a session record, so the session reads as unconnected', + const refusal = captureRefusal(() => readRemoteConnectionState({ stateDir, session })); + + assert.equal(refusal.details?.reason, 'connection_session_mismatch'); + assert.equal(refusal.details?.recordPath, legacyPath); + assert.deepEqual( + recordsIn(stateDir), + [hashedFileName(session), sanitizedFileName(session)].sort(), + 'neither record is lost when both claim the same session', ); }); -test('a record an older build shared with a case-variant session does not lock that session out', () => { +test('a record an older build shared with a case-variant session moves to its owner', () => { const stateDir = mkdtempForTestSync('agent-device-remote-identity-upgrade-'); - const sharedPath = plantRecordSharedByCaseVariants(stateDir, 'Demo'); - const planted = fs.readFileSync(sharedPath, 'utf8'); + plantFileSharedByCaseVariants(stateDir, 'Demo'); assert.equal( readRemoteConnectionState({ stateDir, session: 'demo' }), null, - 'the record an older build named for Demo proves it is not the demo session connection', + 'the record an older build wrote for Demo is not the demo session connection', ); - assert.equal(fs.readFileSync(sharedPath, 'utf8'), planted); + assert.deepEqual(recordsIn(stateDir), [hashedFileName('Demo')]); writeRemoteConnectionState({ stateDir, state: recordFor('demo') }); - assert.equal(readRemoteConnectionState({ stateDir, session: 'demo' })?.runId, 'run-demo'); - assert.equal( - fs.existsSync(path.join(stateDir, RECORDS_DIR, hashedFileName('demo'))), - true, - 'a session whose plain name is taken by another session writes under its hash', - ); + assert.equal(readRemoteConnectionState({ stateDir, session: 'Demo' })?.runId, 'run-Demo'); + + removeRemoteConnectionState({ stateDir, session: 'demo' }); + assert.equal(readRemoteConnectionState({ stateDir, session: 'demo' }), null); assert.equal( readRemoteConnectionState({ stateDir, session: 'Demo' })?.runId, 'run-Demo', - 'the aliased record still serves the session it names', + 'removing one session must not reach the record the other one owns', ); - assert.equal( - fs.readFileSync(sharedPath, 'utf8'), - planted, - 'writing this session record never rewrites the file the other session owns', +}); + +for (const [damage, skip] of [ + ['unreadable', runsAsRoot], + ['unparseable', false], +] as const) { + test.skipIf(skip)( + `an ${damage} record an older build shared with a case-variant session is never removed`, + () => { + const stateDir = mkdtempForTestSync(`agent-device-remote-identity-${damage}-`); + const sharedPath = + damage === 'unreadable' + ? plantFileSharedByCaseVariants(stateDir, 'Demo') + : plantFileSharedByCaseVariants(stateDir, 'Demo', '{"session": "Demo",'); + if (damage === 'unreadable') fs.chmodSync(sharedPath, 0o000); + const planted = recordsIn(stateDir); + try { + const refusal = captureRefusal(() => + readRemoteConnectionState({ stateDir, session: 'demo' }), + ); + assert.equal(refusal.details?.reason, 'connection_record_owner_unknown'); + assert.equal( + readRemoteConnectionState({ stateDir, session: 'Demo' }), + null, + 'a record whose owner is unknown does not serve any session', + ); + captureRefusal(() => writeRemoteConnectionState({ stateDir, state: recordFor('demo') })); + captureRefusal(() => removeRemoteConnectionState({ stateDir, session: 'demo' })); + assert.deepEqual(recordsIn(stateDir), planted, 'no command removed the shared file'); + } finally { + fs.chmodSync(sharedPath, 0o600); + } + }, ); +} - removeRemoteConnectionState({ stateDir, session: 'demo' }); +test('a record that fails validation is removed only for the session it names', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-invalid-'); + const foreignPath = writeRecordFile(stateDir, 'demo.json', { + ...recordFor('other'), + updatedAt: null, + }); + const ownPath = writeRecordFile(stateDir, 'other.json', { + ...recordFor('other'), + updatedAt: null, + }); + + const refusal = captureRefusal(() => readRemoteConnectionState({ stateDir, session: 'demo' })); + assert.equal(refusal.details?.reason, 'connection_session_mismatch'); + assert.equal(fs.existsSync(foreignPath), true, 'an invalid record of another session is kept'); + + assert.equal(readRemoteConnectionState({ stateDir, session: 'other' }), null); + assert.equal(fs.existsSync(ownPath), false, 'an invalid record of this session is removed'); +}); - assert.equal(readRemoteConnectionState({ stateDir, session: 'demo' }), null); - assert.equal( - readRemoteConnectionState({ stateDir, session: 'Demo' })?.runId, - 'run-Demo', - 'removing one session still must not reach the record the other one owns', +test('an invalid record of the U+D800 session survives a U+D801 status read', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-invalid-surrogate-'); + const recordPath = writeRecordFile(stateDir, hashedFileName('\uD800'), { + ...recordFor('\uD800'), + updatedAt: null, + }); + + assert.equal(readRemoteConnectionState({ stateDir, session: '\uD801' }), null); + assert.equal(fs.existsSync(recordPath), true); +}); + +test('a session named by a case alias of the pointer file is stored under its hash', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-pointer-alias-'); + const session = '.ACTIVE-SESSION'; + writeRecordFile(stateDir, `${session}.json`, recordFor(session)); + + writeRemoteConnectionState({ stateDir, state: recordFor('demo') }); + + assert.equal(readRemoteConnectionState({ stateDir, session })?.runId, `run-${session}`); + assert.deepEqual( + recordsIn(stateDir), + [ACTIVE_SESSION_FILE, 'demo.json', hashedFileName(session)].sort(), + 'the legacy record moved to its hashed path instead of sitting on the pointer name', + ); + assert.deepEqual( + JSON.parse(fs.readFileSync(path.join(stateDir, RECORDS_DIR, ACTIVE_SESSION_FILE), 'utf8')), + { session: 'demo' }, ); - assert.equal(fs.existsSync(sharedPath), true); +}); + +test('a record left on the pointer path moves to its owner before the pointer is written', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-pointer-'); + // A build that sanitized names wrote the session `.active-session` to exactly the pointer path. + const session = '.active-session'; + writeRecordFile(stateDir, ACTIVE_SESSION_FILE, recordFor(session)); + + writeRemoteConnectionState({ stateDir, state: recordFor('demo') }); + + assert.equal(readRemoteConnectionState({ stateDir, session })?.runId, `run-${session}`); + assert.deepEqual( + recordsIn(stateDir), + [ACTIVE_SESSION_FILE, 'demo.json', hashedFileName(session)].sort(), + ); +}); + +test('a record of unproven owner on the pointer path refuses the pointer write', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-pointer-foreign-'); + const pointerPath = writeRecordFile(stateDir, ACTIVE_SESSION_FILE, recordFor('team')); + + const refusal = captureRefusal(() => + writeRemoteConnectionState({ stateDir, state: recordFor('demo') }), + ); + + assert.equal(refusal.details?.reason, 'connection_session_mismatch'); + assert.equal(JSON.parse(fs.readFileSync(pointerPath, 'utf8')).session, 'team'); + assert.deepEqual(recordsIn(stateDir), [ACTIVE_SESSION_FILE], 'nothing else was written'); }); test('the last guard names the record it refused and how to clear it', () => { const stateDir = mkdtempForTestSync('agent-device-remote-identity-mismatch-'); - // A record that reached a session's own path while naming another session — a foreign record someone - // planted there, or one that changed under a command in flight. Resolution takes the path the hash - // answers for, so only the contents check can refuse it. + // A foreign record planted at a session's own path, or one that changed under a command in flight. const session = 'team/dev#1'; - const statePath = writeRecordFile(stateDir, hashedFileName(session), 'team:dev#1'); + const statePath = writeRecordFile(stateDir, hashedFileName(session), recordFor('team:dev#1')); const read = captureRefusal(() => readRemoteConnectionState({ stateDir, session })); assert.equal(read.code, 'COMMAND_FAILED'); assert.equal(read.details?.reason, 'connection_session_mismatch'); assert.equal(read.details?.session, session); assert.equal(read.details?.recordPath, statePath); - assert.match(String(read.details?.hint), /disconnect --session team:dev#1/); assert.ok( String(read.details?.hint).includes(statePath), 'the recovery names the file it wants removed', diff --git a/packages/remote/src/remote-connection-state.ts b/packages/remote/src/remote-connection-state.ts index fbba2db431..13ecffd6ad 100644 --- a/packages/remote/src/remote-connection-state.ts +++ b/packages/remote/src/remote-connection-state.ts @@ -226,6 +226,9 @@ const REMOTE_CONNECTION_STATE_REASONS = { // A command named one session and the saved connection it reached names another, so nothing about // that connection was read, replaced, or removed. sessionMismatch: { reason: 'connection_session_mismatch' }, + // A saved connection file could not be read or parsed, so no session is known to own it, and it was + // neither replaced nor removed. + ownerUnknown: { reason: 'connection_record_owner_unknown' }, } as const satisfies ReasonTable<'remote connections'>; export function readRemoteConnectionState(options: { @@ -233,31 +236,42 @@ export function readRemoteConnectionState(options: { session: string; }): RemoteConnectionState | null { const statePath = remoteConnectionStatePath(options); - if (!fs.existsSync(statePath)) return null; - let parsed: unknown; - try { - parsed = JSON.parse(fs.readFileSync(statePath, 'utf8')); - } catch (error) { - removeInvalidRemoteConnectionState(options, error); - return null; + const file = readRecordFile(statePath); + if (file.kind === 'absent') return null; + if (file.kind === 'unknown') + throw recordOwnerUnknownError(options.session, statePath, file.cause); + // Ownership is settled before shape: a record another session owns is never removed as invalid. + if (file.session !== options.session) { + throw sessionMismatchError( + options.session, + statePath, + 'The saved connection belongs to a different session.', + ); } - if (!isRemoteConnectionState(parsed)) { - removeInvalidRemoteConnectionState(options); + if (!isRemoteConnectionState(file.record)) { + removeInvalidRemoteConnectionState(options, statePath); return null; } - if (parsed.session !== options.session) { - // Path resolution already sends a session whose name is taken by another session's record to its - // own hashed path, so reaching here means the record changed between resolving and reading it. - // Nothing is read, written, or removed under a name another session owns; the file is named so a - // caller can see what it is standing on. - throw new AppError('COMMAND_FAILED', 'The saved connection belongs to a different session.', { - reason: REMOTE_CONNECTION_STATE_REASONS.sessionMismatch.reason, - session: options.session, - recordPath: statePath, - hint: `Run disconnect --session ${parsed.session} to release that connection, or remove ${statePath}.`, - }); - } - return parsed; + return file.record; +} + +function sessionMismatchError(session: string, recordPath: string, message: string): AppError { + return new AppError('COMMAND_FAILED', message, { + reason: REMOTE_CONNECTION_STATE_REASONS.sessionMismatch.reason, + session, + recordPath, + hint: `Remove ${recordPath} only if no session needs the connection it holds.`, + }); +} + +function recordOwnerUnknownError(session: string, recordPath: string, cause: unknown): AppError { + return new AppError('COMMAND_FAILED', 'The saved connection file could not be read.', { + reason: REMOTE_CONNECTION_STATE_REASONS.ownerUnknown.reason, + session, + recordPath, + cause: cause instanceof Error ? cause.message : String(cause), + hint: `Make ${recordPath} readable, or remove it if no session needs it.`, + }); } export function writeRemoteConnectionState(options: { @@ -271,6 +285,7 @@ export function writeRemoteConnectionState(options: { onSessionRecordCommitted?: () => void; }): void { const location = { stateDir: options.stateDir, session: options.state.session }; + retireRecordAtActivePointer(options.stateDir, options.state.session); readRemoteConnectionState(location); const statePath = remoteConnectionStatePath(location); fs.mkdirSync(path.dirname(statePath), { recursive: true }); @@ -294,11 +309,14 @@ export function buildRemoteConnectionDaemonState( export function removeRemoteConnectionState(options: { stateDir: string; session: string }): void { readRemoteConnectionState(options); - removeRemoteConnectionStateFile(options); + removeRemoteConnectionStateFile(options, remoteConnectionStatePath(options)); } -function removeRemoteConnectionStateFile(options: { stateDir: string; session: string }): void { - fs.rmSync(remoteConnectionStatePath(options), { force: true }); +function removeRemoteConnectionStateFile( + options: { stateDir: string; session: string }, + statePath: string, +): void { + fs.rmSync(statePath, { force: true }); const activePath = activeConnectionStatePath(options.stateDir); const activeSession = readActiveConnectionSession(options.stateDir); if (activeSession === options.session) { @@ -539,85 +557,148 @@ export function hashRemoteConfigFile(configPath: string): string { /** The pointer to the machine-wide active session. It is not a session record and never names one. */ const ACTIVE_SESSION_FILE_NAME = '.active-session.json'; +/** A session name that is a file name on its own. It cannot start with `.`, so it never names the pointer. */ +const PLAIN_SESSION_NAME = /^[a-z0-9_-][a-z0-9._-]*$/; + /** - * Where a session's saved connection lives. + * Where a session's saved connection lives. The name alone decides it, and no two sessions share it. * - * Contents decide who owns a record; its file name never does. On a case-insensitive filesystem the - * file an older build wrote for `Demo` opens when `demo` asks for its own name, and trusting it would - * have `demo` read, overwrite, or delete a connection it does not own. So a session never resolves to - * a record that proves it belongs to another session: it resolves to the next path its own name - * answers for, finds no record there, and writes its own. The other session's file is left alone. + * A plain name is stored under itself. Any other name is stored under the SHA-256 of its UTF-16 code + * units, so names that differ only in case, or in lone surrogates, get different files. Neither form + * can be a case alias of another session's file or of the active-session pointer. * - * A name that is a filename on its own belongs to that name, and to its hashed path when a record - * there names another session. Any other name belongs to its hashed path, and to the sanitized path - * older builds used only while a record there names this session. + * Before resolving, records that older builds wrote under sanitized names move once to their owners' + * own paths. See {@link migrateLegacyRemoteConnectionState}. */ function remoteConnectionStatePath(options: { stateDir: string; session: string }): string { const recordsDir = path.join(options.stateDir, 'remote-connections'); - - // A name that cannot be a filename on its own — anything starting with `.`, or holding a - // separator — is stored by hash, so it can never take the active-session pointer's file either. - if (/^[a-z0-9_-][a-z0-9._-]*$/.test(options.session)) { - const plain = path.join(recordsDir, `${options.session}.json`); - const hashed = hashedRemoteConnectionStatePath(recordsDir, options.session); - // A session that once found another session's record on its plain path wrote under its hash. - // Keep finding that record after the other session's file is gone. - if (sessionNamedBy(hashed) === options.session) return hashed; - const recorded = sessionNamedBy(plain); - return recorded !== undefined && recorded !== options.session ? hashed : plain; + const canonical = canonicalRemoteConnectionStatePath(recordsDir, options.session); + const sources = new Set([canonical]); + const legacy = path.join(recordsDir, legacyRemoteConnectionFileName(options.session)); + sources.add(legacy); + const lowered = options.session.toLowerCase(); + if (PLAIN_SESSION_NAME.test(lowered)) sources.add(path.join(recordsDir, `${lowered}.json`)); + for (const source of sources) { + migrateLegacyRemoteConnectionState({ recordsDir, source, session: options.session }); } - - const canonical = hashedRemoteConnectionStatePath(recordsDir, options.session); - if (fs.existsSync(canonical)) return canonical; - - // Older records were named by sanitizing the session, so two names that differ only in case could - // share one file. Trust such a file only when its contents prove they name this session. - const legacy = legacyRemoteConnectionStatePath({ recordsDir, session: options.session }); - return legacy !== undefined && sessionNamedBy(legacy) === options.session ? legacy : canonical; + return canonical; } -function hashedRemoteConnectionStatePath(recordsDir: string, session: string): string { - return path.join(recordsDir, `~${connectionSessionIdentity(session)}.json`); +function canonicalRemoteConnectionStatePath(recordsDir: string, session: string): string { + if (PLAIN_SESSION_NAME.test(session)) return path.join(recordsDir, `${session}.json`); + const identity = crypto + .createHash('sha256') + .update(Buffer.from(session, 'utf16le')) + .digest('hex'); + return path.join(recordsDir, `~${identity}.json`); } /** - * The session the record at `statePath` names, or `undefined` when it is absent, unreadable, does not - * parse, or names none. Absence and an unreadable file answer alike: neither proves the record belongs - * to another session, so neither moves a session off the path its own name answers for. + * The file name a build that sanitized session names wrote for `session`. On a case-insensitive + * filesystem it also opens the file of any session whose name differs only in case. */ -function sessionNamedBy(statePath: string | undefined): string | undefined { - if (statePath === undefined) return undefined; +function legacyRemoteConnectionFileName(session: string): string { + const safe = session.replaceAll(/[^a-zA-Z0-9._-]/g, '_'); + if (safe === session) return `${safe}.json`; + const suffix = crypto.createHash('sha256').update(session).digest('hex').slice(0, 8); + return `${safe}-${suffix}.json`; +} + +type RecordFile = + | { kind: 'absent' } + /** The file exists but could not be read or parsed, or names no session: its owner is unknown. */ + | { kind: 'unknown'; cause: unknown } + | { kind: 'owned'; session: string; record: Record }; + +/** What the file at `filePath` holds. Only `ENOENT` means absent. */ +function readRecordFile(filePath: string): RecordFile { + let text: string; + try { + text = fs.readFileSync(filePath, 'utf8'); + } catch (error) { + return isMissingPathError(error) ? { kind: 'absent' } : { kind: 'unknown', cause: error }; + } let parsed: unknown; try { - parsed = JSON.parse(fs.readFileSync(statePath, 'utf8')); - } catch { - return undefined; + parsed = JSON.parse(text); + } catch (error) { + return { kind: 'unknown', cause: error }; + } + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + return { kind: 'unknown', cause: 'The file holds no JSON object.' }; } - if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return undefined; - const session = (parsed as { session?: unknown }).session; - return typeof session === 'string' ? session : undefined; + const record = parsed as Record; + return typeof record.session === 'string' + ? { kind: 'owned', session: record.session, record } + : { kind: 'unknown', cause: 'The file names no session.' }; } -/** - * The SHA-256 of a session name, hex. It is the file identity for a session whose name cannot be a - * filename on its own, so two names that differ only in case never share one record. - */ -export function connectionSessionIdentity(session: string): string { - return crypto.createHash('sha256').update(session).digest('hex'); +/** Whether a parsed file is an active-session pointer, which holds only the session it points at. */ +function isActiveSessionPointer(record: Record): boolean { + return Object.keys(record).every((key) => key === 'session'); } -/** Where a record written before per-session paths lived, or `undefined` when it aliased the pointer. */ -function legacyRemoteConnectionStatePath(options: { +/** + * Moves a record an older build left at `source` to its owner's own path, then removes `source`. + * + * The owner is the session the record names, and only when `source` is a name an older build wrote + * for that session, compared case-insensitively. A file whose owner is unknown or unproven is left + * in place. When the owner's own path is already taken by a different file, `source` is kept and the + * command is refused: one of the two records would otherwise be lost. + */ +function migrateLegacyRemoteConnectionState(options: { recordsDir: string; + source: string; session: string; -}): string | undefined { - const safe = options.session.replaceAll(/[^a-zA-Z0-9._-]/g, '_'); - const name = - safe === options.session - ? safe - : `${safe}-${connectionSessionIdentity(options.session).slice(0, 8)}`; - if (!name || `${name}.json` === ACTIVE_SESSION_FILE_NAME) return undefined; - return path.join(options.recordsDir, `${name}.json`); +}): void { + const file = readRecordFile(options.source); + if (file.kind !== 'owned' || isActiveSessionPointer(file.record)) return; + const target = canonicalRemoteConnectionStatePath(options.recordsDir, file.session); + const sourceName = path.basename(options.source).toLowerCase(); + // Canonical names hold no upper-case letters, so a name that folds onto the target IS the target. + if (path.basename(target) === sourceName) return; + if (legacyRemoteConnectionFileName(file.session).toLowerCase() !== sourceName) return; + try { + fs.linkSync(options.source, target); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error; + if (!isSameFile(options.source, target)) { + throw sessionMismatchError( + options.session, + options.source, + 'An older saved connection cannot move to its session file, because that file already exists.', + ); + } + } + fs.rmSync(options.source, { force: true }); +} + +function isSameFile(left: string, right: string): boolean { + const a = fs.statSync(left); + const b = fs.statSync(right); + return a.dev === b.dev && a.ino === b.ino; +} + +/** + * Keeps a full record an older build wrote at the active-session pointer path, or at a case alias of + * it, from being replaced by the next pointer write. A record whose owner is proven moves to that + * owner's own path first. A file whose owner is unknown refuses the write. + */ +function retireRecordAtActivePointer(stateDir: string, session: string): void { + const recordsDir = path.join(stateDir, 'remote-connections'); + const activePath = activeConnectionStatePath(stateDir); + const file = readRecordFile(activePath); + if (file.kind === 'absent') return; + if (file.kind === 'unknown') throw recordOwnerUnknownError(session, activePath, file.cause); + if (isActiveSessionPointer(file.record)) return; + migrateLegacyRemoteConnectionState({ recordsDir, source: activePath, session }); + if (fs.existsSync(activePath)) { + throw sessionMismatchError( + session, + activePath, + 'The active-session pointer path holds a saved connection whose owner is unproven.', + ); + } } function activeConnectionStatePath(stateDir: string): string { @@ -696,19 +777,17 @@ function sanitizeDaemonBaseUrl(value: string | undefined): string | undefined { return url.toString().replace(/\/+$/, ''); } +/** Removes a record that names this session but fails validation. Callers prove ownership first. */ function removeInvalidRemoteConnectionState( options: { stateDir: string; session: string }, - error?: unknown, + statePath: string, ): void { emitDiagnostic({ level: 'warn', phase: 'remote_connection_state_invalid', - data: { - session: options.session, - cause: error instanceof Error ? error.message : error ? String(error) : undefined, - }, + data: { session: options.session }, }); - removeRemoteConnectionStateFile(options); + removeRemoteConnectionStateFile(options, statePath); } function isRemoteConnectionState(value: unknown): value is RemoteConnectionState { diff --git a/src/__tests__/cli-config.test.ts b/src/__tests__/cli-config.test.ts index 28d81e1fb6..3339adfc68 100644 --- a/src/__tests__/cli-config.test.ts +++ b/src/__tests__/cli-config.test.ts @@ -1138,7 +1138,7 @@ test('disconnect cleans connection state when remote config file is gone', async fs.rmSync(root, { recursive: true, force: true }); }); -test('disconnect removes malformed connection state', async () => { +test('disconnect refuses and keeps a connection state file that does not parse', async () => { const { root, home, project } = makeTempWorkspace(); const stateDir = path.join(root, 'state'); const connectionsDir = path.join(stateDir, 'remote-connections'); @@ -1153,10 +1153,12 @@ test('disconnect removes malformed connection state', async () => { env: { HOME: home }, }); - assert.equal(disconnected.code, null); + // No session can be shown to own an unparseable file, so it is never removed. + assert.equal(disconnected.code, 1); assert.equal(disconnected.calls.length, 0); - assert.equal(fs.existsSync(statePath), false); - assert.equal(fs.existsSync(activePath), false); + assert.match(disconnected.stdout, /connection_record_owner_unknown/); + assert.equal(fs.readFileSync(statePath, 'utf8'), '{not json'); + assert.equal(fs.existsSync(activePath), true); fs.rmSync(root, { recursive: true, force: true }); }); diff --git a/src/cli/commands/connection-case-variant-session.test.ts b/src/cli/commands/connection-case-variant-session.test.ts index ad46aa0bd4..00e9dbb96d 100644 --- a/src/cli/commands/connection-case-variant-session.test.ts +++ b/src/cli/commands/connection-case-variant-session.test.ts @@ -3,7 +3,10 @@ import assert from 'node:assert/strict'; import fs from 'node:fs'; import path from 'node:path'; import { withCapturedStdoutAsync } from '@agent-device/test-kit'; -import { hashRemoteConfigFile } from '@agent-device/remote/remote-connection-state'; +import { + hashRemoteConfigFile, + readRemoteConnectionState, +} from '@agent-device/remote/remote-connection-state'; import { connectionWorkspace, createTestClient, @@ -75,7 +78,7 @@ for (const [name, run] of [ 'agent-device-connection-case-variant-', ); fs.writeFileSync(remoteConfigPath, '{}'); - const sharedPath = plantRecordSharedByCaseVariants({ + plantRecordSharedByCaseVariants({ stateDir, remoteConfigPath, session: 'Demo', @@ -93,10 +96,10 @@ for (const [name, run] of [ const payload = JSON.parse(stdout).data; assert.equal(payload.connected, false); assert.equal(payload.session, 'demo'); - assert.deepEqual( - JSON.parse(fs.readFileSync(sharedPath, 'utf8')).session, - 'Demo', - 'answering for one session leaves the record the other one owns in place', + assert.equal( + readRemoteConnectionState({ stateDir, session: 'Demo' })?.runId, + 'run-Demo', + 'answering for one session keeps the record the other one owns', ); fs.rmSync(tempRoot, { recursive: true, force: true }); }); From 2e7a7c9c1ded0578d85a3c40f7a8852f0fad85b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 22 Nov 2026 09:19:40 +0100 Subject: [PATCH 07/22] chore(gates): drop the unused-export exemption for the removed session identity export --- .fallowrc.json | 8 -------- 1 file changed, 8 deletions(-) diff --git a/.fallowrc.json b/.fallowrc.json index b8fa753135..10904eb4da 100644 --- a/.fallowrc.json +++ b/.fallowrc.json @@ -280,14 +280,6 @@ "file": "packages/maestro/src/internal/program-ir-command-parser.ts", "exports": ["SUPPORTED_MAESTRO_COMMAND_NAMES"] }, - { - // The hash a session's saved-connection file name is built from. Production derives it inside - // remote-connection-state.ts when it resolves that file path and reaches no in-repo consumer of - // the export; it is published so a caller can name a session's record path. The package test - // recomputes it on purpose, so an accidental change to the identity breaks the test. - "file": "packages/remote/src/remote-connection-state.ts", - "exports": ["connectionSessionIdentity"] - }, { // Linux package façade loader is a named external seam. Its dynamic property read is not visible to --production analysis. "file": "packages/platform-linux/src/index.ts", From 2e784e6b87b63c7788192fac4db085ed4048d96d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 22 Nov 2026 09:24:20 +0100 Subject: [PATCH 08/22] test(remote): ignore the fixture's second hard-link name on case-sensitive volumes --- .../src/remote-connection-state-session-identity.test.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/remote/src/remote-connection-state-session-identity.test.ts b/packages/remote/src/remote-connection-state-session-identity.test.ts index 8a38884c46..fd4edf31a0 100644 --- a/packages/remote/src/remote-connection-state-session-identity.test.ts +++ b/packages/remote/src/remote-connection-state-session-identity.test.ts @@ -213,7 +213,12 @@ test('a record an older build shared with a case-variant session moves to its ow null, 'the record an older build wrote for Demo is not the demo session connection', ); - assert.deepEqual(recordsIn(stateDir), [hashedFileName('Demo')]); + // On a case-sensitive volume the fixture's hard link leaves `Demo.json` as a second name of the + // moved record. Only the Demo session retires that name, so ignore it here. + assert.deepEqual( + recordsIn(stateDir).filter((name) => name !== 'Demo.json'), + [hashedFileName('Demo')], + ); writeRemoteConnectionState({ stateDir, state: recordFor('demo') }); assert.equal(readRemoteConnectionState({ stateDir, session: 'demo' })?.runId, 'run-demo'); From e0b79c94c34770a1f56818c75a2b2e945d85b504 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 22 Nov 2026 09:33:31 +0100 Subject: [PATCH 09/22] docs(commands): name the refusal for an unreadable saved connection and its recovery --- website/docs/docs/commands.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 7a99b1b7dd..3384808437 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -2600,6 +2600,8 @@ Exact behavior: `agent-device help disconnect`. +If a saved connection file cannot be read or parsed, agent-device keeps it and refuses `connect`, `connection status`, and `disconnect` for that session with `connection_record_owner_unknown`. The error names the file. Make it readable, or remove it if no session needs it. + Manage cloud login state. From 1f83288c2ae1a8df59f3f2cb2922acd5157dd046 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 22 Nov 2026 10:08:24 +0100 Subject: [PATCH 10/22] fix(remote): find an empty session's older record and read older records in a read-only directory --- ...-connection-state-session-identity.test.ts | 25 ++++++++++++ .../remote/src/remote-connection-state.ts | 38 +++++++++++++++---- website/docs/docs/commands.md | 2 +- 3 files changed, 57 insertions(+), 8 deletions(-) diff --git a/packages/remote/src/remote-connection-state-session-identity.test.ts b/packages/remote/src/remote-connection-state-session-identity.test.ts index fd4edf31a0..4a073feb50 100644 --- a/packages/remote/src/remote-connection-state-session-identity.test.ts +++ b/packages/remote/src/remote-connection-state-session-identity.test.ts @@ -373,3 +373,28 @@ test('the last guard names the record it refused and how to clear it', () => { 'a refused disconnect must not delete the record it would have overwritten', ); }); + +test('an empty session finds the record an older build saved for it as default.json', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-empty-'); + writeRecordFile(stateDir, 'default.json', recordFor('')); + + assert.equal(readRemoteConnectionState({ stateDir, session: '' })?.runId, 'run-'); + assert.deepEqual(recordsIn(stateDir), [hashedFileName('')]); +}); + +test.skipIf(runsAsRoot)( + 'a read-only records directory still reports an older record of the exact session', + () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-readonly-'); + writeRecordFile(stateDir, 'Demo.json', recordFor('Demo')); + const recordsDir = path.join(stateDir, RECORDS_DIR); + fs.chmodSync(recordsDir, 0o500); + try { + assert.equal(readRemoteConnectionState({ stateDir, session: 'Demo' })?.runId, 'run-Demo'); + assert.throws(() => removeRemoteConnectionState({ stateDir, session: 'Demo' })); + assert.deepEqual(recordsIn(stateDir), ['Demo.json']); + } finally { + fs.chmodSync(recordsDir, 0o700); + } + }, +); diff --git a/packages/remote/src/remote-connection-state.ts b/packages/remote/src/remote-connection-state.ts index 13ecffd6ad..3ad0e02a67 100644 --- a/packages/remote/src/remote-connection-state.ts +++ b/packages/remote/src/remote-connection-state.ts @@ -223,11 +223,13 @@ type RemoteConnectionDefaults = { }; const REMOTE_CONNECTION_STATE_REASONS = { - // A command named one session and the saved connection it reached names another, so nothing about - // that connection was read, replaced, or removed. + // A saved connection file cannot be used for the session a command named: it names another session, + // a record from an older build cannot move to its session file because that file already exists, or + // the active-session pointer path holds a record whose owner is unproven. No file was replaced or + // removed. sessionMismatch: { reason: 'connection_session_mismatch' }, - // A saved connection file could not be read or parsed, so no session is known to own it, and it was - // neither replaced nor removed. + // The session's own saved connection file, or the active-session pointer, could not be read or + // parsed, so no session is known to own it. It was neither replaced nor removed. ownerUnknown: { reason: 'connection_record_owner_unknown' }, } as const satisfies ReasonTable<'remote connections'>; @@ -235,7 +237,7 @@ export function readRemoteConnectionState(options: { stateDir: string; session: string; }): RemoteConnectionState | null { - const statePath = remoteConnectionStatePath(options); + const statePath = remoteConnectionStatePath({ ...options, readOnlyFallback: true }); const file = readRecordFile(statePath); if (file.kind === 'absent') return null; if (file.kind === 'unknown') @@ -570,7 +572,15 @@ const PLAIN_SESSION_NAME = /^[a-z0-9_-][a-z0-9._-]*$/; * Before resolving, records that older builds wrote under sanitized names move once to their owners' * own paths. See {@link migrateLegacyRemoteConnectionState}. */ -function remoteConnectionStatePath(options: { stateDir: string; session: string }): string { +function remoteConnectionStatePath(options: { + stateDir: string; + session: string; + /** + * A read may use a record an older build wrote for this exact session in place when the directory + * refuses the move. A save or removal must move it first. + */ + readOnlyFallback?: boolean; +}): string { const recordsDir = path.join(options.stateDir, 'remote-connections'); const canonical = canonicalRemoteConnectionStatePath(recordsDir, options.session); const sources = new Set([canonical]); @@ -579,7 +589,15 @@ function remoteConnectionStatePath(options: { stateDir: string; session: string const lowered = options.session.toLowerCase(); if (PLAIN_SESSION_NAME.test(lowered)) sources.add(path.join(recordsDir, `${lowered}.json`)); for (const source of sources) { - migrateLegacyRemoteConnectionState({ recordsDir, source, session: options.session }); + try { + migrateLegacyRemoteConnectionState({ recordsDir, source, session: options.session }); + } catch (error) { + if (!options.readOnlyFallback || !isWriteRefusedError(error)) throw error; + if (fs.existsSync(canonical)) throw error; + const file = readRecordFile(source); + if (file.kind === 'owned' && file.session === options.session) return source; + throw error; + } } return canonical; } @@ -598,6 +616,7 @@ function canonicalRemoteConnectionStatePath(recordsDir: string, session: string) * filesystem it also opens the file of any session whose name differs only in case. */ function legacyRemoteConnectionFileName(session: string): string { + if (session === '') return 'default.json'; const safe = session.replaceAll(/[^a-zA-Z0-9._-]/g, '_'); if (safe === session) return `${safe}.json`; const suffix = crypto.createHash('sha256').update(session).digest('hex').slice(0, 8); @@ -673,6 +692,11 @@ function migrateLegacyRemoteConnectionState(options: { fs.rmSync(options.source, { force: true }); } +function isWriteRefusedError(error: unknown): boolean { + const code = (error as NodeJS.ErrnoException | undefined)?.code; + return code === 'EACCES' || code === 'EPERM' || code === 'EROFS'; +} + function isSameFile(left: string, right: string): boolean { const a = fs.statSync(left); const b = fs.statSync(right); diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 3384808437..205b97b0a3 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -2600,7 +2600,7 @@ Exact behavior: `agent-device help disconnect`. -If a saved connection file cannot be read or parsed, agent-device keeps it and refuses `connect`, `connection status`, and `disconnect` for that session with `connection_record_owner_unknown`. The error names the file. Make it readable, or remove it if no session needs it. +If a session's own saved connection file cannot be read or parsed, agent-device keeps it and refuses every command that uses that session's saved connection with `connection_record_owner_unknown`. An unreadable active-session pointer refuses `connect` the same way. The error names the file. Make it readable, or remove it if no session needs it. A file from an older build whose owner cannot be proven is left in place and is not used. If an older file cannot move to its session's own file because that file already exists, the command refuses with `connection_session_mismatch`, also when both files name the same session. From 8706c9276f1c8513d3625702d56a1bb3081ede15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 22 Nov 2026 11:12:23 +0100 Subject: [PATCH 11/22] fix(remote): keep connection status read-only and stop following a non-pointer or an empty-session flag Status now uses an observation lookup that never migrates, links, or deletes: it reports a verified older record in place and an invalid record as no connection. Saves and removals always migrate first, so a refused hard link never lets invalid-record cleanup reach an unmigrated legacy path such as default.json. An empty-string pointer session resolves, --session= no longer follows the active pointer, and only a pointer-shaped file is used or removed as the pointer. --- ...-connection-state-session-identity.test.ts | 87 +++++++++- .../remote/src/remote-connection-state.ts | 163 ++++++++++++------ .../commands/connection-empty-session.test.ts | 44 +++++ src/cli/commands/connection.ts | 30 +++- 4 files changed, 264 insertions(+), 60 deletions(-) create mode 100644 src/cli/commands/connection-empty-session.test.ts diff --git a/packages/remote/src/remote-connection-state-session-identity.test.ts b/packages/remote/src/remote-connection-state-session-identity.test.ts index 4a073feb50..853dc38e6d 100644 --- a/packages/remote/src/remote-connection-state-session-identity.test.ts +++ b/packages/remote/src/remote-connection-state-session-identity.test.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest'; +import { test, vi } from 'vitest'; import assert from 'node:assert/strict'; import crypto from 'node:crypto'; import fs from 'node:fs'; @@ -6,6 +6,8 @@ import path from 'node:path'; import { AppError } from '@agent-device/kernel/errors'; import { mkdtempForTestSync } from '@agent-device/test-kit'; import { + observeActiveConnectionState, + observeRemoteConnectionState, readRemoteConnectionState, removeRemoteConnectionState, writeRemoteConnectionState, @@ -293,7 +295,7 @@ test('an invalid record of the U+D800 session survives a U+D801 status read', () updatedAt: null, }); - assert.equal(readRemoteConnectionState({ stateDir, session: '\uD801' }), null); + assert.equal(observeRemoteConnectionState({ stateDir, session: '\uD801' }), null); assert.equal(fs.existsSync(recordPath), true); }); @@ -383,18 +385,93 @@ test('an empty session finds the record an older build saved for it as default.j }); test.skipIf(runsAsRoot)( - 'a read-only records directory still reports an older record of the exact session', + 'a read-only records directory reports an older record of the exact session and refuses its removal', () => { const stateDir = mkdtempForTestSync('agent-device-remote-identity-readonly-'); writeRecordFile(stateDir, 'Demo.json', recordFor('Demo')); const recordsDir = path.join(stateDir, RECORDS_DIR); fs.chmodSync(recordsDir, 0o500); try { - assert.equal(readRemoteConnectionState({ stateDir, session: 'Demo' })?.runId, 'run-Demo'); - assert.throws(() => removeRemoteConnectionState({ stateDir, session: 'Demo' })); + assert.equal(observeRemoteConnectionState({ stateDir, session: 'Demo' })?.runId, 'run-Demo'); + assert.throws(() => removeRemoteConnectionState({ stateDir, session: 'Demo' }), { + code: 'EACCES', + }); assert.deepEqual(recordsIn(stateDir), ['Demo.json']); } finally { fs.chmodSync(recordsDir, 0o700); } }, ); + +test('status on a valid older Demo.json reports it and leaves the directory unchanged', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-observe-legacy-'); + writeRecordFile(stateDir, 'Demo.json', recordFor('Demo')); + writeRecordFile(stateDir, 'default.json', recordFor('')); + + assert.equal(observeRemoteConnectionState({ stateDir, session: 'Demo' })?.runId, 'run-Demo'); + assert.equal(observeRemoteConnectionState({ stateDir, session: '' })?.runId, 'run-'); + assert.equal(observeRemoteConnectionState({ stateDir, session: 'default' }), null); + assert.deepEqual(recordsIn(stateDir), ['Demo.json', 'default.json'], 'status moved no file'); +}); + +test('status on an invalid record that names the session leaves it and its pointer in place', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-observe-invalid-'); + writeRecordFile(stateDir, 'demo.json', { ...recordFor('demo'), updatedAt: null }); + writeRecordFile(stateDir, 'Team.json', { ...recordFor('Team'), updatedAt: null }); + writeRecordFile(stateDir, ACTIVE_SESSION_FILE, { session: 'demo' }); + + assert.equal(observeRemoteConnectionState({ stateDir, session: 'demo' }), null); + assert.equal(observeActiveConnectionState({ stateDir }), null); + assert.equal(observeRemoteConnectionState({ stateDir, session: 'Team' }), null); + assert.deepEqual(recordsIn(stateDir), [ACTIVE_SESSION_FILE, 'Team.json', 'demo.json'].sort()); +}); + +test('an EPERM hard-link failure never deletes default.json', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-eperm-'); + // The empty session's older record, which fails validation, at the literal `default` session path. + const legacyPath = writeRecordFile(stateDir, 'default.json', { + ...recordFor(''), + updatedAt: null, + }); + const link = vi.spyOn(fs, 'linkSync').mockImplementation(() => { + throw Object.assign(new Error('EPERM: operation not permitted, link'), { code: 'EPERM' }); + }); + try { + assert.throws(() => removeRemoteConnectionState({ stateDir, session: '' }), { + code: 'EPERM', + }); + assert.throws(() => writeRemoteConnectionState({ stateDir, state: recordFor('') }), { + code: 'EPERM', + }); + } finally { + link.mockRestore(); + } + assert.equal(fs.existsSync(legacyPath), true); +}); + +test('an empty-session pointer resolves for unnamed status', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-empty-pointer-'); + writeRecordFile(stateDir, hashedFileName(''), recordFor('')); + writeRecordFile(stateDir, ACTIVE_SESSION_FILE, { session: '' }); + + assert.equal(observeActiveConnectionState({ stateDir })?.runId, 'run-'); +}); + +test('a full record at the pointer path is not deleted by disconnect of the session it names', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-pointer-record-'); + writeRemoteConnectionState({ stateDir, state: recordFor('demo') }); + const pointerPath = writeRecordFile(stateDir, ACTIVE_SESSION_FILE, { + ...recordFor('demo'), + runId: 'run-at-pointer', + }); + + assert.equal( + observeActiveConnectionState({ stateDir }), + null, + 'a full record is not a pointer, so unnamed status selects no session from it', + ); + removeRemoteConnectionState({ stateDir, session: 'demo' }); + + assert.equal(JSON.parse(fs.readFileSync(pointerPath, 'utf8')).runId, 'run-at-pointer'); + assert.deepEqual(recordsIn(stateDir), [ACTIVE_SESSION_FILE]); +}); diff --git a/packages/remote/src/remote-connection-state.ts b/packages/remote/src/remote-connection-state.ts index 3ad0e02a67..373e9e8506 100644 --- a/packages/remote/src/remote-connection-state.ts +++ b/packages/remote/src/remote-connection-state.ts @@ -225,19 +225,26 @@ type RemoteConnectionDefaults = { const REMOTE_CONNECTION_STATE_REASONS = { // A saved connection file cannot be used for the session a command named: it names another session, // a record from an older build cannot move to its session file because that file already exists, or - // the active-session pointer path holds a record whose owner is unproven. No file was replaced or - // removed. + // the active-session pointer path holds a record whose owner is unproven. The files that the refusal + // names are kept: the refused file, and the occupied session file it could not move to. sessionMismatch: { reason: 'connection_session_mismatch' }, // The session's own saved connection file, or the active-session pointer, could not be read or // parsed, so no session is known to own it. It was neither replaced nor removed. ownerUnknown: { reason: 'connection_record_owner_unknown' }, } as const satisfies ReasonTable<'remote connections'>; +/** + * The saved connection `session` owns, for a command that saves or removes it next. + * + * Records an older build wrote for the session move to its own path first, and a record that names + * the session but fails validation is removed. A command that only reports the connection uses + * {@link observeRemoteConnectionState}, which changes no file. + */ export function readRemoteConnectionState(options: { stateDir: string; session: string; }): RemoteConnectionState | null { - const statePath = remoteConnectionStatePath({ ...options, readOnlyFallback: true }); + const statePath = remoteConnectionStatePath(options); const file = readRecordFile(statePath); if (file.kind === 'absent') return null; if (file.kind === 'unknown') @@ -257,6 +264,61 @@ export function readRemoteConnectionState(options: { return file.record; } +/** + * The saved connection `session` owns, read without a change to any file. + * + * A record an older build wrote for exactly this session is reported where it is. A record that names + * the session but fails validation is reported as no connection and is kept. + */ +export function observeRemoteConnectionState(options: { + stateDir: string; + session: string; +}): RemoteConnectionState | null { + const recordsDir = path.join(options.stateDir, 'remote-connections'); + const canonical = canonicalRemoteConnectionStatePath(recordsDir, options.session); + const file = readRecordFile(canonical); + if (file.kind === 'unknown') { + throw recordOwnerUnknownError(options.session, canonical, file.cause); + } + // A record that another session's older build left at this path moves away on the next save. + if (file.kind === 'owned' && !isMovableLegacyRecord(recordsDir, canonical, file)) { + if (file.session !== options.session) { + throw sessionMismatchError( + options.session, + canonical, + 'The saved connection belongs to a different session.', + ); + } + return observedRemoteConnectionState(options.session, canonical, file.record); + } + for (const source of remoteConnectionStateSources(recordsDir, options.session)) { + if (source === canonical) continue; + const legacy = readRecordFile(source); + if ( + legacy.kind === 'owned' && + legacy.session === options.session && + isMovableLegacyRecord(recordsDir, source, legacy) + ) { + return observedRemoteConnectionState(options.session, source, legacy.record); + } + } + return null; +} + +function observedRemoteConnectionState( + session: string, + recordPath: string, + record: Record, +): RemoteConnectionState | null { + if (isRemoteConnectionState(record)) return record; + emitDiagnostic({ + level: 'warn', + phase: 'remote_connection_state_invalid', + data: { session, recordPath }, + }); + return null; +} + function sessionMismatchError(session: string, recordPath: string, message: string): AppError { return new AppError('COMMAND_FAILED', message, { reason: REMOTE_CONNECTION_STATE_REASONS.sessionMismatch.reason, @@ -572,34 +634,21 @@ const PLAIN_SESSION_NAME = /^[a-z0-9_-][a-z0-9._-]*$/; * Before resolving, records that older builds wrote under sanitized names move once to their owners' * own paths. See {@link migrateLegacyRemoteConnectionState}. */ -function remoteConnectionStatePath(options: { - stateDir: string; - session: string; - /** - * A read may use a record an older build wrote for this exact session in place when the directory - * refuses the move. A save or removal must move it first. - */ - readOnlyFallback?: boolean; -}): string { +function remoteConnectionStatePath(options: { stateDir: string; session: string }): string { const recordsDir = path.join(options.stateDir, 'remote-connections'); - const canonical = canonicalRemoteConnectionStatePath(recordsDir, options.session); - const sources = new Set([canonical]); - const legacy = path.join(recordsDir, legacyRemoteConnectionFileName(options.session)); - sources.add(legacy); - const lowered = options.session.toLowerCase(); - if (PLAIN_SESSION_NAME.test(lowered)) sources.add(path.join(recordsDir, `${lowered}.json`)); - for (const source of sources) { - try { - migrateLegacyRemoteConnectionState({ recordsDir, source, session: options.session }); - } catch (error) { - if (!options.readOnlyFallback || !isWriteRefusedError(error)) throw error; - if (fs.existsSync(canonical)) throw error; - const file = readRecordFile(source); - if (file.kind === 'owned' && file.session === options.session) return source; - throw error; - } + for (const source of remoteConnectionStateSources(recordsDir, options.session)) { + migrateLegacyRemoteConnectionState({ recordsDir, source, session: options.session }); } - return canonical; + return canonicalRemoteConnectionStatePath(recordsDir, options.session); +} + +/** The paths a record `session` owns can be at: its own path first, then the names older builds wrote. */ +function remoteConnectionStateSources(recordsDir: string, session: string): Set { + const sources = new Set([canonicalRemoteConnectionStatePath(recordsDir, session)]); + sources.add(path.join(recordsDir, legacyRemoteConnectionFileName(session))); + const lowered = session.toLowerCase(); + if (PLAIN_SESSION_NAME.test(lowered)) sources.add(path.join(recordsDir, `${lowered}.json`)); + return sources; } function canonicalRemoteConnectionStatePath(recordsDir: string, session: string): string { @@ -671,12 +720,10 @@ function migrateLegacyRemoteConnectionState(options: { session: string; }): void { const file = readRecordFile(options.source); - if (file.kind !== 'owned' || isActiveSessionPointer(file.record)) return; + if (file.kind !== 'owned' || !isMovableLegacyRecord(options.recordsDir, options.source, file)) { + return; + } const target = canonicalRemoteConnectionStatePath(options.recordsDir, file.session); - const sourceName = path.basename(options.source).toLowerCase(); - // Canonical names hold no upper-case letters, so a name that folds onto the target IS the target. - if (path.basename(target) === sourceName) return; - if (legacyRemoteConnectionFileName(file.session).toLowerCase() !== sourceName) return; try { fs.linkSync(options.source, target); } catch (error) { @@ -692,9 +739,18 @@ function migrateLegacyRemoteConnectionState(options: { fs.rmSync(options.source, { force: true }); } -function isWriteRefusedError(error: unknown): boolean { - const code = (error as NodeJS.ErrnoException | undefined)?.code; - return code === 'EACCES' || code === 'EPERM' || code === 'EROFS'; +/** + * Whether `file` is a record an older build left at `source` for the session it names: `source` is a + * name an older build wrote for that session, compared case-insensitively, and not its own path. + */ +function isMovableLegacyRecord(recordsDir: string, source: string, file: RecordFile): boolean { + if (file.kind !== 'owned' || isActiveSessionPointer(file.record)) return false; + const sourceName = path.basename(source).toLowerCase(); + // Canonical names hold no upper-case letters, so a name that folds onto the target IS the target. + if (path.basename(canonicalRemoteConnectionStatePath(recordsDir, file.session)) === sourceName) { + return false; + } + return legacyRemoteConnectionFileName(file.session).toLowerCase() === sourceName; } function isSameFile(left: string, right: string): boolean { @@ -733,23 +789,28 @@ export function readActiveConnectionState(options: { stateDir: string; }): RemoteConnectionState | null { const session = readActiveConnectionSession(options.stateDir); - return session - ? readRemoteConnectionState({ - stateDir: options.stateDir, - session, - }) - : null; + return session === undefined + ? null + : readRemoteConnectionState({ stateDir: options.stateDir, session }); +} + +/** The connection the active-session pointer names, read without a change to any file. */ +export function observeActiveConnectionState(options: { + stateDir: string; +}): RemoteConnectionState | null { + const session = readActiveConnectionSession(options.stateDir); + return session === undefined + ? null + : observeRemoteConnectionState({ stateDir: options.stateDir, session }); } +/** + * The session the active-session pointer names. A file at the pointer path that is not a pointer, such + * as a full record an older build wrote there, names no session. + */ function readActiveConnectionSession(stateDir: string): string | undefined { - const activePath = activeConnectionStatePath(stateDir); - if (!fs.existsSync(activePath)) return undefined; - try { - const parsed = JSON.parse(fs.readFileSync(activePath, 'utf8')) as Record; - return typeof parsed.session === 'string' ? parsed.session : undefined; - } catch { - return undefined; - } + const file = readRecordFile(activeConnectionStatePath(stateDir)); + return file.kind === 'owned' && isActiveSessionPointer(file.record) ? file.session : undefined; } export function fingerprint(value: string | undefined): string | undefined { diff --git a/src/cli/commands/connection-empty-session.test.ts b/src/cli/commands/connection-empty-session.test.ts new file mode 100644 index 0000000000..83f17b40be --- /dev/null +++ b/src/cli/commands/connection-empty-session.test.ts @@ -0,0 +1,44 @@ +import { test } from 'vitest'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import { withCapturedStdoutAsync } from '@agent-device/test-kit'; +import { readRemoteConnectionState } from '@agent-device/remote/remote-connection-state'; +import { + connectionWorkspace, + createTestClient, + seedConnectionState, +} from '../../__tests__/remote-connection.fixtures.ts'; +import { disconnectCommand } from '../../__tests__/test-utils/host-bound-commands.ts'; + +// `--session=` names the empty session. Read as an omitted session, it followed the active-session +// pointer, so `disconnect --session=` removed the connection the pointer named for another session. + +test('disconnect --session= with no empty-session record keeps the record the pointer names', async () => { + const { tempRoot, stateDir, remoteConfigPath } = connectionWorkspace( + 'agent-device-connection-empty-session-', + ); + fs.writeFileSync(remoteConfigPath, '{}'); + seedConnectionState({ + stateDir, + state: { session: 'Demo', remoteConfigPath, tenant: 'acme', runId: 'run-Demo' }, + }); + + const stdout = await withCapturedStdoutAsync(async () => { + // Every call this client answers throws: the command may not reach the daemon. + await disconnectCommand({ + positionals: [], + flags: { json: true, help: false, version: false, stateDir, session: '' }, + client: createTestClient(), + }); + }); + + const payload = JSON.parse(stdout).data; + assert.equal(payload.connected, false); + assert.equal(payload.session, ''); + assert.equal( + readRemoteConnectionState({ stateDir, session: 'Demo' })?.runId, + 'run-Demo', + 'disconnecting the empty session keeps the record of the session the pointer names', + ); + fs.rmSync(tempRoot, { recursive: true, force: true }); +}); diff --git a/src/cli/commands/connection.ts b/src/cli/commands/connection.ts index 9ebcafac2a..e1d87cda14 100644 --- a/src/cli/commands/connection.ts +++ b/src/cli/commands/connection.ts @@ -3,6 +3,8 @@ import type { CloudProviderSessionResult } from '@agent-device/contracts/observa import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution'; import { resolveRemoteConfigProfile } from '@agent-device/remote/remote-config'; import { + observeActiveConnectionState, + observeRemoteConnectionState, readActiveConnectionState, requireLeasedConnectionSession, sessionLeaseScope, @@ -336,7 +338,7 @@ function scopeConnectProfile( } export const disconnectCommand: ClientCommandHandler = async ({ flags, client, host }) => { - const { session, stateDir, state } = readRequestedConnectionState(flags, host); + const { session, stateDir, state } = readRequestedConnectionState(flags, host, CHANGE_LOOKUP); if (!state) { await writeNoRemoteConnectionOutput(flags, session); return true; @@ -390,7 +392,7 @@ export const connectionCommand: ClientCommandHandler = async ({ positionals, fla if (positionals[0] !== 'status') { throw new AppError('INVALID_ARGS', 'connection accepts only: status'); } - const { session, state } = readRequestedConnectionState(flags, host); + const { session, state } = readRequestedConnectionState(flags, host, OBSERVE_LOOKUP); if (!state) { await writeNoRemoteConnectionOutput(flags, session); return true; @@ -470,9 +472,27 @@ function readConnectProvider( ); } +type ConnectionStateLookup = { + session: (options: { stateDir: string; session: string }) => RemoteConnectionState | null; + active: (options: { stateDir: string }) => RemoteConnectionState | null; +}; + +/** For a command that removes or rewrites the saved connection it reads. */ +const CHANGE_LOOKUP: ConnectionStateLookup = { + session: readRemoteConnectionState, + active: readActiveConnectionState, +}; + +/** For a command that only reports the saved connection: it changes no file. */ +const OBSERVE_LOOKUP: ConnectionStateLookup = { + session: observeRemoteConnectionState, + active: observeActiveConnectionState, +}; + function readRequestedConnectionState( flags: CliFlags, host: HostEnvironment, + lookup: ConnectionStateLookup, ): { session: string; stateDir: string; @@ -483,9 +503,11 @@ function readRequestedConnectionState( cwd: host.cwd, env: host.env, }).baseDir; + // Only a caller that named no session follows the active-session pointer. `--session=` names the + // empty session. const state = - readRemoteConnectionState({ stateDir, session }) ?? - (flags.session ? null : readActiveConnectionState({ stateDir })); + lookup.session({ stateDir, session }) ?? + (flags.session === undefined ? lookup.active({ stateDir }) : null); if (state) requireLeasedConnectionSession(state, flags.session); return { session, stateDir, state }; } From d888c17383ae3a0b6a0de973a0530f6355e33a8f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 22 Nov 2026 11:12:23 +0100 Subject: [PATCH 12/22] docs(commands): scope the saved-connection refusals to the files they name --- website/docs/docs/commands.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 205b97b0a3..1d6617a7c4 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -2600,7 +2600,7 @@ Exact behavior: `agent-device help disconnect`. -If a session's own saved connection file cannot be read or parsed, agent-device keeps it and refuses every command that uses that session's saved connection with `connection_record_owner_unknown`. An unreadable active-session pointer refuses `connect` the same way. The error names the file. Make it readable, or remove it if no session needs it. A file from an older build whose owner cannot be proven is left in place and is not used. If an older file cannot move to its session's own file because that file already exists, the command refuses with `connection_session_mismatch`, also when both files name the same session. +If agent-device cannot read or parse a file and so cannot establish which session owns it, it keeps that file and refuses with `connection_record_owner_unknown`. A session's own saved connection file that cannot be read refuses every command that uses that session's saved connection. An unreadable active-session pointer refuses `connect` and any command that rewrites the saved connection. The error names the file. Make it readable, or remove it if no session needs it. A file from an older build whose owner cannot be proven is left in place and is not used. If an older file cannot move to its session's own file because that file already exists, the command that moves it refuses with `connection_session_mismatch`. This is also true when both files name the same session, and when the occupied file cannot be read. `connection status` changes no file. It reports an older build's file for the session where that file is, and it reports a file that fails validation as no connection. From ea05a48edbd1505a27bf88a194f3f1ba9f331fa6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 22 Nov 2026 12:16:41 +0100 Subject: [PATCH 13/22] fix(remote): make the saved-connection readers observation-only and migrate only on save or remove readRemoteConnectionState and readActiveConnectionState now change no file. Older records move, and invalid records are removed, only inside writeRemoteConnectionState and removeRemoteConnectionState. Remote command defaults and connection materialization no longer need a writable records directory. The active lookup accepts a full record at the pointer path only when that path is the older name of the session the record names. --- ...-connection-state-session-identity.test.ts | 116 +++++++++++++----- .../remote/src/remote-connection-state.ts | 98 +++++++-------- .../connection-status-read-only.test.ts | 52 ++++++++ src/cli/commands/connection.ts | 28 +---- 4 files changed, 184 insertions(+), 110 deletions(-) create mode 100644 src/cli/commands/connection-status-read-only.test.ts diff --git a/packages/remote/src/remote-connection-state-session-identity.test.ts b/packages/remote/src/remote-connection-state-session-identity.test.ts index 853dc38e6d..24e8815f09 100644 --- a/packages/remote/src/remote-connection-state-session-identity.test.ts +++ b/packages/remote/src/remote-connection-state-session-identity.test.ts @@ -6,10 +6,11 @@ import path from 'node:path'; import { AppError } from '@agent-device/kernel/errors'; import { mkdtempForTestSync } from '@agent-device/test-kit'; import { - observeActiveConnectionState, - observeRemoteConnectionState, + hashRemoteConfigFile, + readActiveConnectionState, readRemoteConnectionState, removeRemoteConnectionState, + resolveRemoteConnectionDefaults, writeRemoteConnectionState, type RemoteConnectionState, } from './remote-connection-state.ts'; @@ -159,7 +160,7 @@ test('a session name that cannot be a filename is stored under its hash', () => assert.equal(readRemoteConnectionState({ stateDir, session })?.runId, `run-${session}`); }); -test('a record at the sanitized path that names this session moves to its hashed path', () => { +test('a record at the sanitized path that names this session moves to its hashed path on save', () => { const stateDir = mkdtempForTestSync('agent-device-remote-identity-legacy-match-'); const session = 'team/dev#1'; writeRecordFile(stateDir, sanitizedFileName(session), recordFor(session)); @@ -169,11 +170,15 @@ test('a record at the sanitized path that names this session moves to its hashed `run-${session}`, 'a record written before hashed paths still serves the session it names', ); + assert.deepEqual(recordsIn(stateDir), [sanitizedFileName(session)], 'a read moved no file'); + + writeRemoteConnectionState({ stateDir, state: { ...recordFor(session), runId: 'run-saved' } }); assert.deepEqual( recordsIn(stateDir), - [hashedFileName(session)], + [ACTIVE_SESSION_FILE, hashedFileName(session)].sort(), 'the record now lives only at the hashed path, and the sanitized name is gone', ); + assert.equal(readRemoteConnectionState({ stateDir, session })?.runId, 'run-saved'); }); test('a record at the sanitized path that names another session is left in place', () => { @@ -195,7 +200,8 @@ test('a sanitized record whose hashed path is already taken is kept and refused' const legacyPath = writeRecordFile(stateDir, sanitizedFileName(session), recordFor(session)); writeRecordFile(stateDir, hashedFileName(session), recordFor(session)); - const refusal = captureRefusal(() => readRemoteConnectionState({ stateDir, session })); + assert.equal(readRemoteConnectionState({ stateDir, session })?.runId, `run-${session}`); + const refusal = captureRefusal(() => removeRemoteConnectionState({ stateDir, session })); assert.equal(refusal.details?.reason, 'connection_session_mismatch'); assert.equal(refusal.details?.recordPath, legacyPath); @@ -206,7 +212,7 @@ test('a sanitized record whose hashed path is already taken is kept and refused' ); }); -test('a record an older build shared with a case-variant session moves to its owner', () => { +test('a record an older build shared with a case-variant session moves to its owner on save', () => { const stateDir = mkdtempForTestSync('agent-device-remote-identity-upgrade-'); plantFileSharedByCaseVariants(stateDir, 'Demo'); @@ -215,14 +221,15 @@ test('a record an older build shared with a case-variant session moves to its ow null, 'the record an older build wrote for Demo is not the demo session connection', ); + assert.equal(readRemoteConnectionState({ stateDir, session: 'Demo' })?.runId, 'run-Demo'); + + writeRemoteConnectionState({ stateDir, state: recordFor('demo') }); // On a case-sensitive volume the fixture's hard link leaves `Demo.json` as a second name of the // moved record. Only the Demo session retires that name, so ignore it here. assert.deepEqual( recordsIn(stateDir).filter((name) => name !== 'Demo.json'), - [hashedFileName('Demo')], + [ACTIVE_SESSION_FILE, 'demo.json', hashedFileName('Demo')].sort(), ); - - writeRemoteConnectionState({ stateDir, state: recordFor('demo') }); assert.equal(readRemoteConnectionState({ stateDir, session: 'demo' })?.runId, 'run-demo'); assert.equal(readRemoteConnectionState({ stateDir, session: 'Demo' })?.runId, 'run-Demo'); @@ -269,7 +276,7 @@ for (const [damage, skip] of [ ); } -test('a record that fails validation is removed only for the session it names', () => { +test('a record that fails validation is removed only by a removal for the session it names', () => { const stateDir = mkdtempForTestSync('agent-device-remote-identity-invalid-'); const foreignPath = writeRecordFile(stateDir, 'demo.json', { ...recordFor('other'), @@ -284,18 +291,23 @@ test('a record that fails validation is removed only for the session it names', assert.equal(refusal.details?.reason, 'connection_session_mismatch'); assert.equal(fs.existsSync(foreignPath), true, 'an invalid record of another session is kept'); + captureRefusal(() => removeRemoteConnectionState({ stateDir, session: 'demo' })); + assert.equal(fs.existsSync(foreignPath), true, 'an invalid record of another session is kept'); + assert.equal(readRemoteConnectionState({ stateDir, session: 'other' }), null); + assert.equal(fs.existsSync(ownPath), true, 'a read keeps an invalid record'); + removeRemoteConnectionState({ stateDir, session: 'other' }); assert.equal(fs.existsSync(ownPath), false, 'an invalid record of this session is removed'); }); -test('an invalid record of the U+D800 session survives a U+D801 status read', () => { +test('an invalid record of the U+D800 session survives a U+D801 read', () => { const stateDir = mkdtempForTestSync('agent-device-remote-identity-invalid-surrogate-'); const recordPath = writeRecordFile(stateDir, hashedFileName('\uD800'), { ...recordFor('\uD800'), updatedAt: null, }); - assert.equal(observeRemoteConnectionState({ stateDir, session: '\uD801' }), null); + assert.equal(readRemoteConnectionState({ stateDir, session: '\uD801' }), null); assert.equal(fs.existsSync(recordPath), true); }); @@ -307,15 +319,14 @@ test('a session named by a case alias of the pointer file is stored under its ha writeRemoteConnectionState({ stateDir, state: recordFor('demo') }); assert.equal(readRemoteConnectionState({ stateDir, session })?.runId, `run-${session}`); - assert.deepEqual( - recordsIn(stateDir), - [ACTIVE_SESSION_FILE, 'demo.json', hashedFileName(session)].sort(), - 'the legacy record moved to its hashed path instead of sitting on the pointer name', - ); assert.deepEqual( JSON.parse(fs.readFileSync(path.join(stateDir, RECORDS_DIR, ACTIVE_SESSION_FILE), 'utf8')), { session: 'demo' }, ); + + removeRemoteConnectionState({ stateDir, session }); + assert.equal(readRemoteConnectionState({ stateDir, session }), null); + assert.deepEqual(recordsIn(stateDir), [ACTIVE_SESSION_FILE, 'demo.json'].sort()); }); test('a record left on the pointer path moves to its owner before the pointer is written', () => { @@ -376,12 +387,13 @@ test('the last guard names the record it refused and how to clear it', () => { ); }); -test('an empty session finds the record an older build saved for it as default.json', () => { +test('an empty session moves the record an older build saved for it as default.json on save', () => { const stateDir = mkdtempForTestSync('agent-device-remote-identity-empty-'); writeRecordFile(stateDir, 'default.json', recordFor('')); - assert.equal(readRemoteConnectionState({ stateDir, session: '' })?.runId, 'run-'); - assert.deepEqual(recordsIn(stateDir), [hashedFileName('')]); + writeRemoteConnectionState({ stateDir, state: { ...recordFor(''), runId: 'run-saved' } }); + assert.equal(readRemoteConnectionState({ stateDir, session: '' })?.runId, 'run-saved'); + assert.deepEqual(recordsIn(stateDir), [ACTIVE_SESSION_FILE, hashedFileName('')].sort()); }); test.skipIf(runsAsRoot)( @@ -392,7 +404,7 @@ test.skipIf(runsAsRoot)( const recordsDir = path.join(stateDir, RECORDS_DIR); fs.chmodSync(recordsDir, 0o500); try { - assert.equal(observeRemoteConnectionState({ stateDir, session: 'Demo' })?.runId, 'run-Demo'); + assert.equal(readRemoteConnectionState({ stateDir, session: 'Demo' })?.runId, 'run-Demo'); assert.throws(() => removeRemoteConnectionState({ stateDir, session: 'Demo' }), { code: 'EACCES', }); @@ -403,26 +415,55 @@ test.skipIf(runsAsRoot)( }, ); -test('status on a valid older Demo.json reports it and leaves the directory unchanged', () => { +test.skipIf(runsAsRoot)( + 'remote command defaults resolve from an older Demo.json in a read-only records directory', + () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-readonly-defaults-'); + const remoteConfigPath = path.join(stateDir, 'remote.json'); + fs.writeFileSync(remoteConfigPath, '{}'); + writeRecordFile(stateDir, 'Demo.json', { + ...recordFor('Demo'), + remoteConfigPath, + remoteConfigHash: hashRemoteConfigFile(remoteConfigPath), + }); + const recordsDir = path.join(stateDir, RECORDS_DIR); + fs.chmodSync(recordsDir, 0o500); + try { + const defaults = resolveRemoteConnectionDefaults({ + stateDir, + session: 'Demo', + cwd: stateDir, + env: {}, + }); + assert.equal(defaults?.flags.session, 'Demo'); + assert.equal(defaults?.flags.remoteConfig, remoteConfigPath); + assert.deepEqual(recordsIn(stateDir), ['Demo.json']); + } finally { + fs.chmodSync(recordsDir, 0o700); + } + }, +); + +test('a read on a valid older Demo.json reports it and leaves the directory unchanged', () => { const stateDir = mkdtempForTestSync('agent-device-remote-identity-observe-legacy-'); writeRecordFile(stateDir, 'Demo.json', recordFor('Demo')); writeRecordFile(stateDir, 'default.json', recordFor('')); - assert.equal(observeRemoteConnectionState({ stateDir, session: 'Demo' })?.runId, 'run-Demo'); - assert.equal(observeRemoteConnectionState({ stateDir, session: '' })?.runId, 'run-'); - assert.equal(observeRemoteConnectionState({ stateDir, session: 'default' }), null); - assert.deepEqual(recordsIn(stateDir), ['Demo.json', 'default.json'], 'status moved no file'); + assert.equal(readRemoteConnectionState({ stateDir, session: 'Demo' })?.runId, 'run-Demo'); + assert.equal(readRemoteConnectionState({ stateDir, session: '' })?.runId, 'run-'); + assert.equal(readRemoteConnectionState({ stateDir, session: 'default' }), null); + assert.deepEqual(recordsIn(stateDir), ['Demo.json', 'default.json'], 'a read moved no file'); }); -test('status on an invalid record that names the session leaves it and its pointer in place', () => { +test('a read on an invalid record that names the session leaves it and its pointer in place', () => { const stateDir = mkdtempForTestSync('agent-device-remote-identity-observe-invalid-'); writeRecordFile(stateDir, 'demo.json', { ...recordFor('demo'), updatedAt: null }); writeRecordFile(stateDir, 'Team.json', { ...recordFor('Team'), updatedAt: null }); writeRecordFile(stateDir, ACTIVE_SESSION_FILE, { session: 'demo' }); - assert.equal(observeRemoteConnectionState({ stateDir, session: 'demo' }), null); - assert.equal(observeActiveConnectionState({ stateDir }), null); - assert.equal(observeRemoteConnectionState({ stateDir, session: 'Team' }), null); + assert.equal(readRemoteConnectionState({ stateDir, session: 'demo' }), null); + assert.equal(readActiveConnectionState({ stateDir }), null); + assert.equal(readRemoteConnectionState({ stateDir, session: 'Team' }), null); assert.deepEqual(recordsIn(stateDir), [ACTIVE_SESSION_FILE, 'Team.json', 'demo.json'].sort()); }); @@ -449,12 +490,12 @@ test('an EPERM hard-link failure never deletes default.json', () => { assert.equal(fs.existsSync(legacyPath), true); }); -test('an empty-session pointer resolves for unnamed status', () => { +test('an empty-session pointer resolves for an unnamed read', () => { const stateDir = mkdtempForTestSync('agent-device-remote-identity-empty-pointer-'); writeRecordFile(stateDir, hashedFileName(''), recordFor('')); writeRecordFile(stateDir, ACTIVE_SESSION_FILE, { session: '' }); - assert.equal(observeActiveConnectionState({ stateDir })?.runId, 'run-'); + assert.equal(readActiveConnectionState({ stateDir })?.runId, 'run-'); }); test('a full record at the pointer path is not deleted by disconnect of the session it names', () => { @@ -466,7 +507,7 @@ test('a full record at the pointer path is not deleted by disconnect of the sess }); assert.equal( - observeActiveConnectionState({ stateDir }), + readActiveConnectionState({ stateDir }), null, 'a full record is not a pointer, so unnamed status selects no session from it', ); @@ -475,3 +516,12 @@ test('a full record at the pointer path is not deleted by disconnect of the sess assert.equal(JSON.parse(fs.readFileSync(pointerPath, 'utf8')).runId, 'run-at-pointer'); assert.deepEqual(recordsIn(stateDir), [ACTIVE_SESSION_FILE]); }); + +test('the active lookup accepts a full record at the pointer path that an older build wrote for .active-session', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-pointer-legacy-'); + // A build that sanitized names wrote the session `.active-session` to exactly the pointer path. + writeRecordFile(stateDir, ACTIVE_SESSION_FILE, recordFor('.active-session')); + + assert.equal(readActiveConnectionState({ stateDir })?.runId, 'run-.active-session'); + assert.deepEqual(recordsIn(stateDir), [ACTIVE_SESSION_FILE], 'the active lookup moved no file'); +}); diff --git a/packages/remote/src/remote-connection-state.ts b/packages/remote/src/remote-connection-state.ts index 373e9e8506..5693a6d8c7 100644 --- a/packages/remote/src/remote-connection-state.ts +++ b/packages/remote/src/remote-connection-state.ts @@ -225,52 +225,22 @@ type RemoteConnectionDefaults = { const REMOTE_CONNECTION_STATE_REASONS = { // A saved connection file cannot be used for the session a command named: it names another session, // a record from an older build cannot move to its session file because that file already exists, or - // the active-session pointer path holds a record whose owner is unproven. The files that the refusal - // names are kept: the refused file, and the occupied session file it could not move to. + // the active-session pointer path holds a record whose owner is unproven. The refused file is kept, + // and so is the occupied session file. sessionMismatch: { reason: 'connection_session_mismatch' }, // The session's own saved connection file, or the active-session pointer, could not be read or // parsed, so no session is known to own it. It was neither replaced nor removed. ownerUnknown: { reason: 'connection_record_owner_unknown' }, } as const satisfies ReasonTable<'remote connections'>; -/** - * The saved connection `session` owns, for a command that saves or removes it next. - * - * Records an older build wrote for the session move to its own path first, and a record that names - * the session but fails validation is removed. A command that only reports the connection uses - * {@link observeRemoteConnectionState}, which changes no file. - */ -export function readRemoteConnectionState(options: { - stateDir: string; - session: string; -}): RemoteConnectionState | null { - const statePath = remoteConnectionStatePath(options); - const file = readRecordFile(statePath); - if (file.kind === 'absent') return null; - if (file.kind === 'unknown') - throw recordOwnerUnknownError(options.session, statePath, file.cause); - // Ownership is settled before shape: a record another session owns is never removed as invalid. - if (file.session !== options.session) { - throw sessionMismatchError( - options.session, - statePath, - 'The saved connection belongs to a different session.', - ); - } - if (!isRemoteConnectionState(file.record)) { - removeInvalidRemoteConnectionState(options, statePath); - return null; - } - return file.record; -} - /** * The saved connection `session` owns, read without a change to any file. * * A record an older build wrote for exactly this session is reported where it is. A record that names - * the session but fails validation is reported as no connection and is kept. + * the session but fails validation is reported as no connection and is kept. Only + * {@link writeRemoteConnectionState} and {@link removeRemoteConnectionState} move or remove files. */ -export function observeRemoteConnectionState(options: { +export function readRemoteConnectionState(options: { stateDir: string; session: string; }): RemoteConnectionState | null { @@ -305,6 +275,28 @@ export function observeRemoteConnectionState(options: { return null; } +/** + * The session's own path, ready for a save or a removal. Records an older build wrote for the session + * move there first, and a record there that names the session but fails validation is removed. + */ +function claimRemoteConnectionStatePath(options: { stateDir: string; session: string }): string { + const statePath = remoteConnectionStatePath(options); + const file = readRecordFile(statePath); + if (file.kind === 'absent') return statePath; + if (file.kind === 'unknown') + throw recordOwnerUnknownError(options.session, statePath, file.cause); + // Ownership is settled before shape: a record another session owns is never removed as invalid. + if (file.session !== options.session) { + throw sessionMismatchError( + options.session, + statePath, + 'The saved connection belongs to a different session.', + ); + } + if (!isRemoteConnectionState(file.record)) removeInvalidRemoteConnectionState(options, statePath); + return statePath; +} + function observedRemoteConnectionState( session: string, recordPath: string, @@ -350,8 +342,7 @@ export function writeRemoteConnectionState(options: { }): void { const location = { stateDir: options.stateDir, session: options.state.session }; retireRecordAtActivePointer(options.stateDir, options.state.session); - readRemoteConnectionState(location); - const statePath = remoteConnectionStatePath(location); + const statePath = claimRemoteConnectionStatePath(location); fs.mkdirSync(path.dirname(statePath), { recursive: true }); writeJsonFile(statePath, options.state); options.onSessionRecordCommitted?.(); @@ -372,8 +363,7 @@ export function buildRemoteConnectionDaemonState( } export function removeRemoteConnectionState(options: { stateDir: string; session: string }): void { - readRemoteConnectionState(options); - removeRemoteConnectionStateFile(options, remoteConnectionStatePath(options)); + removeRemoteConnectionStateFile(options, claimRemoteConnectionStatePath(options)); } function removeRemoteConnectionStateFile( @@ -785,23 +775,25 @@ function activeConnectionStatePath(stateDir: string): string { return path.join(stateDir, 'remote-connections', ACTIVE_SESSION_FILE_NAME); } +/** + * The connection the active-session pointer names, read without a change to any file. + * + * A full record an older build wrote at the pointer path counts only when that path is the older name + * of the session the record names. + */ export function readActiveConnectionState(options: { stateDir: string; }): RemoteConnectionState | null { - const session = readActiveConnectionSession(options.stateDir); - return session === undefined - ? null - : readRemoteConnectionState({ stateDir: options.stateDir, session }); -} - -/** The connection the active-session pointer names, read without a change to any file. */ -export function observeActiveConnectionState(options: { - stateDir: string; -}): RemoteConnectionState | null { - const session = readActiveConnectionSession(options.stateDir); - return session === undefined - ? null - : observeRemoteConnectionState({ stateDir: options.stateDir, session }); + const activePath = activeConnectionStatePath(options.stateDir); + const file = readRecordFile(activePath); + if (file.kind !== 'owned') return null; + if ( + !isActiveSessionPointer(file.record) && + !isMovableLegacyRecord(path.dirname(activePath), activePath, file) + ) { + return null; + } + return readRemoteConnectionState({ stateDir: options.stateDir, session: file.session }); } /** diff --git a/src/cli/commands/connection-status-read-only.test.ts b/src/cli/commands/connection-status-read-only.test.ts new file mode 100644 index 0000000000..1b05ee5166 --- /dev/null +++ b/src/cli/commands/connection-status-read-only.test.ts @@ -0,0 +1,52 @@ +import { test } from 'vitest'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { withCapturedStdoutAsync } from '@agent-device/test-kit'; +import { hashRemoteConfigFile } from '@agent-device/remote/remote-connection-state'; +import { + connectionWorkspace, + createTestClient, +} from '../../__tests__/remote-connection.fixtures.ts'; +import { connectionCommand } from '../../__tests__/test-utils/host-bound-commands.ts'; + +// `connection status` only reports the saved connection. A status read that moved an older build's +// record to its session's own file failed where the records directory could not be written. + +test('connection status --session Demo over an older Demo.json leaves the records directory unchanged', async () => { + const { tempRoot, stateDir, remoteConfigPath } = connectionWorkspace( + 'agent-device-connection-status-read-only-', + ); + fs.writeFileSync(remoteConfigPath, '{}'); + const recordsDir = path.join(stateDir, 'remote-connections'); + fs.mkdirSync(recordsDir, { recursive: true }); + const now = new Date().toISOString(); + fs.writeFileSync( + path.join(recordsDir, 'Demo.json'), + `${JSON.stringify({ + version: 1, + session: 'Demo', + remoteConfigPath, + remoteConfigHash: hashRemoteConfigFile(remoteConfigPath), + tenant: 'acme', + runId: 'run-Demo', + connectedAt: now, + updatedAt: now, + })}\n`, + ); + + const stdout = await withCapturedStdoutAsync(async () => { + // Every call this client answers throws: status may not reach the daemon. + await connectionCommand({ + positionals: ['status'], + flags: { json: true, help: false, version: false, stateDir, session: 'Demo' }, + client: createTestClient(), + }); + }); + + const payload = JSON.parse(stdout).data; + assert.equal(payload.session, 'Demo'); + assert.equal(payload.runId, 'run-Demo'); + assert.deepEqual(fs.readdirSync(recordsDir), ['Demo.json'], 'status moved no file'); + fs.rmSync(tempRoot, { recursive: true, force: true }); +}); diff --git a/src/cli/commands/connection.ts b/src/cli/commands/connection.ts index e1d87cda14..2cadcbb2c3 100644 --- a/src/cli/commands/connection.ts +++ b/src/cli/commands/connection.ts @@ -3,8 +3,6 @@ import type { CloudProviderSessionResult } from '@agent-device/contracts/observa import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution'; import { resolveRemoteConfigProfile } from '@agent-device/remote/remote-config'; import { - observeActiveConnectionState, - observeRemoteConnectionState, readActiveConnectionState, requireLeasedConnectionSession, sessionLeaseScope, @@ -338,7 +336,7 @@ function scopeConnectProfile( } export const disconnectCommand: ClientCommandHandler = async ({ flags, client, host }) => { - const { session, stateDir, state } = readRequestedConnectionState(flags, host, CHANGE_LOOKUP); + const { session, stateDir, state } = readRequestedConnectionState(flags, host); if (!state) { await writeNoRemoteConnectionOutput(flags, session); return true; @@ -392,7 +390,7 @@ export const connectionCommand: ClientCommandHandler = async ({ positionals, fla if (positionals[0] !== 'status') { throw new AppError('INVALID_ARGS', 'connection accepts only: status'); } - const { session, state } = readRequestedConnectionState(flags, host, OBSERVE_LOOKUP); + const { session, state } = readRequestedConnectionState(flags, host); if (!state) { await writeNoRemoteConnectionOutput(flags, session); return true; @@ -472,27 +470,9 @@ function readConnectProvider( ); } -type ConnectionStateLookup = { - session: (options: { stateDir: string; session: string }) => RemoteConnectionState | null; - active: (options: { stateDir: string }) => RemoteConnectionState | null; -}; - -/** For a command that removes or rewrites the saved connection it reads. */ -const CHANGE_LOOKUP: ConnectionStateLookup = { - session: readRemoteConnectionState, - active: readActiveConnectionState, -}; - -/** For a command that only reports the saved connection: it changes no file. */ -const OBSERVE_LOOKUP: ConnectionStateLookup = { - session: observeRemoteConnectionState, - active: observeActiveConnectionState, -}; - function readRequestedConnectionState( flags: CliFlags, host: HostEnvironment, - lookup: ConnectionStateLookup, ): { session: string; stateDir: string; @@ -506,8 +486,8 @@ function readRequestedConnectionState( // Only a caller that named no session follows the active-session pointer. `--session=` names the // empty session. const state = - lookup.session({ stateDir, session }) ?? - (flags.session === undefined ? lookup.active({ stateDir }) : null); + readRemoteConnectionState({ stateDir, session }) ?? + (flags.session === undefined ? readActiveConnectionState({ stateDir }) : null); if (state) requireLeasedConnectionSession(state, flags.session); return { session, stateDir, state }; } From 426a2dbb719b2193119fceeb28b7af0d1d4a3e01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 22 Nov 2026 12:16:42 +0100 Subject: [PATCH 14/22] docs(commands): say that only a save or a removal moves an older saved connection --- website/docs/docs/commands.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 1d6617a7c4..384c0d51d8 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -2600,7 +2600,7 @@ Exact behavior: `agent-device help disconnect`. -If agent-device cannot read or parse a file and so cannot establish which session owns it, it keeps that file and refuses with `connection_record_owner_unknown`. A session's own saved connection file that cannot be read refuses every command that uses that session's saved connection. An unreadable active-session pointer refuses `connect` and any command that rewrites the saved connection. The error names the file. Make it readable, or remove it if no session needs it. A file from an older build whose owner cannot be proven is left in place and is not used. If an older file cannot move to its session's own file because that file already exists, the command that moves it refuses with `connection_session_mismatch`. This is also true when both files name the same session, and when the occupied file cannot be read. `connection status` changes no file. It reports an older build's file for the session where that file is, and it reports a file that fails validation as no connection. +If agent-device cannot read or parse a session's own saved connection file or the active-session pointer, it cannot establish which session owns that file. It keeps the file and refuses with `connection_record_owner_unknown`. A session's own saved connection file that cannot be read refuses every command that uses that session's saved connection. An unreadable active-session pointer refuses `connect` and any command that rewrites the saved connection. The error names the file. Make it readable, or remove it if no session needs it. A file from an older build whose owner cannot be proven is left in place and is not used. A command that only reads the saved connection, such as `connection status`, changes no file. It uses an older build's file for the session where that file is, and it treats a file that fails validation as no connection. Only a command that saves or removes the saved connection moves an older file to its session's own file, or removes a file that fails validation. If an older file cannot move because its session's own file already exists, that command refuses with `connection_session_mismatch`. The refused file is kept, and so is the occupied session file. This is also true when both files name the same session, and when the occupied file cannot be read. From 1846b18938fe4b14a214f312095fac20cf2391d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 22 Nov 2026 13:10:00 +0100 Subject: [PATCH 15/22] fix(remote): settle the saved connection before disconnect tears it down Disconnect claims the record at its session's own path before it closes the session or releases the lease, so a record it cannot remove is refused first. A record that names its session but fails validation is removed. --- .../remote/src/remote-connection-state.ts | 82 ++++++++++++++++-- .../commands/connection-disconnect.test.ts | 83 +++++++++++++++++++ src/cli/commands/connection.ts | 23 +++-- 3 files changed, 173 insertions(+), 15 deletions(-) diff --git a/packages/remote/src/remote-connection-state.ts b/packages/remote/src/remote-connection-state.ts index 5693a6d8c7..a930855640 100644 --- a/packages/remote/src/remote-connection-state.ts +++ b/packages/remote/src/remote-connection-state.ts @@ -238,7 +238,8 @@ const REMOTE_CONNECTION_STATE_REASONS = { * * A record an older build wrote for exactly this session is reported where it is. A record that names * the session but fails validation is reported as no connection and is kept. Only - * {@link writeRemoteConnectionState} and {@link removeRemoteConnectionState} move or remove files. + * {@link writeRemoteConnectionState}, {@link claimRemoteConnectionState} and + * {@link removeRemoteConnectionState} move or remove files. */ export function readRemoteConnectionState(options: { stateDir: string; @@ -280,9 +281,25 @@ export function readRemoteConnectionState(options: { * move there first, and a record there that names the session but fails validation is removed. */ function claimRemoteConnectionStatePath(options: { stateDir: string; session: string }): string { + const { statePath, record } = claimRemoteConnectionRecord(options); + if (record && !isRemoteConnectionState(record)) { + removeInvalidRemoteConnectionState(options, statePath); + } + return statePath; +} + +/** + * The session's own path and the record there, if any. Records an older build wrote for the session + * move there first. A file there that no session is proven to own, or that another session owns, + * refuses the claim. + */ +function claimRemoteConnectionRecord(options: { stateDir: string; session: string }): { + statePath: string; + record: Record | undefined; +} { const statePath = remoteConnectionStatePath(options); const file = readRecordFile(statePath); - if (file.kind === 'absent') return statePath; + if (file.kind === 'absent') return { statePath, record: undefined }; if (file.kind === 'unknown') throw recordOwnerUnknownError(options.session, statePath, file.cause); // Ownership is settled before shape: a record another session owns is never removed as invalid. @@ -293,8 +310,46 @@ function claimRemoteConnectionStatePath(options: { stateDir: string; session: st 'The saved connection belongs to a different session.', ); } - if (!isRemoteConnectionState(file.record)) removeInvalidRemoteConnectionState(options, statePath); - return statePath; + return { statePath, record: file.record }; +} + +/** A saved connection a removal has settled at its session's own path. */ +type RemoteConnectionClaim = { + session: string; + /** `null` when the record names the session but fails validation. */ + state: RemoteConnectionState | null; +}; + +/** + * The first step of a removal: the saved connection `session` owns, moved to its session's own path. + * + * A caller runs this before any remote teardown, so a record it cannot remove is refused before a lease + * ends, and finishes with {@link removeRemoteConnectionState}. `session` is `undefined` when the caller + * named none: the `default` session comes first, then the active-session pointer. A missing record + * returns `null`. + */ +export function claimRemoteConnectionState(options: { + stateDir: string; + session: string | undefined; +}): RemoteConnectionClaim | null { + if (options.session !== undefined) { + return claimSessionRecord({ stateDir: options.stateDir, session: options.session }); + } + const claimed = claimSessionRecord({ stateDir: options.stateDir, session: 'default' }); + if (claimed) return claimed; + const activeSession = activeRecordOwner(options.stateDir); + return activeSession === undefined + ? null + : claimSessionRecord({ stateDir: options.stateDir, session: activeSession }); +} + +function claimSessionRecord(options: { + stateDir: string; + session: string; +}): RemoteConnectionClaim | null { + const { record } = claimRemoteConnectionRecord(options); + if (!record) return null; + return { session: options.session, state: isRemoteConnectionState(record) ? record : null }; } function observedRemoteConnectionState( @@ -784,16 +839,27 @@ function activeConnectionStatePath(stateDir: string): string { export function readActiveConnectionState(options: { stateDir: string; }): RemoteConnectionState | null { - const activePath = activeConnectionStatePath(options.stateDir); + const session = activeRecordOwner(options.stateDir); + return session === undefined + ? null + : readRemoteConnectionState({ stateDir: options.stateDir, session }); +} + +/** + * The session the active-session pointer names, or the owner of a full record an older build wrote at + * the pointer path when that path is the older name of the session the record names. + */ +function activeRecordOwner(stateDir: string): string | undefined { + const activePath = activeConnectionStatePath(stateDir); const file = readRecordFile(activePath); - if (file.kind !== 'owned') return null; + if (file.kind !== 'owned') return undefined; if ( !isActiveSessionPointer(file.record) && !isMovableLegacyRecord(path.dirname(activePath), activePath, file) ) { - return null; + return undefined; } - return readRemoteConnectionState({ stateDir: options.stateDir, session: file.session }); + return file.session; } /** diff --git a/src/cli/commands/connection-disconnect.test.ts b/src/cli/commands/connection-disconnect.test.ts index f122000ffc..6d5f48eeea 100644 --- a/src/cli/commands/connection-disconnect.test.ts +++ b/src/cli/commands/connection-disconnect.test.ts @@ -174,3 +174,86 @@ test('disconnect treats an already-inactive lease as released without a failure assert.equal(text.trim(), 'Disconnected remote session "adc-release-inactive".'); fs.rmSync(tempRoot, { recursive: true, force: true }); }); + +test('disconnect removes a record that names its session but fails validation', async () => { + const { tempRoot, stateDir, remoteConfigPath } = connectionWorkspace( + 'agent-device-disconnect-invalid-record-', + ); + fs.writeFileSync(remoteConfigPath, '{}'); + const recordsDir = path.join(stateDir, 'remote-connections'); + const recordPath = path.join(recordsDir, 'demo.json'); + const activePath = path.join(recordsDir, '.active-session.json'); + fs.mkdirSync(recordsDir, { recursive: true }); + fs.writeFileSync( + recordPath, + JSON.stringify({ + version: 1, + session: 'demo', + remoteConfigPath, + remoteConfigHash: 'hash', + tenant: 'acme', + runId: 'run-demo', + connectedAt: new Date().toISOString(), + updatedAt: null, + }), + ); + fs.writeFileSync(activePath, JSON.stringify({ session: 'demo' })); + + const text = await withCapturedStdoutAsync(async () => { + await disconnectCommand({ + positionals: [], + flags: { json: false, help: false, version: false, stateDir, session: 'demo' }, + client: createTestClient(), + }); + }); + + assert.equal(text.trim(), 'No remote connection for "demo".'); + assert.equal(fs.existsSync(recordPath), false); + assert.equal(fs.existsSync(activePath), false); + fs.rmSync(tempRoot, { recursive: true, force: true }); +}); + +test('disconnect refuses a record it cannot remove before it closes the session or releases the lease', async () => { + const { tempRoot, stateDir } = seedReleasableConnection( + 'agent-device-disconnect-occupied-session-path-', + 'Demo', + ); + const recordsDir = path.join(stateDir, 'remote-connections'); + const [hashedName] = fs.readdirSync(recordsDir).filter((name) => name.startsWith('~')); + assert.ok(hashedName, 'the new build saves Demo at its hashed path'); + const hashedPath = path.join(recordsDir, hashedName); + // An older build connected Demo under a run of its own and saved it at the name it wrote. + const legacyPath = path.join(recordsDir, 'Demo.json'); + const legacy = JSON.parse(fs.readFileSync(hashedPath, 'utf8')); + fs.writeFileSync( + legacyPath, + JSON.stringify({ ...legacy, runId: 'run-legacy', leaseId: 'lease-legacy' }), + ); + let closed = 0; + let released = 0; + + await assert.rejects( + disconnectCommand({ + positionals: [], + flags: { json: true, help: false, version: false, stateDir, session: 'Demo' }, + client: createTestClient({ + closeSession: async () => { + closed += 1; + return { session: 'Demo', identifiers: { session: 'Demo' } }; + }, + release: async () => { + released += 1; + return { released: true }; + }, + }), + }), + (error: unknown) => + error instanceof AppError && error.details?.reason === 'connection_session_mismatch', + ); + + assert.equal(closed, 0); + assert.equal(released, 0); + assert.equal(JSON.parse(fs.readFileSync(hashedPath, 'utf8')).leaseId, 'lease-1'); + assert.equal(JSON.parse(fs.readFileSync(legacyPath, 'utf8')).leaseId, 'lease-legacy'); + fs.rmSync(tempRoot, { recursive: true, force: true }); +}); diff --git a/src/cli/commands/connection.ts b/src/cli/commands/connection.ts index 2cadcbb2c3..c5223c3646 100644 --- a/src/cli/commands/connection.ts +++ b/src/cli/commands/connection.ts @@ -3,6 +3,7 @@ import type { CloudProviderSessionResult } from '@agent-device/contracts/observa import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution'; import { resolveRemoteConfigProfile } from '@agent-device/remote/remote-config'; import { + claimRemoteConnectionState, readActiveConnectionState, requireLeasedConnectionSession, sessionLeaseScope, @@ -336,11 +337,19 @@ function scopeConnectProfile( } export const disconnectCommand: ClientCommandHandler = async ({ flags, client, host }) => { - const { session, stateDir, state } = readRequestedConnectionState(flags, host); + const session = flags.session ?? 'default'; + const stateDir = resolveConnectionStateDir(flags, host); + // The record moves to its session's own path before any teardown, so a record this command cannot + // remove is refused before its session closes or its lease ends. + const claim = claimRemoteConnectionState({ stateDir, session: flags.session }); + const state = claim?.state; if (!state) { + // A record that names its session but fails validation still has a known owner to remove it for. + if (claim) removeRemoteConnectionState({ stateDir, session: claim.session }); await writeNoRemoteConnectionOutput(flags, session); return true; } + requireLeasedConnectionSession(state, flags.session); const connectedSession = state.session; let providerData: CloudProviderSessionResult | undefined; @@ -475,21 +484,21 @@ function readRequestedConnectionState( host: HostEnvironment, ): { session: string; - stateDir: string; state: RemoteConnectionState | null; } { const session = flags.session ?? 'default'; - const stateDir = resolveDaemonPaths(flags.stateDir, { - cwd: host.cwd, - env: host.env, - }).baseDir; + const stateDir = resolveConnectionStateDir(flags, host); // Only a caller that named no session follows the active-session pointer. `--session=` names the // empty session. const state = readRemoteConnectionState({ stateDir, session }) ?? (flags.session === undefined ? readActiveConnectionState({ stateDir }) : null); if (state) requireLeasedConnectionSession(state, flags.session); - return { session, stateDir, state }; + return { session, state }; +} + +function resolveConnectionStateDir(flags: CliFlags, host: HostEnvironment): string { + return resolveDaemonPaths(flags.stateDir, { cwd: host.cwd, env: host.env }).baseDir; } async function writeNoRemoteConnectionOutput(flags: CliFlags, session: string): Promise { From 8f115a515cd75c2efa60be6770c1b93fd27f1a6e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 22 Nov 2026 13:14:33 +0100 Subject: [PATCH 16/22] refactor(cli): split disconnect into claim, teardown and removal steps --- src/cli/commands/connection.ts | 114 ++++++++++++++++++++++----------- 1 file changed, 76 insertions(+), 38 deletions(-) diff --git a/src/cli/commands/connection.ts b/src/cli/commands/connection.ts index c5223c3646..492d3138a2 100644 --- a/src/cli/commands/connection.ts +++ b/src/cli/commands/connection.ts @@ -336,47 +336,76 @@ function scopeConnectProfile( }; } -export const disconnectCommand: ClientCommandHandler = async ({ flags, client, host }) => { - const session = flags.session ?? 'default'; - const stateDir = resolveConnectionStateDir(flags, host); - // The record moves to its session's own path before any teardown, so a record this command cannot - // remove is refused before its session closes or its lease ends. +/** + * The record moves to its session's own path before any teardown, so a record this command cannot + * remove is refused before its session closes or its lease ends. Returns undefined after reporting + * that no connection exists. + */ +async function claimOrReportNothingToRemove( + flags: CliFlags, + stateDir: string, +): Promise { const claim = claimRemoteConnectionState({ stateDir, session: flags.session }); - const state = claim?.state; - if (!state) { - // A record that names its session but fails validation still has a known owner to remove it for. - if (claim) removeRemoteConnectionState({ stateDir, session: claim.session }); - await writeNoRemoteConnectionOutput(flags, session); - return true; - } - requireLeasedConnectionSession(state, flags.session); - const connectedSession = state.session; - - let providerData: CloudProviderSessionResult | undefined; - if (state.leaseId || state.runtime || state.metro) { - try { - providerData = ( - await client.sessions.close({ session: connectedSession, shutdown: flags.shutdown }) - ).provider; - } catch { - // Disconnect is idempotent; the session may already be closed. - } + if (claim?.state) return claim.state; + // A record that names its session but fails validation still has a known owner to remove it for. + if (claim) removeRemoteConnectionState({ stateDir, session: claim.session }); + await writeNoRemoteConnectionOutput(flags, flags.session ?? 'default'); + return undefined; +} + +type ConnectionClient = Parameters[0]['client']; + +type DisconnectTeardown = { + providerData: CloudProviderSessionResult | undefined; + released: boolean; + releaseError: string | undefined; +}; + +async function closeConnectedSession( + client: ConnectionClient, + state: RemoteConnectionState, + flags: CliFlags, +): Promise { + if (!state.leaseId && !state.runtime && !state.metro) return undefined; + try { + return (await client.sessions.close({ session: state.session, shutdown: flags.shutdown })) + .provider; + } catch { + // Disconnect is idempotent; the session may already be closed. + return undefined; } +} + +async function tearDownSessionAndLease( + client: ConnectionClient, + state: RemoteConnectionState, + flags: CliFlags, +): Promise { + let providerData = await closeConnectedSession(client, state, flags); await stopMetroCleanup(state.metro); - let released = false; - let releaseError: string | undefined; - if (state.leaseId) { - try { - const release = await releaseRemoteConnectionLease(client, state, flags.daemonAuthToken); - released = release.released; - providerData ??= release.provider; - } catch (error) { - // An inactive lease is already gone. Any other failure leaves a live lease whose only local - // record is removed below, so the output must name it. - if (!isInactiveLeaseError(error)) releaseError = errorMessage(error); - } + if (!state.leaseId) return { providerData, released: false, releaseError: undefined }; + try { + const release = await releaseRemoteConnectionLease(client, state, flags.daemonAuthToken); + providerData ??= release.provider; + return { providerData, released: release.released, releaseError: undefined }; + } catch (error) { + // An inactive lease is already gone. Any other failure leaves a live lease whose only local + // record is removed afterwards, so the output must name it. + return { + providerData, + released: false, + releaseError: isInactiveLeaseError(error) ? undefined : errorMessage(error), + }; } - removeRemoteConnectionState({ stateDir, session: connectedSession }); +} + +async function finishDisconnect( + flags: CliFlags, + stateDir: string, + state: RemoteConnectionState, + { providerData, released, releaseError }: DisconnectTeardown, +): Promise { + removeRemoteConnectionState({ stateDir, session: state.session }); // A failed release keeps the profile: retrying that release needs it. if (!releaseError) { removeGeneratedRemoteConfigIfUnused({ stateDir, remoteConfigPath: state.remoteConfigPath }); @@ -385,13 +414,22 @@ export const disconnectCommand: ClientCommandHandler = async ({ flags, client, h flags, { connected: false, - session: connectedSession, + session: state.session, released, ...(releaseError ? { leaseId: state.leaseId, releaseError } : {}), ...(providerData ? { provider: providerData } : {}), }, () => renderDisconnectOutput(state, providerData, releaseError), ); +} + +export const disconnectCommand: ClientCommandHandler = async ({ flags, client, host }) => { + const stateDir = resolveConnectionStateDir(flags, host); + const state = await claimOrReportNothingToRemove(flags, stateDir); + if (!state) return true; + requireLeasedConnectionSession(state, flags.session); + const teardown = await tearDownSessionAndLease(client, state, flags); + await finishDisconnect(flags, stateDir, state, teardown); return true; }; From 0bc01ce9c990611459eb677516c7eb547d0a626f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 22 Nov 2026 14:19:14 +0100 Subject: [PATCH 17/22] fix(remote): remove each invalid record a disconnect passes and fall through to the active session claimRemoteConnectionState now removes an invalid owned record itself and returns only a valid state, so an unnamed disconnect continues to the active pointer. CLI disconnect setup settles the record before the observation-only defaults reader runs. The pointer-shape exclusion applies only at the active-session pointer path, so a legacy session file holding only its session moves and is removed by disconnect. --- .../remote/src/remote-connection-state.ts | 28 ++++---- .../cli-disconnect-invalid-default.test.ts | 49 ++++++++++++++ src/cli.ts | 3 + .../commands/connection-disconnect.test.ts | 65 +++++++++++++++++++ src/cli/commands/connection.ts | 6 +- 5 files changed, 132 insertions(+), 19 deletions(-) create mode 100644 src/__tests__/cli-disconnect-invalid-default.test.ts diff --git a/packages/remote/src/remote-connection-state.ts b/packages/remote/src/remote-connection-state.ts index a930855640..a5d8766031 100644 --- a/packages/remote/src/remote-connection-state.ts +++ b/packages/remote/src/remote-connection-state.ts @@ -313,25 +313,19 @@ function claimRemoteConnectionRecord(options: { stateDir: string; session: strin return { statePath, record: file.record }; } -/** A saved connection a removal has settled at its session's own path. */ -type RemoteConnectionClaim = { - session: string; - /** `null` when the record names the session but fails validation. */ - state: RemoteConnectionState | null; -}; - /** * The first step of a removal: the saved connection `session` owns, moved to its session's own path. * * A caller runs this before any remote teardown, so a record it cannot remove is refused before a lease * ends, and finishes with {@link removeRemoteConnectionState}. `session` is `undefined` when the caller - * named none: the `default` session comes first, then the active-session pointer. A missing record - * returns `null`. + * named none: the `default` session comes first, then the active-session pointer. A record that names + * its session but fails validation is removed on the way, and the next candidate is tried. A missing + * record returns `null`. */ export function claimRemoteConnectionState(options: { stateDir: string; session: string | undefined; -}): RemoteConnectionClaim | null { +}): RemoteConnectionState | null { if (options.session !== undefined) { return claimSessionRecord({ stateDir: options.stateDir, session: options.session }); } @@ -346,10 +340,12 @@ export function claimRemoteConnectionState(options: { function claimSessionRecord(options: { stateDir: string; session: string; -}): RemoteConnectionClaim | null { - const { record } = claimRemoteConnectionRecord(options); +}): RemoteConnectionState | null { + const { statePath, record } = claimRemoteConnectionRecord(options); if (!record) return null; - return { session: options.session, state: isRemoteConnectionState(record) ? record : null }; + if (isRemoteConnectionState(record)) return record; + removeInvalidRemoteConnectionState(options, statePath); + return null; } function observedRemoteConnectionState( @@ -786,11 +782,13 @@ function migrateLegacyRemoteConnectionState(options: { /** * Whether `file` is a record an older build left at `source` for the session it names: `source` is a - * name an older build wrote for that session, compared case-insensitively, and not its own path. + * name an older build wrote for that session, compared case-insensitively, and not its own path. A + * pointer at the active-session pointer path, or at a case alias of it, is no record. */ function isMovableLegacyRecord(recordsDir: string, source: string, file: RecordFile): boolean { - if (file.kind !== 'owned' || isActiveSessionPointer(file.record)) return false; + if (file.kind !== 'owned') return false; const sourceName = path.basename(source).toLowerCase(); + if (sourceName === ACTIVE_SESSION_FILE_NAME && isActiveSessionPointer(file.record)) return false; // Canonical names hold no upper-case letters, so a name that folds onto the target IS the target. if (path.basename(canonicalRemoteConnectionStatePath(recordsDir, file.session)) === sourceName) { return false; diff --git a/src/__tests__/cli-disconnect-invalid-default.test.ts b/src/__tests__/cli-disconnect-invalid-default.test.ts new file mode 100644 index 0000000000..41e5f78d3a --- /dev/null +++ b/src/__tests__/cli-disconnect-invalid-default.test.ts @@ -0,0 +1,49 @@ +import { test } from 'vitest'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { makeTempWorkspace } from '@agent-device/test-kit'; +import { hashRemoteConfigFile } from '@agent-device/remote/remote-connection-state'; +import { runCliCapture } from './cli-capture.ts'; + +test('an unnamed disconnect removes an invalid default record before it disconnects the active session', async () => { + const { root, home, project } = makeTempWorkspace(); + const stateDir = path.join(root, 'state'); + const connectionsDir = path.join(stateDir, 'remote-connections'); + fs.mkdirSync(connectionsDir, { recursive: true }); + const remoteConfig = path.join(project, 'agent-device.remote.json'); + fs.writeFileSync( + remoteConfig, + JSON.stringify({ daemonBaseUrl: 'http://remote-mac.example.test:9124/agent-device' }), + 'utf8', + ); + const record = (session: string) => ({ + version: 1, + session, + remoteConfigPath: remoteConfig, + remoteConfigHash: hashRemoteConfigFile(remoteConfig), + tenant: 'acme', + runId: `run-${session}`, + connectedAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + }); + const defaultPath = path.join(connectionsDir, 'default.json'); + const teamPath = path.join(connectionsDir, 'team.json'); + const activePath = path.join(connectionsDir, '.active-session.json'); + fs.writeFileSync(defaultPath, JSON.stringify({ ...record('default'), updatedAt: null }), 'utf8'); + fs.writeFileSync(teamPath, JSON.stringify(record('team')), 'utf8'); + fs.writeFileSync(activePath, JSON.stringify({ session: 'team' }), 'utf8'); + + const disconnected = await runCliCapture(['disconnect', '--state-dir', stateDir, '--json'], { + cwd: project, + env: { HOME: home }, + }); + + assert.equal(disconnected.code, null); + assert.equal(JSON.parse(disconnected.stdout).data.session, 'team'); + assert.equal(fs.existsSync(defaultPath), false); + assert.equal(fs.existsSync(teamPath), false); + assert.equal(fs.existsSync(activePath), false); + + fs.rmSync(root, { recursive: true, force: true }); +}); diff --git a/src/cli.ts b/src/cli.ts index 86fb9c4715..69f2c18871 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -56,6 +56,7 @@ import { import { resolveCliOptions } from './cli/resolve-cli-options.ts'; import { maybeRunUpgradeNotifier } from './cli/update-check.ts'; import { + claimRemoteConnectionState, remoteSessionRequiredError, resolveRemoteConnectionDefaults, type RemoteConnectionRequestMetadata, @@ -790,6 +791,8 @@ function resolveActiveConnectionDefaults(options: { ) { return null; } + // Disconnect settles its record and removes invalid ones it passes before the defaults read it. + if (options.command === 'disconnect') claimRemoteConnectionState(options); const defaults = resolveRemoteConnectionDefaults({ stateDir: options.stateDir, session: options.session, diff --git a/src/cli/commands/connection-disconnect.test.ts b/src/cli/commands/connection-disconnect.test.ts index 6d5f48eeea..5f1705295b 100644 --- a/src/cli/commands/connection-disconnect.test.ts +++ b/src/cli/commands/connection-disconnect.test.ts @@ -257,3 +257,68 @@ test('disconnect refuses a record it cannot remove before it closes the session assert.equal(JSON.parse(fs.readFileSync(legacyPath, 'utf8')).leaseId, 'lease-legacy'); fs.rmSync(tempRoot, { recursive: true, force: true }); }); + +test('an unnamed disconnect removes an invalid default record and disconnects the active session', async () => { + const { tempRoot, stateDir, remoteConfigPath } = connectionWorkspace( + 'agent-device-disconnect-invalid-default-', + ); + fs.writeFileSync(remoteConfigPath, '{}'); + seedConnectionState({ + stateDir, + state: { + session: 'demo', + remoteConfigPath, + tenant: 'acme', + runId: 'run-demo', + runtime: { platform: 'android', metroPort: 8081 }, + }, + }); + const recordsDir = path.join(stateDir, 'remote-connections'); + const defaultPath = path.join(recordsDir, 'default.json'); + const demoPath = path.join(recordsDir, 'demo.json'); + const activePath = path.join(recordsDir, '.active-session.json'); + const valid = JSON.parse(fs.readFileSync(demoPath, 'utf8')); + fs.writeFileSync(defaultPath, JSON.stringify({ ...valid, session: 'default', updatedAt: null })); + const closed: string[] = []; + + const text = await withCapturedStdoutAsync(async () => { + await disconnectCommand({ + positionals: [], + flags: { json: false, help: false, version: false, stateDir }, + client: createTestClient({ + closeSession: async (request) => { + closed.push(request?.session ?? ''); + return { session: 'demo', identifiers: { session: 'demo' } }; + }, + }), + }); + }); + + assert.equal(text.trim(), 'Disconnected remote session "demo".'); + assert.deepEqual(closed, ['demo']); + assert.equal(fs.existsSync(defaultPath), false); + assert.equal(fs.existsSync(demoPath), false); + assert.equal(fs.existsSync(activePath), false); + fs.rmSync(tempRoot, { recursive: true, force: true }); +}); + +test('disconnect removes an invalid pointer-shaped record at the legacy file name of its session', async () => { + const { tempRoot, stateDir } = connectionWorkspace('agent-device-disconnect-legacy-pointer-'); + const recordsDir = path.join(stateDir, 'remote-connections'); + const legacyPath = path.join(recordsDir, 'Demo.json'); + fs.mkdirSync(recordsDir, { recursive: true }); + // An older build saved Demo at the name it wrote, and the record holds only its session. + fs.writeFileSync(legacyPath, JSON.stringify({ session: 'Demo' })); + + const text = await withCapturedStdoutAsync(async () => { + await disconnectCommand({ + positionals: [], + flags: { json: false, help: false, version: false, stateDir, session: 'Demo' }, + client: createTestClient(), + }); + }); + + assert.equal(text.trim(), 'No remote connection for "Demo".'); + assert.deepEqual(fs.readdirSync(recordsDir), []); + fs.rmSync(tempRoot, { recursive: true, force: true }); +}); diff --git a/src/cli/commands/connection.ts b/src/cli/commands/connection.ts index 492d3138a2..78ea255165 100644 --- a/src/cli/commands/connection.ts +++ b/src/cli/commands/connection.ts @@ -345,10 +345,8 @@ async function claimOrReportNothingToRemove( flags: CliFlags, stateDir: string, ): Promise { - const claim = claimRemoteConnectionState({ stateDir, session: flags.session }); - if (claim?.state) return claim.state; - // A record that names its session but fails validation still has a known owner to remove it for. - if (claim) removeRemoteConnectionState({ stateDir, session: claim.session }); + const state = claimRemoteConnectionState({ stateDir, session: flags.session }); + if (state) return state; await writeNoRemoteConnectionOutput(flags, flags.session ?? 'default'); return undefined; } From 716fb68a85aa23da38eada17efcc8ab7f9cbe4fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 22 Nov 2026 14:59:20 +0100 Subject: [PATCH 18/22] refactor(remote): merge the claim helpers and drop lookups the name rule already covers One claimSessionRecord replaces three claim helpers. Save and removal migrate only the older name of the session: a hashed path is never a name an older build wrote, and a case-insensitive volume already opens a case variant through that name, so the extra lower-case and canonical sources found nothing new. The pointer owner lookup replaces the second pointer reader, and disconnect is one handler again. --- .../remote/src/remote-connection-state.ts | 208 +++++++----------- src/cli.ts | 1 - src/cli/commands/connection.ts | 108 +++------ 3 files changed, 110 insertions(+), 207 deletions(-) diff --git a/packages/remote/src/remote-connection-state.ts b/packages/remote/src/remote-connection-state.ts index a5d8766031..ad92f95c06 100644 --- a/packages/remote/src/remote-connection-state.ts +++ b/packages/remote/src/remote-connection-state.ts @@ -262,55 +262,13 @@ export function readRemoteConnectionState(options: { } return observedRemoteConnectionState(options.session, canonical, file.record); } - for (const source of remoteConnectionStateSources(recordsDir, options.session)) { - if (source === canonical) continue; - const legacy = readRecordFile(source); - if ( - legacy.kind === 'owned' && - legacy.session === options.session && - isMovableLegacyRecord(recordsDir, source, legacy) - ) { - return observedRemoteConnectionState(options.session, source, legacy.record); - } - } - return null; -} - -/** - * The session's own path, ready for a save or a removal. Records an older build wrote for the session - * move there first, and a record there that names the session but fails validation is removed. - */ -function claimRemoteConnectionStatePath(options: { stateDir: string; session: string }): string { - const { statePath, record } = claimRemoteConnectionRecord(options); - if (record && !isRemoteConnectionState(record)) { - removeInvalidRemoteConnectionState(options, statePath); - } - return statePath; -} - -/** - * The session's own path and the record there, if any. Records an older build wrote for the session - * move there first. A file there that no session is proven to own, or that another session owns, - * refuses the claim. - */ -function claimRemoteConnectionRecord(options: { stateDir: string; session: string }): { - statePath: string; - record: Record | undefined; -} { - const statePath = remoteConnectionStatePath(options); - const file = readRecordFile(statePath); - if (file.kind === 'absent') return { statePath, record: undefined }; - if (file.kind === 'unknown') - throw recordOwnerUnknownError(options.session, statePath, file.cause); - // Ownership is settled before shape: a record another session owns is never removed as invalid. - if (file.session !== options.session) { - throw sessionMismatchError( - options.session, - statePath, - 'The saved connection belongs to a different session.', - ); - } - return { statePath, record: file.record }; + const legacyPath = path.join(recordsDir, legacyRemoteConnectionFileName(options.session)); + const legacy = readRecordFile(legacyPath); + return legacy.kind === 'owned' && + legacy.session === options.session && + isMovableLegacyRecord(recordsDir, legacyPath, legacy) + ? observedRemoteConnectionState(options.session, legacyPath, legacy.record) + : null; } /** @@ -326,26 +284,52 @@ export function claimRemoteConnectionState(options: { stateDir: string; session: string | undefined; }): RemoteConnectionState | null { - if (options.session !== undefined) { - return claimSessionRecord({ stateDir: options.stateDir, session: options.session }); - } - const claimed = claimSessionRecord({ stateDir: options.stateDir, session: 'default' }); + const { stateDir, session } = options; + if (session !== undefined) return claimSessionRecord({ stateDir, session }).state; + const claimed = claimSessionRecord({ stateDir, session: 'default' }).state; if (claimed) return claimed; - const activeSession = activeRecordOwner(options.stateDir); + const activeSession = activeRecordOwner(stateDir); return activeSession === undefined ? null - : claimSessionRecord({ stateDir: options.stateDir, session: activeSession }); + : claimSessionRecord({ stateDir, session: activeSession }).state; } -function claimSessionRecord(options: { - stateDir: string; - session: string; -}): RemoteConnectionState | null { - const { statePath, record } = claimRemoteConnectionRecord(options); - if (!record) return null; - if (isRemoteConnectionState(record)) return record; - removeInvalidRemoteConnectionState(options, statePath); - return null; +/** + * The session's own path and its valid record there, if any. Records an older build wrote for the + * session move there first, and a record there that names the session but fails validation is removed. + * A file there that no session is proven to own, or that another session owns, refuses the claim. + */ +function claimSessionRecord(options: { stateDir: string; session: string }): { + statePath: string; + state: RemoteConnectionState | null; +} { + const recordsDir = path.join(options.stateDir, 'remote-connections'); + const statePath = canonicalRemoteConnectionStatePath(recordsDir, options.session); + // A record at the name an older build wrote for this session moves to its owner's own path first. + // That name can also open another session's record: it can be this session's own path, or a case + // alias of the other session's older name. A hashed path is never a name an older build wrote. + migrateLegacyRemoteConnectionState({ + recordsDir, + source: path.join(recordsDir, legacyRemoteConnectionFileName(options.session)), + session: options.session, + }); + const file = readRecordFile(statePath); + if (file.kind === 'absent') return { statePath, state: null }; + if (file.kind === 'unknown') { + throw recordOwnerUnknownError(options.session, statePath, file.cause); + } + // Ownership is settled before shape: a record another session owns is never removed as invalid. + if (file.session !== options.session) { + throw sessionMismatchError( + options.session, + statePath, + 'The saved connection belongs to a different session.', + ); + } + if (isRemoteConnectionState(file.record)) return { statePath, state: file.record }; + warnInvalidRecord(options.session, statePath); + removeRemoteConnectionStateFile(options, statePath); + return { statePath, state: null }; } function observedRemoteConnectionState( @@ -354,12 +338,16 @@ function observedRemoteConnectionState( record: Record, ): RemoteConnectionState | null { if (isRemoteConnectionState(record)) return record; + warnInvalidRecord(session, recordPath); + return null; +} + +function warnInvalidRecord(session: string, recordPath: string): void { emitDiagnostic({ level: 'warn', phase: 'remote_connection_state_invalid', data: { session, recordPath }, }); - return null; } function sessionMismatchError(session: string, recordPath: string, message: string): AppError { @@ -391,9 +379,11 @@ export function writeRemoteConnectionState(options: { */ onSessionRecordCommitted?: () => void; }): void { - const location = { stateDir: options.stateDir, session: options.state.session }; retireRecordAtActivePointer(options.stateDir, options.state.session); - const statePath = claimRemoteConnectionStatePath(location); + const { statePath } = claimSessionRecord({ + stateDir: options.stateDir, + session: options.state.session, + }); fs.mkdirSync(path.dirname(statePath), { recursive: true }); writeJsonFile(statePath, options.state); options.onSessionRecordCommitted?.(); @@ -414,7 +404,7 @@ export function buildRemoteConnectionDaemonState( } export function removeRemoteConnectionState(options: { stateDir: string; session: string }): void { - removeRemoteConnectionStateFile(options, claimRemoteConnectionStatePath(options)); + removeRemoteConnectionStateFile(options, claimSessionRecord(options).statePath); } function removeRemoteConnectionStateFile( @@ -423,8 +413,7 @@ function removeRemoteConnectionStateFile( ): void { fs.rmSync(statePath, { force: true }); const activePath = activeConnectionStatePath(options.stateDir); - const activeSession = readActiveConnectionSession(options.stateDir); - if (activeSession === options.session) { + if (activeRecordOwner(options.stateDir) === options.session) { fs.rmSync(activePath, { force: true }); } } @@ -671,27 +660,7 @@ const PLAIN_SESSION_NAME = /^[a-z0-9_-][a-z0-9._-]*$/; * A plain name is stored under itself. Any other name is stored under the SHA-256 of its UTF-16 code * units, so names that differ only in case, or in lone surrogates, get different files. Neither form * can be a case alias of another session's file or of the active-session pointer. - * - * Before resolving, records that older builds wrote under sanitized names move once to their owners' - * own paths. See {@link migrateLegacyRemoteConnectionState}. */ -function remoteConnectionStatePath(options: { stateDir: string; session: string }): string { - const recordsDir = path.join(options.stateDir, 'remote-connections'); - for (const source of remoteConnectionStateSources(recordsDir, options.session)) { - migrateLegacyRemoteConnectionState({ recordsDir, source, session: options.session }); - } - return canonicalRemoteConnectionStatePath(recordsDir, options.session); -} - -/** The paths a record `session` owns can be at: its own path first, then the names older builds wrote. */ -function remoteConnectionStateSources(recordsDir: string, session: string): Set { - const sources = new Set([canonicalRemoteConnectionStatePath(recordsDir, session)]); - sources.add(path.join(recordsDir, legacyRemoteConnectionFileName(session))); - const lowered = session.toLowerCase(); - if (PLAIN_SESSION_NAME.test(lowered)) sources.add(path.join(recordsDir, `${lowered}.json`)); - return sources; -} - function canonicalRemoteConnectionStatePath(recordsDir: string, session: string): string { if (PLAIN_SESSION_NAME.test(session)) return path.join(recordsDir, `${session}.json`); const identity = crypto @@ -717,7 +686,9 @@ type RecordFile = | { kind: 'absent' } /** The file exists but could not be read or parsed, or names no session: its owner is unknown. */ | { kind: 'unknown'; cause: unknown } - | { kind: 'owned'; session: string; record: Record }; + | OwnedRecordFile; + +type OwnedRecordFile = { kind: 'owned'; session: string; record: Record }; /** What the file at `filePath` holds. Only `ENOENT` means absent. */ function readRecordFile(filePath: string): RecordFile { @@ -759,10 +730,10 @@ function migrateLegacyRemoteConnectionState(options: { recordsDir: string; source: string; session: string; -}): void { +}): boolean { const file = readRecordFile(options.source); if (file.kind !== 'owned' || !isMovableLegacyRecord(options.recordsDir, options.source, file)) { - return; + return false; } const target = canonicalRemoteConnectionStatePath(options.recordsDir, file.session); try { @@ -778,6 +749,7 @@ function migrateLegacyRemoteConnectionState(options: { } } fs.rmSync(options.source, { force: true }); + return true; } /** @@ -785,8 +757,7 @@ function migrateLegacyRemoteConnectionState(options: { * name an older build wrote for that session, compared case-insensitively, and not its own path. A * pointer at the active-session pointer path, or at a case alias of it, is no record. */ -function isMovableLegacyRecord(recordsDir: string, source: string, file: RecordFile): boolean { - if (file.kind !== 'owned') return false; +function isMovableLegacyRecord(recordsDir: string, source: string, file: OwnedRecordFile): boolean { const sourceName = path.basename(source).toLowerCase(); if (sourceName === ACTIVE_SESSION_FILE_NAME && isActiveSessionPointer(file.record)) return false; // Canonical names hold no upper-case letters, so a name that folds onto the target IS the target. @@ -814,14 +785,12 @@ function retireRecordAtActivePointer(stateDir: string, session: string): void { if (file.kind === 'absent') return; if (file.kind === 'unknown') throw recordOwnerUnknownError(session, activePath, file.cause); if (isActiveSessionPointer(file.record)) return; - migrateLegacyRemoteConnectionState({ recordsDir, source: activePath, session }); - if (fs.existsSync(activePath)) { - throw sessionMismatchError( - session, - activePath, - 'The active-session pointer path holds a saved connection whose owner is unproven.', - ); - } + if (migrateLegacyRemoteConnectionState({ recordsDir, source: activePath, session })) return; + throw sessionMismatchError( + session, + activePath, + 'The active-session pointer path holds a saved connection whose owner is unproven.', + ); } function activeConnectionStatePath(stateDir: string): string { @@ -851,22 +820,10 @@ function activeRecordOwner(stateDir: string): string | undefined { const activePath = activeConnectionStatePath(stateDir); const file = readRecordFile(activePath); if (file.kind !== 'owned') return undefined; - if ( - !isActiveSessionPointer(file.record) && - !isMovableLegacyRecord(path.dirname(activePath), activePath, file) - ) { - return undefined; - } - return file.session; -} - -/** - * The session the active-session pointer names. A file at the pointer path that is not a pointer, such - * as a full record an older build wrote there, names no session. - */ -function readActiveConnectionSession(stateDir: string): string | undefined { - const file = readRecordFile(activeConnectionStatePath(stateDir)); - return file.kind === 'owned' && isActiveSessionPointer(file.record) ? file.session : undefined; + const isPointer = isActiveSessionPointer(file.record); + return isPointer || isMovableLegacyRecord(path.dirname(activePath), activePath, file) + ? file.session + : undefined; } export function fingerprint(value: string | undefined): string | undefined { @@ -918,19 +875,6 @@ function sanitizeDaemonBaseUrl(value: string | undefined): string | undefined { return url.toString().replace(/\/+$/, ''); } -/** Removes a record that names this session but fails validation. Callers prove ownership first. */ -function removeInvalidRemoteConnectionState( - options: { stateDir: string; session: string }, - statePath: string, -): void { - emitDiagnostic({ - level: 'warn', - phase: 'remote_connection_state_invalid', - data: { session: options.session }, - }); - removeRemoteConnectionStateFile(options, statePath); -} - function isRemoteConnectionState(value: unknown): value is RemoteConnectionState { if (!value || typeof value !== 'object' || Array.isArray(value)) return false; const record = value as Record; diff --git a/src/cli.ts b/src/cli.ts index 69f2c18871..649d0f763c 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -791,7 +791,6 @@ function resolveActiveConnectionDefaults(options: { ) { return null; } - // Disconnect settles its record and removes invalid ones it passes before the defaults read it. if (options.command === 'disconnect') claimRemoteConnectionState(options); const defaults = resolveRemoteConnectionDefaults({ stateDir: options.stateDir, diff --git a/src/cli/commands/connection.ts b/src/cli/commands/connection.ts index 78ea255165..35b6a914f5 100644 --- a/src/cli/commands/connection.ts +++ b/src/cli/commands/connection.ts @@ -336,74 +336,43 @@ function scopeConnectProfile( }; } -/** - * The record moves to its session's own path before any teardown, so a record this command cannot - * remove is refused before its session closes or its lease ends. Returns undefined after reporting - * that no connection exists. - */ -async function claimOrReportNothingToRemove( - flags: CliFlags, - stateDir: string, -): Promise { +export const disconnectCommand: ClientCommandHandler = async ({ flags, client, host }) => { + const stateDir = resolveConnectionStateDir(flags, host); + // The record moves to its session's own path before any teardown, so a record this command cannot + // remove is refused before its session closes or its lease ends. const state = claimRemoteConnectionState({ stateDir, session: flags.session }); - if (state) return state; - await writeNoRemoteConnectionOutput(flags, flags.session ?? 'default'); - return undefined; -} - -type ConnectionClient = Parameters[0]['client']; - -type DisconnectTeardown = { - providerData: CloudProviderSessionResult | undefined; - released: boolean; - releaseError: string | undefined; -}; - -async function closeConnectedSession( - client: ConnectionClient, - state: RemoteConnectionState, - flags: CliFlags, -): Promise { - if (!state.leaseId && !state.runtime && !state.metro) return undefined; - try { - return (await client.sessions.close({ session: state.session, shutdown: flags.shutdown })) - .provider; - } catch { - // Disconnect is idempotent; the session may already be closed. - return undefined; + if (!state) { + await writeNoRemoteConnectionOutput(flags, flags.session ?? 'default'); + return true; + } + requireLeasedConnectionSession(state, flags.session); + const connectedSession = state.session; + + let providerData: CloudProviderSessionResult | undefined; + if (state.leaseId || state.runtime || state.metro) { + try { + providerData = ( + await client.sessions.close({ session: connectedSession, shutdown: flags.shutdown }) + ).provider; + } catch { + // Disconnect is idempotent; the session may already be closed. + } } -} - -async function tearDownSessionAndLease( - client: ConnectionClient, - state: RemoteConnectionState, - flags: CliFlags, -): Promise { - let providerData = await closeConnectedSession(client, state, flags); await stopMetroCleanup(state.metro); - if (!state.leaseId) return { providerData, released: false, releaseError: undefined }; - try { - const release = await releaseRemoteConnectionLease(client, state, flags.daemonAuthToken); - providerData ??= release.provider; - return { providerData, released: release.released, releaseError: undefined }; - } catch (error) { - // An inactive lease is already gone. Any other failure leaves a live lease whose only local - // record is removed afterwards, so the output must name it. - return { - providerData, - released: false, - releaseError: isInactiveLeaseError(error) ? undefined : errorMessage(error), - }; + let released = false; + let releaseError: string | undefined; + if (state.leaseId) { + try { + const release = await releaseRemoteConnectionLease(client, state, flags.daemonAuthToken); + released = release.released; + providerData ??= release.provider; + } catch (error) { + // An inactive lease is already gone. Any other failure leaves a live lease whose only local + // record is removed below, so the output must name it. + if (!isInactiveLeaseError(error)) releaseError = errorMessage(error); + } } -} - -async function finishDisconnect( - flags: CliFlags, - stateDir: string, - state: RemoteConnectionState, - { providerData, released, releaseError }: DisconnectTeardown, -): Promise { - removeRemoteConnectionState({ stateDir, session: state.session }); + removeRemoteConnectionState({ stateDir, session: connectedSession }); // A failed release keeps the profile: retrying that release needs it. if (!releaseError) { removeGeneratedRemoteConfigIfUnused({ stateDir, remoteConfigPath: state.remoteConfigPath }); @@ -412,22 +381,13 @@ async function finishDisconnect( flags, { connected: false, - session: state.session, + session: connectedSession, released, ...(releaseError ? { leaseId: state.leaseId, releaseError } : {}), ...(providerData ? { provider: providerData } : {}), }, () => renderDisconnectOutput(state, providerData, releaseError), ); -} - -export const disconnectCommand: ClientCommandHandler = async ({ flags, client, host }) => { - const stateDir = resolveConnectionStateDir(flags, host); - const state = await claimOrReportNothingToRemove(flags, stateDir); - if (!state) return true; - requireLeasedConnectionSession(state, flags.session); - const teardown = await tearDownSessionAndLease(client, state, flags); - await finishDisconnect(flags, stateDir, state, teardown); return true; }; From 4c0e3b963749a11d46a292dc2d995791c0f513c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 22 Nov 2026 14:59:20 +0100 Subject: [PATCH 19/22] test(remote): keep one test per saved-connection behavior Case and surrogate pairs share one table. Tests that repeated another test's assertions, or passed for any read because reads never change files, are removed. The case-variant command test is covered by the store test that fails for the same mutants. The empty-session and invalid-record disconnect tests move into connection-disconnect. --- ...-connection-state-session-identity.test.ts | 429 ++++++------------ .../connection-case-variant-session.test.ts | 106 ----- .../commands/connection-disconnect.test.ts | 102 +++-- .../commands/connection-empty-session.test.ts | 44 -- 4 files changed, 188 insertions(+), 493 deletions(-) delete mode 100644 src/cli/commands/connection-case-variant-session.test.ts delete mode 100644 src/cli/commands/connection-empty-session.test.ts diff --git a/packages/remote/src/remote-connection-state-session-identity.test.ts b/packages/remote/src/remote-connection-state-session-identity.test.ts index 24e8815f09..8270228543 100644 --- a/packages/remote/src/remote-connection-state-session-identity.test.ts +++ b/packages/remote/src/remote-connection-state-session-identity.test.ts @@ -1,4 +1,4 @@ -import { test, vi } from 'vitest'; +import { describe, test, vi } from 'vitest'; import assert from 'node:assert/strict'; import crypto from 'node:crypto'; import fs from 'node:fs'; @@ -103,81 +103,39 @@ function captureRefusal(run: () => unknown): AppError { const runsAsRoot = process.getuid?.() === 0; -test('sessions named Demo and demo keep separate records', () => { - const stateDir = mkdtempForTestSync('agent-device-remote-identity-case-'); - writeRemoteConnectionState({ stateDir, state: recordFor('Demo') }); - writeRemoteConnectionState({ stateDir, state: recordFor('demo') }); - - assert.equal( - readRemoteConnectionState({ stateDir, session: 'Demo' })?.runId, - 'run-Demo', - 'reading one session must not return the record the case-variant session wrote', - ); - assert.equal(readRemoteConnectionState({ stateDir, session: 'demo' })?.runId, 'run-demo'); - assert.deepEqual( - recordsIn(stateDir), - [ACTIVE_SESSION_FILE, 'demo.json', hashedFileName('Demo')].sort(), - 'a name that cannot be a filename gets its own hashed file, never one two names share', - ); -}); - -test('sessions named by the lone surrogates U+D800 and U+D801 keep separate records', () => { - const stateDir = mkdtempForTestSync('agent-device-remote-identity-surrogate-'); - writeRemoteConnectionState({ stateDir, state: recordFor('\uD800') }); - writeRemoteConnectionState({ stateDir, state: recordFor('\uD801') }); - - assert.equal(readRemoteConnectionState({ stateDir, session: '\uD800' })?.runId, 'run-\uD800'); - assert.equal(readRemoteConnectionState({ stateDir, session: '\uD801' })?.runId, 'run-\uD801'); - assert.deepEqual( - recordsIn(stateDir), - [ACTIVE_SESSION_FILE, hashedFileName('\uD800'), hashedFileName('\uD801')].sort(), - 'names that UTF-8 encodes alike must still get different files', - ); -}); - -test('disconnecting one of two case-variant sessions leaves the other record', () => { - const stateDir = mkdtempForTestSync('agent-device-remote-identity-remove-'); - writeRemoteConnectionState({ stateDir, state: recordFor('Demo') }); - writeRemoteConnectionState({ stateDir, state: recordFor('demo') }); - - removeRemoteConnectionState({ stateDir, session: 'Demo' }); - - assert.equal(readRemoteConnectionState({ stateDir, session: 'Demo' }), null); - assert.equal( - readRemoteConnectionState({ stateDir, session: 'demo' })?.runId, - 'run-demo', - 'removing a session must not reach through to the file another session owns', - ); -}); - -test('a session name that cannot be a filename is stored under its hash', () => { - const stateDir = mkdtempForTestSync('agent-device-remote-identity-hashed-'); - const session = 'team/dev#1'; - - writeRemoteConnectionState({ stateDir, state: recordFor(session) }); - - assert.deepEqual(recordsIn(stateDir), [hashedFileName(session), ACTIVE_SESSION_FILE].sort()); - assert.equal(readRemoteConnectionState({ stateDir, session })?.runId, `run-${session}`); +describe.each([ + { first: 'Demo', second: 'demo', files: ['demo.json', hashedFileName('Demo')] }, + { + first: '\uD800', + second: '\uD801', + files: [hashedFileName('\uD800'), hashedFileName('\uD801')], + }, +])('sessions named $first and $second', ({ first, second, files }) => { + test('keep separate records, and removing one leaves the other', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-pair-'); + writeRemoteConnectionState({ stateDir, state: recordFor(first) }); + writeRemoteConnectionState({ stateDir, state: recordFor(second) }); + + assert.equal(readRemoteConnectionState({ stateDir, session: first })?.runId, `run-${first}`); + assert.equal(readRemoteConnectionState({ stateDir, session: second })?.runId, `run-${second}`); + assert.deepEqual(recordsIn(stateDir), [ACTIVE_SESSION_FILE, ...files].sort()); + + removeRemoteConnectionState({ stateDir, session: first }); + assert.equal(readRemoteConnectionState({ stateDir, session: first }), null); + assert.equal(readRemoteConnectionState({ stateDir, session: second })?.runId, `run-${second}`); + }); }); -test('a record at the sanitized path that names this session moves to its hashed path on save', () => { +test('a record at the sanitized path that names this session is read in place and moves on save', () => { const stateDir = mkdtempForTestSync('agent-device-remote-identity-legacy-match-'); const session = 'team/dev#1'; writeRecordFile(stateDir, sanitizedFileName(session), recordFor(session)); - assert.equal( - readRemoteConnectionState({ stateDir, session })?.runId, - `run-${session}`, - 'a record written before hashed paths still serves the session it names', - ); + assert.equal(readRemoteConnectionState({ stateDir, session })?.runId, `run-${session}`); assert.deepEqual(recordsIn(stateDir), [sanitizedFileName(session)], 'a read moved no file'); writeRemoteConnectionState({ stateDir, state: { ...recordFor(session), runId: 'run-saved' } }); - assert.deepEqual( - recordsIn(stateDir), - [ACTIVE_SESSION_FILE, hashedFileName(session)].sort(), - 'the record now lives only at the hashed path, and the sanitized name is gone', - ); + assert.deepEqual(recordsIn(stateDir), [ACTIVE_SESSION_FILE, hashedFileName(session)].sort()); assert.equal(readRemoteConnectionState({ stateDir, session })?.runId, 'run-saved'); }); @@ -200,7 +158,6 @@ test('a sanitized record whose hashed path is already taken is kept and refused' const legacyPath = writeRecordFile(stateDir, sanitizedFileName(session), recordFor(session)); writeRecordFile(stateDir, hashedFileName(session), recordFor(session)); - assert.equal(readRemoteConnectionState({ stateDir, session })?.runId, `run-${session}`); const refusal = captureRefusal(() => removeRemoteConnectionState({ stateDir, session })); assert.equal(refusal.details?.reason, 'connection_session_mismatch'); @@ -216,11 +173,7 @@ test('a record an older build shared with a case-variant session moves to its ow const stateDir = mkdtempForTestSync('agent-device-remote-identity-upgrade-'); plantFileSharedByCaseVariants(stateDir, 'Demo'); - assert.equal( - readRemoteConnectionState({ stateDir, session: 'demo' }), - null, - 'the record an older build wrote for Demo is not the demo session connection', - ); + assert.equal(readRemoteConnectionState({ stateDir, session: 'demo' }), null); assert.equal(readRemoteConnectionState({ stateDir, session: 'Demo' })?.runId, 'run-Demo'); writeRemoteConnectionState({ stateDir, state: recordFor('demo') }); @@ -230,241 +183,108 @@ test('a record an older build shared with a case-variant session moves to its ow recordsIn(stateDir).filter((name) => name !== 'Demo.json'), [ACTIVE_SESSION_FILE, 'demo.json', hashedFileName('Demo')].sort(), ); - assert.equal(readRemoteConnectionState({ stateDir, session: 'demo' })?.runId, 'run-demo'); - assert.equal(readRemoteConnectionState({ stateDir, session: 'Demo' })?.runId, 'run-Demo'); removeRemoteConnectionState({ stateDir, session: 'demo' }); assert.equal(readRemoteConnectionState({ stateDir, session: 'demo' }), null); - assert.equal( - readRemoteConnectionState({ stateDir, session: 'Demo' })?.runId, - 'run-Demo', - 'removing one session must not reach the record the other one owns', - ); + assert.equal(readRemoteConnectionState({ stateDir, session: 'Demo' })?.runId, 'run-Demo'); }); -for (const [damage, skip] of [ - ['unreadable', runsAsRoot], - ['unparseable', false], -] as const) { - test.skipIf(skip)( - `an ${damage} record an older build shared with a case-variant session is never removed`, - () => { - const stateDir = mkdtempForTestSync(`agent-device-remote-identity-${damage}-`); - const sharedPath = - damage === 'unreadable' - ? plantFileSharedByCaseVariants(stateDir, 'Demo') - : plantFileSharedByCaseVariants(stateDir, 'Demo', '{"session": "Demo",'); - if (damage === 'unreadable') fs.chmodSync(sharedPath, 0o000); - const planted = recordsIn(stateDir); - try { - const refusal = captureRefusal(() => - readRemoteConnectionState({ stateDir, session: 'demo' }), - ); - assert.equal(refusal.details?.reason, 'connection_record_owner_unknown'); - assert.equal( - readRemoteConnectionState({ stateDir, session: 'Demo' }), - null, - 'a record whose owner is unknown does not serve any session', - ); - captureRefusal(() => writeRemoteConnectionState({ stateDir, state: recordFor('demo') })); - captureRefusal(() => removeRemoteConnectionState({ stateDir, session: 'demo' })); - assert.deepEqual(recordsIn(stateDir), planted, 'no command removed the shared file'); - } finally { - fs.chmodSync(sharedPath, 0o600); - } - }, - ); -} - -test('a record that fails validation is removed only by a removal for the session it names', () => { - const stateDir = mkdtempForTestSync('agent-device-remote-identity-invalid-'); - const foreignPath = writeRecordFile(stateDir, 'demo.json', { - ...recordFor('other'), - updatedAt: null, - }); - const ownPath = writeRecordFile(stateDir, 'other.json', { - ...recordFor('other'), - updatedAt: null, +describe.each([ + { damage: 'unreadable', skip: runsAsRoot }, + { damage: 'unparseable', skip: false }, +])('an $damage record an older build shared with a case-variant session', ({ damage, skip }) => { + test.skipIf(skip)('is never removed and serves no session', () => { + const stateDir = mkdtempForTestSync(`agent-device-remote-identity-${damage}-`); + const sharedPath = + damage === 'unreadable' + ? plantFileSharedByCaseVariants(stateDir, 'Demo') + : plantFileSharedByCaseVariants(stateDir, 'Demo', '{"session": "Demo",'); + if (damage === 'unreadable') fs.chmodSync(sharedPath, 0o000); + const planted = recordsIn(stateDir); + try { + const refusal = captureRefusal(() => + readRemoteConnectionState({ stateDir, session: 'demo' }), + ); + assert.equal(refusal.details?.reason, 'connection_record_owner_unknown'); + assert.equal(readRemoteConnectionState({ stateDir, session: 'Demo' }), null); + captureRefusal(() => writeRemoteConnectionState({ stateDir, state: recordFor('demo') })); + captureRefusal(() => removeRemoteConnectionState({ stateDir, session: 'demo' })); + assert.deepEqual(recordsIn(stateDir), planted, 'no command removed the shared file'); + } finally { + fs.chmodSync(sharedPath, 0o600); + } }); - - const refusal = captureRefusal(() => readRemoteConnectionState({ stateDir, session: 'demo' })); - assert.equal(refusal.details?.reason, 'connection_session_mismatch'); - assert.equal(fs.existsSync(foreignPath), true, 'an invalid record of another session is kept'); - - captureRefusal(() => removeRemoteConnectionState({ stateDir, session: 'demo' })); - assert.equal(fs.existsSync(foreignPath), true, 'an invalid record of another session is kept'); - - assert.equal(readRemoteConnectionState({ stateDir, session: 'other' }), null); - assert.equal(fs.existsSync(ownPath), true, 'a read keeps an invalid record'); - removeRemoteConnectionState({ stateDir, session: 'other' }); - assert.equal(fs.existsSync(ownPath), false, 'an invalid record of this session is removed'); }); -test('an invalid record of the U+D800 session survives a U+D801 read', () => { - const stateDir = mkdtempForTestSync('agent-device-remote-identity-invalid-surrogate-'); - const recordPath = writeRecordFile(stateDir, hashedFileName('\uD800'), { - ...recordFor('\uD800'), +test('an invalid record of another session at a session path refuses read, save and removal', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-mismatch-'); + // Ownership is settled before shape: a record that fails validation is still another session's. + const statePath = writeRecordFile(stateDir, 'demo.json', { + ...recordFor('other'), updatedAt: null, }); - assert.equal(readRemoteConnectionState({ stateDir, session: '\uD801' }), null); - assert.equal(fs.existsSync(recordPath), true); -}); - -test('a session named by a case alias of the pointer file is stored under its hash', () => { - const stateDir = mkdtempForTestSync('agent-device-remote-identity-pointer-alias-'); - const session = '.ACTIVE-SESSION'; - writeRecordFile(stateDir, `${session}.json`, recordFor(session)); - - writeRemoteConnectionState({ stateDir, state: recordFor('demo') }); - - assert.equal(readRemoteConnectionState({ stateDir, session })?.runId, `run-${session}`); - assert.deepEqual( - JSON.parse(fs.readFileSync(path.join(stateDir, RECORDS_DIR, ACTIVE_SESSION_FILE), 'utf8')), - { session: 'demo' }, - ); - - removeRemoteConnectionState({ stateDir, session }); - assert.equal(readRemoteConnectionState({ stateDir, session }), null); - assert.deepEqual(recordsIn(stateDir), [ACTIVE_SESSION_FILE, 'demo.json'].sort()); -}); - -test('a record left on the pointer path moves to its owner before the pointer is written', () => { - const stateDir = mkdtempForTestSync('agent-device-remote-identity-pointer-'); - // A build that sanitized names wrote the session `.active-session` to exactly the pointer path. - const session = '.active-session'; - writeRecordFile(stateDir, ACTIVE_SESSION_FILE, recordFor(session)); - - writeRemoteConnectionState({ stateDir, state: recordFor('demo') }); + const read = captureRefusal(() => readRemoteConnectionState({ stateDir, session: 'demo' })); + assert.equal(read.code, 'COMMAND_FAILED'); + assert.equal(read.details?.reason, 'connection_session_mismatch'); + assert.equal(read.details?.session, 'demo'); + assert.equal(read.details?.recordPath, statePath); + assert.ok(String(read.details?.hint).includes(statePath), 'the recovery names the file'); - assert.equal(readRemoteConnectionState({ stateDir, session })?.runId, `run-${session}`); - assert.deepEqual( - recordsIn(stateDir), - [ACTIVE_SESSION_FILE, 'demo.json', hashedFileName(session)].sort(), - ); + for (const run of [ + () => writeRemoteConnectionState({ stateDir, state: recordFor('demo') }), + () => removeRemoteConnectionState({ stateDir, session: 'demo' }), + ]) { + assert.equal(captureRefusal(run).details?.reason, 'connection_session_mismatch'); + } + assert.equal(JSON.parse(fs.readFileSync(statePath, 'utf8')).session, 'other'); }); -test('a record of unproven owner on the pointer path refuses the pointer write', () => { - const stateDir = mkdtempForTestSync('agent-device-remote-identity-pointer-foreign-'); - const pointerPath = writeRecordFile(stateDir, ACTIVE_SESSION_FILE, recordFor('team')); - - const refusal = captureRefusal(() => - writeRemoteConnectionState({ stateDir, state: recordFor('demo') }), - ); +test('a read reports an invalid record of its session as no connection and keeps it', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-observe-invalid-'); + writeRecordFile(stateDir, 'demo.json', { ...recordFor('demo'), updatedAt: null }); + writeRecordFile(stateDir, 'Team.json', { ...recordFor('Team'), updatedAt: null }); + writeRecordFile(stateDir, ACTIVE_SESSION_FILE, { session: 'demo' }); - assert.equal(refusal.details?.reason, 'connection_session_mismatch'); - assert.equal(JSON.parse(fs.readFileSync(pointerPath, 'utf8')).session, 'team'); - assert.deepEqual(recordsIn(stateDir), [ACTIVE_SESSION_FILE], 'nothing else was written'); + assert.equal(readRemoteConnectionState({ stateDir, session: 'demo' }), null); + assert.equal(readActiveConnectionState({ stateDir }), null); + assert.equal(readRemoteConnectionState({ stateDir, session: 'Team' }), null); + assert.deepEqual(recordsIn(stateDir), [ACTIVE_SESSION_FILE, 'Team.json', 'demo.json'].sort()); }); -test('the last guard names the record it refused and how to clear it', () => { - const stateDir = mkdtempForTestSync('agent-device-remote-identity-mismatch-'); - // A foreign record planted at a session's own path, or one that changed under a command in flight. - const session = 'team/dev#1'; - const statePath = writeRecordFile(stateDir, hashedFileName(session), recordFor('team:dev#1')); +test('remote command defaults resolve from an older Demo.json without moving it', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-defaults-'); + const remoteConfigPath = path.join(stateDir, 'remote.json'); + fs.writeFileSync(remoteConfigPath, '{}'); + writeRecordFile(stateDir, 'Demo.json', { + ...recordFor('Demo'), + remoteConfigPath, + remoteConfigHash: hashRemoteConfigFile(remoteConfigPath), + }); - const read = captureRefusal(() => readRemoteConnectionState({ stateDir, session })); - assert.equal(read.code, 'COMMAND_FAILED'); - assert.equal(read.details?.reason, 'connection_session_mismatch'); - assert.equal(read.details?.session, session); - assert.equal(read.details?.recordPath, statePath); - assert.ok( - String(read.details?.hint).includes(statePath), - 'the recovery names the file it wants removed', - ); + const defaults = resolveRemoteConnectionDefaults({ + stateDir, + session: 'Demo', + cwd: stateDir, + env: {}, + }); - const write = captureRefusal(() => - writeRemoteConnectionState({ stateDir, state: recordFor(session) }), - ); - assert.equal(write.details?.reason, 'connection_session_mismatch'); - - const remove = captureRefusal(() => removeRemoteConnectionState({ stateDir, session })); - assert.equal(remove.details?.reason, 'connection_session_mismatch'); - assert.equal( - fs.existsSync(statePath), - true, - 'a refused disconnect must not delete the record it would have overwritten', - ); + assert.equal(defaults?.flags.session, 'Demo'); + assert.equal(defaults?.flags.remoteConfig, remoteConfigPath); + assert.deepEqual(recordsIn(stateDir), ['Demo.json']); }); -test('an empty session moves the record an older build saved for it as default.json on save', () => { +test('the empty session owns the default.json an older build wrote for it, and default does not', () => { const stateDir = mkdtempForTestSync('agent-device-remote-identity-empty-'); writeRecordFile(stateDir, 'default.json', recordFor('')); - writeRemoteConnectionState({ stateDir, state: { ...recordFor(''), runId: 'run-saved' } }); - assert.equal(readRemoteConnectionState({ stateDir, session: '' })?.runId, 'run-saved'); - assert.deepEqual(recordsIn(stateDir), [ACTIVE_SESSION_FILE, hashedFileName('')].sort()); -}); - -test.skipIf(runsAsRoot)( - 'a read-only records directory reports an older record of the exact session and refuses its removal', - () => { - const stateDir = mkdtempForTestSync('agent-device-remote-identity-readonly-'); - writeRecordFile(stateDir, 'Demo.json', recordFor('Demo')); - const recordsDir = path.join(stateDir, RECORDS_DIR); - fs.chmodSync(recordsDir, 0o500); - try { - assert.equal(readRemoteConnectionState({ stateDir, session: 'Demo' })?.runId, 'run-Demo'); - assert.throws(() => removeRemoteConnectionState({ stateDir, session: 'Demo' }), { - code: 'EACCES', - }); - assert.deepEqual(recordsIn(stateDir), ['Demo.json']); - } finally { - fs.chmodSync(recordsDir, 0o700); - } - }, -); - -test.skipIf(runsAsRoot)( - 'remote command defaults resolve from an older Demo.json in a read-only records directory', - () => { - const stateDir = mkdtempForTestSync('agent-device-remote-identity-readonly-defaults-'); - const remoteConfigPath = path.join(stateDir, 'remote.json'); - fs.writeFileSync(remoteConfigPath, '{}'); - writeRecordFile(stateDir, 'Demo.json', { - ...recordFor('Demo'), - remoteConfigPath, - remoteConfigHash: hashRemoteConfigFile(remoteConfigPath), - }); - const recordsDir = path.join(stateDir, RECORDS_DIR); - fs.chmodSync(recordsDir, 0o500); - try { - const defaults = resolveRemoteConnectionDefaults({ - stateDir, - session: 'Demo', - cwd: stateDir, - env: {}, - }); - assert.equal(defaults?.flags.session, 'Demo'); - assert.equal(defaults?.flags.remoteConfig, remoteConfigPath); - assert.deepEqual(recordsIn(stateDir), ['Demo.json']); - } finally { - fs.chmodSync(recordsDir, 0o700); - } - }, -); - -test('a read on a valid older Demo.json reports it and leaves the directory unchanged', () => { - const stateDir = mkdtempForTestSync('agent-device-remote-identity-observe-legacy-'); - writeRecordFile(stateDir, 'Demo.json', recordFor('Demo')); - writeRecordFile(stateDir, 'default.json', recordFor('')); - - assert.equal(readRemoteConnectionState({ stateDir, session: 'Demo' })?.runId, 'run-Demo'); assert.equal(readRemoteConnectionState({ stateDir, session: '' })?.runId, 'run-'); assert.equal(readRemoteConnectionState({ stateDir, session: 'default' }), null); - assert.deepEqual(recordsIn(stateDir), ['Demo.json', 'default.json'], 'a read moved no file'); -}); - -test('a read on an invalid record that names the session leaves it and its pointer in place', () => { - const stateDir = mkdtempForTestSync('agent-device-remote-identity-observe-invalid-'); - writeRecordFile(stateDir, 'demo.json', { ...recordFor('demo'), updatedAt: null }); - writeRecordFile(stateDir, 'Team.json', { ...recordFor('Team'), updatedAt: null }); - writeRecordFile(stateDir, ACTIVE_SESSION_FILE, { session: 'demo' }); + assert.deepEqual(recordsIn(stateDir), ['default.json'], 'a read moved no file'); - assert.equal(readRemoteConnectionState({ stateDir, session: 'demo' }), null); - assert.equal(readActiveConnectionState({ stateDir }), null); - assert.equal(readRemoteConnectionState({ stateDir, session: 'Team' }), null); - assert.deepEqual(recordsIn(stateDir), [ACTIVE_SESSION_FILE, 'Team.json', 'demo.json'].sort()); + writeRemoteConnectionState({ stateDir, state: { ...recordFor(''), runId: 'run-saved' } }); + assert.equal(readRemoteConnectionState({ stateDir, session: '' })?.runId, 'run-saved'); + assert.deepEqual(recordsIn(stateDir), [ACTIVE_SESSION_FILE, hashedFileName('')].sort()); }); test('an EPERM hard-link failure never deletes default.json', () => { @@ -498,6 +318,38 @@ test('an empty-session pointer resolves for an unnamed read', () => { assert.equal(readActiveConnectionState({ stateDir })?.runId, 'run-'); }); +test('the record an older build wrote for .active-session at the pointer path is read, then moved before the pointer write', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-pointer-'); + // A build that sanitized names wrote the session `.active-session` to exactly the pointer path. + const session = '.active-session'; + writeRecordFile(stateDir, ACTIVE_SESSION_FILE, recordFor(session)); + + assert.equal(readActiveConnectionState({ stateDir })?.runId, `run-${session}`); + assert.deepEqual(recordsIn(stateDir), [ACTIVE_SESSION_FILE], 'the active lookup moved no file'); + + writeRemoteConnectionState({ stateDir, state: recordFor('demo') }); + + assert.equal(readRemoteConnectionState({ stateDir, session })?.runId, `run-${session}`); + assert.equal(readActiveConnectionState({ stateDir })?.runId, 'run-demo'); + assert.deepEqual( + recordsIn(stateDir), + [ACTIVE_SESSION_FILE, 'demo.json', hashedFileName(session)].sort(), + ); +}); + +test('a record of unproven owner on the pointer path refuses the pointer write', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-pointer-foreign-'); + const pointerPath = writeRecordFile(stateDir, ACTIVE_SESSION_FILE, recordFor('team')); + + const refusal = captureRefusal(() => + writeRemoteConnectionState({ stateDir, state: recordFor('demo') }), + ); + + assert.equal(refusal.details?.reason, 'connection_session_mismatch'); + assert.equal(JSON.parse(fs.readFileSync(pointerPath, 'utf8')).session, 'team'); + assert.deepEqual(recordsIn(stateDir), [ACTIVE_SESSION_FILE], 'nothing else was written'); +}); + test('a full record at the pointer path is not deleted by disconnect of the session it names', () => { const stateDir = mkdtempForTestSync('agent-device-remote-identity-pointer-record-'); writeRemoteConnectionState({ stateDir, state: recordFor('demo') }); @@ -506,22 +358,9 @@ test('a full record at the pointer path is not deleted by disconnect of the sess runId: 'run-at-pointer', }); - assert.equal( - readActiveConnectionState({ stateDir }), - null, - 'a full record is not a pointer, so unnamed status selects no session from it', - ); + assert.equal(readActiveConnectionState({ stateDir }), null, 'a full record is no pointer'); removeRemoteConnectionState({ stateDir, session: 'demo' }); assert.equal(JSON.parse(fs.readFileSync(pointerPath, 'utf8')).runId, 'run-at-pointer'); assert.deepEqual(recordsIn(stateDir), [ACTIVE_SESSION_FILE]); }); - -test('the active lookup accepts a full record at the pointer path that an older build wrote for .active-session', () => { - const stateDir = mkdtempForTestSync('agent-device-remote-identity-pointer-legacy-'); - // A build that sanitized names wrote the session `.active-session` to exactly the pointer path. - writeRecordFile(stateDir, ACTIVE_SESSION_FILE, recordFor('.active-session')); - - assert.equal(readActiveConnectionState({ stateDir })?.runId, 'run-.active-session'); - assert.deepEqual(recordsIn(stateDir), [ACTIVE_SESSION_FILE], 'the active lookup moved no file'); -}); diff --git a/src/cli/commands/connection-case-variant-session.test.ts b/src/cli/commands/connection-case-variant-session.test.ts deleted file mode 100644 index 00e9dbb96d..0000000000 --- a/src/cli/commands/connection-case-variant-session.test.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { test } from 'vitest'; -import assert from 'node:assert/strict'; -import fs from 'node:fs'; -import path from 'node:path'; -import { withCapturedStdoutAsync } from '@agent-device/test-kit'; -import { - hashRemoteConfigFile, - readRemoteConnectionState, -} from '@agent-device/remote/remote-connection-state'; -import { - connectionWorkspace, - createTestClient, -} from '../../__tests__/remote-connection.fixtures.ts'; -import { - connectionCommand, - disconnectCommand, -} from '../../__tests__/test-utils/host-bound-commands.ts'; - -// Upgrading on a case-insensitive filesystem left the record an older build wrote for `Demo` at the -// name `demo` opens. `connection status --session demo` and `disconnect --session demo` both answered -// `connection_session_mismatch`, so the session could neither report nor drop its own connection. - -const RECORDS_DIR = 'remote-connections'; - -/** - * Leaves a saved connection for `session` reachable under the name its case-variant opens too, which is - * what a case-insensitive filesystem does by itself. On such a volume the name `Demo` was written under - * already IS the name `demo` opens; on a case-sensitive one, a hard link stands in for that fold. - */ -function plantRecordSharedByCaseVariants(options: { - stateDir: string; - remoteConfigPath: string; - session: string; -}): string { - const recordsDir = path.join(options.stateDir, RECORDS_DIR); - fs.mkdirSync(recordsDir, { recursive: true }); - const now = new Date().toISOString(); - const written = path.join(recordsDir, `${options.session}.json`); - fs.writeFileSync( - written, - `${JSON.stringify( - { - version: 1, - session: options.session, - remoteConfigPath: options.remoteConfigPath, - remoteConfigHash: hashRemoteConfigFile(options.remoteConfigPath), - tenant: 'acme', - runId: `run-${options.session}`, - connectedAt: now, - updatedAt: now, - }, - null, - 2, - )}\n`, - 'utf8', - ); - const aliased = path.join(recordsDir, `${options.session.toLowerCase()}.json`); - try { - fs.linkSync(written, aliased); - } catch (error) { - // EEXIST: the volume folds the two names onto the file that is already there. - if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error; - assert.equal( - fs.readFileSync(aliased, 'utf8'), - fs.readFileSync(written, 'utf8'), - 'the case-variant name must open the record it shares', - ); - } - return written; -} - -for (const [name, run] of [ - ['connection status', connectionCommand], - ['disconnect', disconnectCommand], -] as const) { - test(`${name} for a session whose saved-connection name an older build shared reports no connection`, async () => { - const { tempRoot, stateDir, remoteConfigPath } = connectionWorkspace( - 'agent-device-connection-case-variant-', - ); - fs.writeFileSync(remoteConfigPath, '{}'); - plantRecordSharedByCaseVariants({ - stateDir, - remoteConfigPath, - session: 'Demo', - }); - - const stdout = await withCapturedStdoutAsync(async () => { - // Every call this client answers throws: neither command may reach the daemon. - await run({ - positionals: name === 'connection status' ? ['status'] : [], - flags: { json: true, help: false, version: false, stateDir, session: 'demo' }, - client: createTestClient(), - }); - }); - - const payload = JSON.parse(stdout).data; - assert.equal(payload.connected, false); - assert.equal(payload.session, 'demo'); - assert.equal( - readRemoteConnectionState({ stateDir, session: 'Demo' })?.runId, - 'run-Demo', - 'answering for one session keeps the record the other one owns', - ); - fs.rmSync(tempRoot, { recursive: true, force: true }); - }); -} diff --git a/src/cli/commands/connection-disconnect.test.ts b/src/cli/commands/connection-disconnect.test.ts index 5f1705295b..8d1e3acdab 100644 --- a/src/cli/commands/connection-disconnect.test.ts +++ b/src/cli/commands/connection-disconnect.test.ts @@ -175,44 +175,6 @@ test('disconnect treats an already-inactive lease as released without a failure fs.rmSync(tempRoot, { recursive: true, force: true }); }); -test('disconnect removes a record that names its session but fails validation', async () => { - const { tempRoot, stateDir, remoteConfigPath } = connectionWorkspace( - 'agent-device-disconnect-invalid-record-', - ); - fs.writeFileSync(remoteConfigPath, '{}'); - const recordsDir = path.join(stateDir, 'remote-connections'); - const recordPath = path.join(recordsDir, 'demo.json'); - const activePath = path.join(recordsDir, '.active-session.json'); - fs.mkdirSync(recordsDir, { recursive: true }); - fs.writeFileSync( - recordPath, - JSON.stringify({ - version: 1, - session: 'demo', - remoteConfigPath, - remoteConfigHash: 'hash', - tenant: 'acme', - runId: 'run-demo', - connectedAt: new Date().toISOString(), - updatedAt: null, - }), - ); - fs.writeFileSync(activePath, JSON.stringify({ session: 'demo' })); - - const text = await withCapturedStdoutAsync(async () => { - await disconnectCommand({ - positionals: [], - flags: { json: false, help: false, version: false, stateDir, session: 'demo' }, - client: createTestClient(), - }); - }); - - assert.equal(text.trim(), 'No remote connection for "demo".'); - assert.equal(fs.existsSync(recordPath), false); - assert.equal(fs.existsSync(activePath), false); - fs.rmSync(tempRoot, { recursive: true, force: true }); -}); - test('disconnect refuses a record it cannot remove before it closes the session or releases the lease', async () => { const { tempRoot, stateDir } = seedReleasableConnection( 'agent-device-disconnect-occupied-session-path-', @@ -302,23 +264,67 @@ test('an unnamed disconnect removes an invalid default record and disconnects th fs.rmSync(tempRoot, { recursive: true, force: true }); }); -test('disconnect removes an invalid pointer-shaped record at the legacy file name of its session', async () => { - const { tempRoot, stateDir } = connectionWorkspace('agent-device-disconnect-legacy-pointer-'); - const recordsDir = path.join(stateDir, 'remote-connections'); - const legacyPath = path.join(recordsDir, 'Demo.json'); - fs.mkdirSync(recordsDir, { recursive: true }); +test.each([ + { + name: 'its own file', + session: 'demo', + fileName: 'demo.json', + record: { session: 'demo', version: 1, runId: 'run-demo', updatedAt: null }, + }, // An older build saved Demo at the name it wrote, and the record holds only its session. - fs.writeFileSync(legacyPath, JSON.stringify({ session: 'Demo' })); + { + name: 'its older pointer-shaped file', + session: 'Demo', + fileName: 'Demo.json', + record: { session: 'Demo' }, + }, +])( + 'disconnect removes a record at $name that names its session but fails validation', + async ({ session, fileName, record }) => { + const { tempRoot, stateDir } = connectionWorkspace('agent-device-disconnect-invalid-record-'); + const recordsDir = path.join(stateDir, 'remote-connections'); + fs.mkdirSync(recordsDir, { recursive: true }); + fs.writeFileSync(path.join(recordsDir, fileName), JSON.stringify(record)); + fs.writeFileSync(path.join(recordsDir, '.active-session.json'), JSON.stringify({ session })); - const text = await withCapturedStdoutAsync(async () => { + const text = await withCapturedStdoutAsync(async () => { + await disconnectCommand({ + positionals: [], + flags: { json: false, help: false, version: false, stateDir, session }, + client: createTestClient(), + }); + }); + + assert.equal(text.trim(), `No remote connection for "${session}".`); + assert.deepEqual(fs.readdirSync(recordsDir), []); + fs.rmSync(tempRoot, { recursive: true, force: true }); + }, +); + +// `--session=` names the empty session. Read as an omitted session, it followed the active-session +// pointer and removed the connection the pointer named for another session. +test('disconnect --session= with no empty-session record keeps the record the pointer names', async () => { + const { tempRoot, stateDir, remoteConfigPath } = connectionWorkspace( + 'agent-device-connection-empty-session-', + ); + fs.writeFileSync(remoteConfigPath, '{}'); + seedConnectionState({ + stateDir, + state: { session: 'Demo', remoteConfigPath, tenant: 'acme', runId: 'run-Demo' }, + }); + + const stdout = await withCapturedStdoutAsync(async () => { + // Every call this client answers throws: the command may not reach the daemon. await disconnectCommand({ positionals: [], - flags: { json: false, help: false, version: false, stateDir, session: 'Demo' }, + flags: { json: true, help: false, version: false, stateDir, session: '' }, client: createTestClient(), }); }); - assert.equal(text.trim(), 'No remote connection for "Demo".'); - assert.deepEqual(fs.readdirSync(recordsDir), []); + const payload = JSON.parse(stdout).data; + assert.equal(payload.connected, false); + assert.equal(payload.session, ''); + assert.equal(readRemoteConnectionState({ stateDir, session: 'Demo' })?.runId, 'run-Demo'); fs.rmSync(tempRoot, { recursive: true, force: true }); }); diff --git a/src/cli/commands/connection-empty-session.test.ts b/src/cli/commands/connection-empty-session.test.ts deleted file mode 100644 index 83f17b40be..0000000000 --- a/src/cli/commands/connection-empty-session.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { test } from 'vitest'; -import assert from 'node:assert/strict'; -import fs from 'node:fs'; -import { withCapturedStdoutAsync } from '@agent-device/test-kit'; -import { readRemoteConnectionState } from '@agent-device/remote/remote-connection-state'; -import { - connectionWorkspace, - createTestClient, - seedConnectionState, -} from '../../__tests__/remote-connection.fixtures.ts'; -import { disconnectCommand } from '../../__tests__/test-utils/host-bound-commands.ts'; - -// `--session=` names the empty session. Read as an omitted session, it followed the active-session -// pointer, so `disconnect --session=` removed the connection the pointer named for another session. - -test('disconnect --session= with no empty-session record keeps the record the pointer names', async () => { - const { tempRoot, stateDir, remoteConfigPath } = connectionWorkspace( - 'agent-device-connection-empty-session-', - ); - fs.writeFileSync(remoteConfigPath, '{}'); - seedConnectionState({ - stateDir, - state: { session: 'Demo', remoteConfigPath, tenant: 'acme', runId: 'run-Demo' }, - }); - - const stdout = await withCapturedStdoutAsync(async () => { - // Every call this client answers throws: the command may not reach the daemon. - await disconnectCommand({ - positionals: [], - flags: { json: true, help: false, version: false, stateDir, session: '' }, - client: createTestClient(), - }); - }); - - const payload = JSON.parse(stdout).data; - assert.equal(payload.connected, false); - assert.equal(payload.session, ''); - assert.equal( - readRemoteConnectionState({ stateDir, session: 'Demo' })?.runId, - 'run-Demo', - 'disconnecting the empty session keeps the record of the session the pointer names', - ); - fs.rmSync(tempRoot, { recursive: true, force: true }); -}); From eb31b81aa56c8d8b4dd50e889bb7eb4fdc08c383 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 22 Nov 2026 14:59:20 +0100 Subject: [PATCH 20/22] test(daemon-client): leave the startup gate publish change to its own PR It fixes a flake unrelated to saved-connection ownership. --- .../src/__tests__/daemon-client-startup-budget.test.ts | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/packages/daemon-client/src/__tests__/daemon-client-startup-budget.test.ts b/packages/daemon-client/src/__tests__/daemon-client-startup-budget.test.ts index 3b05f48edd..7d8d388652 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-startup-budget.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-startup-budget.test.ts @@ -19,7 +19,6 @@ import { startHttpDaemonFixture, skipWhenLoopbackUnavailable, } from '@agent-device/test-kit'; -import { publishFileSync } from '@agent-device/host-kit/file'; import { isProcessAlive } from '@agent-device/host-kit/process'; import { readVersion } from '@agent-device/host-kit/version'; import { @@ -188,8 +187,7 @@ test('a daemon slower than the retired 15 s budget starts successfully while it if (spawned.child && now.value - spawned.at < 80_000) { now.value += 20_000; if (nextPhase < phases.length) { - // Published atomically: the child polls this file, and a partial read would lose a phase. - publishFileSync({ destination: gate, contents: phases[nextPhase]! }); + fs.writeFileSync(gate, phases[nextPhase]!); nextPhase += 1; // Wait for the child's real channel message before advancing the clock again, so each // receipt lands on the virtual time this pause just set. @@ -488,7 +486,7 @@ test('a repeated phase message keeps the first receipt time', async () => { now.value += 1_000; const elapsed = now.value - started; if (elapsed === 1_000 || elapsed === 10_000) { - publishFileSync({ destination: gate, contents: 'lock-acquired' }); + fs.writeFileSync(gate, 'lock-acquired'); sent += 1; for (let attempt = 0; reported.length < sent && attempt < 400; attempt += 1) await realPause(5); From 6e4ab95e29a3dfab39610660b50941eaeeb0ef15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 22 Nov 2026 16:25:03 +0100 Subject: [PATCH 21/22] fix(remote): drive disconnect from its one claim and unlink only a pointer The CLI claims the disconnect record before it builds the client, and the handler now tears down that same record instead of resolving it again. An unnamed disconnect of an older .active-session record at the pointer path no longer reports no connection, and a leased one is still refused. Pointer cleanup removes .active-session.json only when it has pointer shape and names the session. A full record there leaves only through the checked move. --- ...-connection-state-session-identity.test.ts | 54 ++++++++++++----- .../remote/src/remote-connection-state.ts | 47 ++++++++++++++- .../cli-disconnect-invalid-default.test.ts | 60 ++++++++++++++++++- src/cli.ts | 19 +++--- src/cli/commands/connection.ts | 25 ++++++-- src/cli/commands/router-types.ts | 3 + src/cli/commands/router.ts | 1 + 7 files changed, 177 insertions(+), 32 deletions(-) diff --git a/packages/remote/src/remote-connection-state-session-identity.test.ts b/packages/remote/src/remote-connection-state-session-identity.test.ts index 8270228543..30efaefd3b 100644 --- a/packages/remote/src/remote-connection-state-session-identity.test.ts +++ b/packages/remote/src/remote-connection-state-session-identity.test.ts @@ -350,17 +350,43 @@ test('a record of unproven owner on the pointer path refuses the pointer write', assert.deepEqual(recordsIn(stateDir), [ACTIVE_SESSION_FILE], 'nothing else was written'); }); -test('a full record at the pointer path is not deleted by disconnect of the session it names', () => { - const stateDir = mkdtempForTestSync('agent-device-remote-identity-pointer-record-'); - writeRemoteConnectionState({ stateDir, state: recordFor('demo') }); - const pointerPath = writeRecordFile(stateDir, ACTIVE_SESSION_FILE, { - ...recordFor('demo'), - runId: 'run-at-pointer', - }); - - assert.equal(readActiveConnectionState({ stateDir }), null, 'a full record is no pointer'); - removeRemoteConnectionState({ stateDir, session: 'demo' }); - - assert.equal(JSON.parse(fs.readFileSync(pointerPath, 'utf8')).runId, 'run-at-pointer'); - assert.deepEqual(recordsIn(stateDir), [ACTIVE_SESSION_FILE]); -}); +describe.each([ + { owner: 'demo', ownSessionRecord: 'demo.json', activeRunId: undefined }, + // `.ACTIVE-SESSION.json` is the older name of `.ACTIVE-SESSION`, so the record looks like that + // session's. Only the checked move may remove it, and the move refuses the occupied hashed path. + { + owner: '.ACTIVE-SESSION', + ownSessionRecord: hashedFileName('.ACTIVE-SESSION'), + activeRunId: 'run-.ACTIVE-SESSION', + }, +])( + 'a full record at the pointer path that names $owner', + ({ owner, ownSessionRecord, activeRunId }) => { + test('is not deleted by removal of that session', () => { + const stateDir = mkdtempForTestSync('agent-device-remote-identity-pointer-record-'); + writeRecordFile(stateDir, ownSessionRecord, recordFor(owner)); + const pointerPath = writeRecordFile(stateDir, ACTIVE_SESSION_FILE, { + ...recordFor(owner), + runId: 'run-at-pointer', + }); + assert.equal(readActiveConnectionState({ stateDir })?.runId, activeRunId); + // On a case-insensitive volume `.ACTIVE-SESSION.json` opens the pointer file. A case-sensitive + // volume keeps the names apart, so the removal reaches the pointer without the checked move. + const readFileSync = fs.readFileSync; + const read = vi.spyOn(fs, 'readFileSync').mockImplementation(((file, ...rest) => { + if (path.basename(String(file)) === '.ACTIVE-SESSION.json') { + throw Object.assign(new Error('ENOENT: no such file'), { code: 'ENOENT' }); + } + return readFileSync(file, ...rest); + }) as typeof fs.readFileSync); + try { + removeRemoteConnectionState({ stateDir, session: owner }); + } finally { + read.mockRestore(); + } + + assert.equal(JSON.parse(fs.readFileSync(pointerPath, 'utf8')).runId, 'run-at-pointer'); + assert.deepEqual(recordsIn(stateDir), [ACTIVE_SESSION_FILE]); + }); + }, +); diff --git a/packages/remote/src/remote-connection-state.ts b/packages/remote/src/remote-connection-state.ts index ad92f95c06..2ca43e968b 100644 --- a/packages/remote/src/remote-connection-state.ts +++ b/packages/remote/src/remote-connection-state.ts @@ -220,6 +220,8 @@ type RemoteConnectionDefaults = { flags: Partial; runtime?: SessionRuntimeHints; connection?: RemoteConnectionRequestMetadata; + /** Set only by {@link claimRemoteConnectionDefaults}: the record it claimed, or `null` for none. */ + claimed?: RemoteConnectionState | null; }; const REMOTE_CONNECTION_STATE_REASONS = { @@ -412,8 +414,15 @@ function removeRemoteConnectionStateFile( statePath: string, ): void { fs.rmSync(statePath, { force: true }); + // Only a pointer is removed here. A full record an older build wrote at the pointer path leaves only + // through the checked move in migrateLegacyRemoteConnectionState. const activePath = activeConnectionStatePath(options.stateDir); - if (activeRecordOwner(options.stateDir) === options.session) { + const active = readRecordFile(activePath); + if ( + active.kind === 'owned' && + active.session === options.session && + isActiveSessionPointer(active.record) + ) { fs.rmSync(activePath, { force: true }); } } @@ -474,8 +483,42 @@ export function resolveRemoteConnectionDefaults(options: { env: Record; validateRemoteConfigHash?: boolean; }): RemoteConnectionDefaults | null { + return remoteConnectionDefaults(selectRemoteConnectionState(options), options); +} + +/** + * The defaults for `disconnect`, taken from the record {@link claimRemoteConnectionState} claims. + * + * The returned `claimed` record also drives the teardown, so the record is resolved once. A leased + * record is refused when the caller named no session. The defaults are empty when no record is + * claimed or the record connects through another `remoteConfig` than the one requested. + */ +export function claimRemoteConnectionDefaults(options: { + stateDir: string; + session: string | undefined; + remoteConfig?: string; + cwd: string; + env: Record; +}): RemoteConnectionDefaults { + const claimed = claimRemoteConnectionState(options); + if (claimed) requireLeasedConnectionSession(claimed, options.session); + const selected = claimed && matchesRequestedRemoteConfig(claimed, options) ? claimed : null; + const defaults = remoteConnectionDefaults(selected, { + ...options, + validateRemoteConfigHash: false, + }); + return { flags: {}, ...defaults, claimed }; +} + +function remoteConnectionDefaults( + state: RemoteConnectionState | null, + options: { + cwd: string; + env: Record; + validateRemoteConfigHash?: boolean; + }, +): RemoteConnectionDefaults | null { const validateRemoteConfigHash = options.validateRemoteConfigHash ?? true; - const state = selectRemoteConnectionState(options); if (!state) return null; if ( validateRemoteConfigHash && diff --git a/src/__tests__/cli-disconnect-invalid-default.test.ts b/src/__tests__/cli-disconnect-invalid-default.test.ts index 41e5f78d3a..d9d65ccd57 100644 --- a/src/__tests__/cli-disconnect-invalid-default.test.ts +++ b/src/__tests__/cli-disconnect-invalid-default.test.ts @@ -3,7 +3,10 @@ import assert from 'node:assert/strict'; import fs from 'node:fs'; import path from 'node:path'; import { makeTempWorkspace } from '@agent-device/test-kit'; -import { hashRemoteConfigFile } from '@agent-device/remote/remote-connection-state'; +import { + hashRemoteConfigFile, + readRemoteConnectionState, +} from '@agent-device/remote/remote-connection-state'; import { runCliCapture } from './cli-capture.ts'; test('an unnamed disconnect removes an invalid default record before it disconnects the active session', async () => { @@ -47,3 +50,58 @@ test('an unnamed disconnect removes an invalid default record before it disconne fs.rmSync(root, { recursive: true, force: true }); }); + +// A build that sanitized session names wrote the session `.active-session` to exactly the pointer +// path. The unnamed disconnect claims it there, and that claim drives the client and the teardown. +test.each([ + { leaseProvider: undefined, refusal: undefined }, + { leaseProvider: 'proxy', refusal: 'REMOTE_SESSION_REQUIRED' }, +])( + 'an unnamed disconnect of the older .active-session record at the pointer path (leaseProvider $leaseProvider)', + async ({ leaseProvider, refusal }) => { + const { root, home, project } = makeTempWorkspace(); + const stateDir = path.join(root, 'state'); + const connectionsDir = path.join(stateDir, 'remote-connections'); + fs.mkdirSync(connectionsDir, { recursive: true }); + const remoteConfig = path.join(project, 'agent-device.remote.json'); + fs.writeFileSync( + remoteConfig, + JSON.stringify({ daemonBaseUrl: 'http://remote-mac.example.test:9124/agent-device' }), + 'utf8', + ); + const session = '.active-session'; + fs.writeFileSync( + path.join(connectionsDir, '.active-session.json'), + JSON.stringify({ + version: 1, + session, + remoteConfigPath: remoteConfig, + remoteConfigHash: hashRemoteConfigFile(remoteConfig), + tenant: 'acme', + runId: 'run-legacy', + ...(leaseProvider ? { leaseProvider } : {}), + connectedAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + }), + 'utf8', + ); + + const disconnected = await runCliCapture(['disconnect', '--state-dir', stateDir, '--json'], { + cwd: project, + env: { HOME: home }, + }); + + if (refusal) { + assert.equal(disconnected.code, 1); + assert.equal(JSON.parse(disconnected.stdout).error.details.reason, refusal); + assert.equal(readRemoteConnectionState({ stateDir, session })?.runId, 'run-legacy'); + } else { + assert.equal(disconnected.code, null); + assert.equal(JSON.parse(disconnected.stdout).data.session, session); + assert.equal(readRemoteConnectionState({ stateDir, session }), null); + assert.deepEqual(fs.readdirSync(connectionsDir), []); + } + + fs.rmSync(root, { recursive: true, force: true }); + }, +); diff --git a/src/cli.ts b/src/cli.ts index 649d0f763c..a9ad962982 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -56,7 +56,7 @@ import { import { resolveCliOptions } from './cli/resolve-cli-options.ts'; import { maybeRunUpgradeNotifier } from './cli/update-check.ts'; import { - claimRemoteConnectionState, + claimRemoteConnectionDefaults, remoteSessionRequiredError, resolveRemoteConnectionDefaults, type RemoteConnectionRequestMetadata, @@ -655,6 +655,7 @@ async function dispatchCliCommand( replayTestReporterRuntime, commandProgress, leaseDevice: ctx.leaseDevice, + claimedConnection: ctx.connectionDefaults?.claimed, }) ) { return; @@ -779,11 +780,7 @@ function resolveActiveConnectionDefaults(options: { stateDir: string; session: string | undefined; remoteConfig?: string; -}): { - flags: Partial; - runtime?: SessionRuntimeHints; - connection?: RemoteConnectionRequestMetadata; -} | null { +}) { if ( options.command === 'connect' || options.command === 'connection' || @@ -791,16 +788,16 @@ function resolveActiveConnectionDefaults(options: { ) { return null; } - if (options.command === 'disconnect') claimRemoteConnectionState(options); - const defaults = resolveRemoteConnectionDefaults({ + const request = { stateDir: options.stateDir, session: options.session, remoteConfig: options.remoteConfig, cwd: options.host.cwd, env: options.host.env, - validateRemoteConfigHash: options.command !== 'disconnect', - }); - return defaults; + }; + return options.command === 'disconnect' + ? claimRemoteConnectionDefaults(request) + : resolveRemoteConnectionDefaults(request); } // A command that cannot take a session runs on no remote connection. Reading, authenticating or diff --git a/src/cli/commands/connection.ts b/src/cli/commands/connection.ts index 35b6a914f5..1dc4c60a47 100644 --- a/src/cli/commands/connection.ts +++ b/src/cli/commands/connection.ts @@ -336,11 +336,28 @@ function scopeConnectProfile( }; } -export const disconnectCommand: ClientCommandHandler = async ({ flags, client, host }) => { +/** + * The record moves to its session's own path before any teardown, so a record this command cannot + * remove is refused before its session closes or its lease ends. The CLI claims it before it builds + * the client, and that claim is the one torn down. + */ +function claimDisconnectTarget( + claimedConnection: RemoteConnectionState | null | undefined, + stateDir: string, + session: string | undefined, +): RemoteConnectionState | null { + if (claimedConnection !== undefined) return claimedConnection; + return claimRemoteConnectionState({ stateDir, session }); +} + +export const disconnectCommand: ClientCommandHandler = async ({ + flags, + client, + host, + claimedConnection, +}) => { const stateDir = resolveConnectionStateDir(flags, host); - // The record moves to its session's own path before any teardown, so a record this command cannot - // remove is refused before its session closes or its lease ends. - const state = claimRemoteConnectionState({ stateDir, session: flags.session }); + const state = claimDisconnectTarget(claimedConnection, stateDir, flags.session); if (!state) { await writeNoRemoteConnectionOutput(flags, flags.session ?? 'default'); return true; diff --git a/src/cli/commands/router-types.ts b/src/cli/commands/router-types.ts index 83ba4611ac..a76992ba08 100644 --- a/src/cli/commands/router-types.ts +++ b/src/cli/commands/router-types.ts @@ -1,6 +1,7 @@ import type { HostEnvironment } from '@agent-device/kernel/source-value'; import type { CliFlags } from '@agent-device/contracts/command'; import type { LeaseDevice } from '@agent-device/contracts/client'; +import type { RemoteConnectionState } from '@agent-device/remote/remote-connection-state'; import type { AgentDeviceClient } from '@agent-device/command-surface'; import type { CliCommandName } from '@agent-device/command-registry/catalog'; import type { CommandProgressState } from '@agent-device/command-output'; @@ -18,6 +19,8 @@ export type ClientCommandParams = { commandProgress?: CommandProgressState; /** The device a proxy backend granted for the lease's device spec; `open` reports it. */ leaseDevice?: LeaseDevice; + /** The record `disconnect` claimed before its client was built, or `null` when it claimed none. */ + claimedConnection?: RemoteConnectionState | null; }; /** diff --git a/src/cli/commands/router.ts b/src/cli/commands/router.ts index 6b1468e8e7..57b98afa0f 100644 --- a/src/cli/commands/router.ts +++ b/src/cli/commands/router.ts @@ -35,6 +35,7 @@ export async function tryRunClientBackedCommand(params: { replayTestReporterRuntime?: ClientCommandParams['replayTestReporterRuntime']; commandProgress?: ClientCommandParams['commandProgress']; leaseDevice?: ClientCommandParams['leaseDevice']; + claimedConnection?: ClientCommandParams['claimedConnection']; }): Promise { const flags = { ...params.flags }; const loadDedicatedHandler = From ac0b49dba156e4d9fc91973d67cf872bae5b5fed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 22 Nov 2026 18:12:06 +0100 Subject: [PATCH 22/22] docs(reasons): regenerate error-reasons.md after rebase --- website/docs/docs/error-reasons.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 9091c1f074..cbd756a016 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -726,6 +726,13 @@ These reasons can come from more than one command. | `CONNECTION_DEVICE_CONFLICT` | The connection is bound to another device, or its lease was allocated by another device spec; `details.keys` names the disagreeing keys, and is present only for a device-spec mismatch. | | `CONNECTION_PLATFORM_CONFLICT` | The connection is bound to another platform, or the request names one its lease backend does not rent. | +### Remote connections + +| Reason | Meaning | +| --- | --- | +| `connection_session_mismatch` | A saved connection file cannot be used for the session a command named: it names another session, a record from an older build cannot move to its session file because that file already exists, or the active-session pointer path holds a record whose owner is unproven. The refused file is kept, and so is the occupied session file. | +| `connection_record_owner_unknown` | The session's own saved connection file, or the active-session pointer, could not be read or parsed, so no session is known to own it. It was neither replaced nor removed. | + ### Remote daemon | Reason | Meaning |