Repository navigation
Fix: Atomic, symlink-preserving settings writers and one proxy-running check - #1591
Conversation
…g check (#1565) Three verified problems in how agentop writes the user's files and judges the proxy: - writeState and the service unit file wrote in place with os.WriteFile, which truncates before it writes. A kill in that window left the ownership record torn, after which readState refused it and writeState refused to overwrite — every later enable only warned, forever, while the record held the only copy of the user's prior settings. A torn plist meant the proxy silently never started at login. Both now write through writeFileAtomic (CreateTemp + fsync + rename), so a crash mid-write leaves the previous contents intact. - writeSettings, bobWriteKeys and codexEnvFile.write each wrote path+".tmp" with os.WriteFile and renamed it over path: renaming over a SYMLINK replaces the link, so a ~/.claude/settings.json managed into a dotfiles repo silently stopped tracking (reproduced: link replaced, write never reached the target), and a symlink planted at the fixed tmp name would redirect the write. writeFileAtomic now resolves symlinks first — the write lands at the target, the link survives — and CreateTemp's unique name cannot be planted. The back-up-once block, copied word for word in all three writers, is one backupOnce. - The service path's private proxy-running checks (runningPID, livePID, pidExePath) disagreed with setup's (setup_probe.go, which matches install.sh): when ps failed, runningPID returned 0 while setup's deliberately sandbox-blind check reported the proxy running — so in a sandbox the install path did not stop a hand-started proxy and the supervised copy crash-looped against the port. runningPID and adoptablePID are now built on proxyRunning and preRenameProxyRunning; the private copies are deleted. Tests: the torn-write sequence (pinned as the consequence a torn record has, so the fix's inability to produce one is the other side of it), the symlink repro (red before, green after: link survives, target carries the write), a planted-tmp-symlink redirect test, and the two tests that pinned the old behaviors — snapshot-restore of a symlink (which asserted the link replacement as a fixture) and the adoptable stranger's path shape (ps comm vs lsof resolution) — adapted to the new contract with their purposes intact. Fixes #1565 Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Hai Huang <[email protected]>
Walkthrough
Merge Risk:
|
Fixes review: writeFileAtomic's doc comment opened with its first sentence twice; setupPIDExePath's comment pointed at pidExePath, which the unified probe deleted; isProxyComm had no production caller left after runningPID moved to proxyRunning, and only its own test kept it alive. Files: cmd/agentop/cmd_service_platform.go, cmd/agentop/cmd_service_test.go, cmd/agentop/setup_files.go, cmd/agentop/setup_probe.go Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Hai Huang <[email protected]>
clawgenti
left a comment
There was a problem hiding this comment.
Summary
The direction is right: atomic writes for the ownership record and unit file, one shared backupOnce, and building runningPID/adoptablePID on the install.sh-equivalent probes all make sense, and the symlink repro is red on main and green on this branch as the PR says. There is one blocking regression, though. Now that writeFileAtomic writes through a symlink, setup's snapshot/undo stops working for a symlinked settings.json. snapshotFile stores only the link text, so after a rollback the user's dotfiles target still routes to Cortex and the .bak has been deleted. The test change in setup_files_test.go took out the assertion (link target changed) that would have caught this. I also have some suggestions on test strength and on backupOnce.
Author: huang195 (MEMBER — maintainer)
Areas reviewed: Go (cmd/agentop: settings writers, setup snapshot/undo, service proxy probes, tests), Security (symlink/tmp handling)
Agent/IDE config (.claude/.vscode): none
Commits: 2 commits, all signed-off: yes
CI status: passing
Local verification (go1.26.10, linux/amd64):
go build ./...,go vet .,gofmt -l .: clean.- Targeted tests (writers, snapshot, runningPID/adoptablePID, samePath, bob/codex): pass.
- Full
go test ./...in cmd/agentop: 10/11 packages pass. The root package failsTestServiceInstall_RefusesABrokenConfigandTestReportSessionInterruption, but both fail the same way onmainin this sandbox (no systemd user bus), so they are environmental and not caused by this PR. - Repros run against
main:TestWriteSettings_SymlinkReplacedis red (both assertions).TestWriteState_TornWriteBlocksEveryLaterEnableandTestWriteFileAtomic_PlantedTmpSymlinkare green on main, so neither one guards a change in this PR (see the inline comments). - Probe for the must-fix (snapshot a symlinked settings.json and its .bak, run
writeSettings, restore both): on main the target ends up byte-identical to the original. On this branch the target keepsANTHROPIC_BASE_URL=http://127.0.0.1:47600and.bakis gone.
Review round on #1591 (#1565): - snapshotFile captured only the link text for a symlinked path, but writes now go THROUGH the link, so undo could not put the target's bytes back: after a failed setup the user's settings still routed to a proxy the undo had just removed, and the .bak snapshot (existed: false) deleted the only backup. Snapshot the resolved target's bytes and mode too, and restore them through the re-asserted link. - backupOnce kept both problems this PR fixes elsewhere: os.WriteFile could tear the write-once .bak forever, and os.Stat follows a link, so a planted symlink at the .bak name steered the backup's contents to a chosen path. Lstat + writeFileAtomic. - writeFileAtomic's MkdirAll is 0700, not 0755: it can be the write that first creates ~/.cortex or ~/.codex, which hold settings, logs and pidfiles. - The torn-write repro tore the record by hand and the planted-tmp repro called writeFileAtomic directly, so both were green on main and guarded nothing. Added a real regression test (a write that cannot complete leaves the previous record readable) and retargeted the tmp-symlink test at the three writers that had the fixed name; both are red on main, as is the extended symlink-snapshot test. - runningPID's doc claimed "alive AND one of ours"; the probe is deliberately ps-blind and trusts the pidfile, matching install.sh. Stated the trade-off so no one fixes the blindness back on one side only. writeProxyStamp's trailing err-return in a void function is now a plain best-effort discard. Signed-off-by: Hai Huang <[email protected]> Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Hai Huang <[email protected]>
clawgenti
left a comment
There was a problem hiding this comment.
Summary
Re-review at dd41753. Every point from the previous round is addressed. The blocking symlink-undo regression is fixed: snapshotFile now records the resolved target's bytes and mode, and restore re-asserts the link and then writes those bytes back through it. The extended TestSnapshotRestoresASymlinkAsASymlink assertion is red on the previous head (2619c9a) and green here. The new regression tests now guard the change: TestWriteState_FailedWriteKeepsThePreviousRecord, TestWriters_IgnoreAPlantedTmpSymlink (all three subtests) and TestWriteSettings_SymlinkReplaced are all red on main and green on this branch. I have no new blocking findings, so I'm approving.
Author: huang195 (MEMBER — maintainer)
Areas reviewed: Go (cmd/agentop: setup snapshot/undo, writeFileAtomic/backupOnce, service proxy probe docs, regression tests), Security (symlink / planted-name handling)
Agent/IDE config (.claude/.vscode): none
Commits: 3 commits, all signed-off: yes
CI status: passing
Status of previous findings
- must-fix, symlinked settings.json undo: fixed. My throwaway repro snapshots a symlinked settings.json (target mode 0640) and its
.bak, then runsbackupOnce+writeSettingsand restores both. On this head the target is byte-identical to the original, its mode stays 0640, the link still points at the dotfiles target, the.bakthat setup created is removed, and no temp files are left behind. A relative-link variant passes too. backupOncenon-atomic / follows a planted.bak: fixed (Lstat +writeFileAtomic). A planted dangling.baklink no longer gets written through.- parent dir mode 0755: fixed.
writeFileAtomicandsymlinkAtomicnow use 0700.
4/5. tests green on main: fixed, as described above. The hand-torn test is now documented as illustrative only, which is fine. runningPIDdoc: fixed. The trade-off is now stated.
7/8. nits: fixed (real/_ = plantare gone with the rewritten test, andwriteProxyStampuses a plain_ =).
Local verification (go1.26.10, linux/amd64):
go build ./...,go vet .,gofmt -l .: clean.go test ./...in cmd/agentop: 10/11 packages pass. The root package fails onlyTestServiceInstall_RefusesABrokenConfigandTestReportSessionInterruption. Both fail the same way onmainin this sandbox (no systemd user bus), so they are environmental and not caused by this PR.
A minor note that needs no change: writeFileAtomic is shared, so the 0700 MkdirAll also applies when it is the first writer of ~/.local/bin (via copyFile) or ~/.config/systemd/user. That is harmless for per-user directories, but the comment's list ("~/.cortex, ~/.claude, ~/.codex") is a little narrower than what the code actually covers.
Fixes #1565. All three problems verified before the fix — two reproduced with red tests, one confirmed in code. 238 insertions across 9 files, under the 300–450 estimate.
1. The torn-write death loop — reproduced
TestWriteState_TornWriteBlocksEveryLaterEnablewalks the exact sequence: enable writes the ownership record → agentop is killed mid-write (os.WriteFiletruncates before writing, so the file holds a JSON prefix) →readStatefails →writeStaterefuses to overwrite, forever. Every later enable only warns, and the user'sPrior— the only copy of what they had — is hostage in a file nothing can read. The launchd/systemd unit file was written the same way (a torn plist = the proxy silently never starts at login).Fix:
writeState, both unit-file writes, and the proxy stamp write go throughwriteFileAtomic— CreateTemp + fsync + rename — so a crash mid-write leaves the previous record intact and the torn state becomes unproducible by agentop itself. The refusal on a genuinely corrupt record stays (correct for hand-mangled files); the test pins that consequence.2. The symlink break + the fixed
.tmpname — reproduced red, green afterTestWriteSettings_SymlinkReplacedfailed on both assertions before the fix:writeSettingsreplaced a symlinkedsettings.jsonwith a regular file and the write never reached the dotfiles target. Same shape inbobWriteKeysandcodexEnvFile.write; the fixedpath+".tmp"name was additionally a redirect for a planted symlink (userconfig.goalready guarded its own copy against exactly this).Fix:
writeFileAtomicresolves symlinks first — the write lands at the link's target and the link survives — and CreateTemp's unique name can't be planted (TestWriteFileAtomic_PlantedTmpSymlinkpins it: the victim file stays untouched). The back-up-once block, copied word-for-word in three writers, is onebackupOnce.3. The two disagreeing proxy checks — confirmed in code, unified
runningPIDreturned 0 wheneverpsfailed while setup's deliberately sandbox-blindproxyRunningreported the proxy running; the pidfile parsers and exe-path lookups also differed. In a sandbox the install path (adoptablePID) then failed to see and stop a hand-started proxy, and the supervised copy crash-looped against the port — the exact failure the adoption comment says it prevents (not reproduced in a live sandbox, matching the issue's own honesty).Fix:
runningPIDandadoptablePIDare thin compositions oversetup_probe.go'sproxyRunning/preRenameProxyRunning— the set that matches install.sh. The privatelivePID/pidExePathcopies are deleted.Tests adapted, not weakened
Two existing tests pinned the old behaviors:
TestSnapshotRestoresASymlinkAsASymlinkused the link replacement as its fixture (its comment said "What writeSettings does: replace the link" — the bug, verbatim) — it now pins the new contract (write through the link; restore is for when something else breaks the link) with its restore purpose intact. The adoptable-stranger subtest requiredps comm's as-typed path shape, which the unified probe's lsof-first lookup resolves away — the dotdot rule it reached for is pinned directly byTestSamePathFollowsLinksBeforeDotDot, and the subtest still proves a stranger is refused however its executable is spelled.Verification
go vet,gofmt,go mod tidy -diffclean.Assisted-By: Claude (Anthropic AI) [email protected]
Summary by CodeRabbit