Skip to content

fix(daemon): refuse an unsafe state directory before first use - #4783

Merged
thymikee merged 7 commits into
mainfrom
t3/daemon-state-root-admission
Nov 20, 2026
Merged

thymikee merged 7 commits into
mainfrom
t3/daemon-state-root-admission

Conversation

@thymikee

@thymikee thymikee commented Nov 20, 2026 •

Copy link
Copy Markdown
Member

fix(daemon): admit the state root, repairing an owned one the umask left open

Summary

Every state-directory write used to trust the directory it was handed: the launcher chmod'd a loose root into place at launch, and session-script-writer and provider-lease-expiry re-created or re-chmod'd their directories per write. An account that could plant a name on that route steered where the daemon's record, log and recordings went (#4649).

One rule now answers every question about that directory: admitPrivateRoot in packages/host-kit/src/internal/script-destination.ts — the walker that already judges a caller-named script destination (one walker, not two) — asked by admitDaemonStateRoot in packages/daemon-contracts/src/daemon-resolution.ts. Four call sites, one per route that reaches the root:

  • readRegisteredDaemon in packages/daemon-client/src/daemon-client-metadata.ts, in repair mode, as its first statement. That function is the client's ONE reader of daemon.lock and daemon.json, and a public export of packages/daemon-client/src/index.ts: the ensured transport the CLI and the MCP server use, the AI SDK tools, createAgentDeviceClient, ensureDaemon and an attach client all reach it, and none of them pass src/cli.ts.
  • src/cli.ts, in repair mode, where the invocation resolves its DaemonPaths — kept because the connection defaults read, and the upgrade notifier writes, that directory before any client exists, and because a refusal must land with the command's own exit handling rather than inside a client.
  • launchDaemonProcess, in establish mode, before it opens daemon.log.
  • daemon-runtime.ts, in establish mode, which is also the entry an embedded startAgentDevice and a foreign-build daemon take.

Nothing is memoized. An absent root is admitted (a repair creates nothing), so a verdict cannot be carried to the next read: a long-lived MCP server whose root sits under a shared sticky parent must not skip the walk after an outside account plants a link there.

An owned root is repaired, not refused. A root this user owns that is a real directory with safe ancestry, but open through its own group or other bits, is brought to 0700 by one chmod and admitted, in both modes and judged with lstat. The update-check cache, the process lock, the log directory and every root an older build left behind create it under the host's umask, so a mkdir under a wide umask cannot decide whether a command runs (#4649). Only a chmod the host refuses ends it, as not-private. A symbolic link at the root, a foreign owner, a shared or world-writable ancestor, a .. step and a non-directory still refuse, in both modes, with details.reason: "daemon_state_root_unsafe" and { stateDir, component, problem, fix }. The reason is a member of DAEMON_STATE_ROOT_REASONS (as const satisfies Record<string, string>), not a literal at the throw site, so R89 sees a published vocabulary and website/docs/docs/configuration.md words every member.

Establish creates the root on every platform, Windows included, where it creates it recursively after the shape rule and asks no privacy question. Nothing is created below the root: sessions/ and sessions/remote-scripts/ are judged where they stand (link and owner) and the daemon makes each of its own names when it first needs it, so an empty state directory stays empty and a report-only command leaves it absent.

$ AGENT_DEVICE_STATE_DIR=$HOME/.agent-device agent-device daemon status
$ agent-device daemon status --json | jq .error.details.problem   # "not-private" | "symlink" | ...

Deletions: repairStateMode and MODE_REPAIR_SKIPPED_CODES; the Windows log-reset reopen route (now one 'w' handle); the launcher's mkdirSync and its per-path chmodSync; chmodSync(filePath, 0o600) after publishFileSync in provider-lease-expiry (which now asks exactMode); the lease writer's recursive mkdirSync; the duplicate inspect calls in daemon-client-attach.ts, daemon-client-lifecycle.ts and src/cli/commands/daemon.ts.

Reverted as scope creep, suggested follow-up: publishFileSync in src/cli/auth-session.ts and src/cli/connection/generated-config.ts still writes a sensitive file in place.

Review round 1

  1. 0755 roots. admitDirectory closes an owned real directory's own group/other bits with one chmod before it can be a refusal, in admitPrivateRoot, the one place the rule lives. Covered by a root a plain mkdir leaves at the umask default is repaired by the next establish (a mkdirSync under umask 022 — the production order CI hit), an owned root at mode 0755 or 0770 is repaired to 0700, and nothing is created below it, and the live run below. repair mode never creates, and neither mode refuses an owned open root.
  2. Windows. admitDaemonStateRoot creates the root recursively on win32 after the shape check, in establish mode, which covers both the launcher's openSync(logPath, 'a') and daemon-runtime.ts. on a Windows host establish creates a missing root recursively and repair creates nothing runs on a mocked win32 host with an absent root and then opens daemon.log at the absolute name the launcher uses, so the test fails on ENOENT if the create is dropped.
  3. Admission seams. One site per route (see Summary). The three later inspects are deleted: daemon-client-attach.ts, daemon-client-lifecycle.ts and src/cli/commands/daemon.ts are back to main.
  4. Also fixed: DaemonStateRootProblem and the problem/exposure tables are module-private; resolveStateDir splits on / on POSIX and on both separators on win32, so a POSIX directory named a\b is a name, not a traversal; connect, auth and connection-runtime are covered by the src/cli.ts admission (proved live: auth status on a planted link refuses with problem: "symlink" before reading the connection state).
  5. Complexity. admitPrivateRoot is split into admitDirectory and verdictForAncestryFault and is inside the thresholds; no Fallow allowlist or baseline entry was added.

Review round 2

R89 — the reason is published from its table. DAEMON_STATE_ROOT_REASONS.unsafe replaces the literal in unsafeStateRoot, so the throw site reads a declared table and R89 defers it. The layering scan is clean:

$ node --experimental-strip-types scripts/layering/check.ts
Layering guard: OK … and every wire-published reason literal names a value its file published at the merge-base (383 sites in 193 file(s) against 383 in 193).

Fallow, and the two steps CI skipped. fallow audit --base origin/main and check:production-exports both pass at this head — the unused-exports gate reports ✓ No issues found over 720 entry points. The one number the report shows, parseCliInputOrExit cognitive 16, is inherited from main and is not introduced here: main's own src/cli.ts:256 reports 13 cyclomatic · 16 ! cognitive for the same function, and git diff origin/main -- src/cli.ts changes only the two-line admission and one collapsed local. The audit gate exits 0 and names it an inherited finding; no baseline row was added. Round 1's extraction to src/cli/help-request.ts was reverted, because it paid 19 net lines for a finding this branch does not own; src/cli.ts stays at the max-lines limit of 1000.

No verdict is remembered. repairedStateRoots is gone, in both directions: an absent root no longer banks a pass, and no passed root does either, because the ground under a name can change between two reads of it. Two regressions cover it — a repair re-judges the root on every call, so a link planted after one cannot be read (contract) and a client that admitted an absent root refuses a link planted at it before its next read (the public readRegisteredDaemon). ADR 0016 now states the rule as "asks it again at the next one: a verdict is never remembered". The walk costs ~10 µs, so nothing needed memoizing.

The client admission moved to readRegisteredDaemon. It is now the first statement, before inspectProcessLock, and observeLocalDaemon no longer admits. Audit of the remaining client-side state reads, all of which follow an admission on every route:

  • daemon-client-metadata.ts — inspectProcessLock and readDaemonRecord are inside readRegisteredDaemon, after the admission. readDaemonInfo and the getDaemonMetadataState exists-checks in daemon-lifecycle-errors.ts take an already-resolved path.
  • daemon-client-startup.ts — the three inspectProcessLock calls, readDaemonInfo and the log tail all sit on the startup path: after readReusableLocalDaemon (admitted), or after startDaemon → launchDaemonProcess, which admits in establish mode before it opens daemon.log.
  • daemon-client-attach.ts, daemon-client-lifecycle.ts, src/cli/commands/daemon.ts, src/mcp — no direct state-directory reads at all.

The planted-link client test now measures the route the client walks. It watches the SPELLED paths (<stateDir>/daemon.json and <stateDir>/daemon.lock) across readFileSync, openSync, lstatSync, statSync, existsSync and readdirSync, and it watches both transports: net.createConnection for the socket and http.request for HTTP (loadNodeHttpRequester resolves that same module object, so the probe goes through the spy). It runs once per transport.

Failing-before evidence, from the same test file with only admitDaemonStateRoot({ paths, mode: 'repair' }) removed from readRegisteredDaemon. The client reached the planted record on the spelled path in both transports, and the planted pid/port were in hand:

FAIL |unit-core| …daemon-client-startup-state-root.test.ts > a local client refuses a planted link … (socket)
FAIL |unit-core| …daemon-client-startup-state-root.test.ts > a local client refuses a planted link … (http)
AssertionError: Expected values to be strictly deep-equal:
+ [
+   'lstatSync:/private/tmp/…/state/daemon.lock',
+   'readFileSync:/private/tmp/…/state/daemon.json',
+   'existsSync:/private/tmp/…/state/daemon.json',
+   'existsSync:/private/tmp/…/state/daemon.lock'
+ ]
- []
FAIL … > a client refuses a state root another account owns before it reads the record there
AssertionError: Expected values to be strictly equal:
+ 'daemon-record-unreadable'
- 'daemon_state_root_unsafe'
FAIL … > a client that admitted an absent root refuses a link planted at it before its next read
Error: expected a refusal
Tests  4 failed (4)

A refused chmod no longer recommends the step that just failed. not-private keeps its refusal and its problem kind; its fix is one string naming both ways out: Run `chmod 700 <dir>`, or point AGENT_DEVICE_STATE_DIR at a private directory you own if that is refused. configuration.md words the same two steps.

remoteScriptPath keeps its chmod. Restored as it stands on main, with main's comment: that call creates sessions/remote-scripts itself, mkdir's mode is masked by the umask, and admission only ever judges names — it creates none of them. So an owner-bit umask such as 0o200 still leaves a usable directory.

Validation

Android Smoke and iOS Smoke are green at this head — see the checks on this PR. pnpm typecheck, pnpm lint, pnpm format, the eager-closure gate (913), the layering scan, check:production-exports and fallow audit --base origin/main pass.

  • Live, root pre-created at 0755 by a non-admitting writer, re-run at this head:
    $ T=$(mktemp -d) && mkdir -m 755 $T/state && stat -f %Lp $T/state
    755
    $ AGENT_DEVICE_STATE_DIR=$T/state node bin/agent-device.mjs daemon status --json | head -3
    { "success": true, "data": {
    $ stat -f %Lp $T/state && ls -A $T/state
    700
    The root went 755 → 700 and ls -A printed nothing: the repair created nothing below it.
  • Live, planted link, refused before the record is read:
    $ mkdir -m 700 $T/outside && echo '{"pid":4242,"port":42424,"httpPort":42424,"token":"planted"}' > $T/outside/daemon.json
    $ ln -s $T/outside $T/state
    $ AGENT_DEVICE_STATE_DIR=$T/state node bin/agent-device.mjs devices --json
    "reason": "daemon_state_root_unsafe", … "problem": "symlink"
    The same refusal answers daemon status, devices and auth status, on the CLI route and on the client route.
  • win32 host, absent root: on a Windows host establish creates a missing root recursively and repair creates nothing — repair creates nothing, establish creates the nested root, and the launcher's openSync(…'daemon.log', 'a') then succeeds.
  • Suites: full --project unit-core — 2091 files, 20149 tests, 0 failures. --project provider-integration test/integration/provider-scenarios/session-close-leak-oracle.test.ts passes; the leak oracle sees no stray sessions/ residue, because admission creates nothing below the root.
  • LOC: production (non-test under src and packages/*/src) +215 / −66, net +149, within the +150 budget for the whole PR.
  • Docs: ADR 0016's admission section carries the ancestry-before-mode-change order, the per-route admission points including readRegisteredDaemon, and the no-memo rule; website/docs/docs/configuration.md, commands.md, installation.md and agent-setup.md match; docs/agents/security.md says the daemon admits its state directory.

Unresolved risks: the check reads owner and mode bits, not ACLs or mount provenance (ADR 0016 says so); historical exposure of files already inside an admitted root is out of scope by design.

Part of #4649. Follows #4777 (merged).

@github-actions

github-actions Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Size Report

Metric Base Current Diff
Installed (including dependencies) 6.43 MB 6.43 MB +2.7 kB
Package (unpacked) 6.43 MB 6.43 MB +2.7 kB
Package (download) 1.95 MB 1.95 MB +1.2 kB

Startup median (7 runs, lower is better):

Scenario Base Current Diff
CLI --version 18.9 ms 19.1 ms +0.2 ms
CLI --help 42.1 ms 40.9 ms -1.2 ms

@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 dddd24d. The verdict and the full list are in the summary comment.

@thymikee

Copy link
Copy Markdown
Member Author

Thanks for this. At dddd24d the daemon now refuses an existing state root that is not exactly 0700, and it cannot create the root on Windows, so it is not ready yet. CI shows the first problem: Android Smoke Tests fail at the first CLI step with "Refusing to use the daemon state directory ... is open to accounts besides its owner". Integration Tests and the iOS smoke lane use the same launch route and likely fail the same way. There are no conflicts.

An existing root that this user owns, that is a real directory with safe ancestry, but has mode 0755 used to be repaired to 0700. Now establish refuses it with not_private, and the daemon never starts. Several writers create the root without admission: the update-check worker (src/cli/update-check.ts:133), remote-connection-state (packages/remote/src/remote-connection-state.ts:259) and the process-lock mkdir (packages/host-kit/src/internal/process-lock.ts:168). Any root from before this PR also qualifies. Local commands then fail with daemon_startup_failed, including fresh installs where the update check wins the race. Issue #4649 asks for the opposite: an owned level is repaired to 0700 on a best-effort basis, and repair never decides whether the daemon starts. The rule should be: in establish mode, a root that passes every check except its own group/other mode bits (real directory, not a link, owned by this uid, safe ancestry) is made 0700 and admitted. Please put that in one place, admitPrivateRoot or admitDaemonStateRoot, judged with lstat, never through a link and never for a foreign owner. Inspect should keep refusing or reporting. A test should pre-create the root at 0755 through a non-admitting writer, such as the update-check cache, and then launch.

On win32, admitDaemonStateRoot returns after the shape check and creates nothing. This PR also deleted the launcher's mkdirSync(baseDir, { recursive: true }). launchDaemonProcess then calls openSync(logPath, 'a') at daemon-registration-owner.ts:282 in a directory that does not exist, which throws ENOENT. daemon-runtime.ts:210 has the same gap for embedded startAgentDevice. A fresh Windows install, or any new AGENT_DEVICE_STATE_DIR, can no longer start a daemon, and configuration.md says the directory is created when a command starts a daemon. The rule should be: establish creates a missing root on every platform. Creating it recursively on win32 after the shape check covers both the launcher and the runtime. Please add a win32-host test that launches with an absent root. This is the open thread at #4783 (comment), and it still applies.

The docs say that every command that starts, attaches to, stops or reports on the daemon checks the root before it reads or writes anything there. That is not true yet. In src/cli.ts:411-421, resolveActiveConnectionDefaults reads the remote connection state, which can supply the remote daemon URL and config, before ensureManagedDaemon admits at daemon-client-lifecycle.ts:248. maybeRunUpgradeNotifier at src/cli.ts:202 also reads the root, and its worker writes there first. With a planted link or a foreign-owned root, the CLI takes its connection defaults from a directory another account chose. The rule should be: the first state-directory read or write of a CLI invocation follows an admission. Admit (inspect) once where src/cli.ts resolves daemonPaths, before the connection defaults and the notifier, then drop the later duplicate inspect calls. Otherwise, narrow the doc sentence to the daemon routes only.

Not blocking, take or leave: the admission tests build roots with mkdtemp or through admission itself, so none covers the production order where a CLI writer creates the root under umask 022 and launchDaemonProcess then establishes, which is what CI hit; DAEMON_STATE_ROOT_UNSAFE_REASON, DaemonStateRootProblem and windowsStatePathProblem are exported but only tests read them, so the Fallow audit in Repo Guards likely fails on them; on POSIX value.split(/[\\/]/) at daemon-resolution.ts:66 refuses a legitimate name containing a backslash, so split by the host separator rules; connect, auth and connection-runtime write to the state dir without admission (generated-config.ts:24, auth-session.ts:297), so either route them through the single CLI admission or scope the ADR sentence about admitting once before the first I/O; and the comment at session-script-writer.ts:333 says admission creates the directory while the method still runs mkdirSync on every call.

Could the PR be smaller? Keeping the walker reuse, admission could be asked where an operation resolves its DaemonPaths (src/cli.ts:411 for the CLI, host.ts for startAgentDevice, daemon-runtime for a launched daemon) instead of at four client and launcher seams. Establish would then follow the issue's own rule: repair a real, owned, non-link root with safe ancestry to 0700, and create the root on win32 too. That would remove the launcher and client inspect calls, admit the CLI-side reads, and fix the 0755 break without a new refusal class. For that, ADR 0016's "Refuse, do not repair" bullet would first need to go back to the issue's best-effort repair for an owned non-link root, or the hard refusal would need explicit maintainer approval and a migration note.

The change touches daemon startup on every device lane, so it needs green Android and iOS smoke runs at the fixed head. It also needs a live first run with the root pre-created at 0755 by a non-admitting writer, for example mkdir -m 755 $T/state && AGENT_DEVICE_STATE_DIR=$T/state agent-device devices, showing that the daemon starts and the root ends 0700. For Windows, a launch with an absent root should show that daemon.log is created, either on a Windows host or in a win32-host test.

Before merge, the daemon must repair an existing owned 0755 root instead of refusing it, and it must create the root on Windows. The CLI should also admit the root before its first state-directory read.

@thymikee
thymikee force-pushed the t3/daemon-state-root-admission branch from 2608978 to de71e29 Compare November 20, 2026 04:32
@thymikee

Copy link
Copy Markdown
Member Author

All five items are fixed at this head, and the two blockers are proved live.

1. 0755 roots. The repair is in one place: admitPrivateRoot's exposureOfEntry closes an owned real directory's own group/other bits with one chmod before it can be a refusal, judged with lstat, never through a link, never for a foreign owner. Both modes repair; only establish creates. A link, a foreign owner, an unsafe ancestor, a .. step and a non-directory still refuse in both modes. ADR 0016's "Refuse, do not repair" bullet is replaced accordingly, and configuration.md matches. Tests: a mkdirSync under umask 022 then establish (the production order CI hit), and 0755/0770 → 0700. Live on this Mac: a root pre-created at 0755 started the CLI and ended at 0700.

2. Windows. admitDaemonStateRoot creates the root recursively on win32 after the shape check, in establish mode — that covers both launchDaemonProcess's openSync(logPath, 'a') and daemon-runtime.ts. The new win32-host test starts from an absent root and then performs that same openSync on daemon.log, so a dropped create fails the test with ENOENT.

3. Seams. Took the simpler design: three call sites, one per route, each where it resolves its DaemonPaths — src/cli.ts (repair, before resolveActiveConnectionDefaults and maybeRunUpgradeNotifier), launchDaemonProcess (establish), daemon-runtime.ts (establish, also embedded and foreign-build). The inspects in daemon-client-attach.ts, daemon-client-lifecycle.ts and src/cli/commands/daemon.ts are deleted; those files are back to main. No fourth seam was added for a client request: a CLI invocation admits its own root before it builds a client, and startAgentDevice goes through the runtime route. src/host.ts resolves a baseDir it only hands to a client built after the runtime admitted the root, so it asks nothing itself.

4. Also fixed: the three exports are module-private (windowsStatePathProblem was never exported); resolveStateDir splits on / on POSIX and on both on win32, so a POSIX name may contain a backslash; connect, auth and connection-runtime now sit behind the src/cli.ts admission — proved live, auth status on a planted link refuses with problem: "symlink" before reading the connection state; the session-script-writer.ts comment now says the mkdir creates the directory and admission owns its mode.

5. Complexity. admitPrivateRoot is split into exposureOfEntry, makePrivate and verdictForAncestryFault and is under the thresholds, with no allowlist or baseline entry. One thing to flag: parseCliInputOrExit breached the cognitive threshold as soon as src/cli.ts changed at all, because it was already at 16 on main and the CI gate audits changed files. Its --help/help <command> block moved to src/cli/help-request.ts, dynamically imported so no entry's eager closure grows. That is the only file in this PR beyond the admission itself.

One design consequence worth your eye. Admission creates the root and nothing below it. sessions/ and sessions/remote-scripts/ are judged where they stand and are made by the daemon when it first needs them, so an empty state directory stays empty. Eagerly creating them made the leak oracle fail four Integration tests for stray residue, so the managed names are now judged for link and owner only. A managed name of this user that is merely open is still closed to 0700, same rule as the root.

Size: production net +149 versus main, at or under the +150 budget. Android Smoke, iOS Smoke, Integration and Coverage are green at this head; the evidence is in the PR body.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

Thanks for the update. At de71e29 the earlier findings are fixed, but one gap remains: the MCP, AI SDK and Node clients no longer admit the state root before first use.

The delta removes the inspect admission from ensureManagedDaemon and connectToDaemon (daemon-client-lifecycle.ts:246). The reason given is that every CLI call admits first. But the CLI is not the only client. The MCP server (createEnsuredDaemonTransport), the AI SDK tools and createAgentDeviceClient never pass src/cli.ts:401. On those routes the first state-directory read is readRegisteredDaemon(settings.paths) in daemon-client-startup.ts:97, with no admission. If the state root is a planted symlink or a directory another account owns, the client reads that account's daemon.json (pid, port, token). It then reuses the daemon it names, or runs a takeover against it. This is the #4649 threat on the surfaces agents use most. configuration.md:164 and ADR 0016:275 also promise a protection that these routes lack. The rule is: in every process, the first state-directory read or write follows one admission of that root. The owner all client surfaces share is the local-daemon route in daemon-client, so please put admitDaemonStateRoot({ paths: settings.paths, mode: 'repair' }) back in the local branch of ensureManagedDaemon (once per transport, or memoized per base dir), and keep cli.ts:401 for the reads the CLI makes before it builds a client. Please add a planted-link test through createAgentDeviceClient or the MCP command tool that expects daemon_state_root_unsafe before daemon.json is read. If you prefer, narrow those two doc lines to the CLI and daemon-start routes, but the MCP surface then stays exposed.

Because this is security code, please also fix these: script-destination.ts:550 repairs the root's own bits before it judges the ancestry, and makePrivate calls chmodSync by path, so a parent that another account can write allows a swap to a link between the lstat and the chmod (walking path.dirname(root) first, or chmod through an O_NOFOLLOW fd, closes it); line 543 also strips trailing backslashes on POSIX, so AGENT_DEVICE_STATE_DIR='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/x/state\' is judged as /x/state while the daemon uses /x/state\ (strip only the host separator, as resolveStateDir now does); and daemon-resolution.ts:114 maps shared_parent to 'unavailable' where it should join world_writable and shared_group_writable.

On the open threads: the one on daemon-resolution.ts:133 no longer applies, because on win32 establish now creates the root before the launcher opens the log, so please resolve it: #4783 (comment).

CI is green: 21 checks, none failing at de71e29, including Android and iOS Smoke, which exercise the CLI repair route and the launch establish route. There are no conflicts. The live 0755 to 0700 run comes from the PR body, and the win32 test mocks the platform on POSIX and calls admitDaemonStateRoot directly. Before merge, the client-route admission above needs to land with its planted-link test.

@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 d68ca19. The verdict and the full list are in the summary comment.

thymikee and others added 5 commits November 20, 2026 07:55
… walk

Adds `admitPrivateRoot` to the module that already walks a physical path one level at
a time: it judges the root's own name before the walk resolves it, judges each
ancestor, and creates what is missing at 0700 in establish mode, or answers the route
as absent and creates nothing in inspect mode. A root that arrives beside the call is
judged by the bits the walk lands on, not adopted for passing through.

Co-Authored-By: Callstack Apex <noreply@callstack.com>
`admitDaemonStateRoot` asks the host-kit walk once per operation, before the first
state-directory I/O: the launcher before it opens the log, the runtime before it locks
or recovers (which also covers embedded mode), and the client's attach, status and
stop routes in inspect mode, where an absent root stays absent. An unsafe root refuses
with `daemon_state_root_unsafe`, the offending component and one concrete step; there
is no degraded mode, no enrollment and no repair of an existing tree. Windows judges
the path shape only, because multi-account protection is a mode-bits question POSIX
alone answers.

Deletes the launch-time `repairStateMode` repairs, the log reset's reopen route, the
`chmodSync` calls that only repeated a mode `publishFileSync` or admission had already
set, and the duplicate recursive `mkdirSync` calls for directories admission now
creates.

Co-Authored-By: Callstack Apex <noreply@callstack.com>
The fallback reported any unmapped walk verdict as a group-or-other-writable ancestor.
The mapping is now total over the walker's exposures, with 'unavailable' for a route
that could not be checked or created.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… use

An owned state root that the host's umask left at 0755 refused every local
command, because admission answered `not_private` where the old launcher
answered `chmod`. Nothing else creates that directory either: the update-check
cache, the process lock and the log path each `mkdir` it with the umask, and
every root an older build left behind qualifies. #4649 asks for the opposite:
an owned level is repaired to 0700 on a best-effort basis, and the repair
never decides whether the daemon starts.

So the mode question is now asked in one place, `admitPrivateRoot`, and it is
repaired rather than refused: an owned real directory judged with `lstat`, with
safe ancestry, is closed with one `chmod` by both modes, and only a `chmod` the
host refuses becomes `not_private`. A link, a foreign owner, an unsafe
ancestor, a `..` step and a non-directory still refuse. Establish also creates
the root on Windows, where the launcher's `openSync(logPath, 'a')` had nothing
to open, and it creates nothing below the root: the daemon makes `sessions/`
and `sessions/remote-scripts/` itself, so an empty state directory stays empty.

The seams shrink to three, one per route, each where it resolves its
`DaemonPaths`: `src/cli.ts` in repair mode before the connection defaults and
the upgrade notifier read the root, `launchDaemonProcess` in establish mode,
and `daemon-runtime.ts` in establish mode for an embedded or foreign-build
daemon. The client-side inspects go away, so no route asks the same question
twice and none asks it per write.

ADR 0016 carries the rules that differ for the daemon's own root, and
`configuration.md` tells an operator what the check does on each platform.

Co-Authored-By: Callstack Apex <noreply@callstack.com>
The MCP server, the AI SDK tools and `createAgentDeviceClient` never pass the CLI's
admission, so their first state-directory read trusted a record behind a planted link.
Every client route reaches that read in one place now, and it follows a repair admission.

- `observeLocalDaemon` admits `settings.paths` before `readRegisteredDaemon`, and a passed
  repair is remembered per base directory for the process, so repeated requests walk once.
- The root's ancestry is judged to its parent BEFORE its own bits are closed. `chmod`
  follows links, so that order is what keeps a planted link's target out of the mode change.
- A state-dir spelling sheds only the host's own trailing separators: on POSIX `\` is a
  file-name character, so `state\` is judged as the name it is.
- `shared_parent` joins the writable-ancestor problem, and the exposure-to-problem mapping
  is a total `Record`, so a future exposure cannot fall through to `unavailable`.
- `src/cli.ts` keeps its own admission: the connection defaults read, and the upgrade
  notifier writes, the root before any client exists.

Co-Authored-By: Callstack Apex <noreply@callstack.com>
@thymikee

thymikee commented Nov 20, 2026 •

Copy link
Copy Markdown
Member Author

At d68ca19 the earlier findings from de71e29 are fixed: client routes admit the state root again, the repair walks the ancestry first, and the backslash and reason-mapping fixes are in. Three things remain before the label.

The Repo Guards & Compatibility job fails at "Check import-direction DAG" with one R89 violation, and it looks related to this PR. daemon-resolution.ts:177 now publishes 'daemon_state_root_unsafe' as an untyped literal, and main declares no such reason. R89 (#4779) landed after your merge-base and also resolves module-scope consts, so the old const form would fail too. Please publish the reason from an owning typed reason table (an as const satisfies … declaration the docs guards check). The Fallow audit and production-unused-exports steps were skipped after that failure, so their result at this head is unknown. The live 0755 to 0700 run and the win32 evidence in the PR body predate this delta. No device run is needed.

Because this is the state-directory trust boundary, please also fix these two: the planted-link client test in daemon-client-startup-state-root.test.ts asserts on the target path while the client reads the spelled stateDir path, and the net.createConnection spy likely misses the http transport, so the test may pass on pre-fix code; repairedStateRoots.add(baseDir) in daemon-resolution.ts also runs when the repair judged an absent root, so a root planted later under a sticky parent such as /tmp would skip the walk, and a root should be remembered only when it existed and was admitted. Please assert on the path the client actually reads and on every transport, and check the test fails on de71e29. And remember a root only when it existed and was admitted. Separately, not blocking: the session-script-writer.ts comment says admission owns that directory's mode, while the mkdir with mode 0o700 does, so the earlier wording and PR body items 3 and 5 are worth restoring.

The earlier inline thread on win32 root creation (#4783 (comment)) no longer applies, because establish mode creates the root recursively before the launcher opens daemon.log, so you can resolve it.

…n the one client reader (#4649)

R89 measures wire-published reasons: `daemon_state_root_unsafe` is now a member of
`DAEMON_STATE_ROOT_REASONS` and `configuration.md` words it.

- `readRegisteredDaemon` is the client's ONE reader of the lock and `daemon.json`, and a public
  export in its own right, so it admits the root itself. `observeLocalDaemon` no longer does.
- Nothing about a passed repair is remembered: an absent root is admitted and can become a
  planted link before the next read, so every call walks. A regression test covers both.
- The planted-link client test now asserts the SPELLED state-dir paths the client reads, and
  covers the socket and HTTP transports. It fails on the pre-fix code.
- A refused mode change names both ways out: `chmod 700 <dir>`, or a move if that is refused.

Co-Authored-By: Callstack Apex <noreply@callstack.com>
@thymikee
thymikee force-pushed the t3/daemon-state-root-admission branch from d68ca19 to f7644b8 Compare November 20, 2026 07:23
@thymikee

Copy link
Copy Markdown
Member Author

All four items are in f7644b8, pushed and re-measured.

1 — R89, and the two steps CI skipped. daemon_state_root_unsafe is now a member of a table rather than a literal at the throw site:

const DAEMON_STATE_ROOT_REASONS = {
  unsafe: 'daemon_state_root_unsafe',
} as const satisfies Record<string, string>;

unsafeStateRoot publishes DAEMON_STATE_ROOT_REASONS.unsafe, so R89 resolves the site to a declared table and defers it. The scan is clean: Layering guard: OK … every wire-published reason literal names a value its file published at the merge-base (383 sites in 193 file(s) against 383 in 193). configuration.md words that member.

Both skipped steps now run locally. check:production-exports: ✓ No issues found over 720 entry points. fallow audit --base origin/main exits 0; the single number in the report, parseCliInputOrExit cognitive 16, is inherited, not introduced — main's own src/cli.ts:256 reports 13 cyclomatic · 16 ! cognitive for that function and git diff origin/main -- src/cli.ts changes only the two-line admission plus one collapsed local. The audit gate says so too: audit gate excluded 2 inherited findings. No allowlist or baseline row was added. I also reverted round 1's src/cli/help-request.ts extraction: it cost 19 net production lines to pay for a finding this branch does not own, and src/cli.ts is back at the 1000-line limit.

2 — the memo. Deleted outright, as instructed: neither an admitted absent root nor a passed repair is remembered, so every call walks. The PR body records the ~10 µs cost as accepted. Two regressions cover it: a repair re-judges the root on every call, so a link planted after one cannot be read at the contract, and a client that admitted an absent root refuses a link planted at it before its next read through the public readRegisteredDaemon. ADR 0016 now reads "asks it again at the next one: a verdict is never remembered".

3 — the planted-link test. Rewritten to watch the route the client walks, not the planter's path. It spies readFileSync, openSync, lstatSync, statSync, existsSync and readdirSync and asserts nothing touched <stateDir>/daemon.json or <stateDir>/daemon.lock, and it covers both transports: net.createConnection for the socket and http.request for HTTP (loadNodeHttpRequester resolves that same module object, and I checked the spy is not vacuous — a real probe reaches it). It runs once per transport.

Proved failing without the fix, by removing only admitDaemonStateRoot({ paths, mode: 'repair' }) from readRegisteredDaemon and re-running the file: 4 failures. Both transport cases show the spelled record and lock being opened (readFileSync:…/state/daemon.json, lstatSync:…/state/daemon.lock); the foreign-owner case answers daemon-record-unreadable instead of daemon_state_root_unsafe; and the planted-later case returns a record instead of refusing. The full output is in the PR body, and the admission is restored.

The client admission also moved, per the other thread: it is now the first statement of readRegisteredDaemon, before inspectProcessLock, so a caller of that public export cannot skip it, and observeLocalDaemon no longer admits. The PR body lists the audit of the remaining client-side state reads (daemon-client-metadata.ts, daemon-client-startup.ts, and the three files with no direct reads) showing each one follows an admission.

4 — the two non-blocking points. remoteScriptPath has main's fs.chmodSync(directory, 0o700) and main's comment back, so an owner-bit umask cannot leave the directory unusable. The not-private refusal keeps its kind and gains the alternative in one string: Run `chmod 700 <dir>`, or point AGENT_DEVICE_STATE_DIR at a private directory you own if that is refused, asserted by a root whose mode change is refused still refuses as not private. The win32 thread is resolved with a reply pointing at the establishing test.

Re-measured at this head: full unit-core 2091 files / 20149 tests, 0 failures; production +215 / −66, net +149, inside the +150 budget; the live 0755 → 700 run and the live planted-link refusal are re-run at this head and their current output is in the PR body.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

This PR is ready at f7644b8. The Repo Guards & Compatibility job that failed at d68ca19 now passes, and all 21 checks pass at this head. The reason is published from a typed table, no repair is remembered between calls, so a root planted after an earlier admission is refused at the next read, and the client tests pin that through the public reader. The 0755 to 0700 run and the planted-link refusal come from the PR body. This is a daemon-only change, so no device run is needed. No conflicts.

The earlier findings are fixed: the win32 branch creates the root before the launcher opens daemon.log, the session script writer calls chmod on its directory again, and the chmod failure message now points to moving AGENT_DEVICE_STATE_DIR. Those three inline threads can be resolved: #4783 (comment), #4783 (comment) and #4783 (comment).

Not blocking, and you can take it or leave it: daemon-resolution.ts:172 passes the path to replaceAll as a string, so $$ and $& in a directory name are read as replacement patterns and print wrongly (/tmp/a$$b/$&c renders as /tmp/a$b/<dir>c). A replacer function, step.replaceAll('<dir>', () => component), inserts the path literally.

@thymikee thymikee added the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 20, 2026
A directory name holding $$ or $& was read as a replacement pattern.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@apex-sentinel-staging

Copy link
Copy Markdown

Apex Sentinel · ✅ Approve · review of 5043120

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

No open findings.

1 finding below minor hidden (user_settings.min_severity).

Reviewed with this repository's own Sentinel configuration (854bba6c5a18).

💬 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.

@thymikee

Copy link
Copy Markdown
Member Author

Still ready at 5043120. The fix text now passes the path to replaceAll through a function, so $& and $$ in a directory name print literally, and the test uses a $& directory to pin it. The label stays.

@thymikee
thymikee merged commit f53fc53 into main Nov 20, 2026
20 checks passed
@thymikee
thymikee deleted the t3/daemon-state-root-admission branch November 20, 2026 10:16
thymikee added a commit to pcbeingused333/agent-device that referenced this pull request Nov 20, 2026
* origin/main: (70 commits)
  refactor(apple-runner): one RUNNER_ERROR_CODES row per runner error code with parity/docs gates (callstack#4774)
  fix(android): require acknowledgements for test IME typing (callstack#4722)
  feat(scroll): add scroll refresh for pull-to-refresh (callstack#4770)
  refactor(host-kit): add request Scope and use it for the wait capture deadline (callstack#4794)
  fix(android): let permission all change nothing on an app that declares no permissions (callstack#4796)
  fix(cli): replace the CLI session and generated remote config instead of rewriting them in place (callstack#4797)
  fix(host-kit): accept a group-writable script directory the user owns (callstack#4799)
  fix(cli): escape control characters at the CLI's stdout and stderr writes (callstack#4778)
  fix(audit): do not report rows under a persistent bar that scrolling reveals (callstack#4775)
  fix(daemon): refuse an unsafe state directory before first use (callstack#4783)
  refactor: settle remaining single-deadline races through settleWithin (callstack#4788)
  refactor(host-kit): settle deadline races via settleWithin with R87 race ratchet (callstack#4766)
  fix(android): authenticate and bound persistent snapshot helper sessions (callstack#4729)
  fix(daemon): bound upload ingress and finalization (callstack#4721)
  chore(gates): ratchet wire-published reason literals by value (R89) (callstack#4779)
  feat(audit): evaluate role-less clickable views on Android (callstack#4780)
  fix(mutation): keep umask-setting tests out of Stryker's thread pool (callstack#4785)
  feat(audit): report controls that share one accessible name (callstack#4771)
  fix(contracts): pair open runtime hints with their apply operation (callstack#4754)
  refactor(daemon): report startup progress over the launch channel instead of marker files (callstack#4777)
  ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-human Valid work that needs human implementation, judgment, or maintainer merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant