Skip to content

Fix: Atomic, symlink-preserving settings writers and one proxy-running check - #1591

Merged
huang195 merged 3 commits into
mainfrom
fix/settings-writers-1565
Oct 30, 2026
Merged

huang195 merged 3 commits into
mainfrom
fix/settings-writers-1565

Conversation

@huang195

@huang195 huang195 commented Oct 30, 2026 •

Copy link
Copy Markdown
Member

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_TornWriteBlocksEveryLaterEnable walks the exact sequence: enable writes the ownership record → agentop is killed mid-write (os.WriteFile truncates before writing, so the file holds a JSON prefix) → readState fails → writeState refuses to overwrite, forever. Every later enable only warns, and the user's Prior — 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 through writeFileAtomic — 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 .tmp name — reproduced red, green after

TestWriteSettings_SymlinkReplaced failed on both assertions before the fix: writeSettings replaced a symlinked settings.json with a regular file and the write never reached the dotfiles target. Same shape in bobWriteKeys and codexEnvFile.write; the fixed path+".tmp" name was additionally a redirect for a planted symlink (userconfig.go already guarded its own copy against exactly this).

Fix: writeFileAtomic resolves symlinks first — the write lands at the link's target and the link survives — and CreateTemp's unique name can't be planted (TestWriteFileAtomic_PlantedTmpSymlink pins it: the victim file stays untouched). The back-up-once block, copied word-for-word in three writers, is one backupOnce.

3. The two disagreeing proxy checks — confirmed in code, unified

runningPID returned 0 whenever ps failed while setup's deliberately sandbox-blind proxyRunning reported 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: runningPID and adoptablePID are thin compositions over setup_probe.go's proxyRunning / preRenameProxyRunning — the set that matches install.sh. The private livePID / pidExePath copies are deleted.

Tests adapted, not weakened

Two existing tests pinned the old behaviors: TestSnapshotRestoresASymlinkAsASymlink used 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 required ps 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 by TestSamePathFollowsLinksBeforeDotDot, and the subtest still proves a stranger is refused however its executable is spelled.

Verification

  • Both repros red on main, green on this branch; the full agentop module passes (11 packages, one 6-minute run), go vet, gofmt, go mod tidy -diff clean.

Assisted-By: Claude (Anthropic AI) [email protected]

Summary by CodeRabbit

  • Bug Fixes
    • Configuration and service files are now updated more reliably, reducing the chance of partially written files if an update fails.
    • Existing configuration backups are preserved, and configuration files accessed through symlinks continue to update their targets.
    • Setup recovery now retains symlink and target-file details when available.

…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]>
@huang195
huang195 requested a review from a team as a code owner October 30, 2026 00:24
@coderabbitai

coderabbitai Bot commented Oct 30, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Walkthrough

Agentop routes settings, state, and service-file writes through shared atomic-write helpers. The changes also update symlink snapshot and restoration behavior, backup creation, and service proxy detection.

Changes: Agentop file writes and proxy detection

Layer / File(s) Summary
Shared atomic writes and symlink snapshots
cmd/agentop/setup_files.go, cmd/agentop/setup_files_test.go
writeFileAtomic resolves existing symlinks and creates parent directories with mode 0700. Symlink snapshots capture and restore regular target bytes and permissions when available. backupOnce creates a .bak file when one does not exist.
Settings and service writer migration
cmd/agentop/cmd_bob.go, cmd/agentop/cmd_claudecode.go, cmd/agentop/cmd_codex.go, cmd/agentop/cmd_service.go, cmd/agentop/settings_writers_repro_test.go
Settings, state, and service writers use writeFileAtomic; settings writers use backupOnce. New tests cover torn state, failed writes, symlinked settings, and planted .tmp symlinks.
Shared proxy detection and service stamp
cmd/agentop/cmd_service_platform.go, cmd/agentop/cmd_service_test.go, cmd/agentop/setup_probe.go
runningPID and adoptablePID use shared proxy probes. writeProxyStamp uses writeFileAtomic. Service tests use setupPIDExePath and remove the exact-basename helper test.

Priority: Normal

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix · Severity of issue fixed: Medium

Possibly related issues

  • Issue 1554: The PR updates several writers listed in the issue to use writeFileAtomic. The supplied diff summaries do not establish whether the shared helper calls Sync.

Suggested reviewers: mrsabath, alan-cha

Merge Risk: Minimal · up to dd417

No actionable merge-blocking issue is established; the PR is mergeable after normal checks.

Pre-merge checks: Passed 5
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely identifies the main changes: atomic, symlink-preserving settings writers and the proxy-running check update.
Linked Issues check Passed Issue #1565 is active and directly linked. The PR uses writeFileAtomic for state records, service unit files, and proxy stamps. The helper uses a unique temporary file, fsync, and rename. It resolves …
Out of Scope Changes check Passed The changes stay within #1565. The snapshot and restore updates support symlink-preserving settings writes and undo behavior. Test updates adapt existing expectations to the new contract and add regre…
Docstring Coverage Passed Docstring coverage is 93.75% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentati…
Full details: Linked Issues check

Explanation

Issue #1565 is active and directly linked. The PR uses writeFileAtomic for state records, service unit files, and proxy stamps. The helper uses a unique temporary file, fsync, and rename. It resolves existing symlinks and preserves the target path. The settings writers use this helper and share backupOnce. runningPID and adoptablePID now use the setup probe checks. Regression tests cover failed writes, symlink preservation, and planted temporary-file symlinks.

Full details: Out of Scope Changes check

Explanation

The changes stay within #1565. The snapshot and restore updates support symlink-preserving settings writes and undo behavior. Test updates adapt existing expectations to the new contract and add regression coverage. Proxy stamp handling is part of the same atomic-write correction. No unrelated change is established.

Full details: Docstring Coverage

Explanation

Docstring coverage is 93.75% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 16 functions across 9 files.

Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

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 clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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 fails TestServiceInstall_RefusesABrokenConfig and TestReportSessionInterruption, but both fail the same way on main in this sandbox (no systemd user bus), so they are environmental and not caused by this PR.
  • Repros run against main: TestWriteSettings_SymlinkReplaced is red (both assertions). TestWriteState_TornWriteBlocksEveryLaterEnable and TestWriteFileAtomic_PlantedTmpSymlink are 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 keeps ANTHROPIC_BASE_URL=http://127.0.0.1:47600 and .bak is gone.

Comment thread cmd/agentop/setup_files.go Resolved
Comment thread cmd/agentop/setup_files.go Resolved
Comment thread cmd/agentop/cmd_claudecode.go Resolved
Comment thread cmd/agentop/cmd_service_platform.go Resolved
Comment thread cmd/agentop/cmd_service_platform.go Resolved
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 clawgenti left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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

  1. must-fix, symlinked settings.json undo: fixed. My throwaway repro snapshots a symlinked settings.json (target mode 0640) and its .bak, then runs backupOnce + writeSettings and 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 .bak that setup created is removed, and no temp files are left behind. A relative-link variant passes too.
  2. backupOnce non-atomic / follows a planted .bak: fixed (Lstat + writeFileAtomic). A planted dangling .bak link no longer gets written through.
  3. parent dir mode 0755: fixed. writeFileAtomic and symlinkAtomic now 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.
  4. runningPID doc: fixed. The trade-off is now stated.
    7/8. nits: fixed (real / _ = plant are gone with the rewritten test, and writeProxyStamp uses 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 only TestServiceInstall_RefusesABrokenConfig and TestReportSessionInterruption. Both fail the same way on main in 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.

@huang195
huang195 merged commit 2a9152c into main Oct 30, 2026
41 checks passed
@huang195
huang195 deleted the fix/settings-writers-1565 branch October 30, 2026 01:41
@github-project-automation github-project-automation Bot moved this from New/ToDo to Done in Rossoctl Issue Prioritization Oct 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

bug: agentop can lose the user's original settings, breaks symlinked settings files, and has two disagreeing proxy checks

2 participants