From 15c1adb54b342d7eda69928ebe87cdcb97677307 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Mon, 5 Oct 2026 16:40:25 -0700 Subject: [PATCH 1/4] Refuse a CLAUDE.md That Is Not a Regular File Before Installing A CLAUDE.md that is a directory passed the exists() check and the write raised after the hooks and settings were already replaced, and --report crashed reading it. The install now refuses it up front with nothing changed, and the block reader treats a non-file as holding no blocks, so the report gives a verdict. Refs #2423 Co-Authored-By: Claude Opus 5.5 --- host-setup/agent-safety/claude/install.py | 9 ++++++++- host-setup/agent-safety/claude/test_install.py | 17 +++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/host-setup/agent-safety/claude/install.py b/host-setup/agent-safety/claude/install.py index 4f4e40b78..533de1e84 100755 --- a/host-setup/agent-safety/claude/install.py +++ b/host-setup/agent-safety/claude/install.py @@ -547,7 +547,7 @@ def blocks_present(claude_md): Read from the file rather than from what the installer meant to write, since the question the stamp answers is what is on the machine. """ - if not claude_md.exists(): + if not claude_md.is_file(): return {} text = claude_md.read_text(encoding="utf-8", errors="replace") found = {} @@ -1026,6 +1026,13 @@ def main(): if local_problem: sys.stderr.write(f"Nothing was installed: {local_problem}.\n") return 1 + # Refused here rather than at the write, which would raise after the hooks and settings were already replaced. + if claude_md.exists() and not claude_md.is_file(): + sys.stderr.write( + f"Nothing was installed: {claude_md} exists and is not a regular file, so it cannot be " + "rendered. Move it aside and re-run.\n" + ) + return 1 print(f"Installing agent host-safety kit into: {claude_home}") hooks_dir.mkdir(parents=True, exist_ok=True) diff --git a/host-setup/agent-safety/claude/test_install.py b/host-setup/agent-safety/claude/test_install.py index 322e93536..b21117eee 100755 --- a/host-setup/agent-safety/claude/test_install.py +++ b/host-setup/agent-safety/claude/test_install.py @@ -444,6 +444,23 @@ def test_a_local_file_in_a_directory_that_cannot_be_entered_stops_with_a_message self.assertNotIn("Traceback", r.stderr) self.assertFalse(self.home.exists()) + def test_a_claude_md_that_is_a_directory_stops_the_install_with_nothing_changed(self): + """The write would raise after the hooks and settings were already replaced.""" + self.md.mkdir(parents=True) + r = run(self.home) + self.assertEqual(r.returncode, 1, r.stdout + r.stderr) + self.assertIn("is not a regular file", r.stderr) + self.assertNotIn("Traceback", r.stderr) + self.assertFalse((self.home / "hooks").exists()) + + def test_the_report_on_a_claude_md_directory_gives_a_verdict_rather_than_crashing(self): + self.install() + self.md.unlink() + self.md.mkdir() + r = run(self.home, "--report") + self.assertEqual(r.returncode, 1, r.stdout + r.stderr) + self.assertNotIn("Traceback", r.stderr) + def test_a_stamp_failing_its_shape_check_does_not_vouch_for_the_file(self): """A hand-edited stamp could otherwise carry a digest that skips the backup.""" self.install() From bf437f575d255711b1ee3dc63058a3ae689e6d3e Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Mon, 5 Oct 2026 16:45:38 -0700 Subject: [PATCH 2/4] Probe CLAUDE.md for Access Before Installing, Not Its Type A type check let a dangling link, a link loop, and a read-only or unreadable CLAUDE.md through, each raising at the write after the hooks and settings were replaced. The install now probes with lstat, an open for reading, and a write-access check, and refuses with nothing changed. Every reader goes through one helper that returns None rather than raising, so --report gives a verdict, and it says to fix CLAUDE.md first where the installer would refuse it. Refs #2423 Co-Authored-By: Claude Opus 5.5 --- host-setup/agent-safety/claude/install.py | 78 ++++++++++++++----- .../agent-safety/claude/test_install.py | 67 ++++++++++++++-- 2 files changed, 121 insertions(+), 24 deletions(-) diff --git a/host-setup/agent-safety/claude/install.py b/host-setup/agent-safety/claude/install.py index 533de1e84..1fc334919 100755 --- a/host-setup/agent-safety/claude/install.py +++ b/host-setup/agent-safety/claude/install.py @@ -541,15 +541,54 @@ def payload_digest(): return h.hexdigest()[:16] +def read_claude_md(claude_md): + """CLAUDE.md's text, or None where it is absent, not a regular file, or unreadable. + + One reader for every caller, so a file none of them can read gives each the same answer rather + than a traceback in whichever reads it first. + """ + try: + if not claude_md.is_file(): + return None + return claude_md.read_text(encoding="utf-8", errors="replace") + except OSError: + return None + + +def claude_md_problem(claude_md): + """Why CLAUDE.md cannot be rendered in place, or None where it can, checked before any write. + + An access probe rather than a type check: a dangling link, a link loop, and a read-only or + unreadable file each passed `exists()` or `is_file()` and then raised at the write, after the + hooks and settings had already been replaced. + """ + try: + os.lstat(claude_md) + except (FileNotFoundError, NotADirectoryError): + return None + except OSError as e: + return f"{claude_md} cannot be read ({e})" + try: + if not claude_md.is_file(): + return f"{claude_md} is not a regular file, or is a link that leads to none" + with open(claude_md, "rb"): + pass + except OSError as e: + return f"{claude_md} cannot be read ({e})" + if not os.access(claude_md, os.W_OK): + return f"{claude_md} is not writable" + return None + + def blocks_present(claude_md): """The marker version of each block actually in CLAUDE.md, by name. Read from the file rather than from what the installer meant to write, since the question the stamp answers is what is on the machine. """ - if not claude_md.is_file(): + text = read_claude_md(claude_md) + if text is None: return {} - text = claude_md.read_text(encoding="utf-8", errors="replace") found = {} for marker in BLOCK_MARKERS: # A start marker alone is a half-written block, which a presence check reads as installed. @@ -569,9 +608,9 @@ def marker_corruption(claude_md): CLAUDE.md records the same empty block set it reads, so the stamp and the file agree and the corruption reads as a match. Two wrong answers agreeing is the failure this exists to catch. """ - if not claude_md.is_file(): + text = read_claude_md(claude_md) + if text is None: return [] - text = claude_md.read_text(encoding="utf-8", errors="replace") valid = blocks_present(claude_md) out = [] for marker in BLOCK_MARKERS: @@ -594,12 +633,13 @@ def installed_digest(claude_home): # A hook added to the deploy list and not to this one installs and is never covered by the currentness digest. deployed = [claude_home / "hooks" / name for name in DEPLOYED_HOOKS] claude_md = claude_home / "CLAUDE.md" - if not all(f.is_file() for f in deployed) or not claude_md.is_file(): + claude_text = read_claude_md(claude_md) + if not all(f.is_file() for f in deployed) or claude_text is None: return None h = hashlib.sha256() for f in deployed: h.update(normalized(f.read_bytes())) - text = normalized(claude_md.read_text(encoding="utf-8", errors="replace")) + text = normalized(claude_text) for marker in BLOCK_MARKERS: found = re.search( rf".*?", text, re.DOTALL @@ -626,8 +666,8 @@ def build_stamp(claude_home, installed, instructions_digest=None): "blocks": blocks_present(claude_home / "CLAUDE.md"), "instructionsDigest": instructions_digest or ( - text_digest((claude_home / "CLAUDE.md").read_text(encoding="utf-8", errors="replace")) - if (claude_home / "CLAUDE.md").is_file() + text_digest(claude_text) + if (claude_text := read_claude_md(claude_home / "CLAUDE.md")) is not None else None ), "installedUtc": installed, @@ -944,10 +984,13 @@ def report(claude_home): claude_md = claude_home / "CLAUDE.md" local_path = local_instructions_path() local_text, local_problem = read_local_instructions(local_path) + claude_problem = claude_md_problem(claude_md) if local_problem: problems.append(local_problem) - elif claude_md.is_file(): - live_text = normalized(claude_md.read_text(encoding="utf-8", errors="replace")) + if claude_problem: + problems.append(claude_problem) + elif not local_problem and (claude_text := read_claude_md(claude_md)) is not None: + live_text = normalized(claude_text) if live_text != render_instructions(local_path, local_text): if text_digest(live_text) == stamp.get("instructionsDigest"): problems.append( @@ -972,9 +1015,10 @@ def report(claude_home): print("STALE:") for p in problems: print(f" - {p}") - # The installer refuses an unusable local file, so re-running first would only repeat the refusal. - if local_problem: - print(f" Fix {local_path} first, since the installer refuses it as it stands.") + # The installer refuses either file when unusable, so re-running first would only repeat the refusal. + for problem, path in ((local_problem, local_path), (claude_problem, claude_md)): + if problem: + print(f" Fix {path} first, since the installer refuses it as it stands.") print( " Re-run the installer with no arguments. It is idempotent, and it backs up a " "CLAUDE.md edited since the last install before rewriting it." @@ -1027,11 +1071,9 @@ def main(): sys.stderr.write(f"Nothing was installed: {local_problem}.\n") return 1 # Refused here rather than at the write, which would raise after the hooks and settings were already replaced. - if claude_md.exists() and not claude_md.is_file(): - sys.stderr.write( - f"Nothing was installed: {claude_md} exists and is not a regular file, so it cannot be " - "rendered. Move it aside and re-run.\n" - ) + claude_problem = claude_md_problem(claude_md) + if claude_problem: + sys.stderr.write(f"Nothing was installed: {claude_problem}.\n") return 1 print(f"Installing agent host-safety kit into: {claude_home}") diff --git a/host-setup/agent-safety/claude/test_install.py b/host-setup/agent-safety/claude/test_install.py index b21117eee..5b6289dea 100755 --- a/host-setup/agent-safety/claude/test_install.py +++ b/host-setup/agent-safety/claude/test_install.py @@ -444,22 +444,77 @@ def test_a_local_file_in_a_directory_that_cannot_be_entered_stops_with_a_message self.assertNotIn("Traceback", r.stderr) self.assertFalse(self.home.exists()) - def test_a_claude_md_that_is_a_directory_stops_the_install_with_nothing_changed(self): - """The write would raise after the hooks and settings were already replaced.""" - self.md.mkdir(parents=True) - r = run(self.home) + def assert_refused_with_nothing_changed(self, r, reason): + """A refusal before any write leaves no hook, settings file, or stamp behind.""" self.assertEqual(r.returncode, 1, r.stdout + r.stderr) - self.assertIn("is not a regular file", r.stderr) + self.assertIn("Nothing was installed", r.stderr) + self.assertIn(reason, r.stderr) self.assertNotIn("Traceback", r.stderr) self.assertFalse((self.home / "hooks").exists()) + self.assertFalse((self.home / "settings.json").exists()) + self.assertFalse(self.stamp.exists()) + + def test_a_claude_md_that_is_a_directory_stops_the_install_with_nothing_changed(self): + """The write would raise after the hooks and settings were already replaced.""" + self.md.mkdir(parents=True) + self.assert_refused_with_nothing_changed(run(self.home), "is not a regular file") + + def test_a_claude_md_dangling_symlink_stops_the_install_with_nothing_changed(self): + """A dotfiles link whose repository is not cloned yet reads as absent to exists().""" + self.home.mkdir(parents=True) + try: + self.md.symlink_to(self.home.parent / "not-cloned" / "CLAUDE.md") + except OSError: + self.skipTest("this host cannot create a symlink") + self.assert_refused_with_nothing_changed(run(self.home), "is not a regular file") - def test_the_report_on_a_claude_md_directory_gives_a_verdict_rather_than_crashing(self): + def test_a_claude_md_symlink_loop_stops_the_install_with_nothing_changed(self): + self.home.mkdir(parents=True) + try: + self.md.symlink_to(self.md) + except OSError: + self.skipTest("this host cannot create a symlink") + self.assert_refused_with_nothing_changed(run(self.home), str(self.md)) + + def test_a_read_only_claude_md_stops_the_install_with_nothing_changed(self): + if os.name != "posix" or os.geteuid() == 0: + self.skipTest("needs a non-root POSIX user for a file mode to deny access") + self.home.mkdir(parents=True) + self.md.write_text("A constructed note.\n", encoding="utf-8") + self.md.chmod(0o444) + self.addCleanup(self.md.chmod, 0o644) + self.assert_refused_with_nothing_changed(run(self.home), "is not writable") + + def test_an_unreadable_claude_md_stops_the_install_with_nothing_changed(self): + if os.name != "posix" or os.geteuid() == 0: + self.skipTest("needs a non-root POSIX user for a file mode to deny access") + self.home.mkdir(parents=True) + self.md.write_text("A constructed note.\n", encoding="utf-8") + self.md.chmod(0) + self.addCleanup(self.md.chmod, 0o644) + self.assert_refused_with_nothing_changed(run(self.home), "cannot be read") + + def test_the_report_on_a_claude_md_directory_says_to_fix_it_first(self): + """Re-running is refused, so the report must not offer a re-run as the whole remedy.""" self.install() self.md.unlink() self.md.mkdir() r = run(self.home, "--report") self.assertEqual(r.returncode, 1, r.stdout + r.stderr) self.assertNotIn("Traceback", r.stderr) + self.assertIn("is not a regular file", r.stdout) + self.assertIn(f"Fix {self.md} first", r.stdout) + + def test_the_report_on_an_unreadable_claude_md_gives_a_verdict_rather_than_crashing(self): + if os.name != "posix" or os.geteuid() == 0: + self.skipTest("needs a non-root POSIX user for a file mode to deny access") + self.install() + self.md.chmod(0) + self.addCleanup(self.md.chmod, 0o644) + r = run(self.home, "--report") + self.assertEqual(r.returncode, 1, r.stdout + r.stderr) + self.assertNotIn("Traceback", r.stderr) + self.assertIn("cannot be read", r.stdout) def test_a_stamp_failing_its_shape_check_does_not_vouch_for_the_file(self): """A hand-edited stamp could otherwise carry a digest that skips the backup.""" From fbe12215aa308625b8a510501e287e73ba68141e Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Mon, 5 Oct 2026 17:15:40 -0700 Subject: [PATCH 3/4] Render CLAUDE.md First and Let the Real Write Be the Check The access probe predicted whether CLAUDE.md could be written, and each prediction missed a case the write then raised on, and it refused a read-only file that was already current. The CLAUDE.md step now runs before any hook or setting changes, skips the write when nothing would change, and turns a failed read, backup, or write into a clean refusal that names any backup it kept. --report names a CLAUDE.md that exists but cannot be read instead of calling it missing. Refs #2423 Co-Authored-By: Claude Opus 5.5 --- host-setup/agent-safety/claude/install.py | 123 ++++++++---------- .../agent-safety/claude/test_install.py | 70 +++++++--- 2 files changed, 106 insertions(+), 87 deletions(-) diff --git a/host-setup/agent-safety/claude/install.py b/host-setup/agent-safety/claude/install.py index 1fc334919..d8a63790b 100755 --- a/host-setup/agent-safety/claude/install.py +++ b/host-setup/agent-safety/claude/install.py @@ -555,31 +555,6 @@ def read_claude_md(claude_md): return None -def claude_md_problem(claude_md): - """Why CLAUDE.md cannot be rendered in place, or None where it can, checked before any write. - - An access probe rather than a type check: a dangling link, a link loop, and a read-only or - unreadable file each passed `exists()` or `is_file()` and then raised at the write, after the - hooks and settings had already been replaced. - """ - try: - os.lstat(claude_md) - except (FileNotFoundError, NotADirectoryError): - return None - except OSError as e: - return f"{claude_md} cannot be read ({e})" - try: - if not claude_md.is_file(): - return f"{claude_md} is not a regular file, or is a link that leads to none" - with open(claude_md, "rb"): - pass - except OSError as e: - return f"{claude_md} cannot be read ({e})" - if not os.access(claude_md, os.W_OK): - return f"{claude_md} is not writable" - return None - - def blocks_present(claude_md): """The marker version of each block actually in CLAUDE.md, by name. @@ -949,7 +924,7 @@ def report(claude_home): live_installed = installed_digest(claude_home) if live_installed is None: problems.append( - "the deployed hook or CLAUDE.md is missing, so the kit is not fully installed" + "a deployed hook or CLAUDE.md is missing or unreadable, so the kit is not fully installed" ) elif live_installed != current: problems.append("the installed content differs from what this checkout would write") @@ -984,12 +959,13 @@ def report(claude_home): claude_md = claude_home / "CLAUDE.md" local_path = local_instructions_path() local_text, local_problem = read_local_instructions(local_path) - claude_problem = claude_md_problem(claude_md) + claude_text = read_claude_md(claude_md) + claude_unreadable = os.path.lexists(claude_md) and claude_text is None if local_problem: problems.append(local_problem) - if claude_problem: - problems.append(claude_problem) - elif not local_problem and (claude_text := read_claude_md(claude_md)) is not None: + if claude_unreadable: + problems.append(f"{claude_md} exists but is not a readable regular file") + elif not local_problem and claude_text is not None: live_text = normalized(claude_text) if live_text != render_instructions(local_path, local_text): if text_digest(live_text) == stamp.get("instructionsDigest"): @@ -1015,10 +991,11 @@ def report(claude_home): print("STALE:") for p in problems: print(f" - {p}") - # The installer refuses either file when unusable, so re-running first would only repeat the refusal. - for problem, path in ((local_problem, local_path), (claude_problem, claude_md)): - if problem: - print(f" Fix {path} first, since the installer refuses it as it stands.") + # The installer refuses an unusable local file, so re-running first would only repeat the refusal. + if local_problem: + print(f" Fix {local_path} first, since the installer refuses it as it stands.") + if claude_unreadable: + print(f" If the re-run refuses {claude_md}, move it aside first.") print( " Re-run the installer with no arguments. It is idempotent, and it backs up a " "CLAUDE.md edited since the last install before rewriting it." @@ -1070,13 +1047,54 @@ def main(): if local_problem: sys.stderr.write(f"Nothing was installed: {local_problem}.\n") return 1 - # Refused here rather than at the write, which would raise after the hooks and settings were already replaced. - claude_problem = claude_md_problem(claude_md) - if claude_problem: - sys.stderr.write(f"Nothing was installed: {claude_problem}.\n") + print(f"Installing agent host-safety kit into: {claude_home}") + claude_home.mkdir(parents=True, exist_ok=True) + + # 0. CLAUDE.md is rendered whole: a header, one marker block per snippet, then the host-local file. + # It goes first, so a file that cannot be read, backed up, or written stops the run before any hook or setting changes. + # Attempting the real read and write is the check, since a predicted one missed cases the write then raised on. + # The safety block states restrictions only. + # The fleet block enables, so it stays separate from a block whose own text says nothing in it widens a permission. + # A file whose digest matches the stamp is the one the last install wrote, so it is replaced silently. + # Anything else is a hand edit, or a file from before whole-file ownership, so it is backed up first. + # Preserve CLAUDE.md's existing line endings: work in \n internally, write back with its own ending. + # A file that is not valid UTF-8 still decodes for the comparison, and the backup keeps its raw bytes. + # A file already holding the render is left unwritten, so a read-only file that is current still installs. + rendered = render_instructions(local_path, local_text) + try: + raw = claude_md.read_bytes() if claude_md.is_file() else None + except OSError as e: + sys.stderr.write( + f"Nothing was installed: {claude_md} cannot be read ({e}). Move it aside and re-run.\n" + ) return 1 + newline = "\r\n" if raw is not None and b"\r\n" in raw else "\n" + existing = None if raw is None else normalized(raw.decode("utf-8", errors="replace")) + backup = None + if existing == rendered: + action = "already current" + else: + try: + if existing is not None and text_digest(existing) != stamped_instructions_digest( + claude_home + ): + backup = write_backup(claude_md, raw) + claude_md.write_bytes(rendered.replace("\n", newline).encode("utf-8")) + except OSError as e: + kept = f" Its prior content is backed up at {backup}." if backup else "" + sys.stderr.write( + f"Nothing was installed: {claude_md} could not be rewritten ({e}).{kept} " + "Move it aside or make it writable, then re-run.\n" + ) + return 1 + if backup is not None: + action = f"rewritten, the edited prior file backed up to {backup}" + else: + action = "updated" if existing is not None else "written" + print(f" CLAUDE.md -> {claude_md} ({action})") + if backup is not None: + print(f" Move anything host-specific into {local_path}, then re-run to append it.") - print(f"Installing agent host-safety kit into: {claude_home}") hooks_dir.mkdir(parents=True, exist_ok=True) # 1. Stage every hook beside its live path, self-test each staged copy, and only then replace. @@ -1290,33 +1308,6 @@ def reject(where, held, want): for line in done: print(f" settings -> {settings} ({line})") - # 4. CLAUDE.md is rendered whole: a header, one marker block per snippet, then the host-local file. - # The safety block states restrictions only. - # The fleet block enables, so it stays separate from a block whose own text says nothing in it widens a permission. - # A file whose digest matches the stamp is the one the last install wrote, so it is replaced silently. - # Anything else is a hand edit, or a file from before whole-file ownership, so it is backed up first. - # Preserve CLAUDE.md's existing line endings: work in \n internally, write back with its own ending. - # A file that is not valid UTF-8 still decodes for the comparison, and the backup keeps its raw bytes. - rendered = render_instructions(local_path, local_text) - backup = None - if claude_md.exists(): - raw = claude_md.read_bytes() - newline = "\r\n" if b"\r\n" in raw else "\n" - existing = normalized(raw.decode("utf-8", errors="replace")) - if existing == rendered: - action = "already current" - elif text_digest(existing) == stamped_instructions_digest(claude_home): - action = "updated" - else: - backup = write_backup(claude_md, raw) - action = f"rewritten, the edited prior file backed up to {backup}" - else: - newline, action = "\n", "written" - claude_md.write_bytes(rendered.replace("\n", newline).encode("utf-8")) - print(f" CLAUDE.md -> {claude_md} ({action})") - if backup is not None: - print(f" Move anything host-specific into {local_path}, then re-run to append it.") - # 5. Stamp the machine, written last so it records a completed install rather than an attempted one. # The blocks are read back off disk here, so the stamp reports what CLAUDE.md holds rather than what was intended. stamp_path = claude_home / "agent-safety-stamp.json" diff --git a/host-setup/agent-safety/claude/test_install.py b/host-setup/agent-safety/claude/test_install.py index 5b6289dea..fe7450991 100755 --- a/host-setup/agent-safety/claude/test_install.py +++ b/host-setup/agent-safety/claude/test_install.py @@ -445,7 +445,7 @@ def test_a_local_file_in_a_directory_that_cannot_be_entered_stops_with_a_message self.assertFalse(self.home.exists()) def assert_refused_with_nothing_changed(self, r, reason): - """A refusal before any write leaves no hook, settings file, or stamp behind.""" + """A refusal at the CLAUDE.md step leaves no hook, settings file, or stamp behind.""" self.assertEqual(r.returncode, 1, r.stdout + r.stderr) self.assertIn("Nothing was installed", r.stderr) self.assertIn(reason, r.stderr) @@ -454,19 +454,23 @@ def assert_refused_with_nothing_changed(self, r, reason): self.assertFalse((self.home / "settings.json").exists()) self.assertFalse(self.stamp.exists()) + def needs_posix_non_root(self): + if os.name != "posix" or os.geteuid() == 0: + self.skipTest("needs a non-root POSIX user for a file mode to deny access") + def test_a_claude_md_that_is_a_directory_stops_the_install_with_nothing_changed(self): """The write would raise after the hooks and settings were already replaced.""" self.md.mkdir(parents=True) - self.assert_refused_with_nothing_changed(run(self.home), "is not a regular file") + self.assert_refused_with_nothing_changed(run(self.home), "could not be rewritten") def test_a_claude_md_dangling_symlink_stops_the_install_with_nothing_changed(self): - """A dotfiles link whose repository is not cloned yet reads as absent to exists().""" + """A dotfiles link whose repository is not cloned yet has nowhere to write.""" self.home.mkdir(parents=True) try: self.md.symlink_to(self.home.parent / "not-cloned" / "CLAUDE.md") except OSError: self.skipTest("this host cannot create a symlink") - self.assert_refused_with_nothing_changed(run(self.home), "is not a regular file") + self.assert_refused_with_nothing_changed(run(self.home), "could not be rewritten") def test_a_claude_md_symlink_loop_stops_the_install_with_nothing_changed(self): self.home.mkdir(parents=True) @@ -476,45 +480,69 @@ def test_a_claude_md_symlink_loop_stops_the_install_with_nothing_changed(self): self.skipTest("this host cannot create a symlink") self.assert_refused_with_nothing_changed(run(self.home), str(self.md)) - def test_a_read_only_claude_md_stops_the_install_with_nothing_changed(self): - if os.name != "posix" or os.geteuid() == 0: - self.skipTest("needs a non-root POSIX user for a file mode to deny access") + def test_an_unreadable_claude_md_stops_the_install_with_nothing_changed(self): + self.needs_posix_non_root() self.home.mkdir(parents=True) self.md.write_text("A constructed note.\n", encoding="utf-8") - self.md.chmod(0o444) + self.md.chmod(0) self.addCleanup(self.md.chmod, 0o644) - self.assert_refused_with_nothing_changed(run(self.home), "is not writable") + self.assert_refused_with_nothing_changed(run(self.home), "cannot be read") - def test_an_unreadable_claude_md_stops_the_install_with_nothing_changed(self): - if os.name != "posix" or os.geteuid() == 0: - self.skipTest("needs a non-root POSIX user for a file mode to deny access") + def test_a_read_only_edited_claude_md_is_refused_with_its_backup_kept(self): + """The backup lands before the write fails, and the refusal names where it is.""" + self.needs_posix_non_root() self.home.mkdir(parents=True) self.md.write_text("A constructed note.\n", encoding="utf-8") - self.md.chmod(0) + self.md.chmod(0o444) self.addCleanup(self.md.chmod, 0o644) - self.assert_refused_with_nothing_changed(run(self.home), "cannot be read") + r = run(self.home) + self.assert_refused_with_nothing_changed(r, "could not be rewritten") + self.assertIn("backed up at", r.stderr) + self.assertEqual(len(self.backups()), 1) + + def test_a_read_only_claude_md_that_is_current_still_installs_and_reports_current(self): + """Nothing would change, so the file is not written and its mode does not matter.""" + self.needs_posix_non_root() + self.install() + self.md.chmod(0o444) + self.addCleanup(self.md.chmod, 0o644) + r = self.install() + self.assertIn("(already current)", r.stdout) + self.assertEqual(run(self.home, "--report").returncode, 0) + + def test_a_symlinked_claude_md_installs_through_the_link(self): + """The dotfiles case: the link stays a link and the kit lands in its target.""" + self.home.mkdir(parents=True) + target = self.home.parent / "dotfiles-CLAUDE.md" + try: + self.md.symlink_to(target) + except OSError: + self.skipTest("this host cannot create a symlink") + target.write_text("", encoding="utf-8") + self.install() + self.assertTrue(self.md.is_symlink()) + self.assertIn("agent-safety", target.read_text(encoding="utf-8")) + self.assertEqual(run(self.home, "--report").returncode, 0) - def test_the_report_on_a_claude_md_directory_says_to_fix_it_first(self): - """Re-running is refused, so the report must not offer a re-run as the whole remedy.""" + def test_the_report_on_a_claude_md_directory_names_it_rather_than_crashing(self): self.install() self.md.unlink() self.md.mkdir() r = run(self.home, "--report") self.assertEqual(r.returncode, 1, r.stdout + r.stderr) self.assertNotIn("Traceback", r.stderr) - self.assertIn("is not a regular file", r.stdout) - self.assertIn(f"Fix {self.md} first", r.stdout) + self.assertIn("exists but is not a readable regular file", r.stdout) + self.assertIn("move it aside first", r.stdout) def test_the_report_on_an_unreadable_claude_md_gives_a_verdict_rather_than_crashing(self): - if os.name != "posix" or os.geteuid() == 0: - self.skipTest("needs a non-root POSIX user for a file mode to deny access") + self.needs_posix_non_root() self.install() self.md.chmod(0) self.addCleanup(self.md.chmod, 0o644) r = run(self.home, "--report") self.assertEqual(r.returncode, 1, r.stdout + r.stderr) self.assertNotIn("Traceback", r.stderr) - self.assertIn("cannot be read", r.stdout) + self.assertIn("exists but is not a readable regular file", r.stdout) def test_a_stamp_failing_its_shape_check_does_not_vouch_for_the_file(self): """A hand-edited stamp could otherwise carry a digest that skips the backup.""" From fe656bebbfdc6ca9616bdae2d46926c4161cf6a8 Mon Sep 17 00:00:00 2001 From: Pieter Viljoen Date: Mon, 5 Oct 2026 17:25:08 -0700 Subject: [PATCH 4/4] Refuse a CLAUDE.md That Is Not a Regular File, and Name What a Hook Failure Kept With the real write as the check, a FIFO at CLAUDE.md hung the install and a link to a device took the render and kept nothing. Anything at the path that is not a regular file is now refused before the write, except a dangling link, which still writes through to its target. A hook staging or self-test failure now says no hook was replaced, since CLAUDE.md has already been rendered by then. Refs #2423 Co-Authored-By: Claude Opus 5.5 --- host-setup/agent-safety/claude/install.py | 12 ++++++++++-- host-setup/agent-safety/claude/test_install.py | 16 +++++++++++++++- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/host-setup/agent-safety/claude/install.py b/host-setup/agent-safety/claude/install.py index d8a63790b..a4f7650b8 100755 --- a/host-setup/agent-safety/claude/install.py +++ b/host-setup/agent-safety/claude/install.py @@ -1061,7 +1061,15 @@ def main(): # A file that is not valid UTF-8 still decodes for the comparison, and the backup keeps its raw bytes. # A file already holding the render is left unwritten, so a read-only file that is current still installs. rendered = render_instructions(local_path, local_text) + # Anything else at the path, a FIFO or a link to a device, would hang the write or swallow it. + # A dangling link is let through, so a dotfiles link whose target is not created yet still writes it. try: + dangling = claude_md.is_symlink() and not os.path.exists(claude_md) + if os.path.lexists(claude_md) and not claude_md.is_file() and not dangling: + sys.stderr.write( + f"Nothing was installed: {claude_md} is not a regular file. Move it aside and re-run.\n" + ) + return 1 raw = claude_md.read_bytes() if claude_md.is_file() else None except OSError as e: sys.stderr.write( @@ -1111,7 +1119,7 @@ def main(): except OSError as e: for _n, f in staged: f.unlink(missing_ok=True) - sys.stderr.write(f"staging {src_name} failed ({e}); nothing was replaced.\n") + sys.stderr.write(f"staging {src_name} failed ({e}); no hook was replaced.\n") return 1 try: os.chmod(tmp, 0o755) @@ -1128,7 +1136,7 @@ def main(): for _n, f in staged: f.unlink(missing_ok=True) sys.stderr.write( - f"{src_name} self-test FAILED; nothing was replaced.\n" + r.stdout + r.stderr + f"{src_name} self-test FAILED; no hook was replaced.\n" + r.stdout + r.stderr ) return 1 print(f" {src_name} self-test: PASS") diff --git a/host-setup/agent-safety/claude/test_install.py b/host-setup/agent-safety/claude/test_install.py index fe7450991..fee6cba03 100755 --- a/host-setup/agent-safety/claude/test_install.py +++ b/host-setup/agent-safety/claude/test_install.py @@ -461,7 +461,21 @@ def needs_posix_non_root(self): def test_a_claude_md_that_is_a_directory_stops_the_install_with_nothing_changed(self): """The write would raise after the hooks and settings were already replaced.""" self.md.mkdir(parents=True) - self.assert_refused_with_nothing_changed(run(self.home), "could not be rewritten") + self.assert_refused_with_nothing_changed(run(self.home), "is not a regular file") + + def test_a_claude_md_fifo_is_refused_rather_than_hanging_the_write(self): + if not hasattr(os, "mkfifo"): + self.skipTest("this host has no FIFOs") + self.home.mkdir(parents=True) + os.mkfifo(self.md) + self.assert_refused_with_nothing_changed(run(self.home), "is not a regular file") + + def test_a_claude_md_link_to_a_device_is_refused_rather_than_written_into_nothing(self): + if not os.path.exists(os.devnull) or os.name != "posix": + self.skipTest("needs a POSIX null device") + self.home.mkdir(parents=True) + self.md.symlink_to(os.devnull) + self.assert_refused_with_nothing_changed(run(self.home), "is not a regular file") def test_a_claude_md_dangling_symlink_stops_the_install_with_nothing_changed(self): """A dotfiles link whose repository is not cloned yet has nowhere to write."""