Skip to content

fix(daemon): judge the state directory before writing a state diagnostic - #4704

Closed
thymikee wants to merge 21 commits into
mainfrom
t3/private-state-diagnostics
Closed

thymikee wants to merge 21 commits into
mainfrom
t3/private-state-diagnostics

Conversation

@thymikee

@thymikee thymikee commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

Summary

Part of #4649. Put daemon startup markers, log I/O, and shutdown reports behind one private-state directory and verified-file boundary. Unsafe or unreadable diagnostics fail independently of daemon startup and graceful stop. A shutdown report counts only when its author matches the stopped process lifetime.

The final review round preserves native path resolution, including Windows drive-relative paths with a same-drive working directory. It keeps optional reads nonfatal, checks descriptor mode before use, and requires a matching staging entry before cleanup. Script publication adoption remains a separate slice.

Validation

At a71bef41b8d8d93ce0e9780d98ffb786d3433a72 (current head: the state-directory rule split into its own module at the review's ask): pnpm build, pnpm format, pnpm lint, pnpm typecheck, pnpm check:layering and the eager-closure budgets suite (915 tests) passed, plus focused unit-core suites for host-kit (749), daemon-contracts, daemon-client, capture-kit and the state-privacy / log-publication / registration-owner suites (1,848). The three files the review named now sit under the 1000-line rule: atomic-publish.ts 308, script-destination.ts 724, verified-file.ts 614, state-directory.ts 404. The read-leaves-mode-alone test was re-checked against its mutation at this head and still fails when the read narrows the mode.

At c44b5d9b85757ec549534033135d5a44c74d1e82, pnpm install --frozen-lockfile && pnpm build, pnpm format, and seven focused unit-core suites passed (1,066 tests), including eager-closure and staged-file cleanup. pnpm check:affected --run --head HEAD failed in the unit stage (receipt run-8j2oDx): seven fuzz/release tests timed out and an unhandled ECONNRESET was reported near a limrun test. Cause is unproven; earlier stages passed. GitHub CI owns full validation.

At the preceding head c88d1a6, pnpm test:coverage passed 21,625 tests and wrote its stamp with a clean checkout; GitHub Coverage passed. Apple macOS smoke failed in three Swift transport tests with loopback address-in-use errors. The same tests passed on main's 7b6500c run; the unrelated failure was rerun.

@github-actions

github-actions Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Size Report

Metric Base Current Diff
Installed (including dependencies) 6.41 MB 6.43 MB +14.6 kB
Package (unpacked) 6.41 MB 6.42 MB +14.6 kB
Package (download) 1.95 MB 1.95 MB +4.6 kB

Startup median (7 runs, lower is better):

Scenario Base Current Diff
CLI --version 28.3 ms 36.6 ms +8.3 ms
CLI --help 51.0 ms 57.2 ms +6.2 ms

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

Reviewed c3fb4d4. The state-directory rule is a good addition, but the startup marker still writes where the rule says not to, so this needs changes before merge.

The startup marker ignores the state-directory verdict. src/daemon.ts:31 calls ensurePrivateDirectoryChain(ownStateDir), which can answer planted_link, foreign_owned or shared_writable (for example AGENT_DEVICE_STATE_DIR=/tmp). Lines 32-36 only print that to stderr, and the marker is still removed and written (lines 39-40, 52). daemon-runtime.ts:559-564 then writes lock-acquired, listening and more through recordDaemonStartupMarker, which never asks the rule. O_NOFOLLOW guards only the final name, so a link at the state directory itself is followed. Another user who controls the directory can also pre-create a regular file named daemon-startup-phases-.jsonl. In an attacker-owned or sticky directory the daemon cannot unlink it, and openMarkerForAppend checks only isFile, not owner or nlink. The daemon then appends into a file the attacker can read, and on macOS it can append into a daemon-user file the attacker hard-linked to that name. This breaks the #4649 requirement and the PR's own rule that a state diagnostic is refused on ground the daemon does not own. The rule to satisfy: every state-diagnostic write asks judgePrivateDirectoryChain(dirname) and skips its file on any exposure. Please put that check in the marker writer itself, so src/daemon.ts, daemon-runtime.ts and the test-kit registered-daemon fixture all go through it, for example with the same judge-then-skip as writeShutdownReport and a typed state_dir_untrusted failure sent to reportFailure. A daemon-side test where a foreign-owned state directory (serveHostOwnership) yields no marker file and startup continues would prove it.

The marker writer also copies host-kit's file-open rule. In packages/daemon-contracts/src/daemon-startup-phases.ts:83, openMarkerForAppend, openChecked, notARegularFile and lstatIfPresent (~70 lines) reimplement openVerifiedFileForAppend and openVerifiedFile from packages/host-kit/src/internal/verified-file.ts. lstatIfPresent, doc comment included, is verbatim from that file and already exported from @agent-device/host-kit/file. The copies already differ: verified-file re-lstats after the open and retries once, the copy does neither, and it uses O_RDWR. Any future owner or nlink hardening would have to land twice. Please use host-kit's opener (with an O_RDWR append variant, or read the trailing byte through openVerifiedFileForRead) and delete the local copies. If daemon-startup-phases.ts must stay off host-kit/file for a client closure budget, move recordDaemonStartupMarker into a daemon-side module. src/daemon.ts and daemon-runtime.ts already load host-kit/file, and that move also gives the judge above a home.

Repair can follow a link. packages/host-kit/src/internal/atomic-file.ts:924 runs fs.chmodSync(target, mode) by name, and chmod follows links. judgeStateLevel decides on a fresh lstat, then chmods by name, so in the shared-checkout case a group member with a writable parent can swap in a link between the two and have the daemon chmod any path the daemon user owns to 0700. launchDaemonProcess does the same for daemon.log: repairPrivateMode(input.paths.logPath, 0o600) runs right after fs.openSync(logPath, 'a'), even when the chain was just reported as not private. #4649 says repair never follows a link. The rule: a repair changes only the inode that was judged. Open the level with O_RDONLY|O_DIRECTORY|O_NOFOLLOW, compare fstat dev/ino with the judged lstat, then fchmodSync, and for daemon.log call fchmodSync on the descriptor already open. The state-directory race is narrow; the daemon.log case needs only an already exposed chain.

A separate security cross-check of this head found five more gaps in the same boundary. Each needs a fix and a test:

  1. Publication can leave the judged directory. The judge starts at the state directory, and the first lstat resolves every ancestor above it unchecked, so an intermediate symlink can already redirect it. The shutdown report's temporary open and rename then resolve the pathname again (atomic-file.ts:821). Judge the full ancestry, including allowed system aliases such as /var to /private/var. Create missing levels from a trusted parent, and bind the write to the judged directory, using descriptor-relative operations where supported.
  2. The temporary sibling is not owned. The shutdown report goes through the shared publisher's default writeFileSync (atomic-file.ts:114), which can follow a link or truncate an existing file at the generated name, and the cleanup at :288 removes the name even when this call never created it. Open the staging file exclusively at 0600, write through that descriptor, and clean up only an entry this call created.
  3. The readers still trust the path. The graceful-stop client reads the shutdown report by pathname even when the writer refused the directory (daemon-shutdown-report.ts:70). A planted report can supply plausible lease and claim results, and a FIFO there blocks the synchronous read. The startup observer at daemon-client-startup.ts:688 also does a separate stat and open. Read both through the same trusted-directory boundary with a verified regular-file descriptor, non-blocking open and bounded size, and treat a refused or missing record as absent.
  4. A filesystem error can abort startup. The new top-level ensure call in src/daemon.ts:31 sits outside both the marker catch and runDaemon().catch, and lstatEntry handles only absence, so EACCES, ENOTDIR or ELOOP escapes raw. On main the first diagnostic handled these errors inside the marker helper. The launcher has the same gap. Convert expected lookup failures into typed chain refusals, and keep refusals inside the best-effort boundary.
  5. The refusal warning writes through the refused path. A report refusal calls recordRegistrationWarning on the state directory's daemon.log by name before the registration is released (daemon-registration-owner.ts:180). A FIFO at that name can block the append, and a link can redirect it. Report through an already-open trusted descriptor, independent of the refused path and of registration completion.

Simplicity question: could the host-kit chain rule stay, with recordDaemonStartupMarker moved to a daemon-side writer that judges dirname, skips on exposure and appends through openVerifiedFileForAppend, and with repairPrivateMode using an O_NOFOLLOW descriptor? That would fix the first two items in one place and delete about 70 lines. Replacing otherUsersWriteTo with othersCreateEntriesIn and folding the two ensure-and-stderr blocks into one helper would take the total to roughly 100 production lines fewer, with one rule per concern. What would have to change first is confirming whether daemon-startup-phases.ts stays off host-kit/file for a client eager-closure budget. If it does, split the writer from the client reader before reusing verified-file.

Not blocking, take or leave: docs/agents/security.md:6 now says the daemon judges its state directory before it writes there and drops "daemon state" from the not-yet list, but only the shutdown report acts on the verdict (daemon.log, the lock, daemon.json, sessions/ and remote-scripts/ are written regardless), so keep "daemon state" listed except for the shutdown report and the marker once fixed; the test "a shutdown report replaces a symbolic link at its name" at src/tests/daemon-state-privacy.test.ts:44 should also pass on the old code (publishFileSync already renames over the link), so the PR body claim that it fails there is off; otherUsersWriteTo at atomic-file.ts:912 equals othersCreateEntriesIn(authority, trust) once the foreign-owner check runs first, and its sticky-directory comment is wrong; and the ensure-then-stderr block in src/daemon.ts:31-36 and daemon-registration-owner.ts:317-321 is duplicated, the marker keeps a second umask-masked mkdir at daemon-startup-phases.ts:50, "PHYSICAL" in the PrivateDirectoryChain.directory doc should say "resolved", and the planted_link message could hint at a user-chosen link.

CI has not failed: two Smoke Tests jobs are still in progress or queued. The diff overlaps the smoke route, since every smoke run spawns the daemon through launchDaemonProcess and writes the marker and shutdown report, so I would treat a smoke failure as possibly related until its log shows otherwise. No conflicts. Before merge, the marker writer must judge the state chain and skip on exposure through host-kit's opener, and the mode repair must change the judged inode.

@thymikee
thymikee force-pushed the t3/private-state-diagnostics branch from c3fb4d4 to debc04a Compare November 18, 2026 18:57
@thymikee

Copy link
Copy Markdown
Member Author

Head debc04accdf8c7c30de990f5a56f0d23685fac75 (rebased on origin/main, single commit). Disposition per item.

Marker ignores the verdict — fixed. recordDaemonStartupMarker now lives in daemon-registration-owner.ts, so src/daemon.ts, daemon-runtime.ts and the test-kit fixture all go through one writer. It establishes the chain, then asks judgePrivateDirectoryChain(dirname) for itself and refuses on any exposure through host-kit's append owner, sending a typed state_dir_untrusted to reportFailure. Proved by "a state directory another local user owns costs every marker, and the startup goes on" (serveHostOwnership, three phases, no file, three typed refusals).

Copied opener — fixed. openMarkerForAppend/openChecked/notARegularFile/lstatIfPresent are deleted; daemon-startup-phases.ts is now only the client-side reader and remover. Placement was measured: the writer went to the registration owner, which the daemon routes already load — a new daemon-contracts subpath would have grown the gated daemon-client-stop closure, so it did not go there. The seam reads the trailing byte through the verified read owner rather than O_RDWR, and the append refuses to glue bytes it read from a different entry than the one it holds.

Repair followed a link — fixed. chmod by name is gone. The level is looked up, opened O_RDONLY|O_DIRECTORY|O_NOFOLLOW, fstat identity compared with that lookup, then fchmod on the descriptor; ownership decided on the same lookup, so another user's level (root's included) is untouched. Every failure is a skip with a diagnostic. daemon.log mode is said on the descriptor already open. Narrowing starts at the state directory — ancestors above it are judged and left as they stand.

Cross-check 1 (publication left the judged directory) — fixed. The state rule reuses walkSpelledParent, so ancestry is judged from / and a link above the state directory can no longer redirect it; othersCreateEntriesIn then refuses the landed directory, sticky bit or not. The write is spelled from the judged directory, never the caller's, and proved against the entry's identity — descriptor-relative create is what's missing on this host, so the answer is the strongest thing it has.

Cross-check 2 (sibling not owned) — fixed. publishFileSync/publishDurableFileSync openSync(temp, 'wx', 0600), write through that descriptor, and clean up only an entry still claimed by identity.

Cross-check 3 (readers trusted the path) — fixed. readDaemonShutdownReport (now async) and both startup tails go through readPrivateStateFileSync: chain, verified regular file, non-blocking, bounded, refusal == absence.

Cross-check 4 (a filesystem error aborted startup) — fixed. EACCES/ENOTDIR/ELOOP convert to typed exposures inside walkStateRoute, so the launcher's call stays best-effort. Proved by "a state chain this process cannot read is reported and costs the launcher nothing".

Cross-check 5 (warning through the refused path) — fixed. Refusals report to stderr, never to daemon.log's name; the detached launcher already has stdout/stderr on the verified log descriptor.

Simplicity — done. The ~70-line copy is deleted, othersCreateEntriesIn replaces the duplicate predicate, and the two ensure-and-stderr blocks are one establishPrivateDaemonStateDir. I did not reach the ≈100 net reduction: this head is +739 production lines against +393 at c3fb4d4. The rule genuinely needs the ancestry judgment, the descriptor repair, and the three verified state owners, and the shared opener, the folded helper, and the folded predicate are in. The state rule sits in verified-file.ts with the state-file owners: a new module costs every gated closure +1 module and fails the no-growth rule, and an approval row would be a suppression.

Non-blocking. security.md is narrowed to the surfaces enrolled and keeps daemon state in the not-yet list (docs/agents has 39 bytes of headroom). The symlink-test claim is off as you said — the PR body no longer makes it. PHYSICAL → "resolved", the planted_link hint, and the marker's second umask-masked mkdir are all addressed.

Sequence. #4677 still owns host-kit/src/file.ts's export list and the tail of atomic-file.ts; this head touches both, so whichever lands second rebases. The script-publication/ADR 0016 work stays queued behind it.

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

@thymikee

Copy link
Copy Markdown
Member Author

At debc04a, the marker relocation is fixed, but the state and diagnostic paths still need changes before merge. The earlier evidence request is satisfied. No conflicts are known.

When the verified log open refuses a symlink, FIFO, or untrusted directory, launch reopens the same name with blocking append, and registration also truncates it by name. This can hang startup or redirect child output, while inherited stderr can use the same refused sink. Use independent stderr for refusals and warnings, and require every registration log open to use verified truncation or proceed without the log. Launch

The repair gate compares lexical spelling with a physical refused path, so an owned loose state directory reached through an allowed alias such as /var can remain loose and lose diagnostics. Record the resolved state-root boundary and refused entry identity in the walk, and test repair through the raw alias. Repair

Normalization removes raw .. before checking it, so a link followed by .. can cause creation or chmod at a different directory from the supplied path. Check the raw override before any state-path normalization and reject ambiguous diagnostic paths; test a literal link followed by .. in the complete path. Walk

The shared walk follows authorized links at the configured state root, allowing ensure to chmod another owned directory and writers to use it. Distinguish permitted ancestor aliases from links at or below the state root. Walk

The second repair lstat is outside its guard, and unmodeled filesystem failures can escape establishment or optional report reads. Keep repair lookups inside the guard and handle remaining failures at the diagnostic boundary, preserving typed exposures and returning absence for reads. Repair

Repair leaves existing files in place, but the verified opener does not check their owner, write exposure, or link count. A previously planted log can receive output, and existing records lack established provenance. Validate authority on each existing diagnostic descriptor and replace untrusted outputs with fresh owned files inside the judged directory or omit them. Open

Could you confirm that a directory at the shutdown report name makes stale cleanup abort registration? Keep acquisition checks fatal, make diagnostic cleanup best effort, and retain ownership information so a stale entry cannot be reported as this lifetime's result. Cleanup

Could you confirm that the shutdown parser accepts a valid object in the last 1 MiB of an oversized invalid record? Use a bounded whole-record read for shutdown JSON, and retain tail reads for markers and logs. Parser

Could you confirm that fstat failures after exclusive sibling opens leak descriptors and leave unclaimed siblings in both publishers? Enter cleanup immediately after open and centralize staging ownership and close handling, preserving the primary error and avoiding destructive cleanup without identity. Publisher

Could you confirm whether a throwing stderr sink escapes the shutdown warning and skips registration release? Make warning delivery best effort and independent of release, and add a throwing-sink regression at owner.finish. Warning

Could you confirm that mode update failures outside a request diagnostics scope produce no warning when narrowing an already closed directory fails? Return repair failures to the daemon entry's warning sink independently of the exposure verdict. Diagnostic

The repair-race test installs a link before the walk, which refuses before repair and would also pass with pathname chmod. Exercise the repair seam with a judged directory and a different entry at open, then assert refusal and an untouched target. Test

The umask tests leave the requested owner bits unchanged, so they pass without the exact-mode update. Mask an owner bit in each case and check the complete created directory chain and final report mode. Test

The unreadable-route test calls establish directly with every lstat mocked, so it does not exercise launch or startup observation. Exercise launch with failure scoped to the intended lookup and assert that the child starts and the diagnostic is refused; keep separate checks for each errno mapping. Test

Not blocking: These can be taken or left: resume the original state request after repair so descendants are judged, return immediately for an absent staging sibling so a replacement is not removed, and describe atomic publication without promising durability unless it is provided.

Could the shared walk first return resolved state-root authority and depth, with root and link policy defined in ADR 0016's case table, then use one descriptor repair, one staging owner, one state open boundary, and explicit whole-record and tail reads? That could keep the marker relocation, existing module graph and lazy stop import while removing the log reopen ladder, script-error decoding, duplicate wording and identity wrappers, for roughly 100 fewer production lines from the +747 net change.

A separate cross-check of this head adds three items:

  • The judged directory identity is dropped. The walk returns the directory's dev/ino, but the state entry keeps only its path (verified-file.ts:205). A state directory moved and replaced during startup or shutdown can then receive the marker or the report. Please carry the judged identity into the state I/O boundary, and bind opens, staging, commit and cleanup to it.
  • Sticky ancestors pass. A private state directory below a root-owned sticky 01777 directory passes, because the stricter write-bit rule runs only on the final directory (verified-file.ts:630). Please apply the state rule at every level, or state the sticky exception explicitly and test it.
  • The shared publisher's default mode changed. It now defaults to 0600 instead of 0666 filtered by the umask (atomic-file.ts:112). So unrelated outputs such as contact sheets and React profile exports are no longer readable by a separate viewer account. Please keep the old default, and pass 0600 explicitly for the shutdown report.

The last few rounds each closed the previous race and opened a new one, while production grew to +747 lines. The simplicity question above is now the main blocker: the answer is a smaller design, or a short reason why it was rejected.

The open threads on creation mode and startup observations still apply; no lower-priority threads were identified.

The three red CI jobs overlap this change, but the available evidence does not identify their causes: no failed-step excerpts, platform-specific smoke result, matched base failure, or head validation receipt were captured. Static head and base review assessed the tests against the old code and the operations they must distinguish; host-side launch and stop still need process-level regression evidence.

Before merge, make refusals independent of launch and registration completion, fix the state-root and record checks, provide exact-head detached launch and graceful-stop regressions for refusal cases, and diagnose and clear the three red CI jobs.

@thymikee

Copy link
Copy Markdown
Member Author

Follow-up pushed: f5cc76f (fast-forward on debc04a). No merge, no force-push.

Three red jobs from the debc04a run, attributed and closed:

  • Repo Guards & Compatibility (job 135052703837) — Fallow reported unused export parseDaemonShutdownReport, clone group dup:2cd0f815 (fixture ownership doubles), and createMissingLevel complexity. All three fixed at the invariant, no allowlist/baseline: the two functions became module-private; the clone was resolved by making the two doubles genuinely different (host-kit's serves only lstat and mutates the fresh Stats in place, because host-kit's rules ask ownership only from lstat, while test-kit's keeps serving stat for rules outside host-kit); createMissingLevel split into createLevelDirectory / judgedLevelEntry / narrowCreatedLevel / adoptStandingLevel. pnpm check:fallow at this head: dead code 0 · complexity 0 · duplication 0, no issues in the changed set.
  • Coverage (job 135052704885) — the fault matrix at runner-lease-filesystem-boundary-faults.test.ts:96 asserted EMFILE/ENOSPC/EIO surfacing but got plain simple: the injected faults never reached the lease write path. Rewritten on test-kit's registerFilesystemBoundaryMatrix with a routing test proving the lease lands at the env-routed path at 0600; 7 pass locally.
  • Smoke Tests (job 135052704356) — the runner lost emulator-5554 mid-step (adb: device 'emulator-5554' not found from getprop sys.boot_completed onward, then the catalog contract at failed-step-113). No product or test change warranted; the same suite passed in the sibling jobs of the same run.

Review items closed in this push (per the CoS review): log open/truncate and all warning destinations honor the verified boundary on every entrypoint, with stderr/null-device sinks on refusal and no reopen-by-name ladder; descriptor ownership/nlink/mode validated so pre-existing planted or shared records confer no trust; repair reaches aliases, .. after a link, and links at/below the state root (walk positions, not path text); the repair lstat is guarded; shutdown-report cleanup is best-effort and never aborts startup; staging has one owner, closes its descriptor on every path, and cleans up even when the identity lookup fails; a throwing warning sink cannot lose a refusal; judged identity travels to every open/stage/commit/cleanup; sticky ancestors no longer pass; generic publishFileSync keeps its umask-governed mode (see reply on r4619337502); refused marker reads answer refused and cannot fake a stall (see reply on r4619337527).

Simplicity. Consolidated this round: the three state openers became one openStateEntrySync + purpose flag-table, the two hand-rolled publishers became one publishStagedSync (owned-process-record.ts −11 SLOC), the duplicated lstatIfPresent has one owner, the diagnostics-scope memo is gone, and refusal construction is one helper. Measured code-only SLOC across the changed production files: merge-base 3492 → debc04a 3887 → this head 4075. I did not reach −100 below debc04a, and the honest reason is the one the review should weigh: the must-fix list added capabilities (descriptor-ownership validation, the alias-proof repair gate, typed refusal answers, the null-device fallback), and the remaining size is those capabilities, not ceremony — what ceremony existed is what this round deleted (verified-file.ts peaked at 949 lines at debc04a and is 545 code-SLOC now; eager-closure growth vs merge-base is 0 at unchanged 909 ceiling).

Gate state at f5cc76f (local): tsc clean · oxlint clean · format clean · check:fallow clean · check:layering 483/483 · check:production-exports clean · check:agent-guidance 5/5 · eager-closure budgets 909/909 · apple-runner fault matrix 7/7 · unit suites: host-kit+daemon-contracts+daemon-client 1126, src daemon suites, lease/diagnostics suites — all green. Full test:coverage + check:coverage-changed running against exactly this head; CI will re-prove it.

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

@thymikee

thymikee commented Nov 18, 2026 •

Copy link
Copy Markdown
Member Author

Follow-up pushed: 5eed9ca (normal fast-forward on f5cc76f, one commit; no force-push, no merge).

Independent defensive review — where each item is closed at the actual I/O boundary

  • Verify descriptor and parent authority before truncation or writes. O_TRUNC is gone from the state truncate purpose: it emptied bytes before anything proved them (a hard-linked record passes the verified open and is refused only when its names are counted — the refusal used to arrive with the contents already gone). The purpose opens O_RDWR, and ftruncate(…, 0) runs only after the descriptor proof (uid, nlink === 1, mode) and the re-lstat of the judged directory. Pinned by a truncation asked for a record with a second name leaves those bytes alone.
  • Diagnostic output on an authorized descriptor or an explicit discard/stderr sink, including final flush. See the reply on r4621330141 — sink at first line, every line and the forced flush through the judged handle, refusal and breakage routed to stderr, close at scope end, no sink carried across a log-path handoff.
  • Descriptor read authority. readStateEntrySync now asks the judged directory both sides of the open and the handle's own uid/name-count, so bytes another user owns or that stand under a second name answer refused, not bytes. Pinned by a record with a second name is refused as a read too, not just as a write.
  • Parent checks retained through staging/publication. publishPrivateStateFileSync passes the directory judgment as the staging owner's assertDestination, which publishStagedSync asks before the first write and again immediately before the commit — the same seam the durable/script publishers already used, now shared rather than duplicated.
  • Shutdown reports correlated to the stopped lifetime. A report states writtenBy: {pid, startTime}; the stop hands the reader the identity it acted on (stopRecordedDaemon → readDaemonShutdownReport(stateDir, observed)), and a record naming another author — or one whose start time cannot be compared — answers as no report, so cleanupConfidence says unknown instead of claiming releases that daemon did not make. Pinned by a report left by an earlier run of the same pid is not this stop's cleanup record, and by a detached start/stop on the built CLI: the graceful stop's report named {"pid":13578,"startTime":"Wed Nov 18 23:40:04 2026"}, mode: graceful, cleanupConfidence: known.
  • All optional diagnostics nonfatal, including the warning sink. The flush is wrapped (daemon_log_flush_failed to stderr), the sink's failing write routes the line to stderr and never raises, and reportStateRecordFailure/reportRefusedStateSink keep their non-throwing contract.
  • Staging cleanup only while identity is still established. Unchanged and re-verified: the claim is the exclusive create, removeTempBestEffort removes the name only while it still holds the claimed identity (or nothing), and the ours === undefined case falls back on the claim — an exclusive create cannot have met another process's entry. Deliberately not tightened further: the earlier must-fix was that cleanup is guaranteed even when the identity lookup itself fails, and a name this call created exclusively is still this call's.
  • Generic output mode and existing safe behavior preserved. publishFileSync still defaults to createMode 0o666 priced by the umask; only callers that want privacy ask 0o600.
  • One common checked owner; redundant establishment per marker removed. establishPrivateDaemonStateDir — the create-and-repair ACTION — is asked once per state directory per process (memoized on the normalized spelling), and recordDaemonStartupMarker now only calls that owner instead of driving ensurePrivateDirectoryChain itself. The security judgment stays per-write: every state open still walks, spells, opens O_NOFOLLOW, and proves the descriptor it got; nothing inherits a repair's answer.
  • Raw route position and state-specific policy through the alias walk, with descriptor-bound repair. Unchanged from f5cc76f: WalkPolicy.noLinksAtRouteNameOrBelow + the WalkRefusal position slot, repair gated on policy.refusal.atRouteName >= stateRootRouteName, narrowing on O_DIRECTORY|O_NOFOLLOW with identity compared to the judged lookup.

Android smoke at f5cc76f. The rerun of that exact head (run 44404007744, job 135158675344) is green, 6m20s, whole Android matrix. The exit-255 keyboard-state-query failure and the earlier emulator disappearance were both runner-side and neither reproduced; job evidence retained, no product or test change made on either.

#4677 is still open (verified: not an ancestor of origin/main). A trial merge (git merge-tree) still conflicts in host-kit/src/file.ts, internal/atomic-file.ts, internal/verified-file.ts; nothing from its script-writer work is mixed in here. Sequencing note for whoever merges last: this branch consolidated the walk helpers, the publisher surface and the state openers those files carry, so the rebase belongs on whichever lands second.

Simplicity. Consolidations this round: the verdict+reopen pair became one sink owner used by both diagnostics and the registration owner's report path; the privateStateDescriptorExposure answer is shared by write and read instead of a second copy of the same three questions; the directory guard is one threaded option, not a per-caller wrapper; the establishment walk went from per-marker to per-directory. Code-only SLOC across the changed production files: merge-base 3492 → debc04a 3887 → f5cc76f 4075 → 5eed9ca 4180. I am still above the −100 target and the reason is the one the review should weigh: every one of the +105 this round is a named capability (post-open parent re-assert on reads, descriptor read authority, ftruncate-after-proof, the sink seam, report correlation), not ceremony — and the ceremony the previous round left (verdict-only opens, duplicated exposure checks, per-marker walks) is what this round deleted.

Gate state at 5eed9ca (local). tsc clean · oxlint clean · format:check clean · check:fallow dead code 0 · complexity 0 · duplication 0 (35 changed files) · check:layering 483/483 · check:production-exports clean · check:agent-guidance 5/5 · adr-citations 2/2 · eager-closure budgets 909/909 at unchanged ceiling · unit-core+apple-runner 2162 files / 20657 tests green · detached-daemon start→graceful-stop lane on the built CLI green (state dir 0700, daemon.json/daemon.log/report all 0600, no staging siblings left). test:coverage on exactly this commit: 2257 files / 21096 tests green (10 skipped), lcov produced. check:coverage-changed against origin/main: PASS — changed-line coverage 389/410 (94.88%) against the 70% gate, changed-branch 275/314.

@apex-sentinel-staging

This comment has been minimized.

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

@thymikee

Copy link
Copy Markdown
Member Author

Checkpoint while validation finishes.

Both CI breaks named on d43304f657 are fixed at 35166e551f and re-run there: pnpm typecheck
(tsc -b tsconfig.typecheck.json examples/sdk/tsconfig.json) is clean, and check:layering exits 0 with R84 held
at 150 unmatched tests against 150 at the merge-base — the establishment test is now
daemon-registration-owner-state-dir-establishment.test.ts, named for the module it imports
(./daemon-registration-owner.ts).

35166e551f also replaces the resolution half of d43304f657: a configured state dir with a .. step is now
refused by resolveStateDir with reason: state_dir_parent_escape, because the record names are derived with
path.join, which folds the step away — passing the spelling on would have a route judged as one directory and
written into as another.

Already green at this SHA: pnpm lint, format:check, check:fallow (dead code / complexity / duplication 0),
check:layering, check:production-exports, check:agent-guidance, check:adr-citations, eager-closure 909, and
the focused lanes (424 files / 3901 tests across host-kit internals, daemon-contracts, daemon-client, src/__tests__).
pnpm test:coverage and then pnpm check:coverage-changed are running at 35166e551f now; the summary comment and
the PR body's tested SHA are updated with that result.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

Round closed at 70610f35ce (GitHub head)

Pushed as normal fast-forwards: 5eed9ca196 → d43304f657 → 35166e551f → 70610f35ce. No force-push, no merge.

The two Apex threads, evaluated together

Same seam in both: the base the rule judged and the base the record names were built from could disagree. Answered in
#discussion_r4622614324 — resolveStateDir
folds once and every DaemonPaths entry derives from that base; an ordinary ../shared-state is accepted again (the
blanket .. refusal in 35166e551f was a regression: at the merge-base resolveUserPath folded it for every caller);
a step that backs out of a directory which is a symbolic link is refused with state_dir_parent_step_through_link,
because name/.. lands at the target's parent while the fold says the named directory, and then no base can be proven
to be the one the state rule judges. Absence answers as no link, so the pre-first-start route keeps its textual fold and
the state rule's own judgment of created ground is unchanged. One accepted base for all five entries, no fold through an
unchecked link. No new abstraction: one fold function and one lstat helper at the resolution owner.

CI fixes from d43304f657 — validated and available at head

  • pnpm typecheck (tsc -b tsconfig.typecheck.json examples/sdk/tsconfig.json) exit 0 at 35166e551f and again at
    70610f35ce: the sink doubles at diagnostics.test.ts:245,287 carry close, and the 2-argument toBe at
    verified-file-state.test.ts:372 is an expect message.
  • R84: the establishment test is daemon-registration-owner-state-dir-establishment.test.ts, named for the module it
    imports; check:layering exit 0, 150 unmatched against 150 at the merge-base.

Size

The bundle job reads +12.4 kB unpacked with a mixed startup sample — one startup hook is not measurable when its
calls overlap, so that median moves with noise in both directions. The growth is the state rule's own body: one open
boundary that proves directory and descriptor authority, one staging owner that removes only what it can claim, and the
containment that makes an optional report optional. No new layer appears in the diff — no package, entry point, registry
or generic diagnostic framework. The CI fixes and this round's fold are fixture- and owner-level: two close: () => {}
doubles, one moved assertion message, one fold function and one lstat helper at the resolution owner, which is less
code than a helper abstraction would have cost. Startup cost stays bounded by design — the state walk runs once per
configured route rather than per record, a sink is asked at the first line rather than at scope entry, and this round's
proof adds at most one lstat per .. step, only for a route that spells one.

Evidence, by SHA

  • 35166e551f — full suite: pnpm test:coverage 21117 passed / 10 skipped, and check:coverage-changed PASS at
    443/470 changed lines (94.26%) against the 70% gate, branches 298/338. Collected, not re-run.
  • 70610f35ce — gates green locally: typecheck, lint, format:check, check:fallow (dead code / complexity /
    duplication 0), check:layering, check:production-exports, check:agent-guidance, check:adr-citations,
    eager-closure 909, and the focused lanes at 424 files / 3905 tests. The full-suite Coverage job for this head is
    running in CI (no local duplicate); the PR body's tested SHA moves to 70610f35ce once it reports.

New rows are benign contract tests only (a real directory symlink in a temp dir, no privileges, no exploit
reproduction). #4677 stays separate; #4649 stays the parent issue.

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

@thymikee

Copy link
Copy Markdown
Member Author

Portability and fault-tolerance correction published at 27399cb582

One normal fast-forward from 70610f35ce. No force-push, no merge.

The fold in 70610f35ce was a portability and defensive-correctness blocker, as reported in
#discussion_r4622679162.
Both halves are closed at the same resolution owner, answered in
#discussion_r4622712939:

  • Platform-native root and separator. The fold asks platform.parse(route).root and rejoins with platform.sep, so
    a drive (C:\) and a UNC scope (\\server\share\) survive the fold instead of becoming an ordinary directory under a
    POSIX root. Names split on the host's own separator only, so a POSIX name containing a backslash stays one filename
    byte-sequence rather than becoming a .. step the host never sees. The guard's lstat is now asked of the real
    spelling, so it is not inert on Windows.
  • Absent is not unverified. hostStandingAt answers link | plain | absent | unverified. ENOENT keeps the
    ordinary ../shared-state fold textual — before a daemon's first start the level stands nowhere and cannot be a link.
    Any other lookup fault (EACCES, ENOTDIR, …) says nothing about what stands there and is refused with
    state_dir_parent_step_unverified, so an uncertain route is never folded into a different state base.

Ordinary ../shared-state stays accepted where the ground is verified. Cost stays bounded: at most one lstat per
.. step, only for a route that spells one. No new abstraction — the existing fold function and one lookup helper, and
the cross-platform rows pass path.win32 / path.posix through that existing parameter rather than adding a seam.

Validation at 27399cb582 (the pushed SHA)

  • Full unit lane: pnpm test:unit exit 0 — 2164 files, 20700 passed / 10 skipped.
  • typecheck (tsc -b tsconfig.typecheck.json examples/sdk/tsconfig.json) exit 0, lint clean, format:check clean,
    check:fallow no issues in 38 changed files, check:layering exit 0 at 150 unmatched against 150 at the merge-base,
    check:production-exports, check:agent-guidance, check:adr-citations clean, eager-closure 909.
  • New rows are benign contract tests only: real directory symlink in a temp dir, one mocked lstatSync with a restored
    double, no privileges and no vulnerability reproduction.
  • Changed-line coverage was collected at 35166e551f (443/470 = 94.26% against the 70% gate). This round adds rows and
    two refusal branches; the CI Coverage job for this head is the authoritative re-run — no local duplicate started.

Latest size report is +13.1 kB unpacked. #4677 stays separate; #4649 stays the parent issue.

@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

Thanks for the update. At 422d7ba most of my earlier review is fixed: the generic publish mode is umask-governed again, loose owned state directories are narrowed, a refused marker read no longer reads as a stall, and '..' is folded once before any state path is built. One defect on the request path and three missing regression tests remain. All 18 checks pass, and there are no conflicts.

The plain branch of appendDiagnosticLine now catches an append or mkdir failure, writes to stderr and returns normally. At the merge-base the throw reached flushDiagnosticsToSessionFile, which returned null. Now the flush returns { path, ref }, and request-finalization.ts:44 and request-router.ts:749 copy it into the error's logPath and diagnosticsRecord. When the session record cannot be written (ENOSPC, EROFS, a removed sessions directory), a failed request points callers at a file that holds none of its events, instead of telling them no record exists. This is the request path, not daemon state, so it is outside #4649. Also, ensureDirectoryForLog (:536-539) adds the directory to ensuredDirectories before mkdir runs, so one failed mkdir is never retried in that scope. The rule: a flush returns a locator only for lines that reached that record. Please make the plain branch report whether the append landed (return false, or rethrow after the stderr warning), make the flush return null when it did not, and record the directory only after mkdir succeeds. The existing 'a plain log path whose write fails' and EROFS tests should then assert flushDiagnosticsToSessionFile({force:true}) === null.

The test a launch whose log the state rule refuses still starts the daemon and says so spawns a child that only writes the reported cwd and prints nothing. If the reopen-by-name ladder came back (opened.descriptor ?? fs.openSync(input.paths.logPath, 'a') at daemon-registration-owner.ts:460), the symlink target would be opened for append, but no bytes would go through it, so the victim would still read 'not yours' and the test would stay green. This PR's launcher rule, that child output never reaches a refused log's target, has no regression test. Please have the child write known bytes to both streams, then assert the victim still reads exactly 'not yours\n' and neither marker appears in it.

publishing creates at 0600 whatever the umask runs under umask 022, where a plain create already lands at 0600. Removing exactMode: true from publishPrivateStateFileSync (verified-file.ts:508) leaves it green. My earlier review raised this, and the directory case was fixed at atomic-file-state.test.ts:53, but this one is not. Please run the publication under an umask that removes an owner bit (0o277, as in atomic-file-state.test.ts:64) and assert the report mode is 0600 with no leftover sibling.

The repair seam is protected by the identity comparison between the walk's lstat and the fstat of the O_DIRECTORY|O_NOFOLLOW descriptor (verified-file.ts:801-804). No test replaces the directory between that lookup and the open. The 'NAME is a link' row at atomic-file-state.test.ts:204 installs the link before the walk, so the walk refuses first. No test reaches 'directory changed as it was opened', so deleting the identity check leaves every test green. Two earlier rounds asked for this race fix, and a refactor could drop it unnoticed. Please spy on fs.openSync for the state directory's directory open. Inside the spy, rename the judged directory away and create a same-owner directory at 0777 at that name, then return the real open. Assert the replacement keeps 0777, the original is not narrowed, and the chain answers an exposure.

Not blocking, and fine to take or leave: clearStaleDaemonRecords (daemon-registration-owner.ts:344), sweepDaemonStartupPhasesFiles and removeDaemonStartupPhasesFile (daemon-startup-phases.ts:42,52) remove files by name without using the judged directory, so cleanup could use the state boundary or security.md could say it stays outside the rule; hasParentEscape (verified-file.ts:875) copies the '..' predicate from daemon-resolution.ts:233,255, so keep one owner; four new best-effort stderr writers (daemon-diagnostics-scope.ts:149, diagnostics.ts:492, daemon-registration-owner.ts:220,294) could share one exported from host-kit; anchorDriveRelativeStateRoute adds a new state_dir_drive_relative refusal for Windows C:work routes that path.resolve accepted at the merge-base, and the establishingLogSink guard (diagnostics.ts:437) cannot fire through the only factory, so keep path.resolve and drop the flag or give it a caller; production grew from +747 net at the earlier head to +1980 net here.

Could the design be smaller? 1) One state opener: give openStateEntrySync a 'read' purpose (no create, no fchmod) and make readStateEntrySync a try/catch around it that applies the whole or tail bound. That removes the repeated judge, re-assert and exposure sequence. 2) Route stale-report and marker cleanup through the same judged entry: unlink by chain.directory after assertStateDirectoryJudged. 3) Give resolution one owner of '..': keep the merge-base resolveUserPath and, before it, refuse only when a textual prefix ending right before a '..' is a symlink or cannot be lstat'ed. That would delete anchorDriveRelativeStateRoute, the spelled-route helpers, the drive-relative refusal and hasParentEscape. 4) Let the daemon scope open its verified append fd lazily and hand host-kit a plain line writer, dropping the generic factory and the establishingLogSink and reportingUndeliverableLine flags, with the request-record path left as at the merge-base. Together this plausibly removes several hundred production lines and keeps what the review rounds asked for. What would have to change first is ADR 0016: it needs the state-route case table (no links at or below the state root, a shared level refused anywhere on the route including sticky ones, ancestor aliases allowed, '..' after a link refused at resolution), which #4649's completion conditions require and which today lives only in code comments.

None of the earlier inline threads still applies at this head, so please resolve them: the umask-governed publish default #4704 (comment), loose directory narrowing and the stall check #4704 (comment), the removed verdict-only open at scope entry #4704 (comment), the single folded '..' base #4704 (comment), every path derived from that base #4704 (comment), and the drive and UNC roots #4704 (comment). All six are fixed in the code.

The three test findings come from reading the test inputs against the production code; Windows behavior follows path.win32 semantics. Before merge, the request-path flush needs to stop returning a locator for lines that never landed, and the launch, report-mode and repair-seam regressions need to fail on their mutations. Then please answer the smaller-design question above.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

At 3e66f58 the findings from the earlier review (#4704 (comment)) are fixed. No conflicts. Two CI checks fail on routes this change touched. The Coverage job fails eager-closure-budgets.test.ts:861 because host-kit/internal/diagnostics.ts now imports the new host-stderr.ts, which adds one module to ten capture-kit closures. The context budget check fails agent-guidance-contract.test.ts:51 because docs/agents is 40529 bytes against a limit of 40000 (main is 39990, and the security.md additions add 539). The unit tests themselves passed.

Before merge, please turn both checks green. The best-effort stderr writer must live in a module every one of its callers already evaluates, so define writeHostStderrBestEffort in host-kit/internal/diagnostics.ts and delete host-stderr.ts. Then move the cleanup-boundary paragraph from security.md into ADR 0016's "Where the guarantee does not reach" section, and keep one short line in security.md that points to it. Also update the PR body Validation to the new head and answer the open smaller-design items 1 and 4.

Not blocking, and you can take or leave these: nothing reads the boolean returned by the stderr helper, so it can return void; emitDiagnostic can advance liveWrittenEventCount past an event whose live append failed (the mkdir-retry test never writes first_after_fault, and this gap predates the PR), so appending events.slice(liveWrittenEventCount) in order would close it and the test could assert it; and stepsBackOut in daemon-resolution.ts:253 is now a pass-through to spelledRouteStepsBackOut, so its call sites can use the latter directly.

Of the earlier inline threads, all six are fixed at this head, so please resolve them: umask publish default #4704 (comment), loose state-dir narrowing #4704 (comment), verdict-only open at scope entry #4704 (comment), relative .. state dir #4704 (comment), records from the folded base #4704 (comment), and drive and UNC roots #4704 (comment).

@thymikee

Copy link
Copy Markdown
Member Author

This branch now conflicts with main after the latest merges. Please rebase onto main and push. The open items from the last review are unchanged: the two budget checks and smaller-design items 1 and 4.

@thymikee
thymikee force-pushed the t3/private-state-diagnostics branch from 3e66f58 to d4ae257 Compare November 19, 2026 12:27
@thymikee

Copy link
Copy Markdown
Member Author

Rebased onto current main (8804ce24cc) and both red checks are green at this head. The two review fixes and the smaller-design measurements are below.

The two checks

Smaller-design item 1 — one state opener with a read purpose

Implemented and measured, not argued: PrivateStateOpenPurpose gains 'read', OPEN_STATE_ENTRY.read = openVerifiedFileForRead, and readStateEntrySync becomes a try/catch around openStateEntrySync(pathname, 'read') that applies the whole-or-tail bound. It typechecks and the host-kit, daemon-contracts and state-privacy lanes pass.

It is +15 net lines (36 added, 21 deleted) in verified-file.ts, which takes that file to 1006 lines against the repo's 1000-line max-lines limit — pnpm lint fails it. So the shape as specified grows the module instead of shrinking it, and I did not push it.

Three differences between a read and a write have to be carried, and each is what the added lines spend on:

  1. A read creates nothing, so it is the only purpose that can answer "no entry stands there". The opener's return type becomes number | undefined, and each of the three creating callers then has to say absence cannot happen for it — a ! or a synthetic error. That invented error is itself one of the added functions.
  2. A read must not fchmod. assertPrivateStateDescriptor gains a purpose parameter and a purpose test. This one is a real behavior rule and it had no owner before: I pinned it with a read leaves a record mode alone, because it writes nothing (0644 read stays 0644). Deleting the guard fails that test, so it is not decoration.
  3. A read answers a refusal as a status; a write throws it. Sharing the opener means the opener throws and the reader catches, so the read's own absent-versus-refused discrimination has to travel either as an error tag or as undefined — both variants measured the same +13 to +15.

What item 1 calls the "repeated judge, re-assert and exposure sequence" is five statements, and the two paths do not state the same thing: the writer's asks sit inside the throwing owner with typed wording that names the record's nlink count, and the reader's are the same two questions answered as refused. I also tried factoring only those two checks into one assertStateHandle helper without the read purpose: it removes neither call site (both still owe the ask) and it replaces the writer's that record has N names message with a generic one, so it costs the diagnostic detail to save nothing. Happy to take a shape that keeps the opener's return type number — the growth is entirely in absence and mode, not in the checks.

Smaller-design item 4 — lazy daemon log fd, plain line writer, no flags

The fd is already lazy. appendDiagnosticLine asks the factory on the first line, never before one exists, and keeps the sink that answer produced. a log path with no line never asks for a sink, and every line after one goes through it asserts the factory is never called for a scope that emits nothing. So the first half of item 4 is the current behavior; what is left to remove is the factory indirection and the two flags.

Both flags are load-bearing, and I checked each by deleting it:

  • establishingLogSink — you are right that this one is not load-bearing in production today, and I checked rather than assumed. The only emit inside the state path is reportSkippedModeRepair (verified-file.ts:773), and it sits on narrowDirectoryMode, which runs only when create is true. The sink opens through tryOpenPrivateStateFileSync, whose chain question is judgePrivateDirectoryChain — create: false, so no narrowing and no emit. daemonLogSink answers its own failures with sayOnStderr, not emitDiagnostic. So no production factory emits during setup, and the flag currently guards a case only a test-supplied factory produces; a line the sink setup itself emits never travels through the sink being built is what pins it. Dropping it means host-kit promises nothing about a factory that emits while it sets up — that line would be appended at the name whose authority setup is deciding. I would rather keep the guarantee host-kit makes to any factory than trade it for one boolean, but that is your call and I will drop it on a word.
  • reportingUndeliverableLine — this one IS reachable from production, and it is the recursion guard. reportUndeliverableDiagnosticLine emits diagnostic_log_write_failed, and that event's route is the log route that just failed: the request-record path has a logPath with no factory, so its first append failure reaches this catch, and the warning's own append fails the same way. I deleted the guard and ran the lane: it did not fail, it hung — no test summary after 15 minutes, killed by hand. A plain line writer has nowhere to put this guard, because it has to sit where the write is attempted, which is host-kit.

For the size claim: host-kit's sink plumbing is 24 lines of types (DiagnosticLineSink, DiagnosticLineSinkFactory, docs included), establishDiagnosticLineSink (33) and closeDiagnosticLineSink (11); daemon-diagnostics-scope.ts owns 72 lines across daemonLogSink, verifiedDaemonLogSink and stderrSink. A plain writer still needs the judged open, the failure-to-stderr route and the drop-and-re-ask, so most of the daemon's 72 lines survive; what actually goes away is the close and re-ask bookkeeping plus one boolean, against the two guards above.

The request-record path is already left alone. logSinkFactory is optional and daemon-diagnostics-scope.ts is its only supplier in production, so the request record keeps the merge-base by-name append. It differs only in what happens when that append fails: the flush now answers null instead of naming a file that holds none of the events.

Non-blocking items

Taken: the helper returns void (nothing read the boolean) and the one-line sayDiagnosticLineOnStderr wrapper is gone; stepsBackOut is deleted and its single call site asks spelledRouteStepsBackOut directly.

Left as-is, with the measurement: liveWrittenEventCount cannot express a gap, and appending events.slice(liveWrittenEventCount) in order trades one wrong answer for another. I implemented the suggested version and got three outcomes from it, each observed: the failed event reaches the log, its order does not — the recovered line lands after the lines that already went out, so the assertion that the log is chronological fails; and because a dropped sink is re-established and the successful line is written again through it, the log came out as second, first, second, i.e. a duplicated event. The current counter loses a line whose live append failed; the alternative mis-orders and duplicates. Closing the gap without either needs per-event landed state rather than one counter, which is a wider change than the gap deserves — and the gap predates this PR, so it is better as its own issue.

Validation

Rebased onto 8804ce24cc (includes #4670's privateAncestry trust rule, whose owner scriptTrust/ScriptDestinationTrust the state chain now consumes; the state rule asks scriptTrust({}) because its extra strictness is the walk's policy, not the executable-state option). pnpm check:affected --run --head d4ae25714f runs at this head; pnpm format:check, pnpm lint, pnpm typecheck and pnpm check:layering pass. Growth against the merge-base is production +2332/−389, tests +2479/−152, docs +61/−3.

@apex-sentinel-staging

This comment has been minimized.

The daemon creates its state directory and writes its startup marker, its shutdown report and its log
handle there without being asked, so that tree is the daemon's own. Until now it trusted it: a
mode-less mkdir left it group-writable under a shared checkout's umask, the mode repair said a chmod at
a name, and every writer and reader resolved the final name, so another local user who could write it
could point a record wherever they liked, or stop a client on a FIFO.

host-kit owns the one rule now. A state route is judged by the destination rule's own walk — every
level from `/` down, links where ADR 0016 allows them, so an allowed system alias such as `/var` still
answers — and one thing more: the directory a state entry is CREATED in is closed to entries from other
local users, sticky bit or not. Missing levels are created at 0700 and the mode is said again so no
umask can price it down; a level this user owns that stands loose is narrowed on a link-free
descriptor, reaching only the inode the judgment read; a level another user owns is refused and left
alone, and levels above the state directory are judged and never narrowed.

Every state-diagnostic write and read asks that rule for its own directory and skips its record on any
exposure, through host-kit's one verified append, publish and read owner: a regular file, opened
non-blocking, bounded in size, with a refusal answering as absence. The staging sibling is opened
exclusively at 0600, written through that descriptor, and cleaned up only while it is the entry this
call created. The marker writer leaves the ~70 lines of copied open rules behind and lives with the
registration owner, so daemon-startup-phases.ts is the client-side reader. EACCES, ENOTDIR and ELOOP on
the way in become typed refusals inside the best-effort boundary, and a refusal is reported to stderr,
never by appending to the refused path's name.

Repair never decides whether a daemon starts, and a refused diagnostic never stops a shutdown.

Issue #4649
…boundary

The review found that judging one state write is not judging the state directory, and that the answer had
spread itself over three openers and two hand-rolled publishers that could drift apart.

Every state open now goes through ONE boundary that judges the directory, spells the entry from it, opens
without following anything, and proves both the directory and the entry are what the judgment described:
the directory's identity is re-`lstat`ed against the walk's own answer, and the descriptor's `fstat` must
be this process's uid with exactly one name before the mode is narrowed on that descriptor. Previously
shared or planted ancestry therefore confers no trust on a record that is already there. A refusal is an
answer, not a crash: a launch whose log is refused takes the null device and says so on stderr, a
truncation it cannot make verified is skipped, and the diagnostics scope drops the refused log as a sink so
events leave by stderr. Nothing reopens a refused path by name, so the report about a planted link never
travels through it.

The walk answers one more question, as a position and not as text: whether a link stands at or below the
state root's own route name. An ancestor alias such as `/var` stays allowed, a link at the state directory
is refused with no repair attempted, and the repair gate is read from that position, so an alias cannot
smuggle ground above the state directory into a `chmod` and a renamed-away directory cannot pass for the
one that was judged. A `..` is refused from the raw spelling, before anything resolves it away.

Staging has one owner too. `publishStagedSync` claims the sibling at the exclusive create, writes and
narrows through that one descriptor, closes it on every path, and cleans up by identity even when the
claim's own lookup failed; the durable publisher and the private-state publisher both ride it, so
`owned-process-record.ts` lost its hand-rolled copy. A generic `publishFileSync` call keeps the mode it
always got — `0666` priced down by the umask — and a caller that wants a private file asks for `0600`.

Reads answer with why they have nothing: a marker read the state chain refused is a fact about the host and
no evidence about the daemon, so a startup wait keeps waiting to its ceiling instead of accusing a healthy
daemon of stalling, and a whole-record read refuses an entry too long to be a record rather than handing
back a parsable tail. Stale-record cleanup is tidying: each step is caught on its own, reported, and never
releases the registration.

Issue #4649
…ugh the handle that was judged

The review found two places where the boundary was asked too late, and a diagnostics sink that paid for a
verdict with the log itself.

A truncation asked as an open flag (`O_TRUNC`) empties the bytes a moment before anything says whose they
are: a record given a second name by a hard link stands verified at the open and is refused only when its
names are counted, so the refusal arrived with its contents already gone. The truncate purpose now opens
`O_RDWR` and empties with `ftruncate` on the PROVED descriptor, and a refusal costs a log line and never
somebody else's file. Reads ask the same authority the writes do — the judged directory re-`lstat`ed after
the open, and the handle's own uid and name-count — so a record another user owns, or one standing under a
second name, is refused as a read too: a verdict about this daemon is not made from bytes somebody else can
change behind this reader's back. State publication asks its directory guard at both staging seams, before
the first byte and again before the rename commits, so a directory swapped mid-write cannot receive bytes
judged somewhere else.

The daemon log's diagnostics sink is now a handle, not a verdict. The old shape appended once at every scope
entry to decide whether it may log, so a state directory with no `daemon.log` gained a 0600 one, and an
existing log had its mode said, because some code opened a scope. host-kit's diagnostics owner asks for a
sink at the FIRST line and writes every line after it — the forced final flush included — through that
judged descriptor and never at the name again, so an idle scope creates nothing and holds nothing. A line
that fails to land is said on stderr and drops the sink, and the next line is re-judged: a route that breaks
mid-run costs one line and not the rest of the run's events. A scope that hands its log to another path —
the session request record — closes the old handle and loses the old judge, because a sink answers for one
path and no other.

A shutdown report now names the lifetime that wrote it. The report is read AFTER a stop, from a directory
that outlives every run in it, so an earlier daemon's leftover — left standing precisely because this run's
own write was refused — would otherwise be reported as the cleanup of the daemon that just exited. The reader
is given the identity the stop acted on, `pid` and `startTime`, and a record naming another author, or an
author its own start time cannot be compared with, answers as no report; a stop says its confidence is
unknown rather than claiming releases it did not make. Establishment, the create-and-repair ACTION, is asked
once per state directory per process instead of once per phase marker; the per-write judgment is per-write
and is never inherited from a repair.

Issue #4649
…ts provable

Closes the six findings of the defensive review of 5eed9ca, each at the owner
that already holds the rule.

Diagnostics: a scope flags itself while it asks for its log sink, so a warning the
sink's own setup emits is routed to stderr instead of being appended at the name
whose judgment is still being made, and no half-made handle can carry bytes. The
daemon log sink re-asserts the state mode on the descriptor before adopting it, so
events never land in a file every local user can read. The plain append, a throwing
sink write, and the "could not write this line" warning are each contained, and that
warning is guarded against recursing into the route that just failed.

Configured route: the state path is judged as it is configured. Establishment passes
the spelling on untouched and resolveStateDir joins a relative state dir textually,
because path.resolve folds a `..` away and a step back out is exactly the name whose
meaning depends on what the route physically stands in - through a link, link/..
lands beside the link, not inside its target. The exposure line is written on a
contained stderr and its verdict, failed ones included, is remembered per spelling,
so losing the report costs the line and not the verdict or the startup.

State policy: WalkPolicy gained sharedLevelRefusedOnRoute, which the state rule asks
so ground other local users can add a name to is refused at every level from the
state directory down, sticky bit or not, while levels above it keep ADR 0016's
pass-through answer. Creation proves its mode through the masked mkdir instead of a
chmod at a name, so no window opens for a planted link.

Staging: a sibling is removed only while it is present, its identity is not another
entry's, and the caller's own directory judgment still holds; a directory renamed
away and made again meanwhile is not tidied by this call. The identity lookup itself
is best effort, so a host that answers no identity costs the write nothing and
leaves the exclusive create standing as the claim.

Shutdown report: when a stop expects attribution, the record must state a valid
author and a non-null start time on both sides, so an author-less record - exactly
what a recycled pid looks like - answers as no report and the stop says its cleanup
confidence is unknown.

Refs #4649
…x the two gate breaks

Three fixes on top of d43304f, two of them gates CI named.

A state dir containing a `..` step is refused by resolveStateDir with a typed
reason. Passing the spelling on, as d43304f did, cannot work: the record names
are derived with path.join, which folds the step away, so such a route would be
JUDGED as one directory and WRITTEN into as another. A `..` is also the one name
whose meaning depends on what the route physically stands in - through a link,
link/.. lands beside the link, not inside its target - so no walk could establish
where the records land even if the spelling survived. Refusing the spelling is true
of every route it could mean.

Typecheck: the two sink fixtures that hand back a write-only object now answer the
handle they hand back with a close, and one assertion message moves to expect's own
argument instead of being passed to toBe.

R84: the establishment test is named for the module it judges,
daemon-registration-owner-state-dir-establishment.test.ts.

Refs #4649
…t a proven base

Closes the two review threads on `d43304f657` at the resolution owner.

A `--state-dir ../shared-state` is an existing configuration and works again. It is
folded where it is read, once, and every record name is derived from that one base:
the names come from `path.join`, which folds a `..` away anyway, so an un-folded
base would be judged as one directory and written into as another, and `daemon.json`
would record a directory holding no records.

Folding is proven rather than assumed. `name/..` returns to the parent of whatever
NAME resolves to, so a symbolic link at `name` gives the spelling two meanings - the
target's parent, and the directory the text names. Each step back out is therefore
asked of the one host fact that decides it, an `lstat` of the directory it leaves,
and a step through a link is refused with `state_dir_parent_step_through_link`: no
base could be proven to be the one the state rule judges. Absence answers as no link,
which is what the ordinary configuration is before a daemon's first start, and the
state rule's own judgment of the created ground is unchanged.

Refs #4649
…th rules

Closes the portability and fault-tolerance gaps left in 70610f3.

The fold rebuilt every route from a fixed '/' and split on both separators. It now
asks the platform's path API: parse() answers the root, so a drive (C:\) or a UNC
scope (\\server\share\) survives the fold instead of being rewritten into another
scope, and names are split on the host's own separator, so a POSIX name containing a
backslash stays one filename byte instead of becoming a step back out the host never
sees.

The lookup that decides a fold no longer answers every failure as absence. Absent
means the level cannot be a link, which is the ordinary ../shared-state case before a
daemon's first start, and the fold stays textual. A refused or failed lookup says
nothing about what stands there, so it is refused with
state_dir_parent_step_unverified: an uncertain route is never folded into a different
state base.

Refs #4649
Each fix answers one way a state record's ground could stop being what the
judgment described, and each is pinned by a test that fails without it.

- The walk's route position survives a `..` carried by a link's TARGET, not
  just the caller's own: clearing it at an alias's own step-back recounted
  every caller name below the alias from zero, so the state rule's
  position-bounded planted-link refusal and repair gate stopped recognizing
  their own ground below such an alias.
- `readStateEntrySync` contains its ancestry judgment too: an optional read
  (the graceful-stop report, a startup tail) now answers a refusal for any
  host fault instead of throwing through a caller that already succeeded.
- The 0600 mode is certified at the one state opener and refuses the open
  when POSIX will not carry it, instead of warning while the launcher, a
  warning writer, or a diagnostics sink keeps writing through the handle.
  The diagnostics sink's duplicate re-ask is gone; the refusal answers at
  the open with its reason inside it.
- The state rule's parent-escape test now honors the separator the host
  itself honors, matching the fold in daemon-resolution: a backslash is an
  ordinary filename byte on POSIX. A Windows drive-relative state dir
  (`C:work`) is decided by one owner: a working directory absolute on that
  same drive is where the drive stands, so the route is anchored there and
  its names reach the existing checked fold un-folded; with no anchor on
  that drive the base is refused typed rather than guessed.
- Staging cleanup no longer removes a sibling whose identity the host will
  not say: the claim alone does not prove the name still stands where this
  call made it, so an unprovable or replaced entry is left to its owner
  with a typed skip reason, and the publish's own error stays the answer.
…etween

- host-kit: `appendDiagnosticLine` answers whether its line landed, and a
  flush hands out a locator only for bytes that reached that record. A
  refused `mkdir` is asked for again rather than remembered as made.
- host-kit: one best-effort stderr owner, so a report about a failed route
  stops carrying its own try/catch in each of four places.
- tests: the launch, report-mode and repair-seam rows now fail on the
  mutations they were written for — the child says bytes on both streams,
  the publication runs under an umask that removes an owner bit, and the
  repair's identity comparison is met by a directory moved as it opened.
- docs: ADR 0016 gains the state-route case table and the standing-name
  verdicts #4649's completion conditions ask for.
The `..` predicate stood in two places: `anchorDriveRelativeStateRoute`'s
fold in daemon-resolution and `hasParentEscape` in the state chain. Both ask
one host rule — which bytes separate a name — and two owners is two places
that rule can drift apart on Windows, where both separators count.

host-kit's path-resolution owner answers it now, with the route-name split it
is built from. The state chain and the resolver both consume it.

Also writes down where stale-record cleanup stands: an unlink costs one name
and follows nothing, so it is outside the judged-entry rule by design.
… lives

The shared stderr writer stood in a module of its own, and the eager-closure
budget named it: every entry that already evaluated the diagnostics owner grew
by one module for a nine-line helper. The rule now sits beside the owner that
states why a line has to leave by stderr at all, and the four callers reach it
through host-kit's diagnostics surface.
…te rule

An unlink costs one name and follows nothing, so the stale-report removal and
the dead-pid marker sweep cannot write through a planted entry and write no
bytes. That is the boundary, written down rather than left to be re-asked.
The cleanup boundary is a fact about the state chain, so it belongs in ADR
0016's "Where the guarantee does not reach" rather than in the security
summary, which keeps one pointer.

The summary's line that daemon state "except its marker and report" does not
follow these rules stopped being true at this branch.
Rebased onto main, `atomic-file.ts` stands at 1014 lines against the 1000-line
lint limit (this branch 1000, #4670 +14). Trimmed this branch's own restated
prose rather than splitting the module, which would move closure counts the
eager-closure gate holds: the two staging guards are documented once, at the
staging owner, and the `claimed` parameter every call site passed as `true` is
gone with the claim step it described.

The state chain now says beside `scriptTrust({})` why it asks the script rule's
own trust: its extra strictness is the walk's policy, not #4670's
private-ancestry option, because a state record is data rather than an
executable another user could compile.
main's boundary line said the daemon trusts its state directory. This branch
made that false: the state route and every state write, read and open are judged
now (#4649), so the line says what the code does, and one line points at the
ADR that names what the judgment leaves out.

docs/agents sits 9 bytes under its 40000 budget after #4670, so the state
pointer is that one line and the cleanup boundary lives in ADR 0016's "Where the
guarantee does not reach".
Nothing read the stderr helper's boolean, so it says the line and reports
nothing, and the one-line wrapper that only called it is gone.

`stepsBackOut` in daemon-resolution.ts had become a pass-through to
`spelledRouteStepsBackOut`, so its one call site asks that owner directly and
the local alias is deleted.
Only a writer has a reason to make the mode exact: it keeps appending through that handle. A reader that
tightened a file it was only asked about would be an unasked-for write, and no test said which side stood.
@thymikee
thymikee force-pushed the t3/private-state-diagnostics branch from c88d1a6 to c44b5d9 Compare November 19, 2026 14:59
`verified-file.ts` carried both rules at once once main's destination work landed, and passed the
1000-line rule with them. `state-directory.ts` now answers the ground question: whether a directory the
daemon picked for itself is private at the whole route, what the narrowest repair is where one exists,
and which exposure a refusal names. `verified-file.ts` keeps the verified open and the record's bytes.

No rule changes. The walk, the trust record, the exposure wording, the typed failure and the repair move
with the code that enforces them; `file.ts` names both owners, and each test suite follows the module it
describes. The approvals table pays for the one file boundary this adds, for the reason it states.
@thymikee

Copy link
Copy Markdown
Member Author

Rebased onto current main and split the two oversized modules. Head a71bef41b8d8d93ce0e9780d98ffb786d3433a72.

The splits. state-directory.ts (404 lines) is the new owner of the state-directory rule: the chain walk, the repair, the exposure wording and the typed reason. verified-file.ts keeps the verified opens and a record's bytes and is now 614 lines. Main's #4745 had already split the other side, so this branch follows main's layout rather than carrying its own: atomic-publish.ts 308, script-destination.ts 724, entry-name.ts 169, script-destination-refusal.ts 95. All five are inside the 1000-line rule and pnpm lint is clean.

The three points. atomic-publish.ts keeps this branch's identity-checked cleanup — the sibling is removed only when the lstat of the name answers the identity fstat gave the create, and the caller's directory judgment is asked again before the name is touched — on main's temporaryNamePrefix / TEMP_NAME_STEM_BYTES naming. The five sibling-name tests now capture the staged name from a real publish instead of the folded-away seam. openVerifiedFileForRead uses main's optionalNonBlockFlag(), and lstatIfPresent has one definition in the package. file.ts unions both sides' exports and names the module each one lives in.

One thing to flag. The split adds a file boundary to closures that already loaded this code through file.ts, which the eager-closure gate counts as growth, so the approvals table carries one row naming state-directory.ts. The alternative — keeping the rule inside verified-file.ts — is what the head before this one did, and it is the file the review asked to be split.

pnpm build, format, lint, typecheck, check:layering and the eager-closure budgets (915 tests) pass, plus host-kit (749) and the daemon-contracts / daemon-client / capture-kit / state-privacy suites (1,848). The read-leaves-mode-alone test was re-checked against its mutation at this head and still fails when a read narrows the mode.

@apex-sentinel-staging

Copy link
Copy Markdown

Apex Sentinel · ✅ Approve · review of a71bef4

Warning

The isolation lease for this review ended before the review finished (an artifact of the staging environment). There is a chance that some of its findings are unverified, or that something was missed. Comment @apex-sentinel-staging review to run it again.

Since the review of 39e30bc: 0 new · 0 still open · 1 no longer raised

No open findings.

Not in the reviewers' prompt (5 files)
  • docs/adr/0016-active-session-script-publication.md: left out as an asset or for its size; reviewers could still search it
  • docs/adr/README.md: left out as an asset or for its size; reviewers could still search it
  • docs/agents/security.md: left out as an asset or for its size; reviewers could still search it
  • packages/host-kit/src/internal/state-directory.test.ts: left out as an asset or for its size; reviewers could still search it
  • packages/host-kit/src/internal/verified-file-state.test.ts: left out as an asset or for its size; reviewers could still search it

1 finding below minor hidden (user_settings.min_severity).

Reviewed with this repository's own Sentinel configuration (629128d531ba).

💬 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

This PR is ready at a71bef4. The notes from the earlier review at d4ae257 are fixed, and the split is a pure move. All 19 checks pass on a head rebased onto main, and there are no conflicts. Nothing else needs to happen before merge.

Not blocking, take or leave: after the rebase, skipOnWindows is exported from script-destination-host.fixtures.ts, but state-directory.test.ts and verified-file-state.test.ts still declare it locally, so importing it from that fixture and deleting the local consts would remove the duplicate.

The one remaining inline thread, on the pid-only stop path in daemon-client-stop.ts, does not apply, so please resolve it: #4704 (comment). That file is unchanged between c88d1a6 and a71bef4, and the case is unreachable because daemon-process.ts refuses a live pid with no start time before any signal or report read, which daemon-client-stop.test.ts pins.

@thymikee thymikee added the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 19, 2026
@thymikee

Copy link
Copy Markdown
Member Author

Closing this PR in favor of a smaller design.

The size (about 5,500 lines) comes from one choice: the daemon keeps running when its state directory is unsafe, so every file write has to protect itself. We're reversing that choice. The daemon checks the state root once, before anything uses it: the root must be a real directory owned by the daemon's user, mode 0700, under a parent that other accounts can't write to. If that check fails, the daemon refuses to start and says how to fix it. After that, ordinary atomic writes are enough, and the per-write chain walks, descriptor checks and path interpreter here aren't needed.

The replacement is a short stack:

  1. Per-launch startup progress replaces the startup-marker files. This alone fixes the reproduced write through a planted link.
  2. Private state is admitted at startup, and daemon-picked scripts adopt it.
  3. Readiness is published from an explicit daemon lifecycle machine.
  4. Shutdown reports count only when their author matches the stopped daemon's lifetime.

#4649 will be amended to match before slice 2. Thanks to everyone who reviewed this; the edge cases found here feed straight into the new tests.

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