Repository navigation
Conversation
Size Report
Startup median (7 runs, lower is better):
|
This comment has been minimized.
This comment has been minimized.
|
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:
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. |
c3fb4d4 to
debc04a
Compare
|
Head Marker ignores the verdict — fixed. Copied opener — fixed. Repair followed a link — fixed. Cross-check 1 (publication left the judged directory) — fixed. The state rule reuses Cross-check 2 (sibling not owned) — fixed. Cross-check 3 (readers trusted the path) — fixed. Cross-check 4 (a filesystem error aborted startup) — fixed. Cross-check 5 (warning through the refused path) — fixed. Refusals report to stderr, never to Simplicity — done. The ~70-line copy is deleted, Non-blocking. Sequence. #4677 still owns |
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
Apex Sentinel: 2 new findings on debc04a. The verdict and the full list are in the summary comment.
|
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 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. |
|
Follow-up pushed: f5cc76f (fast-forward on debc04a). No merge, no force-push. Three red jobs from the debc04a run, attributed and closed:
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, Simplicity. Consolidated this round: the three state openers became one 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 |
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
Apex Sentinel: 1 new finding on f5cc76f. The verdict and the full list are in the summary comment.
|
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
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 ( Simplicity. Consolidations this round: the verdict+reopen pair became one sink owner used by both diagnostics and the registration owner's report path; the Gate state at 5eed9ca (local). tsc clean · oxlint clean · |
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
Apex Sentinel: 2 new findings on d43304f. The verdict and the full list are in the summary comment.
|
Checkpoint while validation finishes. Both CI breaks named on
Already green at this SHA: |
This comment has been minimized.
This comment has been minimized.
Round closed at
|
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
Apex Sentinel: 1 new finding on 70610f3. The verdict and the full list are in the summary comment.
Portability and fault-tolerance correction published at
|
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
|
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 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 ( publishing creates at 0600 whatever the umask runs under umask 022, where a plain create already lands at 0600. Removing The repair seam is protected by the identity comparison between the walk's lstat and the fstat of the Not blocking, and fine to take or leave: Could the design be smaller? 1) One state opener: give 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 |
This comment has been minimized.
This comment has been minimized.
|
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 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 Not blocking, and you can take or leave these: nothing reads the boolean returned by the stderr helper, so it can return void; 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 |
|
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. |
3e66f58 to
d4ae257
Compare
|
Rebased onto current The two checks
Smaller-design item 1 — one state opener with a
|
This comment has been minimized.
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.
c88d1a6 to
c44b5d9
Compare
`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.
|
Rebased onto current The splits. The three points. One thing to flag. The split adds a file boundary to closures that already loaded this code through
|
Apex Sentinel · ✅ Approve · review of
|
| Command | What it does |
|---|---|
@apex-sentinel-staging note <context> |
Adds context; Sentinel re-checks the cited code |
@apex-sentinel-staging pivot <why> |
Says the finding is wrong; Sentinel re-checks the cited code |
@apex-sentinel-staging like |
Marks the finding as useful |
@apex-sentinel-staging dislike <why> |
Marks it as not useful, so it is not raised again |
On this conversation, comment @apex-sentinel-staging review to run a full review once again.
|
This 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, The one remaining inline thread, on the pid-only stop path in |
|
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:
#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. |
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:layeringand 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.ts308,script-destination.ts724,verified-file.ts614,state-directory.ts404. 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 HEADfailed in the unit stage (receiptrun-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:coveragepassed 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's7b6500crun; the unrelated failure was rerun.