phiward 0.2.0b1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. phiward/__init__.py +8 -0
  2. phiward/__main__.py +5 -0
  3. phiward/_toml.py +211 -0
  4. phiward/adapters/__init__.py +105 -0
  5. phiward/adapters/claude.py +429 -0
  6. phiward/broker.py +831 -0
  7. phiward/carryover.py +1613 -0
  8. phiward/claude_settings.py +1307 -0
  9. phiward/cli.py +110 -0
  10. phiward/config.py +936 -0
  11. phiward/confine.py +476 -0
  12. phiward/copying.py +533 -0
  13. phiward/core.py +105 -0
  14. phiward/data/agents-section.md +43 -0
  15. phiward/doctor.py +1132 -0
  16. phiward/fasthook.py +70 -0
  17. phiward/fsinfo.py +241 -0
  18. phiward/gateway.py +159 -0
  19. phiward/githooks.py +248 -0
  20. phiward/guards/__init__.py +0 -0
  21. phiward/guards/protected_paths.py +1138 -0
  22. phiward/hidden.py +281 -0
  23. phiward/init.py +155 -0
  24. phiward/install.py +828 -0
  25. phiward/inventory.py +173 -0
  26. phiward/mcp.py +186 -0
  27. phiward/mcp_config.py +1736 -0
  28. phiward/names.py +5 -0
  29. phiward/packs/dates.toml +17 -0
  30. phiward/packs/genomics.toml +51 -0
  31. phiward/packs/msk.toml +32 -0
  32. phiward/pathid.py +403 -0
  33. phiward/pathmatch.py +98 -0
  34. phiward/paths.py +942 -0
  35. phiward/pin.py +214 -0
  36. phiward/procinfo.py +73 -0
  37. phiward/remote.py +448 -0
  38. phiward/run.py +788 -0
  39. phiward/safeio.py +84 -0
  40. phiward/sanitize.py +691 -0
  41. phiward/selfcheck.py +1506 -0
  42. phiward/service.py +321 -0
  43. phiward/session_note.py +86 -0
  44. phiward/setup_cmd.py +886 -0
  45. phiward/shell.py +504 -0
  46. phiward/wholetool.py +1463 -0
  47. phiward-0.2.0b1.dist-info/METADATA +147 -0
  48. phiward-0.2.0b1.dist-info/RECORD +53 -0
  49. phiward-0.2.0b1.dist-info/WHEEL +5 -0
  50. phiward-0.2.0b1.dist-info/entry_points.txt +3 -0
  51. phiward-0.2.0b1.dist-info/licenses/LICENSE +662 -0
  52. phiward-0.2.0b1.dist-info/licenses/NOTICE +16 -0
  53. phiward-0.2.0b1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1307 @@
1
+ """Read Claude Code's settings files (never write them) and decide whether its sandbox confines
2
+ the agent's shell commands as phiward needs.
3
+
4
+ Confined means all of these hold, from the merged settings:
5
+ - `sandbox.enabled` is true;
6
+ - `sandbox.allowUnsandboxedCommands` is false (so the model cannot retry outside the sandbox);
7
+ - `sandbox.failIfUnavailable` is true (else commands run unsandboxed when the sandbox cannot
8
+ start), and none of the settings in OPENERS is true, and `network.allowMachLookup` is empty;
9
+ - `sandbox.filesystem.denyRead` and `denyWrite` cover every protected root (the root or a
10
+ folder above it);
11
+ - `sandbox.filesystem.denyWrite` covers the phiward config and code (config.guard_files);
12
+ - `sandbox.excludedCommands` is empty (gateway calls are clients of the broker; they run in the
13
+ sandbox like any command);
14
+ - `sandbox.network.allowAllUnixSockets` is not true and `allowUnixSockets` is empty (a socket
15
+ such as Docker's reaches a process outside the sandbox);
16
+ - no `sandbox.filesystem.allowRead` entry re-opens any part of a root. Claude Code applies the
17
+ narrower of two overlapping read rules, so an allow inside the deny that covers a root, or at
18
+ the same depth, re-opens it; an allow wider than that deny does not.
19
+
20
+ Paths use Claude Code's sandbox prefixes: `/` or `//` absolute, `~/` the home folder, `./` or no
21
+ prefix relative to the project folder (project files) or the user folder (user file). A relative
22
+ entry in a managed file has no known base: as a deny it covers nothing, as an allow it is taken
23
+ against both bases. A deny with a wildcard covers nothing; an allow with a wildcard counts from
24
+ its fixed part.
25
+ A protected pattern counts as denied by a wildcard entry: its literal start in the file
26
+ system's own spelling, then the pattern (or with `/**`), in denyRead and denyWrite; only on
27
+ macOS (`_patterns_unconfined`): elsewhere the sandbox cannot deny writes to a wildcard path.
28
+
29
+ Where the files are: managed settings and their `managed-settings.d`
30
+ drop-ins; project settings in `$CLAUDE_PROJECT_DIR` (Claude Code sets it for hooks; the shell's
31
+ working folder can be anywhere below it); user settings in `$CLAUDE_CONFIG_DIR`, else
32
+ `~/.claude`. Without `CLAUDE_PROJECT_DIR` the project files cannot be found, so the shell is not
33
+ treated as confined. Settings passed with `--settings` cannot be seen at all (a stated limit).
34
+ """
35
+
36
+ import glob
37
+ import json
38
+ import os
39
+ import sys
40
+ from typing import Any, Callable, Dict, List, Mapping, NamedTuple, Optional, Sequence, Tuple
41
+
42
+ from phiward import config, pathmatch
43
+
44
+ MANAGED = ["/Library/Application Support/ClaudeCode/managed-settings.json",
45
+ "/etc/claude-code/managed-settings.json"]
46
+
47
+
48
+ JSON_LIMIT = 64 * 1024 * 1024 # ~/.claude.json holds every project's history: it grows large
49
+
50
+
51
+ def read_json(path: str) -> Tuple[Optional[Dict[str, Any]], str, List[str]]:
52
+ """The one reader of Claude Code's JSON files (settings, ~/.claude.json, .mcp.json):
53
+ (the object, why it cannot be read, the keys given twice). As JSON.parse reads it: the last
54
+ of two equal keys wins, no NaN, no byte-order mark. Through a link (a dotfiles setup), but
55
+ only a regular file, never waiting on a FIFO, at most JSON_LIMIT bytes. An empty file is
56
+ `{}`; a missing one is (None, "", [])."""
57
+ from phiward import safeio
58
+ try:
59
+ text = safeio.read_text(path, limit=JSON_LIMIT, follow=True)
60
+ except FileNotFoundError:
61
+ return None, "", []
62
+ except (OSError, ValueError) as exc:
63
+ return None, type(exc).__name__, []
64
+ if not text.strip():
65
+ return {}, "", []
66
+ twice: List[str] = []
67
+
68
+ def pairs(items: List[Tuple[str, Any]]) -> Dict[str, Any]:
69
+ seen = set()
70
+ for k, _v in items:
71
+ if k in seen and k not in twice:
72
+ twice.append(k)
73
+ seen.add(k)
74
+ return dict(items)
75
+ try:
76
+ data = json.loads(text, object_pairs_hook=pairs, parse_constant=_no_constant)
77
+ except ValueError as exc:
78
+ return None, type(exc).__name__, []
79
+ return (data, "", twice) if isinstance(data, dict) else (None, "not a JSON object", [])
80
+
81
+
82
+ def read_settings(path: str) -> Tuple[Optional[Dict[str, Any]], str]:
83
+ """(a settings file as a dict, why it cannot be read), as Claude Code reads it (`read_json`:
84
+ a key given twice, the last one)."""
85
+ data, why, _twice = read_json(path)
86
+ return data, why
87
+
88
+
89
+ def _read(path: str) -> Optional[Dict[str, Any]]:
90
+ """A settings file's JSON object, or None when it is missing or cannot be read."""
91
+ return read_settings(path)[0]
92
+
93
+
94
+ def _no_constant(name: str) -> Any:
95
+ raise ValueError(f"{name} is not JSON")
96
+
97
+
98
+ def user_dir(home: str, env: Optional[Mapping[str, str]] = None) -> str:
99
+ env = os.environ if env is None else env
100
+ return env.get("CLAUDE_CONFIG_DIR") or os.path.join(home, ".claude")
101
+
102
+
103
+ # what bash and zsh read when they start (Claude Code makes its shell snapshot from them)
104
+ SHELL_STARTUP = (".bashrc", ".bash_profile", ".bash_login", ".profile", ".bash_aliases",
105
+ ".bash_logout", ".zshrc", ".zshenv", ".zprofile", ".zlogin", ".zlogout")
106
+ _ZSH_STARTUP = (".zshrc", ".zshenv", ".zprofile", ".zlogin", ".zlogout")
107
+
108
+
109
+ def shell_code_paths(home: str, env: Optional[Mapping[str, str]] = None) -> List[str]:
110
+ """What a shell runs before an agent's command: the bash and zsh startup files (also under
111
+ `$ZDOTDIR`), the files `$BASH_ENV` and `$ENV` name, and Claude Code's shell snapshots (it
112
+ sources one before each Bash command). A `phiward` function or alias planted there would
113
+ stand in for phiward in a shell no kernel confines, so no file tool and no `exec` command
114
+ may write them."""
115
+ env = os.environ if env is None else env
116
+ out = [os.path.join(home, n) for n in SHELL_STARTUP]
117
+ zdot = env.get("ZDOTDIR", "")
118
+ if zdot.startswith("/"):
119
+ out += [os.path.join(zdot, n) for n in _ZSH_STARTUP]
120
+ for name in ("BASH_ENV", "ENV"):
121
+ v = env.get(name, "")
122
+ if v.startswith("/"):
123
+ out.append(v)
124
+ out.append(os.path.join(user_dir(home, env), "shell-snapshots"))
125
+ return list(dict.fromkeys(os.path.normpath(p) for p in out))
126
+
127
+
128
+ # variables a project's `env` must not set: they choose what the hook reads (where phiward's
129
+ # config and spool are, the ticket and user names its hidden list uses), make the shell that
130
+ # starts a hook run code (SHELLOPTS=xtrace with a PS4 that holds `$(...)`, exported functions,
131
+ # BASH_ENV, ENV), choose the `phiward` the plugin's and project hooks start by name (PATH), or
132
+ # the project whose settings the hook reads (CLAUDE_PROJECT_DIR). The hook refuses every call while
133
+ # one is set; it cannot undo what such a shell already ran, which is why the agent may not write
134
+ # these files (docs/threat-model.md, "A project's settings can run code before phiward starts").
135
+ # Not here: PYTHON*, __PYVENV_LAUNCHER__, LD_* and DYLD_* (the hooks unset them before phiward
136
+ # starts; projects set PYTHONPATH and LD_LIBRARY_PATH for their own builds; the loader ones
137
+ # reach the shell and awk first, which `doctor` reports and the threat model states), and HOME,
138
+ # TMPDIR, XDG_* and CLAUDE_CONFIG_DIR (Claude Code itself ignores them in a project's `env`).
139
+ REDIRECT_PREFIXES = ("PHIWARD_", "KRB5", "BASH_FUNC_")
140
+ REDIRECT_NAMES = ("USER", "LOGNAME", "PATH", "SHELLOPTS", "BASHOPTS", "PS4", "BASH_ENV", "ENV",
141
+ "PROMPT_COMMAND", "IFS", "CDPATH", "GLOBIGNORE", "CLAUDE_PROJECT_DIR",
142
+ # a project's prefix or shell wins over the user's (part 1 of the plan)
143
+ "CLAUDE_CODE_SHELL_PREFIX", "CLAUDE_CODE_SHELL")
144
+
145
+
146
+ def project_files(project: str, home: str) -> List[str]:
147
+ """The project's settings files Claude Code may read for a session in `project`: its
148
+ `settings.json`, and every `settings.local.json` it may read (`local_candidates`). In a
149
+ session opened in the home folder the project's `settings.json` is the user settings file,
150
+ the operator's own (where `install` pins the shell): it is not a project's."""
151
+ shared = os.path.join(project, ".claude", "settings.json")
152
+ user = os.path.join(user_dir(home), "settings.json")
153
+ own = os.path.realpath(shared) == os.path.realpath(user)
154
+ return ([] if own else [shared]) + local_candidates(project, home)
155
+
156
+
157
+ def redirect_text(found: List[str]) -> str:
158
+ """`project_redirects` in words, for the hook's refusal and `doctor`."""
159
+ keys = ", ".join("env." + k for k in found if not k.startswith("unreadable:"))
160
+ bad = [k.split(":", 1)[1] for k in found if k.startswith("unreadable:")]
161
+ parts = ([f"set {keys}"] if keys else []) + (
162
+ ["have a settings file that cannot be read as JSON (" + ", ".join(bad) + ")"]
163
+ if bad else [])
164
+ return "this project's Claude Code settings " + " and ".join(parts)
165
+
166
+
167
+ def project_folders(cwd: str, home: str) -> List[str]:
168
+ """The project folders a call may belong to: `$CLAUDE_PROJECT_DIR`, and every folder at or
169
+ above `cwd` that holds `.claude` or `.git` (not the home folder, whose `.claude` is the
170
+ user's). Not only the nearest one: a submodule or a folder with its own `.claude` inside the
171
+ project must not hide the project's own settings. A project's `env` could point
172
+ `$CLAUDE_PROJECT_DIR` elsewhere: the call's own folders are read too."""
173
+ out: List[str] = []
174
+ named = os.environ.get("CLAUDE_PROJECT_DIR")
175
+ if named:
176
+ out.append(named)
177
+ d = os.path.abspath(cwd) if cwd else ""
178
+ top = os.path.realpath(home)
179
+ while d:
180
+ if os.path.realpath(d) != top and \
181
+ any(os.path.lexists(os.path.join(d, x)) for x in (".claude", ".git")) and \
182
+ not any(os.path.realpath(o) == os.path.realpath(d) for o in out):
183
+ out.append(d)
184
+ parent = os.path.dirname(d)
185
+ if parent == d:
186
+ break
187
+ d = parent
188
+ return out
189
+
190
+
191
+ def _holds(top: str, path: str) -> bool:
192
+ """Whether `path` is `top` or below it, compared in canonical spelling (letter case and
193
+ Unicode form as the volume stores them)."""
194
+ from phiward import pathid
195
+ a, b = pathid.canon(os.path.abspath(top)), pathid.canon(os.path.abspath(path))
196
+ return b == a or b.startswith(a.rstrip("/") + "/")
197
+
198
+
199
+ def named_project_holds(cwd: str) -> bool:
200
+ """Whether `$CLAUDE_PROJECT_DIR` is set and is `cwd` or a folder above it. When it is not,
201
+ the settings Claude Code reads may be in a folder phiward cannot find from the call."""
202
+ named = os.environ.get("CLAUDE_PROJECT_DIR")
203
+ return bool(named and cwd and _holds(named, cwd))
204
+
205
+
206
+ def confining_folders(cwd: str, home: str) -> List[str]:
207
+ """The project folders whose settings must confine the shell for a call in `cwd`: the
208
+ named project and the folders in it at or above `cwd` (a nested repository or `.claude`).
209
+ A folder above the named project is not one Claude Code reads for this session (its
210
+ `env` is still read for redirects: `project_folders`)."""
211
+ named = os.environ.get("CLAUDE_PROJECT_DIR")
212
+ if not named:
213
+ return []
214
+ return [f for f in project_folders(cwd, home) if f == named or _holds(named, f)]
215
+
216
+
217
+ def project_redirects(project: str, home: str) -> List[str]:
218
+ """The `env` keys of the project's settings that are REDIRECTs, and "unreadable:<file>"
219
+ for a settings file that exists but does not parse (its `env` cannot be seen)."""
220
+ return _project_env(project, home,
221
+ lambda k: k.startswith(REDIRECT_PREFIXES) or k in REDIRECT_NAMES,
222
+ unreadable=True)
223
+
224
+
225
+ # cleared by the hooks, but read by sh and awk before they are cleared: the dynamic loader's and
226
+ # glibc's own (character set modules, locale files), and the memory allocator's (macOS
227
+ # `MallocLogFile` writes a file)
228
+ LOADER_PREFIXES = ("LD_", "DYLD_", "MALLOC_", "Malloc")
229
+ LOADER_NAMES = ("GCONV_PATH", "LOCPATH")
230
+
231
+
232
+ def project_loader_keys(project: str, home: str) -> List[str]:
233
+ """The `env` keys of the project's settings that the hook's shell reads before they are
234
+ cleared."""
235
+ return _project_env(project, home,
236
+ lambda k: k.startswith(LOADER_PREFIXES) or k in LOADER_NAMES,
237
+ unreadable=False)
238
+
239
+
240
+ def _project_env(project: str, home: str, wanted: Callable[[str], bool], *,
241
+ unreadable: bool) -> List[str]:
242
+ found: List[str] = []
243
+ for f in project_files(project, home):
244
+ data = _read(f)
245
+ if data is None:
246
+ if unreadable and os.path.lexists(f):
247
+ found.append(f"unreadable:{f}")
248
+ continue
249
+ env = data.get("env")
250
+ if isinstance(env, dict):
251
+ found += [k for k in env if wanted(k) and k not in found]
252
+ return found
253
+
254
+
255
+ def _owned(path: str) -> bool:
256
+ try:
257
+ return os.stat(path, follow_symlinks=False).st_uid == os.getuid()
258
+ except FileNotFoundError:
259
+ return True # missing: nothing to own
260
+ except OSError:
261
+ return False # cannot be checked: not counted as this user's
262
+
263
+
264
+ def _repo_root(dot: str, home: str) -> Optional[str]:
265
+ """The folder git takes as the repository's root for the `.git` entry `dot` (for a linked
266
+ worktree, the main checkout), or None when git would not accept it. A `.git` file counts
267
+ only as git counts it: a worktree's `gitdir` names a folder directly under
268
+ `<common>/worktrees/`, whose own `gitdir` file points back to `dot`, in a common git folder
269
+ that is a real one (`config._sane_git_dir`); a submodule's names a real git folder."""
270
+ if os.path.isdir(dot): # a folder, or a link to one (git follows it)
271
+ return os.path.dirname(dot) if _is_repository(dot) else None
272
+ if not os.path.isfile(dot):
273
+ return None
274
+ dirs = config.git_dirs(dot)
275
+ if len(dirs) < 2 or not config._sane_git_dir(dirs[1], home):
276
+ return None
277
+ entry = os.path.realpath(dirs[1])
278
+ if os.path.basename(os.path.dirname(entry)) != "worktrees":
279
+ return os.path.dirname(dot) # a submodule: its own work tree is the root
280
+ common = os.path.dirname(os.path.dirname(entry))
281
+ back = _read_line(os.path.join(entry, "gitdir"))
282
+ # git 2.48+ may write it relative to its own folder (`worktree.useRelativePaths`)
283
+ if not back or os.path.realpath(os.path.join(entry, back)) != os.path.realpath(dot) \
284
+ or not config._sane_git_dir(common, home) or os.path.basename(common) != ".git":
285
+ return None
286
+ return os.path.dirname(common)
287
+
288
+
289
+ def git_redirects(project: str, home: str) -> List[str]:
290
+ """Where git would take its config and hooks from for `project` when that is a folder the
291
+ session can write and not inside a repository's own `.git` folder: a `commondir` in the
292
+ project's `.git`, or a `.git` file whose git folder (or the common folder it leads to) lies
293
+ there. Each as "FILE -> FOLDER", for doctor and the session note. A report, not a guard: the
294
+ shell writes these before any hook sees them (docs/threat-model.md, git's control files)."""
295
+ writable = [w.rstrip("/") + "/" for w in agent_writable(project, home)]
296
+
297
+ def open_to_agent(d: str) -> bool:
298
+ r = os.path.realpath(d)
299
+ if ".git" in r.split("/"):
300
+ return False # inside a repository's own git folder: git made it there
301
+ return any((r.rstrip("/") + "/").startswith(w) for w in writable)
302
+
303
+ out: List[str] = []
304
+ for dot in config.enclosing_git_dirs(project):
305
+ if os.path.isdir(dot):
306
+ common = os.path.join(dot, "commondir")
307
+ if os.path.lexists(common):
308
+ text = _read_line(common)
309
+ out.append(f"{common} -> {os.path.realpath(os.path.join(dot, text)) if text else '?'}")
310
+ continue
311
+ for d in config.git_dirs(dot)[1:]:
312
+ if open_to_agent(d):
313
+ out.append(f"{dot} -> {os.path.realpath(d)}")
314
+ break
315
+ return out
316
+
317
+
318
+ def _is_repository(d: str) -> bool:
319
+ """A `.git` folder git itself takes as a repository: HEAD, objects/ and refs/."""
320
+ return (os.path.isfile(os.path.join(d, "HEAD")) and os.path.isdir(os.path.join(d, "objects"))
321
+ and os.path.isdir(os.path.join(d, "refs")))
322
+
323
+
324
+ def _read_line(path: str) -> str:
325
+ from phiward import safeio
326
+ try:
327
+ return safeio.read_text(path, limit=4096).strip().splitlines()[0]
328
+ except (OSError, UnicodeDecodeError, ValueError, IndexError):
329
+ return ""
330
+
331
+
332
+ def local_file(project: str, home: str) -> str:
333
+ """The `settings.local.json` Claude Code reads for a session in `project`: at the git
334
+ repository's root (`_repo_root`), or in the project folder when there is no repository
335
+ (an invalid `.git` file: git refuses it), the root is the home folder, or the root, its
336
+ `.git` or `.claude` is not owned by this user. An invalid `.git` folder is passed over, as
337
+ git passes over it."""
338
+ fallback = os.path.join(project, ".claude", "settings.local.json")
339
+ for dot in config.enclosing_git_dirs(project):
340
+ if os.path.isdir(dot) and not _is_repository(dot):
341
+ continue
342
+ root = _repo_root(dot, home)
343
+ if root is None or os.path.realpath(root) == os.path.realpath(home) or not all(
344
+ _owned(p) for p in (root, os.path.join(root, ".git"),
345
+ os.path.join(root, ".claude"))):
346
+ return fallback
347
+ return os.path.join(root, ".claude", "settings.local.json")
348
+ return fallback
349
+
350
+
351
+ def local_candidates(project: str, home: str) -> List[str]:
352
+ """Every `settings.local.json` that Claude Code may read for `project`, the one it reads
353
+ (`local_file`) first: the project folder's, and that of each enclosing work tree whose
354
+ root and `.git` are this user's (another user's folder above cannot change the verdict).
355
+ The others may only make the confinement check stricter."""
356
+ out = [local_file(project, home), os.path.join(project, ".claude", "settings.local.json")]
357
+ for dot in config.enclosing_git_dirs(project):
358
+ root = os.path.dirname(dot)
359
+ if _owned(root) and _owned(dot):
360
+ out.append(os.path.join(root, ".claude", "settings.local.json"))
361
+ return list(dict.fromkeys(out))
362
+
363
+
364
+ INSTALL_STEP = "the operator runs `(cd ~ && phiward install claude --user --write)`"
365
+ # the excludedCommands entries an older phiward wrote; install removes them (`install.merge`),
366
+ # so a list of only these is one install fixes
367
+ OLD_EXCLUDES = ["phiward run *", "phiward copy *",
368
+ "python3 -m phiward run *", "python3 -m phiward copy *"]
369
+
370
+
371
+ def install_removes(entry: Any) -> bool:
372
+ """Whether `install claude --user --write` removes this excludedCommands entry."""
373
+ return entry in OLD_EXCLUDES
374
+
375
+
376
+ def _only_old_excludes(node: Any) -> bool:
377
+ return isinstance(node, list) and all(install_removes(c) for c in node)
378
+
379
+
380
+ class Reason(NamedTuple):
381
+ """Why the shell is not confined, and the one step that fixes it (the same in the hook's
382
+ refusal and in doctor)."""
383
+ text: str
384
+ step: str
385
+
386
+
387
+ def levels(project: Optional[str], home: str, env: Optional[Mapping[str, str]] = None,
388
+ local: str = "") -> List[Tuple[str, str, Optional[Dict[str, Any]]]]:
389
+ """(level, path, data) from the highest precedence down. `project` is the project folder
390
+ ($CLAUDE_PROJECT_DIR), or None when it is not known; `local`, the `settings.local.json` to
391
+ take as the one read (default: `local_file`)."""
392
+ files = []
393
+ for m in MANAGED:
394
+ # the drop-ins merge on top of the base file in name order, so the last one wins: listed
395
+ # first here (highest precedence first)
396
+ files += [("managed", p) for p in reversed(sorted(
397
+ glob.glob(os.path.join(os.path.dirname(m), "managed-settings.d", "*.json"))))]
398
+ files.append(("managed", m))
399
+ if project:
400
+ files += [("project local", local or local_file(project, home)),
401
+ ("project", os.path.join(project, ".claude", "settings.json"))]
402
+ files.append(("user", os.path.join(user_dir(home, env), "settings.json")))
403
+ return [(lvl, p, _read(p)) for lvl, p in files]
404
+
405
+
406
+ def _at(data: Any, keys: Sequence[str]) -> Any:
407
+ """`data[k1][k2]...`, or None where a step is not an object."""
408
+ for k in keys:
409
+ data = data.get(k) if isinstance(data, dict) else None
410
+ return data
411
+
412
+
413
+ def _first(levels_: Sequence[Tuple[str, str, Optional[Dict[str, Any]]]], *keys: str) -> Any:
414
+ for _, _, data in levels_:
415
+ node = _at(data, keys)
416
+ if node is not None:
417
+ return node
418
+ return None
419
+
420
+
421
+ def _merged_list(levels_, *keys: str) -> List[str]:
422
+ out: List[str] = []
423
+ for _, _, data in levels_:
424
+ node = _at(data, keys)
425
+ if isinstance(node, list):
426
+ out += [str(v) for v in node if str(v) not in out]
427
+ return out
428
+
429
+
430
+ def _shown_file(path: str, project: str, home: str) -> str:
431
+ """A settings file or folder as the operator knows it: relative to the project, or `~/...`
432
+ (always `~/...` in a session started from the home folder)."""
433
+ if project and home and os.path.normpath(project) == os.path.normpath(home):
434
+ project = ""
435
+ for base, lead in ((project, ""), (home, "~/")):
436
+ if base and path.startswith(base.rstrip("/") + "/"):
437
+ return lead + os.path.relpath(path, base)
438
+ return path
439
+
440
+
441
+ def _bases(level: str, project: str, home: str, env: Optional[Mapping[str, str]]) -> List[str]:
442
+ if level.startswith("project"):
443
+ return [project]
444
+ if level == "user":
445
+ return [user_dir(home, env)]
446
+ return [project, user_dir(home, env)] # managed: unknown
447
+
448
+
449
+ def _resolve(entry: str, bases: Sequence[str], home: str) -> List[str]:
450
+ if entry.startswith("//"):
451
+ entry = entry[1:]
452
+ if entry.startswith("/"):
453
+ return [entry]
454
+ if entry == "~" or entry.startswith("~/"):
455
+ return [home + entry[1:]]
456
+ return [os.path.join(b, entry) for b in bases]
457
+
458
+
459
+ def _fixed_dir(p: str) -> str:
460
+ """The deepest folder of a glob pattern with no wildcard in it."""
461
+ cut = min([i for i in (p.find("*"), p.find("?"), p.find("[")) if i >= 0] or [len(p)])
462
+ return p[:cut].rsplit("/", 1)[0] or "/"
463
+
464
+
465
+ def _paths(levels_, project: str, home: str, env, key: str, deny: bool) -> List[str]:
466
+ """Every entry of sandbox.filesystem.<key> as absolute paths, in both spellings."""
467
+ out: List[str] = []
468
+ for level, _, data in levels_:
469
+ node = _at(data, ("sandbox", "filesystem", key))
470
+ if not isinstance(node, list):
471
+ continue
472
+ for v in node:
473
+ v = str(v)
474
+ wild = any(c in v for c in "*?[")
475
+ if deny and wild:
476
+ continue
477
+ bases = _bases(level, project, home, env)
478
+ if deny and level == "managed" and not (v.startswith("/") or v.startswith("~")):
479
+ continue
480
+ if wild: # an allow pattern stays a pattern; _reopened matches it
481
+ for p in _resolve(v, bases, home):
482
+ fixed = _fixed_dir(p)
483
+ for sp in {os.path.normpath(fixed), os.path.realpath(fixed)}:
484
+ pat = sp.rstrip("/") + "/" + p[len(fixed):].lstrip("/")
485
+ if pat not in out:
486
+ out.append(pat)
487
+ continue
488
+ for p in _resolve(v, bases, home):
489
+ for sp in (os.path.normpath(p), os.path.realpath(p)):
490
+ if sp not in out:
491
+ out.append(sp)
492
+ return out
493
+
494
+
495
+ def _inside(p: str, folder: str) -> bool:
496
+ """Whether the deny entry `folder` covers `p`. "Covered" relaxes the hook, so this is
497
+ strict: the entry counts only when it is written in the file system's own spelling (the one
498
+ the kernel compares), and `p`, in that spelling, is it or inside it."""
499
+ from phiward import pathid
500
+ if pathid.canon(folder) != folder:
501
+ return False
502
+ p = pathid.canon(p)
503
+ return p == folder or p.startswith(folder.rstrip("/") + "/")
504
+
505
+
506
+ def _spell(p: str) -> List[str]:
507
+ return list({os.path.normpath(p), os.path.realpath(p)})
508
+
509
+
510
+ def _covers(deny: Sequence[str], root: str) -> bool:
511
+ return any(_inside(s, d) for s in _spell(root) for d in deny)
512
+
513
+
514
+ def _reopened(root: str, deny: Sequence[str], allow: Sequence[str]) -> bool:
515
+ """Whether an allowRead entry re-opens part of `root`: the allow overlaps the root and is
516
+ not wider than the narrowest deny that covers the root. A glob entry re-opens it when it can
517
+ match the root or a path inside it."""
518
+ for s in _spell(root):
519
+ covering = [d for d in deny if _inside(s, d)]
520
+ if not covering:
521
+ continue
522
+ narrowest = max(covering, key=len)
523
+ for a in allow:
524
+ if _wild(a):
525
+ if _reaches_into(pathmatch.fold(a), pathmatch.fold(s)):
526
+ return True
527
+ continue
528
+ overlaps = _inside(a, s) or _inside(s, a)
529
+ if overlaps and _inside(a, narrowest): # as narrow as the deny, or narrower
530
+ return True
531
+ return False
532
+
533
+
534
+ # sandbox settings that let a sandboxed command reach past the sandbox: with any of them true,
535
+ # the shell does not count as confined
536
+ OPENERS = (("filesystem", "disabled"), ("enableWeakerNestedSandbox",), ("allowAppleEvents",),
537
+ ("allowNestedUserNamespaces",), ("network", "allowLocalBinding"))
538
+
539
+
540
+ def _opened(lv) -> Optional[Tuple[str, Tuple[str, ...], bool]]:
541
+ """Why these settings let a sandboxed command reach past the sandbox: (the reason, the keys
542
+ under `sandbox`, whether it is a list), or None."""
543
+ for keys in OPENERS:
544
+ if _first(lv, "sandbox", *keys) is True:
545
+ return f"sandbox.{'.'.join(keys)} is true (it opens the sandbox)", tuple(keys), False
546
+ if _merged_list(lv, "sandbox", "excludedCommands"):
547
+ return "sandbox.excludedCommands is not empty", ("excludedCommands",), True
548
+ if _first(lv, "sandbox", "network", "allowAllUnixSockets") is True:
549
+ return ("sandbox.network.allowAllUnixSockets is true",
550
+ ("network", "allowAllUnixSockets"), False)
551
+ if _merged_list(lv, "sandbox", "network", "allowUnixSockets"):
552
+ return ("sandbox.network.allowUnixSockets is not empty",
553
+ ("network", "allowUnixSockets"), True)
554
+ if _merged_list(lv, "sandbox", "network", "allowMachLookup"):
555
+ return ("sandbox.network.allowMachLookup is not empty (a listed service acts outside "
556
+ "the sandbox)", ("network", "allowMachLookup"), True)
557
+ return None
558
+
559
+
560
+ def _globs(levels_, project: str, home: str, env, key: str) -> List[str]:
561
+ """The wildcard entries of sandbox.filesystem.<key>, as absolute paths."""
562
+ out: List[str] = []
563
+ for level, _, data in levels_:
564
+ node = _at(data, ("sandbox", "filesystem", key))
565
+ for v in node if isinstance(node, list) else []:
566
+ v = str(v)
567
+ # not `_wild`: a deny entry counts only as written (a brace is an ordinary character
568
+ # to the sandbox), while an allow entry with a brace is read widely (`_reaches_into`)
569
+ if any(c in v for c in "*?[") and not (level == "managed" and v[:1] not in "/~"):
570
+ out += [p for p in _resolve(v, _bases(level, project, home, env), home)
571
+ if p not in out]
572
+ return out
573
+
574
+
575
+ def pattern_entries(pattern: str) -> List[str]:
576
+ """The sandbox entries that deny a protected pattern: its literal start in the file system's
577
+ own spelling, then the pattern, and the same with `/**` (what is inside a match)."""
578
+ from phiward import paths
579
+ form = paths.canon_prefix(pattern).rstrip("/")
580
+ return [form, form + "/**"]
581
+
582
+
583
+ def _wild(entry: str) -> bool:
584
+ """Whether a sandbox entry may be a wildcard: `*`, `?`, `[`, or `{` (taken as one, in case
585
+ the sandbox expands braces)."""
586
+ return any(c in entry for c in "*?[{")
587
+
588
+
589
+ def _parts_meet(a: str, p: str) -> bool:
590
+ """Whether one name can match both parts (taken widely when both may hold a wildcard)."""
591
+ if not _wild(a):
592
+ return pathmatch.match_part(p, a)
593
+ if not _wild(p) and "{" not in a:
594
+ return pathmatch.match_part(a, p)
595
+ return True
596
+
597
+
598
+ def _reaches_into(allow: str, pattern: str) -> bool:
599
+ """Whether an allowRead entry can name a match of `pattern` or a path inside one: its parts
600
+ meet the pattern's one by one (a `**` meets whatever follows) and it goes as deep as a match
601
+ or deeper. A wildcard entry whose literal start is at or below the pattern's literal start
602
+ counts too (taken widely). An entry that ends above every match is wider than the deny, which
603
+ holds under it (docs: a wildcard deny holds under a wider allowRead)."""
604
+ p = pathmatch.parts(pattern)
605
+ a = pathmatch.parts(allow)
606
+ if _wild(allow) and ".." in a:
607
+ return True # where a `..` after a wildcard lands is not known here
608
+ if _wild(allow):
609
+ head = p[:next((i for i, c in enumerate(p) if "*" in c), len(p))]
610
+ if pathmatch.parts(_fixed_dir(allow))[:len(head)] == head:
611
+ return True
612
+ for i, part in enumerate(a):
613
+ if "**" in part or (i < len(p) and "**" in p[i]):
614
+ return True
615
+ if i >= len(p):
616
+ return True # inside a match
617
+ if not _parts_meet(part, p[i]):
618
+ return False
619
+ return len(a) >= len(p)
620
+
621
+
622
+ def _pattern_step(version: Optional[Tuple[int, int, int]]) -> str:
623
+ """The step for pattern entries the sandbox lacks: install writes them only for Claude Code
624
+ VERSION_PATTERNS or newer, as `claude --version` tells it in the operator's terminal."""
625
+ need = version_text(VERSION_PATTERNS)
626
+ if version is None:
627
+ return (f"{INSTALL_STEP} in a terminal where `claude --version` prints {need} or newer "
628
+ "(update Claude Code first if it is older)")
629
+ if version < VERSION_PATTERNS:
630
+ return (f"the operator updates Claude Code to {need} or newer, then runs `phiward "
631
+ "install claude --user --write` (or protects folders instead of patterns)")
632
+ return INSTALL_STEP
633
+
634
+
635
+ def _patterns_unconfined(lv, project: str, home: str, env, patterns: Sequence[str],
636
+ version: Optional[Tuple[int, int, int]] = None) -> Optional[Reason]:
637
+ """Why the sandbox settings leave a protected pattern open, or None. Only macOS's sandbox can
638
+ deny writes to a wildcard path (on Linux only a trailing `/**` works, and a match made while
639
+ a command runs is readable in it: docs/threat-model.md)."""
640
+ if not patterns:
641
+ return None
642
+ if sys.platform != "darwin":
643
+ return Reason("Claude Code's sandbox cannot deny writes to a protected pattern on this "
644
+ "system (only a trailing /** works here)",
645
+ "the operator protects the folders instead of patterns ([protected_paths] "
646
+ "roots), or runs the agent under `phiward launch`")
647
+ for key in ("denyRead", "denyWrite"):
648
+ have = set(_globs(lv, project, home, env, key))
649
+ # both: the pattern (a match itself) and `pattern/**` (what is inside one)
650
+ miss = [p for p in patterns if not set(pattern_entries(p)) <= have]
651
+ if miss:
652
+ return Reason(f"sandbox.filesystem.{key} does not cover {len(miss)} protected "
653
+ "pattern(s)", _pattern_step(version))
654
+ for level in lv:
655
+ allow = _paths([level], project, home, env, "allowRead", deny=False)
656
+ if any(_reaches_into(a, pathmatch.fold(pattern_entries(p)[0]))
657
+ for a in map(pathmatch.fold, allow) for p in patterns):
658
+ return Reason("sandbox.filesystem.allowRead re-opens part of a protected pattern's "
659
+ "matches", _step_in(level[0], level[1], project, home, env,
660
+ "that allowRead entry", False))
661
+ return None
662
+
663
+
664
+ def _env_value(project: str, home: str, env: Optional[Mapping[str, str]], name: str) -> Tuple[Optional[str], str]:
665
+ """(the value Claude Code takes for `env.<name>`, why it cannot tell): it must be the same
666
+ whichever `settings.local.json` Claude Code reads, and every settings file must parse."""
667
+ found: List[Optional[str]] = []
668
+ for local in local_candidates(project, home):
669
+ lv = levels(project, home, env, local)
670
+ for _l, f, data in lv:
671
+ if data is None and os.path.lexists(f):
672
+ return None, f"{f} cannot be read as JSON"
673
+ value = _first(lv, "env", name)
674
+ found.append(value if isinstance(value, str) else None)
675
+ if len(set(found)) != 1:
676
+ return None, f"env.{name} differs between the settings.local.json files Claude Code may read"
677
+ return found[0], ""
678
+
679
+
680
+ # the files of a project folder that change what Claude Code runs (hooks, sandbox, MCP servers)
681
+ PROJECT_FILES = (".claude/settings.json", ".claude/settings.local.json", ".mcp.json")
682
+
683
+
684
+ def bash_pinned(project: Optional[str], home: str,
685
+ env: Optional[Mapping[str, str]] = None) -> bool:
686
+ """Whether the settings Claude Code reads set its shell to /bin/bash (part 4 of the plan)."""
687
+ return bool(project) and _env_value(project or "", home, env, "CLAUDE_CODE_SHELL")[0] == BASH
688
+
689
+
690
+ BASH = "/bin/bash"
691
+ # the Claude Code versions a setting needs (docs: settings reference; part 1 of the plan)
692
+ VERSION_PATTERNS = (2, 1, 236) # macOS: a wildcard denyRead holds under a wider allowRead
693
+ VERSION_BLOCK_READS = (2, 1, 257) # permissions.blockReadsOutsideWorkingDirectories
694
+ VERSION_DENY_PROMPTS = (2, 1, 319) # permissions.denyInsteadOfPrompting
695
+
696
+
697
+ def version_text(version: Tuple[int, int, int]) -> str:
698
+ return ".".join(map(str, version))
699
+
700
+
701
+ def claude_version() -> Optional[Tuple[int, int, int]]:
702
+ """The installed Claude Code's version (`claude --version`), or None when it cannot tell."""
703
+ import re
704
+ import shutil
705
+ import subprocess
706
+ from phiward import service
707
+ # never a `claude` the agent could have planted: the PATH folders the broker searches, but
708
+ # a tool's own clone in the home folder (nvm, asdf) counts (the agent's sandbox does not
709
+ # write it); found only elsewhere, the version is unknown and nothing runs
710
+ path = os.environ.get("PATH", "")
711
+ exe = shutil.which("claude", path=":".join(
712
+ service.path_entries(path, service.path_inputs(), work_trees=False)))
713
+ if not exe:
714
+ return None
715
+ try:
716
+ out = subprocess.run([exe, "--version"], capture_output=True, text=True, timeout=20,
717
+ stdin=subprocess.DEVNULL).stdout
718
+ except (OSError, subprocess.SubprocessError):
719
+ return None
720
+ m = re.match(r"\s*(\d+)\.(\d+)\.(\d+)", out)
721
+ return (int(m.group(1)), int(m.group(2)), int(m.group(3))) if m else None
722
+
723
+
724
+ def _user_file(home: str, env: Optional[Mapping[str, str]]) -> str:
725
+ return os.path.join(user_dir(home, env), "settings.json")
726
+
727
+
728
+ def _step_in(level: str, f: str, project: str, home: str, env: Optional[Mapping[str, str]],
729
+ what: str, install_fixes: bool) -> str:
730
+ """The step for `what` (a setting, or "that ... entry") set in the settings file `f`."""
731
+ if level == "managed":
732
+ return f"an admin changes the managed settings ({f})"
733
+ if install_fixes and os.path.normpath(f) == os.path.normpath(_user_file(home, env)):
734
+ return INSTALL_STEP
735
+ return (f"the operator removes {what} from {_shown_file(f, project, home)} (install never "
736
+ "removes it)" if not install_fixes else
737
+ f"the operator removes {what} from {_shown_file(f, project, home)}")
738
+
739
+
740
+ def _step_for(lv, project: str, home: str, env: Optional[Mapping[str, str]], keys: Sequence[str],
741
+ install_fixes: Any, merged: bool = False) -> str:
742
+ """The step for a setting by the file whose value Claude Code uses (`merged`: the first file
743
+ with a non-empty list); none at all: install, which writes the user file. `install_fixes`:
744
+ whether install sets or removes it, or a function of the value that says so."""
745
+ for level, f, data in lv:
746
+ node = _at(data, keys)
747
+ if node is None or (merged and not node):
748
+ continue
749
+ fixes = install_fixes(node) if callable(install_fixes) else install_fixes
750
+ return _step_in(level, f, project, home, env, ".".join(keys), bool(fixes))
751
+ return INSTALL_STEP
752
+
753
+
754
+ def confinement_reason(project: Optional[str], home: str, roots: Sequence[str],
755
+ patterns: Sequence[str],
756
+ guard: Sequence[str] = (), env: Optional[Mapping[str, str]] = None,
757
+ hidden: Sequence[str] = (),
758
+ user_data: Optional[Dict[str, Any]] = None,
759
+ version: Optional[Tuple[int, int, int]] = None) -> Optional[Reason]:
760
+ """Why the shell is not confined, with its step, or None. `user_data`: the user settings to take in place of the file (what
761
+ `install claude --user --write` would write, for doctor), in every level whose file is the user
762
+ file (a session started from the home folder reads it as its project file too). `version`:
763
+ the Claude Code version when it is known (doctor; the hook cannot run `claude --version`),
764
+ for the step of a pattern the sandbox does not cover. `hidden`: the hidden list's paths that exist; the sandbox must deny
765
+ reading every one, or the shell does not count as confined and the hook checks its text
766
+ (an older install left credentials readable to Bash). It must hold whichever of the
767
+ `settings.local.json` files Claude Code may read is the one it reads (`local_candidates`):
768
+ a file the agent can choose (with a planted `.git`) cannot make the shell count as
769
+ confined. A settings file that exists but does not parse means not confined."""
770
+ if sys.platform.startswith("win"):
771
+ return Reason("Claude Code runs commands unsandboxed on native Windows",
772
+ "run Claude Code in WSL")
773
+ if not project:
774
+ return Reason("$CLAUDE_PROJECT_DIR is not set, so the project's Claude Code settings "
775
+ "cannot be read", NO_PROJECT_STEP)
776
+ for w in session_write_places(project, home):
777
+ why = startup_write_problem(w, home)
778
+ if why:
779
+ where = "the session's folder" if os.path.realpath(w) == os.path.realpath(project) \
780
+ else f"the write place {_shown_file(w, project, home)}"
781
+ return Reason(f"Claude Code's sandbox may write {where}, and {why}: a shell command "
782
+ "could set up a program that runs later with your rights",
783
+ "open Claude Code in a project folder, and keep your home folder, "
784
+ "~/.config, ~/.local/bin and ~/Library/LaunchAgents out of "
785
+ "allowWrite and additionalDirectories")
786
+ candidates = local_candidates(project, home)
787
+ for local in candidates:
788
+ lv = levels(project, home, env, local)
789
+ if user_data is not None:
790
+ mine = os.path.normpath(_user_file(home, env)) # install replaces the file there
791
+ lv = [(lvl, f, user_data if os.path.normpath(f) == mine else d) for lvl, f, d in lv]
792
+ r = _confined_with(lv, project, home, roots, patterns, guard, env, hidden, version)
793
+ if r is not None:
794
+ if local != candidates[0]: # not the file Claude Code is thought to read
795
+ r = Reason(f"{r.text}, with {local} as the settings.local.json Claude Code may "
796
+ "read", r.step)
797
+ return r
798
+ return None
799
+
800
+
801
+ NO_PROJECT_STEP = "update Claude Code (it gives hooks $CLAUDE_PROJECT_DIR)"
802
+ OUTSIDE_PROJECT_STEP = "run the command inside the project folder ($CLAUDE_PROJECT_DIR)"
803
+
804
+
805
+ def _confined_with(lv, project: str, home: str, roots: Sequence[str], patterns: Sequence[str],
806
+ guard: Sequence[str], env: Optional[Mapping[str, str]],
807
+ hidden: Sequence[str],
808
+ version: Optional[Tuple[int, int, int]] = None) -> Optional[Reason]:
809
+ """`confinement_reason` for one set of settings files (`levels`)."""
810
+ for _l, f, data in lv:
811
+ if data is None and os.path.lexists(f):
812
+ return Reason(f"{f} cannot be read as JSON",
813
+ f"the operator fixes or removes {_shown_file(f, project, home)}")
814
+ for key, want, text in (("enabled", True, "sandbox.enabled is not true"),
815
+ ("allowUnsandboxedCommands", False,
816
+ "sandbox.allowUnsandboxedCommands is not false"),
817
+ ("failIfUnavailable", True,
818
+ "sandbox.failIfUnavailable is not true (without it, commands run "
819
+ "unsandboxed when the sandbox cannot start)")):
820
+ if _first(lv, "sandbox", key) is not want:
821
+ # install sets these three in the user file
822
+ return Reason(text, _step_for(lv, project, home, env, ("sandbox", key), True))
823
+ opened = _opened(lv)
824
+ if opened:
825
+ text, keys, merged = opened
826
+ fixes = _only_old_excludes if keys == ("excludedCommands",) else False
827
+ return Reason(text, _step_for(lv, project, home, env, ("sandbox",) + keys, fixes, merged))
828
+ r = _patterns_unconfined(lv, project, home, env, patterns, version)
829
+ if r is not None:
830
+ return r
831
+ deny_read = _paths(lv, project, home, env, "denyRead", deny=True)
832
+ deny_write = _paths(lv, project, home, env, "denyWrite", deny=True)
833
+ for key, deny in (("denyRead", deny_read), ("denyWrite", deny_write)):
834
+ missing = [r for r in roots if not _covers(deny, r)]
835
+ if missing:
836
+ return Reason(f"sandbox.filesystem.{key} does not cover {len(missing)} protected "
837
+ "root(s)", INSTALL_STEP)
838
+ for level in lv:
839
+ # one file at a time, so the step names the file that holds the entry
840
+ allow_read = _paths([level], project, home, env, "allowRead", deny=False)
841
+ if any(_reopened(r, deny_read, allow_read) for r in roots):
842
+ return Reason("sandbox.filesystem.allowRead re-opens part of a protected root",
843
+ _step_in(level[0], level[1], project, home, env,
844
+ "that allowRead entry", False))
845
+ if any(_reopened(h, deny_read, allow_read) for h in hidden):
846
+ return Reason("sandbox.filesystem.allowRead re-opens a credential path",
847
+ _step_in(level[0], level[1], project, home, env,
848
+ "that allowRead entry", False))
849
+ miss = [h for h in hidden if not _covers(deny_read, h)]
850
+ if miss:
851
+ return Reason(f"sandbox.filesystem.denyRead does not cover {len(miss)} credential "
852
+ "path(s)", INSTALL_STEP)
853
+ denied = config.sandbox_denied(dict(env) if env is not None else None)
854
+ for level in lv:
855
+ # one settings file at a time, so the refusal names the file that holds the entry (an
856
+ # older phiward's `allowWrite ~/.phiward/spool` may be in a project's file too)
857
+ allow_write = _paths([level], project, home, env, "allowWrite", deny=False)
858
+ for d in denied:
859
+ if any(a == d or a.startswith(d.rstrip("/") + "/") for a in allow_write):
860
+ f = _shown_file(level[1], project, home)
861
+ return Reason(f"sandbox.filesystem.allowWrite in {f} re-opens part of "
862
+ f"{_shown_file(d, project, home)}, phiward's own folder",
863
+ _step_in(level[0], level[1], project, home, env,
864
+ "that entry", False))
865
+ if any(not _covers(deny_write, g) for g in list(guard) + denied):
866
+ return Reason("sandbox.filesystem.denyWrite does not cover the phiward config and code "
867
+ "(an upgrade)", INSTALL_STEP)
868
+ return None
869
+
870
+
871
+ # --- the folders Claude Code lets the agent write ----------------------------------------------
872
+
873
+ # what Claude Code runs as code, beside its settings files: under any `.claude` folder (not its
874
+ # `worktrees`) and under the user config folder (CLAUDE_CONFIG_DIR may have another name). A skill
875
+ # or subagent may hold hooks in its frontmatter, a skill or command `!` lines, a plugin hooks and
876
+ # MCP servers; `launch.json` names what the app's preview starts. The one list: the hook asks
877
+ # before a file tool writes one (`code_place`), and carryover quarantines them.
878
+ SETTINGS_NAMES = ("settings.json", "settings.local.json")
879
+ CODE_DIRS = ("skills", "agents", "commands", "hooks", "workflows", "plugins", "routines")
880
+ CODE_FILES = ("launch.json", "scheduled_tasks.json")
881
+ # what an editor or a tool runs from a project, wherever it is in the tree: an editor's workspace
882
+ # settings (tasks, an interpreter path, MCP servers) and the files git and ripgrep read for
883
+ # commands. Claude Code's sandbox denies them to the shell; the hook asks before a file tool
884
+ # writes one, and `launch --entry` makes them read-only
885
+ WORKSPACE_CODE_DIRS = (".vscode", ".idea")
886
+ WORKSPACE_CODE_FILES = (".gitmodules", ".ripgreprc")
887
+ # git's control files below any `.git` folder under the home folder (a submodule's config, a
888
+ # worktree's commondir, hooks): git runs what they name, and Claude Code runs git outside its
889
+ # sandbox. Anchored to the control files themselves, so a branch named `config` or `hooks/x`
890
+ # (under refs/ and logs/) stays writable; the hooks folder itself too, so it cannot be renamed
891
+ # and replaced. Wildcards: written for macOS and Claude Code VERSION_PATTERNS or newer only
892
+ GIT_CONTROL_GLOBS = ("~/**/.git/config", "~/**/.git/config.worktree", "~/**/.git/commondir",
893
+ "~/**/.git/hooks", "~/**/.git/hooks/**",
894
+ "~/**/.git/modules/*/config", "~/**/.git/modules/*/config.worktree",
895
+ "~/**/.git/modules/*/hooks", "~/**/.git/modules/*/hooks/**",
896
+ "~/**/.git/worktrees/*/commondir", "~/**/.git/worktrees/*/config.worktree")
897
+
898
+
899
+ def workspace_code(path: str) -> bool:
900
+ """Whether `path` is a file an editor or a tool runs commands from (WORKSPACE_CODE_DIRS,
901
+ WORKSPACE_CODE_FILES), as the file system compares names."""
902
+ from phiward import pathid
903
+ for v in (os.path.normpath(path), os.path.realpath(path)):
904
+ parts = pathid.fold(v).split("/")
905
+ if any(p in WORKSPACE_CODE_DIRS for p in parts[:-1]) or parts[-1] in WORKSPACE_CODE_FILES:
906
+ return True
907
+ return False
908
+
909
+
910
+ def _spellings(path: str) -> List[str]:
911
+ """`path` as the file system may compare it: as written, where it really leads, and in the
912
+ file system's own spelling (case and Unicode form folded on macOS)."""
913
+ from phiward import pathid
914
+ out = []
915
+ real = os.path.realpath(path)
916
+ for v in (os.path.normpath(path), real, pathid.canon_new(real)):
917
+ f = pathid.fold(v)
918
+ if f not in out:
919
+ out.append(f)
920
+ return out
921
+
922
+
923
+ def _code_rel(parts: Sequence[str]) -> bool:
924
+ """Whether a path below a Claude Code config folder (its parts below it) is a code place."""
925
+ return bool(parts) and (parts[0] in CODE_DIRS or (len(parts) == 1 and parts[0] in CODE_FILES))
926
+
927
+
928
+ # the code folders are walked for their links, followed until nothing new turns up: each linked
929
+ # tree up to TREE_WALK entries, all of them up to LINK_WALK; a tree past its bound still counts as
930
+ # code as a whole (only the links deep inside it are not followed), and `doctor` names it.
931
+ # `plugins` only to the level where an install is (marketplaces/NAME,
932
+ # cache/MARKETPLACE/PLUGIN/VERSION): deeper, a link is the plugin's own, written by its installer
933
+ TREE_WALK = 50_000
934
+ LINK_WALK = 200_000
935
+ _PLUGIN_DEPTH = 3
936
+
937
+
938
+ def _too_wide(real: str, keep: Sequence[str]) -> bool:
939
+ """A link target no code folder can mean: `/`, or a folder that is or holds one of `keep`
940
+ (the home folder, the user config folder: taken as code it would hold every write there),
941
+ as the file system compares names; `doctor` names the link."""
942
+ from phiward import pathid
943
+ if real == "/":
944
+ return True
945
+ r = pathid.fold(real).rstrip("/") + "/"
946
+ return any((pathid.fold(k).rstrip("/") + "/").startswith(r) for k in keep if k)
947
+
948
+
949
+ def _code_walk(starts: Sequence[Tuple[str, Optional[int], str]], home: str = ""
950
+ ) -> "Tuple[List[Tuple[str, str]], List[Tuple[str, str, str]]]":
951
+ """The code roots below `starts` ([(a real code folder, how deep to walk or None, how it is
952
+ named)]): each start, and where every link inside one leads, a linked folder walked in turn
953
+ (a cycle guard), with `os.scandir` (no stat per entry). ([(real path, the link that led
954
+ there)], [(why, real path, link)] for `doctor`: "tree" a tree past TREE_WALK, "total" one not
955
+ walked once LINK_WALK was passed (both still code as a whole; links deep in them not
956
+ followed), "wide" a target that is or holds the home or user config folder, not taken as
957
+ code)."""
958
+ roots: List[Tuple[str, str]] = []
959
+ notes: List[Tuple[str, str, str]] = []
960
+ keep = [os.path.realpath(home)] + ([os.path.realpath(user_dir(home))] if home else [])
961
+ todo = list(starts)
962
+ done = set()
963
+ total = 0
964
+ while todo:
965
+ top, limit, via = todo.pop(0)
966
+ if top in done:
967
+ continue
968
+ done.add(top)
969
+ if via and _too_wide(top, keep):
970
+ notes.append(("wide", top, via))
971
+ continue
972
+ roots.append((top, via))
973
+ if total > LINK_WALK:
974
+ notes.append(("total", top, via))
975
+ continue
976
+ seen = 0
977
+ stack = [(top, 0)]
978
+ while stack:
979
+ here, depth = stack.pop()
980
+ try:
981
+ entries = list(os.scandir(here))
982
+ except OSError:
983
+ continue
984
+ for e in entries:
985
+ seen += 1
986
+ total += 1
987
+ if seen > TREE_WALK:
988
+ notes.append(("tree", top, via))
989
+ stack = []
990
+ break
991
+ try:
992
+ if e.is_symlink():
993
+ real = os.path.realpath(e.path)
994
+ if os.path.isdir(real):
995
+ todo.append((real, None, e.path))
996
+ elif real not in done:
997
+ done.add(real)
998
+ if not _too_wide(real, keep):
999
+ roots.append((real, e.path)) # a file, or nothing yet
1000
+ elif (limit is None or depth < limit) and e.is_dir(follow_symlinks=False):
1001
+ stack.append((e.path, depth + 1))
1002
+ except OSError:
1003
+ continue # an entry that vanished, or cannot be read (/dev/fd)
1004
+ return roots, notes
1005
+
1006
+
1007
+ def _spellings_memo(path: str, memo: Dict[Any, Any]) -> List[str]:
1008
+ key = ("sp", path)
1009
+ if key not in memo:
1010
+ memo[key] = _spellings(path)
1011
+ return memo[key]
1012
+
1013
+
1014
+ def _claude_places(path: str, home: str, bases: Sequence[str],
1015
+ env: Optional[Mapping[str, str]] = None,
1016
+ memo: Optional[Dict[Any, Any]] = None) -> "Tuple[List[str], List[Tuple[str, str, bool]]]":
1017
+ """The Claude Code config folders that may hold `path`, and their settings and code
1018
+ places, by what they are, not their names: (the folders, [(place, kind, is a folder)]).
1019
+ The folders: the user config folder, and the `.claude` of every folder above `path` (as
1020
+ written and as it really leads) and above each of `bases` (the project, the working
1021
+ folder), each where it really leads (a `.claude` that is a link to `cfg` makes `cfg` one,
1022
+ also before `cfg` exists). The places: each child named in SETTINGS_NAMES, CODE_DIRS and
1023
+ CODE_FILES of such a folder, where it really leads (`skills -> ../.agents/skills`). All
1024
+ folded real paths; `memo` holds one tool call's (a call may name thousands)."""
1025
+ memo = {} if memo is None else memo
1026
+ real_folders: List[str] = []
1027
+
1028
+ def dot_claude(d: str) -> str:
1029
+ key = ("dc", d)
1030
+ if key not in memo:
1031
+ c = os.path.join(d, ".claude")
1032
+ # a link counts even when it leads nowhere yet: the write may make its target
1033
+ memo[key] = os.path.realpath(c) if os.path.lexists(c) else ""
1034
+ return memo[key]
1035
+
1036
+ def add(real: str) -> None:
1037
+ if real and real not in real_folders:
1038
+ real_folders.append(real)
1039
+
1040
+ add(os.path.realpath(user_dir(home, env)))
1041
+ starts = [os.path.dirname(os.path.normpath(path)), os.path.dirname(os.path.realpath(path))]
1042
+ starts += [b for b in bases if b]
1043
+ for s in starts:
1044
+ d = s
1045
+ while True:
1046
+ add(dot_claude(d))
1047
+ up = os.path.dirname(d)
1048
+ if up == d:
1049
+ break
1050
+ d = up
1051
+ folders: List[str] = []
1052
+ places: List[Tuple[str, str, bool]] = []
1053
+ for real in real_folders:
1054
+ key = ("pl", real)
1055
+ if key not in memo:
1056
+ fs = [f.rstrip("/") for f in _spellings(real)]
1057
+ ps: List[Tuple[str, str, bool]] = []
1058
+ for n in SETTINGS_NAMES + CODE_FILES + CODE_DIRS:
1059
+ c = os.path.join(real, n)
1060
+ if os.path.lexists(c): # a link: where it leads (`skills -> ../shared/skills`)
1061
+ kind = "settings" if n in SETTINGS_NAMES else "code"
1062
+ for f in _spellings(os.path.realpath(c)):
1063
+ ps.append((f.rstrip("/"), kind, n in CODE_DIRS))
1064
+ memo[key] = (fs, ps)
1065
+ fs, ps = memo[key]
1066
+ folders += [f for f in fs if f and f not in folders]
1067
+ places += [p for p in ps if p not in places]
1068
+ memo[("rf", path, tuple(bases))] = real_folders
1069
+ return folders, places
1070
+
1071
+
1072
+ def _code_starts(real_folders: Sequence[str],
1073
+ env: Optional[Mapping[str, str]] = None) -> List[Tuple[str, Optional[int], str]]:
1074
+ """Where the walk of code roots starts: each code folder of each Claude folder, where it
1075
+ really leads, and the plugin folders Claude Code may keep elsewhere
1076
+ (CLAUDE_CODE_PLUGIN_CACHE_DIR, CLAUDE_CODE_PLUGIN_SEED_DIR)."""
1077
+ env = os.environ if env is None else env
1078
+ out: List[Tuple[str, Optional[int], str]] = []
1079
+ for real in real_folders:
1080
+ for n in CODE_DIRS:
1081
+ c = os.path.join(real, n)
1082
+ if os.path.isdir(c):
1083
+ out.append((os.path.realpath(c), _PLUGIN_DEPTH if n == "plugins" else None,
1084
+ c if os.path.islink(c) else ""))
1085
+ for k in ("CLAUDE_CODE_PLUGIN_CACHE_DIR", "CLAUDE_CODE_PLUGIN_SEED_DIR"):
1086
+ v = env.get(k) or ""
1087
+ if v.startswith("/") and os.path.isdir(v):
1088
+ # the like of plugins/cache: MARKETPLACE/PLUGIN/VERSION
1089
+ out.append((os.path.realpath(v), _PLUGIN_DEPTH - 1, f"${k}"))
1090
+ return out
1091
+
1092
+
1093
+ def code_roots(real_folders: Sequence[str], env: Optional[Mapping[str, str]] = None,
1094
+ memo: Optional[Dict[Any, Any]] = None, home: str = ""
1095
+ ) -> "Tuple[List[Tuple[str, str]], List[Tuple[str, str, str]]]":
1096
+ """The one list of what Claude Code runs as code, below the given Claude folders
1097
+ (`_code_walk`: the roots, and the notes `doctor` gives), kept in `memo` for one call. Read
1098
+ by the hook and by `doctor`."""
1099
+ memo = {} if memo is None else memo
1100
+ key = ("roots", tuple(real_folders))
1101
+ if key not in memo:
1102
+ memo[key] = _code_walk(_code_starts(real_folders, env), home)
1103
+ return memo[key]
1104
+
1105
+
1106
+ def code_root_report(project: str, home: str, env: Optional[Mapping[str, str]] = None
1107
+ ) -> "Tuple[List[Tuple[str, str]], List[Tuple[str, str, str]]]":
1108
+ """For `doctor`: (the code roots a session in `project` can write, its shell too, with the
1109
+ link that leads there: those inside `agent_writable(project)` and outside the user config
1110
+ folder, as the file system compares names), and the walk's notes (`_code_walk`)."""
1111
+ from phiward import pathid
1112
+ memo: Dict[Any, Any] = {}
1113
+ _claude_places(os.path.join(project, "x"), home, [project], env, memo)
1114
+ real_folders = memo[("rf", os.path.join(project, "x"), (project,))]
1115
+ roots, notes = code_roots(real_folders, env, memo, home)
1116
+ user = pathid.fold(os.path.realpath(user_dir(home, env))).rstrip("/") + "/"
1117
+ writable = [pathid.fold(w).rstrip("/") + "/" for w in agent_writable(project, home)]
1118
+ out = []
1119
+ for real, via in roots:
1120
+ r = pathid.fold(real).rstrip("/") + "/"
1121
+ if not via or r.startswith(user):
1122
+ continue
1123
+ if any(r.startswith(w) for w in writable):
1124
+ out.append((real, via))
1125
+ elif any(w.startswith(r) for w in writable):
1126
+ # it holds this project: Claude Code may run anything in it, so every write here
1127
+ # is asked or refused as code
1128
+ notes.append(("holds", real, via))
1129
+ return out, notes
1130
+
1131
+
1132
+ def writable_code_roots(project: str, home: str,
1133
+ env: Optional[Mapping[str, str]] = None) -> List[Tuple[str, str]]:
1134
+ """The code roots a session in `project` can write (`code_root_report`)."""
1135
+ return code_root_report(project, home, env)[0]
1136
+
1137
+
1138
+ def claude_place(path: str, home: str, bases: Sequence[str] = (),
1139
+ env: Optional[Mapping[str, str]] = None,
1140
+ memo: Optional[Dict[Any, Any]] = None) -> str:
1141
+ """What `path` (absolute) is to Claude Code: "settings" (a settings file), "code" (one it
1142
+ runs as code: `CODE_DIRS`, `CODE_FILES`) or "". Below a `.claude` folder by name (any, but
1143
+ its `worktrees`), below a Claude config folder by what it is, or at one of its settings and
1144
+ code places where they really lead (`_claude_places`)."""
1145
+ def kind(rel: List[str]) -> str:
1146
+ if not rel or rel[0] == "worktrees":
1147
+ return ""
1148
+ if len(rel) == 1 and rel[0] in SETTINGS_NAMES:
1149
+ return "settings"
1150
+ return "code" if _code_rel(rel) else ""
1151
+ memo = {} if memo is None else memo
1152
+ key = ("cp", path, tuple(bases))
1153
+ if key in memo:
1154
+ return memo[key]
1155
+ memo[key] = _claude_place(path, home, bases, env, memo, kind)
1156
+ return memo[key]
1157
+
1158
+
1159
+ def _claude_place(path: str, home: str, bases: Sequence[str],
1160
+ env: Optional[Mapping[str, str]], memo: Dict[Any, Any], kind: Any) -> str:
1161
+ found = ""
1162
+ folders, places = _claude_places(path, home, bases, env, memo)
1163
+ roots, _notes = code_roots(memo[("rf", path, tuple(bases))], env, memo, home)
1164
+ rkey = ("rootset", tuple(r for r, _v in roots))
1165
+ if rkey not in memo:
1166
+ memo[rkey] = {f.rstrip("/") for r, _v in roots for f in _spellings_memo(r, memo)}
1167
+ rootset = memo[rkey]
1168
+ for v in _spellings_memo(path, memo):
1169
+ # the path, or a folder above it, is a code root: O(depth)
1170
+ d = v
1171
+ while d and d != "/":
1172
+ if d in rootset:
1173
+ found = found or "code"
1174
+ break
1175
+ d = d.rsplit("/", 1)[0]
1176
+ parts = v.split("/")
1177
+ for i, c in enumerate(parts[:-1]):
1178
+ if c == ".claude":
1179
+ found = found or kind(parts[i + 1:])
1180
+ for f in folders:
1181
+ if v.startswith(f + "/"):
1182
+ found = found or kind(v[len(f) + 1:].split("/"))
1183
+ for place, k, is_dir in places:
1184
+ if v == place or (is_dir and v.startswith(place + "/")):
1185
+ if k == "settings":
1186
+ return k
1187
+ found = found or k
1188
+ if found == "settings":
1189
+ return found
1190
+ return found
1191
+
1192
+
1193
+ def code_place(path: str, home: str, env: Optional[Mapping[str, str]] = None) -> bool:
1194
+ """Whether `path` (absolute) is one Claude Code runs as code (`claude_place`)."""
1195
+ return claude_place(path, home, (), env) == "code"
1196
+
1197
+
1198
+ def memory_places(home: str, env: Optional[Mapping[str, str]] = None) -> List[str]:
1199
+ """Where Claude Code itself writes its memory and plans (the file tools may write there in
1200
+ any mode): `projects/*/memory`, `agent-memory` and `plans` under the user config folder, and
1201
+ `autoMemoryDirectory` and `plansDirectory` of the user and managed settings (never a
1202
+ project's, which the agent can write) unless one is the home folder or above it. Real paths;
1203
+ a `*` stands for one name."""
1204
+ base = user_dir(home, env)
1205
+ out = [os.path.join(base, "projects", "*", "memory"), os.path.join(base, "agent-memory"),
1206
+ os.path.join(base, "plans")]
1207
+ lv = levels(None, home, env)
1208
+ for key in ("autoMemoryDirectory", "plansDirectory"):
1209
+ v = _first(lv, key)
1210
+ if not isinstance(v, str) or not v.strip():
1211
+ continue
1212
+ v = home + v[1:] if v == "~" or v.startswith("~/") else v
1213
+ if not v.startswith("/"):
1214
+ continue
1215
+ real = os.path.realpath(v)
1216
+ h = os.path.realpath(home)
1217
+ if real == h or h.startswith(real.rstrip("/") + "/") or real == "/":
1218
+ continue
1219
+ out.append(real)
1220
+ return [os.path.realpath(o) if "*" not in o else o for o in out]
1221
+
1222
+
1223
+ def _temp_roots() -> List[str]:
1224
+ """The temp folders Claude Code's sandbox lets the agent write."""
1225
+ import tempfile
1226
+ return [tempfile.gettempdir(), "/tmp"]
1227
+
1228
+
1229
+ def agent_writable(project: str, home: str) -> List[str]:
1230
+ """The folders Claude Code lets the agent write, from its own settings (as its sandbox reads
1231
+ them): the project, the temp folders, phiward's spool, `sandbox.filesystem.allowWrite` (a
1232
+ pattern: its fixed part) and `permissions.additionalDirectories`. Real paths."""
1233
+ lv = levels(project, home)
1234
+ roots = [project, config.spool_dir()] + _temp_roots()
1235
+ for p in _paths(lv, project, home, None, "allowWrite", deny=False):
1236
+ cut = min([p.index(c) for c in "*?[" if c in p] or [len(p)])
1237
+ roots.append(p if cut == len(p) else os.path.dirname(p[:cut]))
1238
+ for d in _merged_list(lv, "permissions", "additionalDirectories"):
1239
+ d = str(d)
1240
+ roots.append(os.path.join(project, d) if not d.startswith(("/", "~")) else
1241
+ os.path.expanduser(d.replace("~", home, 1) if d.startswith("~/") else d))
1242
+ out: List[str] = []
1243
+ for r in roots:
1244
+ real = os.path.realpath(r)
1245
+ if r and real not in out:
1246
+ out.append(real)
1247
+ return out
1248
+
1249
+
1250
+ # the folders under the home folder from which your own tools start programs later (login items,
1251
+ # user services, shell and editor settings, a PATH folder): a session whose sandbox may write one
1252
+ # of them is not confined, and a file tool asks before it writes there
1253
+ STARTUP_PLACES = (".config", ".local/bin", "Library/LaunchAgents")
1254
+
1255
+
1256
+ def startup_write_problem(root: str, home: str) -> str:
1257
+ """Why the write place `root` reaches files that start programs later, or "": the home folder
1258
+ or a folder above it, or a STARTUP_PLACES folder, a folder inside one, or one above it under
1259
+ the home folder (`~/.local`, `~/Library`)."""
1260
+ from phiward import pathid
1261
+ r = pathid.fold(os.path.realpath(root)).rstrip("/") or "/"
1262
+ h = pathid.fold(os.path.realpath(home)).rstrip("/")
1263
+ if h == r or h.startswith(r + "/") or r == "/":
1264
+ return "it is your home folder or above it"
1265
+ for s in STARTUP_PLACES:
1266
+ place = pathid.fold(os.path.join(h, s))
1267
+ if r == place or r.startswith(place + "/") or (
1268
+ place.startswith(r + "/") and r.startswith(h + "/")):
1269
+ return f"it holds ~/{s}, where programs that start later are set up"
1270
+ return ""
1271
+
1272
+
1273
+ def session_write_places(project: str, home: str) -> List[str]:
1274
+ """The write places a session's own settings give: the project, `allowWrite` and
1275
+ `additionalDirectories` (not phiward's spool or the temp folders). Real paths."""
1276
+ skip = {os.path.realpath(p) for p in [config.spool_dir()] + _temp_roots()}
1277
+ return [w for w in agent_writable(project, home)
1278
+ if w not in skip or os.path.realpath(w) == os.path.realpath(project)]
1279
+
1280
+
1281
+ def agent_writable_anywhere(home: str) -> List[str]:
1282
+ """The folders the agent's sandbox may write in every project, as far as they are known
1283
+ without one (the broker's PATH): the spool, and the allowWrite and additionalDirectories
1284
+ entries of the managed and user settings that are absolute paths (a relative one would be
1285
+ resolved against a project, which is not known here). Real paths. The temp folders are
1286
+ `_temp_roots`."""
1287
+ lv = levels(None, home)
1288
+ roots = [config.spool_dir()]
1289
+ for p in _paths(lv, "", home, None, "allowWrite", deny=False):
1290
+ cut = min([p.index(c) for c in "*?[" if c in p] or [len(p)])
1291
+ roots.append(p if cut == len(p) else os.path.dirname(p[:cut]))
1292
+ for d in _merged_list(lv, "permissions", "additionalDirectories"):
1293
+ d = str(d)
1294
+ roots.append(home + d[1:] if d == "~" or d.startswith("~/") else d)
1295
+ out: List[str] = []
1296
+ for r in roots:
1297
+ if r.startswith("/"):
1298
+ real = os.path.realpath(r)
1299
+ if real not in out:
1300
+ out.append(real)
1301
+ return out
1302
+
1303
+
1304
+ def inside(path: str, roots: List[str]) -> bool:
1305
+ """Whether `path` (as it really leads) is one of `roots` or inside one."""
1306
+ real = os.path.realpath(path)
1307
+ return any(real == r or real.startswith(r.rstrip("/") + "/") for r in roots)