Repository navigation
Write Kit Files Atomically Through a Temporary File Beside Each Target - #4336
Conversation
The agent-safety kit's shared writer truncated each file and rewrote it in place, so an interrupt between the truncate and the last write left CLAUDE.md, settings.json, or a Codex or opencode rule file empty or partial. global_rules.py writes through the same function. write_regular_file now writes to a temporary file in the target's own directory, flushes it, and swaps it in with os.replace. A link is resolved and its target replaced, so a dotfiles symlink stays a link. The target is still opened for writing first and judged on that descriptor, so a read-only file, a FIFO, a device, or a directory is refused before anything is made. A replaced file keeps its permission bits. The backup callback now runs once the new content is whole on disk, just before the swap, so a write that cannot finish leaves no backup. The temporary file is removed on any failure or interrupt where its path still holds the file this call created. A failure can no longer leave the target holding neither version, so IncompleteWrite, the restore of the prior content, and the stamp record of a cut-short CLAUDE.md go, along with the prior parameter that only the restore read. Co-Authored-By: Claude Opus 5.5 <[email protected]>
install.py now creates a temporary file for every write, so it takes the interrupt rule: one handler for SIGINT and SIGTERM raises KeyboardInterrupt, main prints one line naming the signal, and the entry point re-raises it. A SIGTERM therefore unwinds through the writer's cleanup rather than killing the process with the temporary file left. The staged hook copies are removed when an interrupt or error unwinds through the staging, and the hooks' data file goes through write_regular_file instead of its own copy-then-replace. read_regular_file and the writer's target check now share one open-without-blocking-and-judge-the-descriptor primitive. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A module-level annotation is evaluated at import, and list[int] raises on Python 3.8 before the installer can print its 3.11+ refusal. The PowerShell wrapper checks only the major version, so such a host would have seen a traceback. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
A recorded local strict-review pass covers head |
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 18 minutes. View limit details
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. |
There was a problem hiding this comment.
🟡 Changes recommended
A critical active issue remains because the target can be replaced after validation but before os.replace, allowing a newer intervening edit to be overwritten.
1 open issue
What changed in this PR
This pull request makes agent-safety kit file writes atomic and interrupt-safe, preserving existing configuration during failed or interrupted updates.
Changes:
- Writes through temporary files beside targets and swaps them with
os.replace. - Preserves symlinks and permission bits while cleaning up failed writes.
- Adds signal handling, staged-hook cleanup, and comprehensive failure and interruption tests.
- Removes obsolete partial-write recovery and leftover-stamp logic.
| File | Description |
|---|---|
| tests/test_global_rules.py | Tests atomic global-rule writes, including interrupted writes, symlink targets, cleanup, and real signal handling. |
| host-setup/agent-safety/global_rules.py | Routes Codex and opencode rule-file writes through the shared atomic writer. |
| host-setup/agent-safety/claude/test_install.py | Tests atomic, interrupted, failed, symlinked, permission-preserving, and signal-driven installer writes. |
| host-setup/agent-safety/claude/install.py | Implements atomic file replacement, temporary-file cleanup, signal handling, staged-hook cleanup, and simplified stamp behavior. |
Review effort: Lite
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## develop #4336 +/- ##
===========================================
+ Coverage 79.15% 79.54% +0.39%
===========================================
Files 45 45
Lines 15926 15918 -8
===========================================
+ Hits 12606 12662 +56
+ Misses 3320 3256 -64
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
os.readlink on Windows returns an absolute target with the \\?\ prefix, so comparing it to the path the test linked failed there although the link was kept. The test now checks that the path is still a link and resolves to the destination. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
A recorded local strict-review pass covers head |
|
@coderabbitai review |
|
/review |
Action not completed
|
…ocal Cover, UTF-8 Children (#4342) Promotes the eight pull requests that landed on develop since the last promotion. - #4334: Create the PR with the `comments` label in drive-pr. - #4337: Correct the reviewer reference on CodeRabbit in private repositories. - #4335: Probe each Python candidate in `install.ps1` and bound the profile mask. - #4336: Write kit files atomically through a temporary file beside each target. - #4338: Pin the governance sections the host CLAUDE.md blocks mirror. - #4340: Let an attested pass cover a main head with no Copilot table. - #4339: Rebase or append where an upstream rejects merges or rewrites. - #4341: Pass `PYTHONIOENCODING` to every Python child a test decodes as UTF-8. Closes #1577 Closes #2274 Closes #4176 Closes #4322 Closes #3601 Closes #4317 Closes #4031 Closes #4113 Closes #3925 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Improvements** * The Windows agent installer now detects a working Python 3.11+ interpreter and reports which options were unavailable or too old. * Agent installation better preserves existing files if interrupted or if a write fails. * Installer logs more accurately distinguish profile paths from similarly named folders. * Pull request review guidance clarifies when local review coverage can qualify and how labels affect review runs. * **Documentation** * Updated contribution, review, and agent setup guidance, including governance synchronization checks. <!-- end of auto-generated comment: release notes by coderabbit.ai -->

Summary
The agent-safety kit's shared writer,
write_regular_fileinhost-setup/agent-safety/claude/install.py, truncated each file and then rewrote it in place. An interrupt or a full disk between the truncate and the last write leftCLAUDE.md,settings.json, or the stamp empty or partial.host-setup/agent-safety/global_rules.pywrites Codex's and opencode's rule files through the same function, so it had the same window. Those rule files hold the maintainer's own host rules, so a truncation could lose content no install restores.The writer now:
os.replace. A failure or an interrupt at any point leaves the target as it was, holding its prior content or absent.BaseExceptionincluded, where its path still holds the file this call created. The identity check that used to guard a created target now guards the temporary file.install.pynow holds a temporary file during every write, so it takes the interrupt ruleglobal_rules.pyalready follows. One handler for SIGINT and SIGTERM raisesKeyboardInterrupt.mainprints one line naming the signal, and the entry point re-raises it. A SIGTERM therefore unwinds through the writer's cleanup instead of killing the process and leaving the temporary file behind. The oldmainbody is nowrun. The staged hook copies are removed when an interrupt or error unwinds through the staging. The hooks' data file now goes throughwrite_regular_fileinstead of its own copy-then-replace.read_regular_fileand the writer's target check share one open-without-blocking-and-judge-the-descriptor primitive,_open_regular_file.An atomic swap cannot leave the target holding neither version. So
IncompleteWrite, the restore of the prior content, thepriorparameter that only the restore read, andrecord_leftover_instructionswith its stamp field are removed. The--reportbranch that readinstructionsLeftoveris removed too. A stamp an older release wrote with that field now reads as the installer's own output, which it is, and the re-run replaces it without a backup as before.Behavior changes worth reading
os.replacestays on one filesystem.os.replacefails while another process holds the target open without delete sharing. The target is then unchanged and the error is reported.Tests
host-setup/agent-safety/claude/test_install.py: the in-place truncation, restore, and leftover-stamp tests are replaced by tests of the new invariant. A write cut short by a size limit or by anOSError, and a write interrupted byKeyboardInterrupt, both directly and throughmain, leave the prior file intact with no temporary file and no backup. Symlink cases cover an interrupted write and a completed one through a relative link. Further cases cover permission bits, a failed close, a failed swap, a refused backup, a temporary file that cannot be removed or identified, and another writer's file at the temporary path.test_install.pyalso delivers a real SIGINT and SIGTERM to the installer's interpreter inside theCLAUDE.mdwrite, and interrupts a hook self-test. Each shows the prior file intact, death by the signal, and no temporary or staged file left.tests/test_global_rules.py: an in-processKeyboardInterruptinside the kit's write, for a plain target and a symlinked one, and a real SIGINT and SIGTERM delivered mid-write. Each shows the prior file intact and no temporary file or backup left behind.python3 -m unittest test_install(246 tests),python3 -m unittest tests.test_global_rules(60 tests), and the fullunittest discover -s testssuite (4638 tests, run on the first commit). The installer run under Python 3.8 still prints its 3.11+ refusal.Local review
Four recorded
local-strict-reviewpasses, the last over this head with no findings.install.pytook no SIGINT/SIGTERM handling once it held a temporary file, and it had no signal test (e07b05c9).e07b05c9).read_regular_file's open-and-judge block (e07b05c9).list[int]annotation would raise on Python 3.8 before the 3.11+ refusal (a7b1216c).os.open(..., O_CREAT|O_EXCL, 0o666)withtempfile.mkstemp.mkstempalways creates the file 0600, so a new target would need the umask, and Python can only read the umask by setting it process-wide. A 64-bit random name that collides raisesFileExistsErrorand never overwrites. The hub's other atomic writers are separate scripts the standalone kit cannot import.Review findings
os.readlinkreturning a\\?\-prefixed absolute path in the global_rules symlink test. The test now compares where the link resolves (854e0d5d).install.py:850, revalidate the target before the swap): the lost-update window is each caller's read-decide-write, and the in-place write had it too. Revalidating beforeos.replacecloses nothing, and in a hand-run per-user installer a concurrent edit is ruled out perGOVERNANCE.md"Trust Boundaries and Hardening Effort". The reasons are in the thread.Closes on promotion: #4317
🤖 Generated with Claude Code