Skip to content

Write Kit Files Atomically Through a Temporary File Beside Each Target - #4336

Merged
ptr727 merged 4 commits into
developfrom
burndown/rule-files-atomic-write
Nov 22, 2026
Merged

ptr727 merged 4 commits into
developfrom
burndown/rule-files-atomic-write

Conversation

@ptr727

@ptr727 ptr727 commented Nov 22, 2026 •

Copy link
Copy Markdown
Owner

Summary

The agent-safety kit's shared writer, write_regular_file in host-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 left CLAUDE.md, settings.json, or the stamp empty or partial. host-setup/agent-safety/global_rules.py writes 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:

  • writes the new content to a temporary file in the target's own directory, flushes it, and swaps it in with os.replace. A failure or an interrupt at any point leaves the target as it was, holding its prior content or absent.
  • resolves a link and replaces the file it points at, so a dotfiles symlink stays a link.
  • still opens the target for writing first, without truncating it, and judges it on that descriptor. A read-only file, a FIFO, a device, or a directory is refused before anything is made.
  • keeps a replaced file's permission bits.
  • runs the backup callback once the new content is whole on disk, just before the swap. A write that cannot finish therefore leaves no backup behind.
  • removes the temporary file on any failure or interrupt, BaseException included, 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.py now holds a temporary file during every write, so it takes the interrupt rule global_rules.py already follows. 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 instead of killing the process and leaving the temporary file behind. The old main body is now run. The staged hook copies are removed when an interrupt or error unwinds through the staging. The hooks' data file now goes through write_regular_file instead of its own copy-then-replace. read_regular_file and 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, the prior parameter that only the restore read, and record_leftover_instructions with its stamp field are removed. The --report branch that read instructionsLeftover is 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

  • A file in a directory the user cannot write is now refused, where the in-place write used to succeed. The temporary file has to live beside the target so that os.replace stays on one filesystem.
  • A hard link to a target no longer shares the new content, since the swap replaces the directory entry. A symlink is resolved and keeps working.
  • Ownership is not copied to the new file. The kit writes the user's own files as that user, so the owner is unchanged in its deployment.
  • On Windows, os.replace fails 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 an OSError, and a write interrupted by KeyboardInterrupt, both directly and through main, 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.py also delivers a real SIGINT and SIGTERM to the installer's interpreter inside the CLAUDE.md write, 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-process KeyboardInterrupt inside 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.
  • Each new interrupt and failure test fails against a writer that skips the temporary-file cleanup, and against one that writes in place.
  • Local runs: python3 -m unittest test_install (246 tests), python3 -m unittest tests.test_global_rules (60 tests), and the full unittest discover -s tests suite (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-review passes, the last over this head with no findings.

  • Fixed: install.py took no SIGINT/SIGTERM handling once it held a temporary file, and it had no signal test (e07b05c9).
  • Fixed: the hooks' data-file copy repeated the writer's temp-then-replace (e07b05c9).
  • Fixed: the writer's target check repeated read_regular_file's open-and-judge block (e07b05c9).
  • Fixed: a module-level list[int] annotation would raise on Python 3.8 before the 3.11+ refusal (a7b1216c).
  • Declined: replacing the temporary file's os.open(..., O_CREAT|O_EXCL, 0o666) with tempfile.mkstemp. mkstemp always 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 raises FileExistsError and never overwrites. The hub's other atomic writers are separate scripts the standalone kit cannot import.

Review findings

  • Fixed: the Windows unit test job failed on os.readlink returning a \\?\-prefixed absolute path in the global_rules symlink test. The test now compares where the link resolves (854e0d5d).
  • Declined (Copilot, 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 before os.replace closes nothing, and in a hand-run per-user installer a concurrent edit is ruled out per GOVERNANCE.md "Trust Boundaries and Hardening Effort". The reasons are in the thread.

Closes on promotion: #4317

🤖 Generated with Claude Code

ptr727 and others added 3 commits November 21, 2026 20:09
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]>
@ptr727 ptr727 added the comments Permits the comment lines the pull request adds or edits, which the prose gate otherwise refuses label Nov 22, 2026
Copilot AI lite review requested due to automatic review settings November 22, 2026 04:24
@ptr727 ptr727 added the comments Permits the comment lines the pull request adds or edits, which the prose gate otherwise refuses label Nov 22, 2026
@ptr727

ptr727 commented Nov 22, 2026

Copy link
Copy Markdown
Owner Author

A recorded local strict-review pass covers head a7b1216c41cf6ef2ff60c7546fabbbcc8e1924b0, the content this pull request carries at that commit against develop, and it recorded 0 findings.

@coderabbitai

coderabbitai Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

You'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.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 66dd36c and 854e0d5.

Files selected for processing: 4

  • host-setup/agent-safety/claude/install.py
  • host-setup/agent-safety/claude/test_install.py
  • host-setup/agent-safety/global_rules.py
  • tests/test_global_rules.py
  • 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

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 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

codecov Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 28.24427% with 94 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.54%. Comparing base (66dd36c) to head (854e0d5).
⚠️ Report is 2 commits behind head on develop.

Files with missing lines Patch % Lines
host-setup/agent-safety/claude/install.py 28.24% 94 Missing ⚠️
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     
Flag Coverage Δ
python-3.13 79.54% <28.24%> (+0.39%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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]>
@ptr727

ptr727 commented Nov 22, 2026

Copy link
Copy Markdown
Owner Author

A recorded local strict-review pass covers head 854e0d5d9fdf20d1934d4725d834dba50401fe2c, the content this pull request carries at that commit against develop, and it recorded 0 findings.

@ptr727

ptr727 commented Nov 22, 2026

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@ptr727

ptr727 commented Nov 22, 2026

Copy link
Copy Markdown
Owner Author

/review

@coderabbitai

coderabbitai Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Action not completed

Review rate limited.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@ptr727
ptr727 merged commit ceeb78b into develop Nov 22, 2026
14 checks passed
@ptr727
ptr727 deleted the burndown/rule-files-atomic-write branch November 22, 2026 14:59
ptr727 added a commit that referenced this pull request Nov 22, 2026
…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 -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comments Permits the comment lines the pull request adds or edits, which the prose gate otherwise refuses

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants