Keep the mode of ~/.claude.json and the models file when loop-claude rewrites them

This commit is contained in:
2026-09-27 15:07:09 +02:00
parent 4b2ebc95a5
commit 82f1a208bf
4 changed files with 35 additions and 20 deletions
+1
View File
@@ -15,3 +15,4 @@
- `settings.json`, the agents and the status line run on any machine unedited; the status line shows reset times in the machine's own time zone.
- `loop-claude`'s no-premises exit names what is wrong: `README.md` unopenable or not UTF-8, a `## Goals` or `## Audience` heading missing or repeated, or nothing under one.
- `bin/` runs on Python 3.11 or newer.
- `loop-claude` keeps the mode of `~/.claude.json` and of its models file when it rewrites them, and creates the models file 0600.
+17 -14
View File
@@ -227,6 +227,21 @@ def make_private(folder):
os.umask(mask)
def replace_json(path, data, **dump):
staged = f"{path}.{os.getpid()}"
try:
mode = os.stat(path).st_mode & 0o7777 if os.path.exists(path) else 0o600
with open(os.open(staged, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w", encoding="utf-8") as handle:
os.fchmod(handle.fileno(), mode)
json.dump(data, handle, **dump)
os.replace(staged, path)
except OSError as failure:
if os.path.exists(staged):
os.remove(staged)
return failure
return None
def model(variable, chosen):
return ["--model", os.environ.get(variable) or chosen]
@@ -248,14 +263,7 @@ def project_model(root):
chosen = ask_model(name, saved)
# Reread: another loop may have saved its project while this one waited on the human.
models = {**read_models(saved), name: chosen}
staged = f"{saved}.{os.getpid()}"
try:
with open(staged, "w", encoding="utf-8") as handle:
json.dump(models, handle, indent="\t", sort_keys=True)
os.replace(staged, saved)
except OSError as failure:
if os.path.exists(staged):
os.remove(staged)
if failure := replace_json(saved, models, indent="\t", sort_keys=True):
sys.exit(f"could not save the model in {saved}: {failure.strerror}")
print(f"{name} runs on {chosen}", file=sys.stderr)
return chosen
@@ -511,12 +519,7 @@ def trust(paths):
return
for path in granted:
projects.setdefault(path, {})["hasTrustDialogAccepted"] = True
staged = f"{config}.loop-claude"
try:
with open(staged, "w", encoding="utf-8") as handle:
json.dump(data, handle, indent=2)
os.replace(staged, config)
except OSError as failure:
if failure := replace_json(config, data, indent=2):
print(f"could not write {config}: {failure.strerror}", file=sys.stderr)
return
print("trusted for the interrupt: " + ", ".join(granted), file=sys.stderr)
+17 -2
View File
@@ -30,6 +30,15 @@ def human(content):
return {"type": "user", "message": {"content": content}}
@contextlib.contextmanager
def umask(mask):
previous = os.umask(mask)
try:
yield
finally:
os.umask(previous)
class Sections(unittest.TestCase):
def test_keeps_every_headed_section_with_its_bodies(self):
text = "# Title\n\nintro\n\n## Goals\n\n1. one\n```sh\n# not a heading\n```\n### Later\n2. two\n#1 priority\n\n## Empty\n\n## Audience\nme\n## Audience\nagain\n# Appendix\nnot audience\n"
@@ -147,7 +156,7 @@ class WorkerArgs(unittest.TestCase):
class ProjectModel(unittest.TestCase):
def test_asks_once_per_project_from_the_newest_catalog_and_saves_the_answer(self):
with tempfile.TemporaryDirectory() as home, unittest.mock.patch.dict(os.environ, {"HOME": home}), unittest.mock.patch.object(sys, "stderr", io.StringIO()):
with tempfile.TemporaryDirectory() as home, unittest.mock.patch.dict(os.environ, {"HOME": home}), unittest.mock.patch.object(sys, "stderr", io.StringIO()), umask(0o022):
for variable in ("LOOP_CLAUDE_JUDGE_MODEL", "LOOP_CLAUDE_WORKER_MODEL"):
os.environ.pop(variable, None)
saved = pathlib.Path(home, ".claude", "loop-claude-models.json")
@@ -176,6 +185,8 @@ class ProjectModel(unittest.TestCase):
self.assertIn("pick 1 to 2", sys.stderr.getvalue())
self.assertIn("srv/a runs on claude-sonnet-5", sys.stderr.getvalue())
self.assertNotIn("claude-opus-5)", sys.stderr.getvalue())
self.assertEqual(stat.S_IMODE(saved.stat().st_mode), 0o600)
saved.chmod(0o640)
def saved_elsewhere_while_asking(prompt):
saved.write_text(json.dumps({**json.loads(saved.read_text()), "srv/d": "haiku"}))
return "opus[1m]"
@@ -192,6 +203,7 @@ class ProjectModel(unittest.TestCase):
loop.project_model("/srv/c")
self.assertEqual(stopped.exception.code, f"could not save the model in {saved}: Permission denied")
self.assertEqual(json.loads(saved.read_text()), {"srv/a": "claude-sonnet-5", "srv/b": "opus[1m]", "srv/d": "haiku"})
self.assertEqual(stat.S_IMODE(saved.stat().st_mode), 0o640)
self.assertEqual(sorted(os.listdir(saved.parent)), ["cache", "loop-claude-models.json"])
for shape in ({"fetchedAt": 3, "catalog": {"config": {"models": []}}}, {"fetchedAt": 3, "catalog": None}, {"fetchedAt": 3, "catalog": {"config": []}}, {"fetchedAt": 3, "catalog": {"config": {"models": "x"}}}):
catalog.joinpath("new.json").write_text(json.dumps(shape))
@@ -284,7 +296,7 @@ class Interrupt(unittest.TestCase):
class Trust(unittest.TestCase):
def test_says_why_the_config_cannot_be_read_and_records_only_what_is_new(self):
with tempfile.TemporaryDirectory() as home, unittest.mock.patch.dict(os.environ, {"HOME": home}):
with tempfile.TemporaryDirectory() as home, unittest.mock.patch.dict(os.environ, {"HOME": home}), umask(0o022):
config = pathlib.Path(home, ".claude.json")
with contextlib.redirect_stderr(io.StringIO()) as err:
loop.trust(["/a"])
@@ -301,6 +313,7 @@ class Trust(unittest.TestCase):
self.assertEqual(json.loads(config.read_text()), shape)
data = {"other": 1, "projects": {"/a": {"hasTrustDialogAccepted": True, "kept": 2}}}
config.write_text(json.dumps(data))
config.chmod(0o600)
with contextlib.redirect_stderr(io.StringIO()) as err:
loop.trust(["/a"])
self.assertEqual(err.getvalue(), "")
@@ -317,6 +330,8 @@ class Trust(unittest.TestCase):
loop.trust(["/c"])
self.assertEqual(err.getvalue(), f"could not write {config}: Permission denied\n")
self.assertEqual(json.loads(config.read_text()), data)
self.assertEqual(stat.S_IMODE(config.stat().st_mode), 0o600)
self.assertEqual(os.listdir(home), [".claude.json"])
class Parse(unittest.TestCase):
-4
View File
@@ -1,9 +1,5 @@
# todo
## Security
- Write `~/.claude.json` in `trust` and the models file in `bin/loop-claude` back with their own mode, today each staged copy takes the process umask, so a 0600 `~/.claude.json` holding the account email comes back 0644.
## 0.1.0
Ships when a four-seat scoring run puts every dimension and the overall at 7.0 or above (`docs/decisions.md`). Ordered by the dimension each item lifts, lowest first, per the 2026-09-26 panel; each is one chunk.