Skip to content

fix(remote): give each session its own saved-connection file - #4925

Open
thymikee wants to merge 22 commits into
mainfrom
fix/remote-connection-state-session-identity
Open

thymikee wants to merge 22 commits into
mainfrom
fix/remote-connection-state-session-identity

Conversation

@thymikee

@thymikee thymikee commented Nov 21, 2026 •

Copy link
Copy Markdown
Member

Summary

Each remote session owns its own saved-connection file. Base sanitized names, so Demo and demo shared one file on a case-insensitive filesystem, and one session read, overwrote or deleted the other's record.

The name alone decides the path: <name>.json for /^[a-z0-9_-][a-z0-9._-]*$/, otherwise ~<sha256(UTF-16LE)>.json.

Exported readers (connection status, remote command defaults) only observe. They report a record an older build wrote in place, and they report an invalid record as no connection.

Only save and removal move an older record to its verified owner (hard link, then unlink) and delete an invalid record that names the session. An occupied target refuses with connection_session_mismatch. An unreadable file refuses with connection_record_owner_unknown. disconnect claims the record before teardown. An unnamed claim removes an invalid default record, then follows the active pointer. Follow-ups: #4946.

Before / after

  • connection status --session demo after Demo saved, case-insensitive volume: base reports Demo's run. Head reports no connection.
  • disconnect --session Demo with an older Demo.json beside the hashed record: head refuses before any close or release, and keeps both files.
  • Unnamed disconnect with an invalid default.json and a pointer to team: head removes both files and disconnects team.

Validation

At a57843d: vitest run packages/remote src/cli/commands src/__tests__/cli-config.test.ts src/__tests__/cli-disconnect-invalid-default.test.ts 505 passed. typecheck, lint, format, check:command-docs and check:fallow pass. The disconnect-claim and pointer-cleanup tests each fail with their fix reverted.

@github-actions

github-actions Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Size Report

Metric Base Current Diff
Installed (including dependencies) 6.52 MB 6.52 MB +3.5 kB
Package (unpacked) 6.52 MB 6.52 MB +3.5 kB
Package (download) 1.99 MB 1.99 MB +1.0 kB

Startup median (7 runs, lower is better):

Scenario Base Current Diff
CLI --version 17.9 ms 20.3 ms +2.4 ms
CLI --help 37.1 ms 41.0 ms +3.9 ms

@thymikee
thymikee force-pushed the fix/remote-connection-state-session-identity branch 3 times, most recently from b77b6eb to 29fd24a Compare November 21, 2026 19:19
@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apex Sentinel: 2 new findings on 29fd24a. The verdict and the full list are in the summary comment.

@thymikee

Copy link
Copy Markdown
Member Author

Reviewed 29fd24a. Six problems remain, and the first one breaks the stated invariant that each remote session owns its saved-connection file. All 22 code checks pass, and the only non-passing check is the cancelled 'Body rules' run, which is likely unrelated because the diff changes no workflow or body-rule input. There are no conflicts. The first problem must be fixed before merge.

remote-connection-state.ts:541: After an upgrade on macOS or Windows, a legacy remote-connections/Demo.json that names 'Demo' passes the contents check and stays the live record for 'Demo'. Writes go back to that legacy path, so the record never moves to ~sha256(Demo).json. Session 'demo' matches the plain regex (:533) and resolves to demo.json, which is the same file. Its first read finds parsed.session === 'Demo' and throws connection_session_mismatch (:248). So connect (connection-context.ts:27, before any lease), connect --force, status and disconnect all refuse for 'demo' while 'Demo' stays connected. Two sessions still resolve to one file, which contradicts the '0 sessions sharing one file' result. The failure is closed, with no cross-read or overwrite, but a fresh session is locked out and the error names neither the owner nor a remedy. The rule: every record lives at the path remoteConnectionStatePath derives for the session it names, and no record stays at a sanitized legacy name after any resolve. The smallest fix is inside remoteConnectionStatePath / readRemoteConnectionState: when a hashed-category session's legacy file names that session, rename it to the canonical hashed path and return that path. When a plain path holds a valid record for another session whose canonical path is free, move it there instead of refusing. Keep connection_session_mismatch only for a true conflict, and put the owning session name in its details. Please add a test that writes a legacy Demo.json naming 'Demo', then connects 'demo' and reads 'Demo'. Write the legacy record at demo.json to simulate case-insensitivity, so the test also runs on Linux CI.

A second independent pass found remote-connection-state.ts:533 has the same shape on a case-sensitive filesystem. At base, connect for session a/b keeps its valid record at a_b-c14cddc0.json. After the upgrade, that filename is also the direct path for session a_b-c14cddc0. The old owner still reads and rewrites the file through the legacy branch (:543-547), and the other session fails before it can connect, including with --force. status, disconnect and remote defaults fail too. The rule: when a session's direct filename is occupied by another session's record, the direct-name session gets a canonical path outside the legacy namespace, and the original record stays with the session it names.

A second independent pass found remote-connection-state.ts:268 can let a stale legacy write or removal destroy another session's record. On a case-insensitive filesystem, start with legacy Demo.json holding a valid record for 'Demo'. A connect or lease update for 'Demo' resolves that path and pauses before publishing, or a disconnect pauses before the rm at :294. A second process disconnects 'Demo', and a third connects 'demo' and creates demo.json with its own lease ID. The first process then replaces or deletes that file, because the publisher uses a replacing rename (packages/host-kit/src/internal/atomic-publish.ts:44). The same sequence works with a/b and a_b-c14cddc0 on a case-sensitive filesystem. The rule: state is published only to paths outside the legacy namespace, and ownership checks and changes to a shared legacy pathname are serialized across processes, including retirement or deletion of an old record. A one-time migration (see the question below) removes the shared pathname.

A second independent pass found remote-connection-state.ts:571 can lose a lease record at the legacy pointer filename. The base writer commits a full record before it updates the pointer (d6767e0:packages/remote/src/remote-connection-state.ts:260-262). If it is interrupted between those writes for session .active-session, the full record is still readable and disconnectable at base. Head drops that record from the lookup. On a case-insensitive filesystem with .ACTIVE-SESSION, the exact-name exclusion misses it and head accepts the full record as legacy. A reconnect then writes the record there and replaces it with a pointer at :272. An unrelated connect also replaces the leftover record through its pointer update, so neither route keeps the recorded lease ID. The rule: case-insensitive aliases of the pointer filename are recognized, and a full record found at the pointer path moves to the recorded session's canonical path before a pointer is published.

A second independent pass found remote-connection-state.ts:558 lets distinct config session names share one canonical digest. Two explicit JSON CLI configs can supply session strings containing a lone U+D800 or U+D801 code unit (parsed at packages/command-surface/src/schema/cli-config.ts:90-106). Node's UTF-8 hash input encodes both as U+FFFD. After the first session connects, the second reaches the same file and cannot connect because of the owner check. If both pass the check while the file is absent, their replacing publishes can overwrite each other. The rule: canonical filenames hash a lossless encoding of the exact JavaScript string, such as UTF-16LE, while the eight-character suffix for legacy lookup keeps the old UTF-8 digest.

A second independent pass found remote-connection-state.ts:244 deletes an identifiable record that belongs to another session. On a case-insensitive filesystem, take a legacy Demo.json that still names 'Demo' and has its leaseId, but whose updatedAt is null. Reading 'demo', including through connection status, targets that file, fails shape validation before the stored name is checked, and deletes it through :245 and :663. A write for 'demo' then puts a new record at the same path. A read-only status can therefore destroy the only saved reference to Demo's lease. The rule: a parsed object's string session field is checked before any invalid-state cleanup, and a record naming a different session is kept even when the rest of its payload fails validation.

Simplicity question: would it be the same size or smaller to make the legacy branch a one-time migration that renames a matching legacy file to its canonical path, instead of a permanent second live location? The mismatch refusal would then guard only true conflicts, and the lockout above and the missing recovery hint would go away without new error surface. No smaller design was found for the plain/hashed split itself, since hashing every name would move every existing lowercase record for no gain.

The open inline threads still apply: the legacy path resolving to the same file is raised to the invariant in the first problem above, and the unhelpful mismatch error still holds. Disconnecting the owning session recovers, but nothing tells the caller that.

Not blocking, and each can be taken or left: connectionSessionIdentity is exported (:557) with no consumer, and a production-exports allowlist entry at .fallowrc.json:364 lets it pass the gate, so dropping export and the entry is cleaner (sessionLeaseScope at :447 could also reuse it); the test at remote-connection-state-session-identity.test.ts:88 passes at base on a case-sensitive filesystem, so writing the other variant's record at the lowercase path and asserting read, write and remove outcomes would cover the upgrade route better than the directory listing; the mismatch error at :249 would help callers by carrying the owning session and record path in its details and naming the recovery in its message; and the unrelated atomic gate-file fix in daemon-client-startup-budget.test.ts:191 would be easier to review in its own PR or named as a second change in the summary.

Not verified here: the tests were not run, and the base-failure and lockout claims come from reading base safeStateName and the head code, not from a run on a case-insensitive filesystem. The check:affected run and the 1443-test run cited in the PR body were not repeated, and the cancelled 'Body rules' job log was not inspected.

Before merge, the legacy sanitized-name records need a one-time migration to their canonical path, with an upgrade-route test that covers a legacy 'Demo' record next to a new 'demo' session.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

Sentinel findings addressed in 1b11290.

Path resolution now answers with contents rather than with a file name: when the plain <name>.json a session resolves to parses and names a different session, the session resolves to its canonical ~<sha256(session)>.json. Both findings share that one rule — after upgrading on macOS or Windows, demo reads no state, writes its own hashed record, and Demo's record is left untouched, so connection status, disconnect and connect --force all work without hand-deleting a file. The connection_session_mismatch guard stays for a record whose contents still disagree after resolution, and now names the refused path and the session that owns it.

@thymikee

Copy link
Copy Markdown
Member Author

At 1b11290, the upgrade-route lockout from the earlier review is fixed, but a session's saved-connection file can still change under it or be overwritten by another session. Checks are green (22 reported, none failing) and there are no conflicts. The first item below must be fixed before merge.

A plain-name session's path still depends on another session's file (remote-connection-state.ts#L556). Take an upgrade on macOS or Windows with a legacy Demo.json naming Demo. connect --session demo sees demo.json (the same file) naming Demo, so it writes its record and lease to ~sha256(demo).json. When Demo later disconnects, removeRemoteConnectionStateFile deletes Demo.json, and demo resolves back to the plain demo.json. Its live record is never read again. The same happens on a case-sensitive volume for a/b (legacy a_b-c14cddc0.json) and a plain session a_b-c14cddc0. Then connection status --session demo reports not connected while its lease is live, disconnect --session demo prints no connection and never releases the lease, and connect --session demo allocates a second lease beside the orphaned record. That record also keeps its remote profile referenced forever. The rule to satisfy: a session's resolved path is a function of its name alone once any record has been placed for it, and a record only lives at the path its own session derives. In remoteConnectionStatePath, migrate a non-canonical file that holds a record naming session S to S's canonical path once (link to the absent target, then unlink the source; leave it and refuse only if the target is occupied). After that, resolve plain names to plain and all others to hashed, with no content sniffing. Please add a test: legacy Demo record, connect demo, disconnect Demo, then status and disconnect for demo must still see its record.

A hashed-name session whose legacy record names it still publishes to the shared legacy pathname (#L568). This was in the earlier review and is unchanged. The publish at writeJsonFile is a replacing rename. Process A updates Demo and resolves Demo.json. Process B disconnects Demo. Process C connects demo, finds demo.json absent and writes its record there. Process A then publishes over demo's record, or A's paused disconnect deletes it. The new test uses this shared file but runs it without a race. One session can overwrite or delete another's record and lease reference. The migration above fixes this too: no write or delete may target a legacy pathname once the record has moved to its owner's canonical path.

Two session names that differ only in a lone surrogate still share one hashed file (#L598). This was in the earlier review and is unchanged. connectionSessionIdentity hashes with the default UTF-8 encoding, which maps every lone surrogate to U+FFFD, so U+D800 and U+D801 names collide. The second session is refused by the owner check, or both publish while the file is absent and overwrite each other. Please hash a lossless encoding of the exact string for canonical names, such as update(session, 'utf16le'). Keep the UTF-8 digest only for the 8-character legacy suffix at lines 606-610. A second independent pass found more routes from the same root cause. A session pair can have separate config files (cli-config.ts#L90-L106), so the second session can create the shared canonical path while the first still has a base-format record. The first then refuses even though its own record is present. A second independent pass also found that the derived client and run scopes (connection.ts#L312-L334) use the same lossy identity. With a leased remote profile and a pinned device key, the U+D801 session can reuse and later release the U+D800 session's proxy lease from a separate saved file (lease-registry.ts#L103-L105). Use the lossless identity for derived scopes too. Keep saved scopes for their owners and do not reuse a pre-upgrade lossy scope for a new session. A second independent pass also found that a foreign record at the shared canonical path can be deleted (#L244). If that record has a string session but fails full validation (for example updatedAt: null), validation fails before the session comparison at line 248. Cleanup then unlinks the other session's record. Compare the parsed string session before full validation. Refuse cleanup for a foreign owner, and act on the same verified file or revision under the mutation guard.

A second independent pass found that an upgraded legacy record stays at the shared filename (#L568). Reads for the legacy owner leave Demo.json in place, writes replace it there, and removal uses the same resolver at lines 274-277 and 295-301. That filename is also eligible as another session's plain path. The a/b case behaves the same in a_b-c14cddc0.json. Move the matching legacy record to its owner's canonical path on first use. Serialize ownership verification and retirement of an aliased legacy name, and publish later writes only to the canonical path.

A second independent pass found that deleting the legacy owner strands the other session's hashed record (#L557). Connect demo while Demo.json holds the old Demo record, then disconnect Demo. With the plain path now empty, status, disconnect and remote defaults for demo no longer find its record and lease ID. A later connect creates demo.json beside the orphan. This is the same switch as the first item, seen from the hashed side. Use one stable canonical location per session. If hashed fallback records are kept, honor an existing one before considering a plain path, and treat any move between paths as an explicit migration.

A second independent pass found that a stale legacy write or unlink can destroy a newly connected session (#L275). Pause a Demo reconnect after it resolves Demo.json and before the publish at line 277. Another process disconnects Demo, and a third connects demo into the free demo.json. The paused rename then replaces demo's record. A Demo disconnect paused after it resolves its unlink argument at line 301 deletes it the same way. An ownership read before the operation leaves both interleavings open. Publish and remove live records only at stable, disjoint canonical paths. Protect the ownership check and the unlink or migration of shared legacy filenames against concurrent claims of the same pathname.

A second independent pass found that an interrupted legacy writer can leave the only lease record at the pointer path (#L611). At base, a writer interrupted after the record publish and before the pointer publish leaves a complete, readable and disconnectable record at .active-session.json (base L255-L262). Head excludes that exact name from legacy lookup, so the named and active lookups lose it. On a case-insensitive volume, .ACTIVE-SESSION bypasses the exclusion and reads the full record. Its next write then publishes the pointer over the record, and the next read removes that pointer as invalid. A write for any unrelated session also replaces either legacy full record. Tell a legacy full record apart from a pointer at the reserved pathname, including case aliases. Move the full record to the canonical path of the session it names before any lookup or pointer replacement.

A second independent pass found that an unreadable legacy record is treated as available and deleted (#L585). On a case-insensitive volume, take a valid Demo.json with a saved lease and a mode that makes reading fail with EACCES for the CLI user, with a writable parent directory. For demo, sessionNamedBy swallows the read error and picks the aliased plain path. The read at line 239 fails again, and invalid-state cleanup unlinks Demo's file. A status command alone triggers this. The a/b record in a_b-c14cddc0.json behaves the same on a case-sensitive volume. Tell an absent legacy path apart from an existing path whose owner could not be read. Keep the latter intact, and either refuse or use a disjoint canonical path without cleanup of the legacy file.

Could this be simpler? Resolve by name only: plain-category names to <name>.json, all others to ~sha256(utf16le session).json. Before resolving, migrate once: if the session's sanitized legacy path or its plain path holds a record naming session S, hard-link it to S's canonical path when that target is absent, then unlink the source. Keep it and refuse with connection_session_mismatch only when the target is occupied. That removes sessionNamedBy from the hot path after migration. It closes the path flip, the publish to the shared name and the pointer-path record, and leaves line 248 as the only ownership guard.

Not blocking, and these can be taken or left: the new hint at #L257 says to run disconnect --session <owner>, but that command resolves the owner's own path (lines 549-568), not the refused file at the requester's hashed path. With the PR's own test record it prints no connection, and with a real record elsewhere it releases that unrelated live connection while the block stays. Lead with removing the named recordPath and drop the disconnect remedy, or say the file is not reachable by any session command. The comment above it (lines 249-252) also says reaching the throw means a race, but a planted record at the hashed path reaches it without one, as the PR's test shows.

For a follow-up issue, not for this PR: the pointer exclusion at remote-connection-state.ts#L611 compares only the exact .active-session.json, so on a case-insensitive volume .ACTIVE-SESSION with an absent canonical file accepts a base-written full record at the pointer file, and a session literally named .active-session loses lookup of a base-interrupted record there. This was in the earlier review and is unchanged. Compare pointer aliases case-insensitively.

The mismatch-hint thread still applies, as the non-blocking note above. The upgrade-route lockout thread no longer applies, because the plain branch at lines 555-559 no longer reaches the throw, and the remaining guard at 253-257 now carries recordPath; it can be resolved.

Not verified here: no tests were run, and the first, second and fourth items are traced from the head code and the CLI handlers, not reproduced on a case-insensitive volume. The race in the second item needs three concurrent processes. No cross-process lock was found in connection.ts, connection-runtime.ts or remote-connection-state.ts, but host-level serialization elsewhere was not searched exhaustively. The PR body's validation runs (unit-core, check:fallow, check:layering) were not repeated.

Before merge, fix the path flip in the first item, which leaves a live lease unreachable after the other session disconnects. Then fix the rest and push.

@thymikee
thymikee force-pushed the fix/remote-connection-state-session-identity branch from 1b11290 to bdf7f43 Compare November 22, 2026 07:06
@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apex Sentinel: 1 new finding on bdf7f43. The verdict and the full list are in the summary comment.

@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apex Sentinel: 1 new finding on 55c33d2. The verdict and the full list are in the summary comment.

@thymikee

Copy link
Copy Markdown
Member Author

Follow-up to the earlier review (#4925 (comment)). The hashed-first lookup now keeps a session on its hashed record after its legacy file is removed, and the aliased-name lockout on the upgrade route is gone. Several ways to overwrite or delete another session's record remain at 55c33d2.

The code is not ready to merge. The 21 reported checks pass, and there are no conflicts. Before merge, the legacy-record paths below must stop sharing a pathname with another session.

A hashed-category session whose legacy record names it still resolves to the legacy pathname (https://github.com/callstack/agent-device/blob/55c33d2/packages/remote/src/remote-connection-state.ts#L576). Examples are Demo with Demo.json, or a/b with a_b-c14cddc0.json. Updates still publish there with a replacing rename (https://github.com/callstack/agent-device/blob/55c33d2/packages/remote/src/remote-connection-state.ts#L277), and removal unlinks there (https://github.com/callstack/agent-device/blob/55c33d2/packages/remote/src/remote-connection-state.ts#L301). The same pathname is the plain path of the case-variant or collision-named session. Process A resolves Demo.json. Process B disconnects Demo. Process C connects demo and claims the now-empty plain path. A then publishes over C's record, or a paused disconnect unlinks it. demo's lease is then orphaned. The rule: no write or unlink may target a pathname that another session can also derive. Migrate once inside remoteConnectionStatePath. When the legacy path holds a record naming this session, hard-link it to the canonical hashed path if that is absent, then unlink the legacy name. If the target is occupied, refuse with connection_session_mismatch. Every later read, write and remove then uses the canonical path.

A second independent pass found the same root on the route where a matching legacy record never moves to its owner's path (https://github.com/callstack/agent-device/blob/55c33d2/packages/remote/src/remote-connection-state.ts#L576). A valid Demo.json naming Demo stays the live record, and it accepts reconnect, lease updates and disconnect (lines 274–279 and 301). The migration above covers it. It must run before the record is returned, and it must retire the legacy entry under the same ownership check.

A second independent pass found that an in-flight legacy publish or unlink can destroy the next owner's file (https://github.com/callstack/agent-device/blob/55c33d2/packages/remote/src/remote-connection-state.ts#L277). Pause a Demo update after line 275 or a second disconnect after line 301. Meanwhile Demo disconnects and demo claims the emptied path. Resuming replaces or unlinks demo's record. The rule: normal publishes and removals use disjoint canonical destinations. Owner verification, retirement and claims of any legacy pathname are serialized while it can still alias a session's destination.

A second independent pass found that the hashed path can be abandoned while its record exists (https://github.com/callstack/agent-device/blob/55c33d2/packages/remote/src/remote-connection-state.ts#L565). Make demo's hashed record unreadable to its user, then disconnect Demo. The probe treats the present record as missing and takes the plain path. Status then reports no connection, disconnect skips the lease, and reconnect can create a second record. The rule: an existing hashed path stays authoritative when its contents cannot be read. Tell absence apart from unreadable or unparseable content, and refuse to create through another path until ownership is known.

A second independent pass found that a read can delete an unreadable legacy record owned by another session (https://github.com/callstack/agent-device/blob/55c33d2/packages/remote/src/remote-connection-state.ts#L567). Leave a valid Demo.json with a mode that denies reads but a directory that permits unlink. connection status --session demo selects the plain alias when the probe gets EACCES (lines 588–595). The next read fails and cleanup unlinks Demo's file (lines 239–242, 301, 711). The same happens for a/b in a_b-c14cddc0.json, and reconnect runs the same cleanup before publishing. The rule: only ENOENT means absent. A legacy file with unconfirmed ownership is left untouched, and the call routes to a disjoint canonical path or refuses.

A second independent pass found that distinct session strings can resolve to one canonical filename (https://github.com/callstack/agent-device/blob/55c33d2/packages/remote/src/remote-connection-state.ts#L606). The config reader admits nonempty strings, so configs can name sessions with the lone code units U+D800 and U+D801. UTF-8 hashing encodes both as U+FFFD, so both get the same filename (line 580). The second session is refused even with --force, and if both publish while the path is absent, the later rename overwrites the other. Hash a lossless encoding of the exact string, such as UTF-16LE, for canonical names. Keep the UTF-8 eight-character digest only to find existing sanitized files.

A second independent pass found that validation can delete a foreign record whose session is intact (https://github.com/callstack/agent-device/blob/55c33d2/packages/remote/src/remote-connection-state.ts#L244). After a U+D800 session saves a hashed record, make updatedAt null and leave session and leaseId intact. A U+D801 status call reaches the same file (lines 570–571 and 605–606), rejects the shape before checking the owner, and unlinks the record. The rule: check the parsed session before handling shape errors. Delete only a record whose ownership was established and whose identity still matches under the mutation guard.

A second independent pass found that the upgrade route lets a second session obtain and release the old owner's lease (https://github.com/callstack/agent-device/blob/55c33d2/packages/remote/src/remote-connection-state.ts#L454). On base, U+D800 materializes a live proxy lease from an explicit leased remote config with a pinned device key. After upgrade its record is still at the sanitized legacy path. U+D801 then connects through the same profile into a separate hashed file, because the legacy lookup skips the old owner (lines 570–576). Both derive identical run and client IDs. The second open gets the first session's lease ID back (src/cli/commands/connection-lease-transaction.ts:389, packages/daemon/src/resources/lease-registry.ts:203–219), persists it, and can release it on disconnect (src/cli/commands/connection-runtime.ts:170, src/cli/commands/connection.ts:359–370). Changing only the canonical filename leaves this open. Derive new leased-profile scopes from a lossless session identity. Preserve the stored scope when loading the exact owning session, and keep new sessions from deriving its old lossy scope.

A second independent pass found that the active pointer can hide or overwrite a saved legacy lease record (https://github.com/callstack/agent-device/blob/55c33d2/packages/remote/src/remote-connection-state.ts#L619). An older process can stop after publishing the full record for .active-session but before the pointer write (base b03e32b, lines 255–262). Base status and disconnect still see that record (lines 225–242). Head skips it, so named lookup and the active fallback lose it. On a case-insensitive volume, .ACTIVE-SESSION leaves an alias at the same path. Head accepts it as legacy, but the next save writes the record there and the pointer overwrites it at once (lines 277–279). A save for any unrelated session also replaces either record when it writes the pointer. Treat all case aliases as one reserved pointer path. Migrate a legacy record found there to its verified owner's canonical path before lookup or pointer replacement, and keep the entry if ownership cannot be determined.

Would a simpler shape close most of this at once? Resolve by name only: plain-category names to .json, all others to ~sha256(utf16le session).json. Before resolving, migrate once. If the session's legacy sanitized path, or its plain path when that holds a hashed-category record, contains a record naming session S, hard-link it to S's canonical path when that is absent, then unlink the source. Keep the source and refuse with connection_session_mismatch only when the target is occupied. That removes the :565 and :567 sniffing from the hot path. It also covers the first, second, third and fourth items above, and it leaves the owner check at :248 plus an owner-confirming cleanup as the only guards.

Not blocking: when an own hashed record is unreadable or corrupt (sessionNamedBy returns undefined), https://github.com/callstack/agent-device/blob/55c33d2/packages/remote/src/remote-connection-state.ts#L565 treats it as absent. demo then resolves to a free plain path and writes a second record beside its stranded hashed file, where base cleaned the corrupt record up. The same canonical-path-by-name fix covers it. This note and the stale hint at https://github.com/callstack/agent-device/blob/55c33d2/packages/remote/src/remote-connection-state.ts#L257 (Run disconnect --session <owner> resolves the owner's own path, not the refused file) can be taken or left.

For a follow-up issue, not for this PR: the lone-surrogate collision above also affects the lease scope hash at https://github.com/callstack/agent-device/blob/55c33d2/packages/remote/src/remote-connection-state.ts#L454; and readRemoteConnectionState deletes the resolved file on a read or validation failure before the owner check (https://github.com/callstack/agent-device/blob/55c33d2/packages/remote/src/remote-connection-state.ts#L241), which is the same cleanup rule as above applied to every read site.

Open threads: the thread on unreadable legacy records and cleanup (#4925 (comment)) still stands. The thread on the hashed-first return at :565 (#4925 (comment)) is fixed at this commit and can be resolved, as is the aliased-name thread at :567 (#4925 (comment)). One lower-priority thread still applies.

Not verified here: tests were not run, and the new test failing before the fix was traced from code. The three-process race and the case-insensitive alias routes (APFS or NTFS) were traced, not reproduced. No cross-process lock was found in remote-connection-state.ts or the connection handlers, but host-level serialization was not searched exhaustively. The PR body still describes 1b11290, and its validation runs were not repeated.

@thymikee

Copy link
Copy Markdown
Member Author

Addressed the review at 153b6d3 with the suggested simpler shape. Records now resolve by name only: a plain name maps to <name>.json, and every other name maps to ~sha256(UTF-16LE). A legacy record moves once to its verified owner's path (hard link, then unlink). If the owner's path is already taken, the call refuses with connection_session_mismatch. Only ENOENT counts as absent. An unconfirmed file is never deleted, and the call refuses with connection_record_owner_unknown. All case aliases of the pointer path are reserved. The mismatch hint now names the refused file. Lease-scope identity and cross-process serialization of the move are in #4946.

@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apex Sentinel: 1 new finding on 0a25080. The verdict and the full list are in the summary comment.

Comment thread src/__tests__/cli-config.test.ts Resolved
@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

Code review at 47aedf2: the earlier findings from 55c33d2 (#4925 (comment)) are now fixed, but three problems remain. Unknown files now refuse before any unlink, path resolution returns only the canonical path, and the errors carry the refused file with a removal hint.

A second independent pass found that an explicit empty session no longer finds its legacy record. The CLI accepts --session= and connect keeps that value as the record owner. Base mapped the empty name to default.json, so status and disconnect found the record. Head probes .json and the empty string's hash instead, so status reports no connection. A later connect can save a second record, and a literal default session then refuses the old file as a mismatch. Please restore the empty-name mapping to default.json in legacyRemoteConnectionFileName and leave canonical path selection unchanged, so only a record whose parsed session is empty moves to the empty session's hashed path.

A second independent pass found that status now needs directory write access for a readable legacy record. Take a valid legacy Demo.json in a remote-connections directory with mode 0500. Base connection status --session Demo reads it and reports the connection. At head, status reaches the mandatory hard link before returning the record and fails with EACCES. Please let status return the verified record for the exact requested session when the canonical file is absent and migration cannot modify the directory. Leave the source in place, and require a successful migration before any save or removal.

A second independent pass found that the documented refusal does not match legacy lookup and migration conflicts. With only a malformed Demo.json and no hashed record, status reports no connection and connect can save a new record, which the tests expect but the docs do not say. If Demo.json is readable and the matching hashed file is unreadable, migration raises connection_session_mismatch naming Demo.json before the hashed file can produce connection_record_owner_unknown. Please scope the command documentation to the unreadable files that actually cause connection_record_owner_unknown. Also describe how unproven legacy files are kept, and how an occupied migration target causes a mismatch, including when both files name the same session. The connection_session_mismatch row says another session was named, but two files naming the same session also trigger it.

Not blocking, take or leave: the sentence at commands.md:2592 should say that agent-device refuses every command that uses that session's saved connection, since an unreadable default.json now fails snapshot, tap and similar commands, and should add that an unreadable active-session pointer refuses connect until it is removed. The connection_session_mismatch row and its ReasonTable comment could also cover a legacy record that cannot move because its session's file exists, and a pointer record with an unproven owner.

The open inline thread at #4925 (comment) still applies only for the command list, which the first note above covers. These threads are fixed at 47aedf2 and can be resolved: #4925 (comment) (only ENOENT is absent, unknown files refuse before unlink), #4925 (comment) (the hashed-first return is gone), #4925 (comment) (errors carry the record path and a removal hint), #4925 (comment) (the hint names the refused file, not disconnect).

CI is green: 21 checks, none failing at 47aedf2. Not verified here: tests were not run locally, the case-insensitive APFS and NTFS routes were traced and not reproduced, hard-link failure on filesystems without hard links was not evaluated, and the PR body's validation claims come from 153b6d3. Cross-process races are out of scope (#4946). No conflicts. Before merge, the three findings above must be fixed.

@thymikee

Copy link
Copy Markdown
Member Author

Addressed #4925 (comment) in 9b5a468:

  • An empty session name maps to default.json again for legacy lookup. Canonical path selection is unchanged.
  • A read uses a verified legacy record for the exact session in place when the directory refuses the move (EACCES, EPERM or EROFS) and the canonical file is absent. Save and removal still require the move.
  • commands.md and both reason rows now describe the actual refusals: unreadable own file or pointer, kept unproven legacy files, and an occupied migration target, including when both files name the same session.
    Each of the two new tests fails without the fix.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

The three findings from the earlier review (#4925 (comment)) are fixed at 9b5a468, but a second independent pass found seven new defects in the delta. All 21 checks pass at this commit. The PR needs these fixes, then a green re-run, before merge. Tests were not run locally; regression validity was judged by reading the pre-delta code path.

A second independent pass found that connection status is no longer read-only. With a valid legacy Demo.json, connection status --session Demo links the record to its canonical name and removes Demo.json; the unnamed path can do the same to default.json. A parseable, invalid record that names the requested session is also removed, with its active pointer. Both lookups at connection.ts:487-488 use the migrating reader at remote-connection-state.ts:593, and cleanup runs at :253-254 and :814. If the directory cannot allocate an entry, link returns ENOSPC and head fails before reading a record that base reports. Status needs an observation-only lookup, including the active-pointer fallback, that returns a verified legacy record in place and reports invalid records without cleanup. Migration and invalid-record cleanup should stay on the mutation path.

A second independent pass found that a failed migration can delete another session's canonical file. Take a readable default.json with a parseable record for the empty session and an invalid updatedAt, and no canonical file for the empty session. If hard-link creation returns EPERM but unlink is allowed (protected hardlinks, foreign-owned file, writable non-sticky directory), the fallback at remote-connection-state.ts:598 returns default.json. Cleanup at :253-254 and :814 then unlinks it at :321. That path is also the literal default session's canonical file. Write and removal reach the fallback through their preflights at :291 and :313, before strict path resolution. The fallback should stay off mutation preflights, a fallback record should be validated before it is returned for observation, and its path should stay out of invalid-record cleanup.

A second independent pass found that unnamed callers lose the active connection for the empty session. An older connect --session= without a lease provider saved the record in default.json and wrote { "session": "" } to the active pointer. Base reports it through the default lookup. At head that lookup moves the record to the empty session's hashed file, and the pointer read at remote-connection-state.ts:736 drops the empty name as falsy, so unnamed status reports no connection. Only undefined should count as an absent pointer session.

A second independent pass found that disconnect --session= can delete another session's record. Save Demo, let the active pointer name it, and leave the empty session without a record. The handler at connection.ts:488 treats the explicit empty flag as omitted, follows the pointer to Demo, and removes it at :370. Status with the same input reports Demo. The defaults lookup at remote-connection-state.ts:431-434 already tells an empty string from an omitted session. readRequestedConnectionState should consult the active pointer only when flags.session === undefined.

A second independent pass found that pointer cleanup can delete a full record the write guard refuses to own. Keep a valid demo.json, and put a separate full record naming demo at .active-session.json. readActiveConnectionSession accepts it as a pointer at :749, so disconnect for demo deletes it at :324 while clearing the pointer, and unnamed status can select a session from it. This contradicts the promise at commands.md:2592 that an unproven record is kept and unused. An entry should have the pointer shape before it is used as a pointer or unlinked as pointer cleanup, and a real legacy connection at that path should be recovered through the verified legacy lookup.

A second independent pass found that the command docs promise the wrong reason for one case. With a readable legacy Demo.json beside an unreadable canonical Demo file, migration sees the occupied target and throws connection_session_mismatch at remote-connection-state.ts:681-689. The first sentence at commands.md:2592 says any unreadable file for the session gives connection_record_owner_unknown. The docs should say an occupied migration target gives connection_session_mismatch even when the target is unreadable, and scope connection_record_owner_unknown to the file the command refuses because it cannot establish ownership.

A second independent pass found that a mismatch does not guarantee that no file was removed, which error-reasons.md:341 now claims. On a case-sensitive volume with legacy Demo.json and demo.json both naming Demo, a lookup for Demo migrates and removes Demo.json, then refuses demo.json because its target now exists. A save can also retire a verified full record at the pointer path (remote-connection-state.ts:290) before a later mismatch. The preservation claim should cover only the entries implicated in the refusal, including the occupied migration target, and the reason table at remote-connection-state.ts:225-230 needs the same wording.

Not blocking, and these can be taken or left: retireRecordAtActivePointer runs on every writeRemoteConnectionState, including the post-reply rewrite in forgetEndedConnectionLease, so an unreadable pointer also fails that rewrite and the docs at commands.md:2592 could say "connect and any command that rewrites the saved connection"; and the assert.throws in remote-connection-state-session-identity.test.ts:395 asserts no error code, so it could assert { code: 'EACCES' } to tell a write refusal from any other throw.

Not verified here: legacy migration on a filesystem without hard links, where link may return ENOTSUP on some macOS volumes and isWriteRefusedError does not cover it (outside this delta, and also left unevaluated earlier); the case-insensitive APFS and NTFS routes for the read fallback, which were traced and not reproduced; and a read-only directory with an unreadable canonical file and a legacy file, which surfaces the raw errno instead of connection_record_owner_unknown (:596) and was traced, not run. Lease scope identity and cross-process mutation stay out of scope (#4946).

All five earlier inline threads are fixed at this commit, so they can be resolved: the mismatch hint now names the refused file (#4925 (comment)), the mismatch error carries recordPath and a removal hint (#4925 (comment)), no hashed-first return remains (#4925 (comment)), only ENOENT counts as absent and unknown files refuse before any unlink (#4925 (comment)), and commands.md names the refusal and the manual removal, with the --force escape hatch deferred to #4946 (#4925 (comment)). No other inline threads still apply.

@thymikee

Copy link
Copy Markdown
Member Author

Addressed #4925 (comment) at 0b5f2ec:

  • connection status now uses an observation-only lookup. It never links, moves or deletes a file. It returns a verified legacy record in place and treats an invalid record as no connection. Migration and cleanup run only on the mutation path, and readOnlyFallback is gone.
  • The empty session name is a valid pointer session. --session= no longer follows the pointer.
  • .active-session.json is used or cleared as a pointer only when it has the pointer shape.
  • The docs and reason table now scope the refusals, and the files implicated in a refusal are kept.

This is the last round for this PR. Remaining hardening goes to #4946: other read sites using observation, ENOTSUP on volumes without hard links, and the raw errno when the directory is read-only and the session's own file is unreadable.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

The delta at 0b5f2ec fixes the earlier findings (#4925 (comment)) on the mismatch hint, the hashed-first early return, the unknown-file refusal and the docs, but one regression remains for remote commands that only read the saved connection, plus two related lookups.

The delta removed the read fallback from readRemoteConnectionState, and only status moved to the observation reader. selectRemoteConnectionState (remote-connection-state.ts:494) still calls the migrating reader, and resolveRemoteConnectionDefaults runs it for every remote command except connect and connection (cli.ts:419, :793). Take a valid legacy Demo.json from an older build, in a records directory where the link fails (mode 0500, a read-only mount, a full directory or protected hard links). Then agent-device snapshot --session Demo reaches the migration, linkSync throws the raw errno at :728, and the command fails before it uses the connection. Base reads Demo.json directly and runs. The mode-0500 test was also rewritten onto observeRemoteConnectionState, so the reader every remote command uses is no longer covered. The JSDoc at :236-242 says this reader is for a command that saves or removes next, and these callers do neither. The rule: a lookup whose caller only uses the record must not need a link or unlink to succeed, and only writeRemoteConnectionState and removeRemoteConnectionState migrate. Making selectRemoteConnectionState use observeRemoteConnectionState and observeActiveConnectionState satisfies it. Please restore the mode-0500 test on resolveRemoteConnectionDefaults.

A second independent pass found the same assumption elsewhere: connection-runtime.ts:72 loads existing state through the mutating reader for commands that can reuse a saved connection without rewriting it. With a valid base-written Demo.json and a records directory at mode 0500, agent-device session list --session Demo reaches the remote daemon on base and fails with EACCES at head. The observation lookups already read the file, so materialization can use them, and strict migration stays in the save and removal paths.

A second independent pass found one more lookup change: at remote-connection-state.ts:813 the shared active-session reader now rejects every full record. Interrupt connect --session .active-session --remote-config <non-leased-profile> after the session record is published and before the pointer is replaced, with no default record. On base, unnamed connection status and disconnect found that valid record. At head they report no connection, and unnamed commands skip the saved connection, although connection status --session .active-session still finds the same record in place. The rule: pointer-only validation stays for pointer cleanup, and an active lookup accepts a full record at the pointer path only when that path is its verified legacy pathname, through the observation or mutation reader that suits the caller.

Could the exported readers be observation-only instead? readRemoteConnectionState would become today's observeRemoteConnectionState and readActiveConnectionState would become observeActiveConnectionState, with migration and invalid-record cleanup private to the write and remove functions, which already call remoteConnectionStatePath. The observe* exports and the CLI's CHANGE_LOOKUP/OBSERVE_LOOKUP table could then go, and the 'only on the mutation path' claim would hold by construction. The cost is that an invalid record is cleaned on the next save instead of on any read.

Not blocking, and these can be taken or left: no handler-level test pins connection status as observation-only, because swapping OBSERVE_LOOKUP back to CHANGE_LOOKUP at connection.ts:395 keeps every test green, so a connectionCommand status --session Demo test over a lone legacy Demo.json that asserts an unchanged directory listing would pin it; and commands.md:2592 says any unreadable file is refused with connection_record_owner_unknown while an unreadable legacy file is skipped, and says the mismatch row names both kept files while the error details name only the source, so 'a session's own saved connection file or the active-session pointer' and 'the refused file is kept, and so is the occupied session file' would match the code.

None of the earlier inline threads still apply, so these can be resolved: the mismatch hint (#4925 (comment)), the mismatch error details (#4925 (comment)), the hashed-first early return (#4925 (comment)), the ENOENT-only absence check (#4925 (comment)) and the docs refusal text (#4925 (comment), with the --force option deferred by the author).

No conflicts are known. Two 'Body rules' runs show as cancelled, which looks like superseded runs: they validate PR body text and the diff touches no workflow, script or template on their route, and the other 21 checks pass. Not verified here: tests were not run, and the regression was judged by reading the 9b5a468 code for each new test; the regression was traced through cli.ts:419, :793 and remote-connection-state.ts:494, :637-640, :728, not executed; the EROFS, ENOSPC and EPERM variants and the case-insensitive APFS and NTFS routes were traced, not reproduced. Before merge, remote commands must resolve defaults through the observation reader, with the mode-0500 test restored on that route.

@thymikee

Copy link
Copy Markdown
Member Author

Addressed #4925 (comment) at 73cc3f1 with the suggested shape:

  • The exported readers only observe. They never link, move or delete a file.
  • Migration and invalid-record cleanup are private to save and remove.
  • The observe* exports and the lookup table are gone.
  • The active lookup accepts a full record at the pointer path only at its verified legacy name.
  • The mode-0500 test is restored on resolveRemoteConnectionDefaults.
  • A new handler test checks that status leaves the directory unchanged.

Please take any further hardening to #4946.

@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apex Sentinel: 1 new finding on 05501e6. The verdict and the full list are in the summary comment.

@thymikee

Copy link
Copy Markdown
Member Author

The earlier findings are fixed at 05501e6: disconnect now has CLI-route and handler tests, and case-variant session names no longer share one file (earlier review: #4925 (comment)). Two new problems remain in disconnect, so the PR needs one more change before merge. The only check that did not pass is Body rules, which was cancelled. It lints the PR body and runs no code under packages/remote or src/cli, so it looks unrelated. The other 22 checks pass.

A second independent pass found that an unnamed disconnect can lose the active selection (src/cli.ts:794). Take a valid unleased legacy record for session .active-session stored directly in .active-session.json, with no valid default record. Base disconnects it. At this head, CLI setup claims the record, links it to its hashed path and unlinks .active-session.json (remote-connection-state.ts:283-295,734-752), then discards the selected state. The defaults lookup and the handler (connection.ts:343-346) both resolve an absent selector again. The CLI then reports no connection and leaves the saved connection and any runtime live. A leased record in the same position also skips the explicit-session refusal. The rule: the state returned by the disconnect claim must drive both the client defaults and the teardown, and the original session argument must still decide the explicit-session requirement.

A second independent pass also found that pointer cleanup can unlink a separate valid legacy record (remote-connection-state.ts:416). On a case-sensitive volume, take a full valid legacy record naming .ACTIVE-SESSION stored at .active-session.json, plus a separate hashed file for .ACTIVE-SESSION. Explicit disconnect checks only the exact-case legacy name at lines 311-315. If the hashed file is invalid, the claim removes it and reports no connection, and pointer cleanup then unlinks the valid legacy file. If the hashed file is valid and names a different run, disconnect tears that run down and still unlinks the legacy record. activeRecordOwner matches the full record case-insensitively (lines 760-767 and 819-826), so cleanup treats it as a pointer without migrating it or checking the occupied target. The rule: .active-session.json may be unlinked as pointer cleanup only when it has pointer shape and names the matching session, and every full legacy record must go through the checked migration before it is removed.

Not blocking, and fine to take or leave: the disconnect pre-claim in src/cli.ts:794 discards its result, so on the one crash-left state where base wrote a full legacy record and then overwrote it, the defaults read can diverge from the claim (passing claimed?.session ?? options.session to the defaults read would align them), and it migrates a leased legacy record before the leased-session refusal, which only changes the error in a read-only records directory; both look unreachable after a completed base write and recoverable, so a follow-up issue (for example on #4946) is enough.

The open thread about a corrupt default.json stopping unnamed read-only commands does not apply here, because the maintainer deferred it to #4946, so it can be resolved: #4925 (comment). No other open threads from other reviewers still apply.

Not verified here: any of this by running code. The new tests were judged to fail on the earlier head by reading the code. Case-insensitive aliasing (Demo.json and demo.json) was checked by reasoning and not reproduced on a case-insensitive volume. The mutation-run claim and the deletion of connection-case-variant-session.test.ts and connection-empty-session.test.ts were not mutation-verified. Only the PR's own commits after the rebase onto caa232e were reviewed as the delta.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

The earlier findings from 05501e6 (#4925 (comment)) are fixed at a57843d, but a second independent pass found two defects in how a legacy .active-session record is migrated.

A second independent pass found that a failed disconnect can strand the active connection (remote-connection-state.ts:794). Take a valid legacy record at .active-session.json with no default record. An unnamed disconnect moves the record to its hashed path and unlinks the only active entry before the explicit-session check at line 504 or auth resolution at src/cli.ts:482-490. If the record is unleased and uses cloud auth, the first disconnect fails for missing auth. After auth is supplied, the retry passes a null claim to src/cli/commands/connection.ts:360-363 and reports no connection. Base keeps the active entry and disconnects on retry. A leased record in the same state returns REMOTE_SESSION_REQUIRED on base every time, but on head only the first time. The rule: after the checked hard link succeeds, atomically replace the migrated full record at the active pointer path with a pointer to the same owner, and let the existing owner-checked pointer cleanup remove it after teardown. The current claim should stay the source of defaults and teardown.

A second independent pass also found that a failed save can discard the previous active selection (remote-connection-state.ts:384). Take a valid legacy .active-session record and no default record, then save another session where the hard link succeeds but publishing the new record fails (for example ENOSPC on the temporary file). Head retires the full active record and unlinks its old name at lines 831 and 794 before it publishes the new record at line 390. The old record is then reachable by name only, and a later unnamed disconnect reports no connection. The same loss happens if the new record lands but publishing the new pointer fails at line 392. Base leaves the old active entry in place in both cases. The rule: when retiring a full record from the active path, atomically replace it with a pointer to its verified owner after the exclusive canonical link, and overwrite that pointer with the new selection only after the new session record is committed.

Not blocking, and fine to take or leave: on the production route disconnect always arrives with claimedConnection set, because resolveActiveConnectionDefaults always claims for disconnect, so the second-claim fallback in claimDisconnectTarget and the repeated refusal at connection.ts:365 only matter to tests that call the handler directly; making claimedConnection required for disconnect would let both go.

The one open inline thread about a corrupt default.json stopping unnamed read-only commands (#4925 (comment)) does not apply here. It is already resolved, and the maintainer deferred that read-only fallback to #4946, which is out of scope for this PR. No high-priority or lower-priority threads from other reviewers still apply.

The code needs the two fixes above before it is ready.

The Body rules check was cancelled, not failed. It only lints the PR body and runs no code under packages/remote or src/cli, so it does not touch this diff. The other 21 checks, including unit tests and typecheck, pass at a57843d.

The PR has merge conflicts with main.

Before merge, rebase onto main. The conflict is in website/docs/docs/error-reasons.md, a page generated from the reason tables, where #4936 added rows. Regenerate it with pnpm generate:reasons instead of merging it by hand, and let CI re-run test/repo-guards/reason-tables.test.ts.

Not verified here: no code was run, so both earlier fixes and the fail-without-fix claims were judged by reading 05501e6 against a57843d. Not verified here: the case-insensitive aliasing of .ACTIVE-SESSION.json to .active-session.json, which was checked by reasoning only; the test simulates a case-sensitive volume with a readFileSync spy, and the result was not reproduced on a real volume of either kind. Not verified here: the conflict check was a local merge against main at 2fc19f2, and main may have moved since.

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.
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.
…ort 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.
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.
… legacy records once

A plain session name maps to <name>.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.
…n-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.
…igrate 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.
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.
…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.
…ule 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.
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.
It fixes a flake unrelated to saved-connection ownership.
…inter

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.
@thymikee

Copy link
Copy Markdown
Member Author

Rebased onto main and regenerated error-reasons.md. The two findings in #4925 (comment) concern a session literally named .active-session whose full record sits at the pointer path. That case already collided with the pointer before this PR, so it is not a regression. Both items are tracked in #4946.

@thymikee
thymikee force-pushed the fix/remote-connection-state-session-identity branch from a57843d to ac0b49d Compare November 22, 2026 17:12
@apex-sentinel-staging

Copy link
Copy Markdown

Apex Sentinel · ✅ Approve · review of ac0b49d

Since the review of a57843d: 0 new · 0 still open · 0 no longer raised

No open findings.

Reviewed with this repository's own Sentinel configuration (033ed3fc9032).

💬 Talking to Sentinel

In a finding's thread, reply with:

Command What it does
@apex-sentinel-staging note <context> Adds context; Sentinel re-checks the cited code
@apex-sentinel-staging pivot <why> Says the finding is wrong; Sentinel re-checks the cited code
@apex-sentinel-staging like Marks the finding as useful
@apex-sentinel-staging dislike <why> Marks it as not useful, so it is not raised again

On this conversation, comment @apex-sentinel-staging review to run a full review once again.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant