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
phiward/doctor.py ADDED
@@ -0,0 +1,1132 @@
1
+ """`phiward doctor`: what is configured, whether it loads, and what may turn the guards off.
2
+
3
+ It reads settings files and never writes them. Paths from the config are shown only as counts,
4
+ unless `--show-paths` is given (this output may reach the model).
5
+ """
6
+
7
+ import json
8
+ import os
9
+ import re
10
+ import sys
11
+ from dataclasses import dataclass, field
12
+ from typing import Any, Dict, List, Optional, Tuple
13
+
14
+ from phiward import claude_settings, config, install, pathid
15
+
16
+
17
+ def _hook_words(h: Dict[str, Any]) -> List[str]:
18
+ import shlex
19
+ try:
20
+ return shlex.split(str(h.get("command", ""))) + [str(a) for a in h.get("args", []) or []]
21
+ except ValueError:
22
+ return []
23
+
24
+
25
+ _PYTHON_NAME = re.compile(r"python(?:3(?:\.\d+)?t?)?")
26
+
27
+
28
+ def hook_form(h: Dict[str, Any]) -> str:
29
+ """Which phiward hook an entry is, by its exact shape only: "isolated" (what
30
+ `install --user` writes: `install.isolated_command`), "launcher" (an older user form: an
31
+ absolute `.../phiward hook claude`, or a Python with `-I` and no clean-up of the loader
32
+ variables), "project" (`install --project` and the plugin: phiward by name), or "" (not
33
+ phiward's guard, whatever it mentions; not a command hook; not run by sh)."""
34
+ if h.get("type", "command") != "command" or h.get("shell") not in (None, "bash"):
35
+ return ""
36
+ if h.get("args"):
37
+ # the exec form an older phiward wrote with its shell prefix: the same isolated command
38
+ py = install.isolated_python(install._entry_text(h))
39
+ return "isolated" if py and _PYTHON_NAME.fullmatch(os.path.basename(py)) else ""
40
+ command = str(h.get("command", ""))
41
+ if command == install.PROJECT_HOOK or command in install.OLD_PROJECT_HOOKS:
42
+ return "project"
43
+ py = install.isolated_python(command)
44
+ if py:
45
+ if not _PYTHON_NAME.fullmatch(os.path.basename(py)):
46
+ return ""
47
+ # only this install's own Python: another environment's (an older phiward in a project
48
+ # venv) runs its own phiward, whatever its interpreter is
49
+ return "isolated" if _same_folder(py, sys.executable) else "launcher"
50
+ words = _hook_words(h)
51
+ if len(words) == 3 and words[0].startswith("/") and words[1:] == ["hook", "claude"] \
52
+ and os.path.basename(words[0]) in config.PROGRAMS:
53
+ return "launcher"
54
+ if len(words) == 6 and words[0].startswith("/") and words[1:] == [
55
+ "-I", "-m", "phiward", "hook", "claude"] \
56
+ and _PYTHON_NAME.fullmatch(os.path.basename(words[0])):
57
+ return "launcher"
58
+ return ""
59
+
60
+
61
+ def _same_folder(a: str, b: str) -> bool:
62
+ """Whether two programs sit in the same folder (by device and inode of the folder)."""
63
+ try:
64
+ x, y = os.stat(os.path.dirname(a)), os.stat(os.path.dirname(b))
65
+ except OSError:
66
+ return False
67
+ return (x.st_dev, x.st_ino) == (y.st_dev, y.st_ino)
68
+
69
+
70
+ def _program_there(h: Dict[str, Any]) -> bool:
71
+ import shutil
72
+ first = install.isolated_python(str(h.get("command", ""))) or (_hook_words(h) or [""])[0]
73
+ if h.get("command") in (install.PROJECT_HOOK, install.PROJECT_NOTE) + install.OLD_PROJECT_HOOKS:
74
+ first = "phiward" # the project hook: phiward by name
75
+ if "/" in first:
76
+ return os.path.isfile(first) and os.access(first, os.X_OK)
77
+ return shutil.which(first) is not None
78
+
79
+
80
+ @dataclass
81
+ class Wiring:
82
+ """What Claude Code's settings files say about phiward's hook, for `doctor` and its
83
+ `--headless` check. `problems` are the reasons a session here would not be guarded;
84
+ `isolated` whether the user or managed settings run the isolated hook (`hook_form`)."""
85
+ lines: List[str] = field(default_factory=list)
86
+ problems: List[str] = field(default_factory=list)
87
+ wired: bool = False
88
+ isolated: bool = False
89
+
90
+
91
+ def wiring_state(project: str, home: str) -> Wiring:
92
+ w = Wiring()
93
+ wired_levels: List[str] = []
94
+ disable: Optional[Tuple[str, bool]] = None # the highest level that sets it wins
95
+ covered: set = set()
96
+ isolated: set = set() # matchers the user or managed settings run the isolated hook for
97
+ bare_name = False
98
+ managed_only = False
99
+ lv = claude_settings.levels(project, home)
100
+ for level, path, _ in lv:
101
+ data, err = claude_settings.read_settings(path)
102
+ if err:
103
+ w.lines.append(f" {level}: {path} cannot be read ({err})")
104
+ w.problems.append(f"the {level} settings file {path} cannot be read as JSON, so "
105
+ "what it sets (hooks, the sandbox) cannot be checked")
106
+ continue
107
+ if data is None:
108
+ continue
109
+ mine = [(g, h, form) for g in (data.get("hooks", {}) or {}).get("PreToolUse", []) or []
110
+ if isinstance(g, dict) for h in g.get("hooks", []) or [] if isinstance(h, dict)
111
+ for form in [hook_form(h)] if form]
112
+ if mine:
113
+ wired_levels.append(level)
114
+ blocks = all(h.get("onFailure") == "block" for _g, h, _f in mine)
115
+ note = "phiward wired" + ("" if blocks else ", WITHOUT onFailure: block")
116
+ if not blocks:
117
+ w.problems.append(f"a phiward hook entry in the {level} settings has no "
118
+ "onFailure: block (a hook that fails lets the tool run)")
119
+ for _g, h, form in mine:
120
+ if not _program_there(h):
121
+ w.problems.append(f"a phiward hook in the {level} settings names a program "
122
+ "that is not there")
123
+ if h.get("async") or h.get("asyncRewake") or "if" in h:
124
+ w.problems.append(f"a phiward hook entry in the {level} settings has "
125
+ "`async` or `if`, so it does not decide every tool call")
126
+ bare_name = bare_name or form == "project"
127
+ if level in ("user", "managed") and form == "isolated":
128
+ isolated.add(str(_g.get("matcher", "")))
129
+ covered |= {str(g.get("matcher", "")) for g, _h, _f in mine}
130
+ elif level == "project local" and isinstance(data.get("sandbox"), dict):
131
+ note = "this machine's entries for the sandbox and rules (personal, not committed)"
132
+ elif level == "project" and isinstance(data.get("sandbox"), dict):
133
+ note = "sandbox and permission rules (hooks come from your user wiring)"
134
+ else:
135
+ note = "phiward not wired"
136
+ w.lines.append(f" {level}: {path}: {note}")
137
+ if disable is None and "disableAllHooks" in data:
138
+ disable = (level, bool(data["disableAllHooks"]))
139
+ if level == "managed" and data.get("allowManagedHooksOnly") is True:
140
+ managed_only = True
141
+ read = {p for _l, p, _d in lv}
142
+ for f in claude_settings.project_files(project, home):
143
+ data = claude_settings.read_settings(f)[0] if f not in read else None
144
+ if data and data.get("disableAllHooks") is True:
145
+ w.problems.append(f"disableAllHooks is true in {f}, a settings file Claude Code "
146
+ "may read")
147
+ if disable and disable[1]:
148
+ w.lines.append(f" WARNING: disableAllHooks is true at the {disable[0]} level: user and "
149
+ "project hooks do not run (managed hooks still do).")
150
+ if "managed" not in wired_levels:
151
+ w.problems.append(f"disableAllHooks is true at the {disable[0]} level")
152
+ if managed_only and "managed" not in wired_levels:
153
+ w.problems.append("managed settings allow only managed hooks, and they do not run phiward")
154
+ on, level, off, path = install.plugin_state(project, home)
155
+ if on:
156
+ w.lines.append(f" the phiward plugin is enabled ({level} settings): it carries hooks")
157
+ bare_name = True # the plugin's hooks run `phiward` by name
158
+ if level in ("user", "managed"):
159
+ wired_levels.append(level)
160
+ if off:
161
+ w.lines.append(" WARNING: this project's settings turn the phiward plugin off: only "
162
+ "your user wiring's own hooks guard this project")
163
+ if path:
164
+ w.lines.append(" WARNING: this project's settings set env.PATH: the plugin's hooks run "
165
+ "`phiward` by name, so the project could choose the program")
166
+ if bare_name:
167
+ w.problems.append("the project's settings set env.PATH, and a hook runs `phiward` "
168
+ "by name")
169
+ w.wired = bool(wired_levels) or on
170
+ w.isolated = any(m in isolated for m in install.ALL_TOOLS)
171
+ if not w.wired:
172
+ w.lines.append(" WARNING: no Claude Code settings file runs phiward "
173
+ "(see `phiward install claude`).")
174
+ w.problems.append("Claude Code is not wired: no settings file or plugin runs phiward's "
175
+ "hook (`(cd ~ && phiward install claude --user --write)`)")
176
+ else:
177
+ if not any(m in covered for m in install.ALL_TOOLS) and not on:
178
+ w.problems.append("phiward's hook covers only some tools (an older install): run "
179
+ "`(cd ~ && phiward install claude --user --write)`")
180
+ if not any(lv in ("user", "managed") for lv in wired_levels):
181
+ # found in practice: a session opened on the folder above the project loaded none
182
+ # of the project's settings, so nothing guarded it
183
+ w.lines.append(" WARNING: only this project is wired: a session opened in any other "
184
+ "folder (a parent folder, another checkout) has no protection. Wire "
185
+ "your user settings too: `(cd ~ && phiward install claude --user --write)`.")
186
+ return w
187
+
188
+
189
+ def claude_report(project: str, home: str) -> List[str]:
190
+ return wiring_state(project, home).lines
191
+
192
+
193
+ def _merged_rules(project: str, home: str) -> List[str]:
194
+ out: List[str] = []
195
+ for _, path, _ in claude_settings.levels(project, home):
196
+ data, _err = claude_settings.read_settings(path)
197
+ if isinstance(data, dict):
198
+ perms = data.get("permissions")
199
+ if isinstance(perms, dict) and isinstance(perms.get("deny"), list):
200
+ out += [r for r in perms["deny"] if isinstance(r, str)]
201
+ return out
202
+
203
+
204
+ def mcp_servers(project: str, home: str) -> List[Tuple[str, bool]]:
205
+ """(name, wrapped) for every MCP server in the user's and the project's MCP config
206
+ (mcp_config.servers)."""
207
+ from phiward import mcp_config
208
+ return [(s.name, s.wrapped) for s in mcp_config.servers(project, home).values()]
209
+
210
+
211
+ def bare_split(project: str, home: str) -> Tuple[List[str], List[Tuple[str, str]]]:
212
+ """The servers that run with the operator's rights: (names `phiward mcp wrap` can change,
213
+ [(name, why it cannot be wrapped)]), by `mcp_config.entry_state`, the answer `mcp list`,
214
+ `wrap` and the hook's advice give too."""
215
+ from phiward import mcp_config
216
+ states = mcp_config.name_states(project, home)
217
+ can, cannot = [], []
218
+ for n, w in mcp_servers(project, home):
219
+ if w or n.startswith("\0"):
220
+ continue # an unreadable file is named by mcp_config.problems
221
+ why = mcp_config.cannot_wrap_why(states.get(n, set()))
222
+ if why:
223
+ cannot.append((n, why))
224
+ else:
225
+ can.append(n)
226
+ return sorted(can), sorted(cannot)
227
+
228
+
229
+ def install_lines() -> List[str]:
230
+ """doctor's lines for how phiward itself is installed: a shared environment, and the
231
+ self-check. Setup does not change them, so they show before setup too."""
232
+ out = []
233
+ if os.path.isdir(os.path.join(sys.prefix, "conda-meta")) or \
234
+ os.path.basename(sys.prefix).lower() in ("anaconda3", "miniconda3", "mambaforge",
235
+ "miniforge3"):
236
+ # its folder is a guard file: the agent may not change it, so a shared environment
237
+ # (conda base) becomes read-only for the agent's own package installs
238
+ out.append("WARNING: phiward is installed in a shared Python environment ("
239
+ f"{os.path.basename(sys.prefix)}); its folder is protected from the agent, so "
240
+ "the agent cannot install packages there. Install phiward with `uv tool "
241
+ "install` or `pipx` instead (see docs/setup.md).")
242
+ return out + selfcheck_lines()
243
+
244
+
245
+ def selfcheck_lines() -> List[str]:
246
+ """doctor's lines for phiward's self-check and its full check of phiward's own Python: one
247
+ WARNING for the package (what `launch` and every wrapped MCP server check before they start,
248
+ and refuse), one for the rest of its Python (which another account could change), each with
249
+ its own step."""
250
+ from phiward import selfcheck
251
+ try:
252
+ installed, package, python = selfcheck.check_full_isolated()
253
+ except Exception as exc: # noqa: BLE001 - doctor reports; it does not stop
254
+ return [f"WARNING: phiward's self-check could not run ({type(exc).__name__})"]
255
+ if not installed:
256
+ return []
257
+ out = []
258
+ here = selfcheck._running_package()
259
+ if package and selfcheck._kind(package[0]) == selfcheck.K_NO_ANSWER:
260
+ # doctor ran the full check; `launch` runs a shorter one, which may answer
261
+ return [f"WARNING: {selfcheck.refusal(package)}: " + selfcheck.fix_text(package, here)]
262
+ if package:
263
+ out.append(f"WARNING: {selfcheck.refusal(package)}, so `phiward launch` and every "
264
+ "wrapped MCP server refuse to start: " + selfcheck.fix_text(package, here))
265
+ # each WARNING its own step, from its own whole list (the package's is what `launch` says);
266
+ # the second only when its step differs, with the lines that step fixes
267
+ step = selfcheck.fix_text(python, here)
268
+ if any(p != selfcheck.MORE for p in python) and \
269
+ (not package or step != selfcheck.fix_text(package, here)):
270
+ out.append("WARNING: phiward's Python can be changed by another account (" +
271
+ selfcheck._listed(python) + "): " + step)
272
+ return out
273
+
274
+
275
+ def path_risks(project: str, home: str, path: str) -> List[Tuple[str, str, int]]:
276
+ """(entry name, program, how many folders) for each MCP entry that names its program without
277
+ a path, when `path` (Claude Code's PATH) has folders the agent can write before the folder
278
+ where the program is found: a relative or empty entry (Claude Code's own folder), or one
279
+ inside `agent_writable`."""
280
+ from phiward import mcp_config
281
+ roots = claude_settings.agent_writable(project, home)
282
+ out: List[Tuple[str, str, int]] = []
283
+ for e in mcp_config.entries(project, home):
284
+ if e.state in ("remote", "here", "no-command") or not isinstance(e.spec, dict):
285
+ continue
286
+ cmd = mcp_config._command(e.spec)
287
+ if not cmd or not cmd[0] or "/" in cmd[0]:
288
+ continue
289
+ bad = 0
290
+ for d in path.split(":"):
291
+ if not d.startswith("/"):
292
+ bad += 1 # relative to the folder Claude Code runs in, the project
293
+ continue
294
+ if claude_settings.inside(d, roots):
295
+ bad += 1
296
+ continue
297
+ if os.access(os.path.join(d, cmd[0]), os.X_OK) and \
298
+ os.path.isfile(os.path.join(d, cmd[0])):
299
+ break
300
+ if bad:
301
+ out.append((e.name, cmd[0], bad))
302
+ return out
303
+
304
+
305
+ # the settings keys whose value is a command Claude Code runs with your rights
306
+ _COMMAND_KEYS = ("apiKeyHelper", "awsAuthRefresh", "awsCredentialExport", "otelHeadersHelper")
307
+
308
+
309
+ def _settings_commands(data: Dict[str, Any]) -> List[Tuple[str, str]]:
310
+ """(where, command) for each command a settings file makes Claude Code run."""
311
+ out: List[Tuple[str, str]] = []
312
+ hooks = data.get("hooks") if isinstance(data.get("hooks"), dict) else {}
313
+ for event, groups in hooks.items():
314
+ for g in groups if isinstance(groups, list) else []:
315
+ for h in (g.get("hooks") if isinstance(g, dict) else None) or []:
316
+ if isinstance(h, dict) and isinstance(h.get("command"), str):
317
+ out.append((f"a {event} hook", h["command"]))
318
+ for key in ("statusLine", "fileSuggestion"):
319
+ v = data.get(key)
320
+ if isinstance(v, dict) and isinstance(v.get("command"), str):
321
+ out.append((key, v["command"]))
322
+ for key in _COMMAND_KEYS:
323
+ if isinstance(data.get(key), str):
324
+ out.append((key, data[key]))
325
+ return out
326
+
327
+
328
+ def _script_files(command: str, project: str, home: str) -> List[str]:
329
+ """The files a command runs: its first word, and when that is a launcher (`sh`, `node`,
330
+ `python3`...: config.LAUNCHERS) each later word that is an existing file. `~` and
331
+ `$CLAUDE_PROJECT_DIR` expanded, a relative path taken in the project (where Claude Code
332
+ runs hooks); a word with `${CLAUDE_PLUGIN_ROOT}` (a plugin's own folder) and a bare name (a
333
+ PATH lookup, which differs per terminal) are left out."""
334
+ import shlex
335
+ try:
336
+ words = shlex.split(command)
337
+ except ValueError:
338
+ return []
339
+ out: List[str] = []
340
+ # `env [VAR=x]... [-opts] PROGRAM ...`: the program is what runs; `-u VAR`, `-C DIR` and
341
+ # `-P PATH` take a word, `-S STRING` is split into words
342
+ while words and os.path.basename(words[0]) == "env":
343
+ words = words[1:]
344
+ while words and ("=" in words[0] or words[0].startswith("-")):
345
+ w, words = words[0], words[1:]
346
+ if w == "--":
347
+ break
348
+ if w in ("-S", "--split-string") and words:
349
+ try:
350
+ words = shlex.split(words[0]) + words[1:]
351
+ except ValueError:
352
+ return []
353
+ elif w.startswith("-S") and not w.startswith("--"):
354
+ try:
355
+ words = shlex.split(w[2:]) + words
356
+ except ValueError:
357
+ return []
358
+ elif w in ("-u", "-C", "-P", "--unset", "--chdir") and words:
359
+ words = words[1:]
360
+
361
+ def place(w: str) -> str:
362
+ if "CLAUDE_PLUGIN_ROOT" in w:
363
+ return ""
364
+ for var in ("${CLAUDE_PROJECT_DIR}", "$CLAUDE_PROJECT_DIR"):
365
+ w = w.replace(var, project)
366
+ for var in ("${HOME}", "$HOME"):
367
+ w = w.replace(var, home)
368
+ if w == "~" or w.startswith("~/"):
369
+ w = home + w[1:]
370
+ if "/" not in w or "$" in w:
371
+ return ""
372
+ return w if w.startswith("/") else os.path.join(project, w)
373
+
374
+ first = place(words[0]) if words else ""
375
+ if first and os.path.isfile(first):
376
+ out.append(first)
377
+ if words and config.runs_other_code(words[0]):
378
+ for w in words[1:]:
379
+ # a launcher's argument names a file, also with no `/` (`python3 x.py`)
380
+ p = place(w) or (os.path.join(project, w) if "/" not in w and "$" not in w
381
+ and not w.startswith("-") and "CLAUDE_PLUGIN_ROOT" not in w else "")
382
+ if p and os.path.isfile(p) and p not in out:
383
+ out.append(p)
384
+ return out
385
+
386
+
387
+ def init_lines(project: str, home: str) -> List[str]:
388
+ """A NOTE in a project (a git work tree other than the home folder) whose own settings do
389
+ not deny the shell its Claude Code settings (`phiward init`, `install --project`)."""
390
+ if os.path.realpath(project) == os.path.realpath(home) or \
391
+ not os.path.exists(os.path.join(project, ".git")):
392
+ return []
393
+ data, _why = claude_settings.read_settings(os.path.join(project, ".claude", "settings.json"))
394
+ deny = (((data or {}).get("sandbox") or {}).get("filesystem") or {}).get("denyWrite") or []
395
+ if "./.claude/settings.json" in deny:
396
+ return []
397
+ return [" NOTE: this project is not set up with `phiward init`: a shell command here could "
398
+ "rewrite its Claude Code settings (your user wiring's hook still checks every tool "
399
+ "call); run `phiward init` in it (it writes an AGENTS.md section, a .gitignore line, "
400
+ ".claude/settings.json and git hooks)"]
401
+
402
+
403
+ def settings_script_lines(project: str, home: str) -> List[str]:
404
+ """doctor's lines for what Claude Code's settings make it run: a script a session in
405
+ `project` can write (its shell too), a WARNING with its step (into the user folder's
406
+ `hooks/`, or, when a session here can write that too, a project folder to work in); a
407
+ PermissionRequest hook, a NOTE (it can answer the prompts phiward's hook asks for code
408
+ files and writes outside the sandbox's folders). phiward's own hooks are left out."""
409
+ writable = [pathid.fold(w).rstrip("/") + "/" for w in
410
+ claude_settings.agent_writable(project, home)]
411
+ hooks_dir = os.path.join(claude_settings.user_dir(home), "hooks")
412
+ shown_dir = "~" + hooks_dir[len(home):] if pathid.inside(hooks_dir, home) else hooks_dir
413
+ if any((pathid.fold(os.path.realpath(hooks_dir)) + "/").startswith(w) for w in writable):
414
+ step = (f"a session in {project} can write {shown_dir} too: start Claude Code in a "
415
+ "project folder, not here")
416
+ else:
417
+ step = (f"move it into `{shown_dir}/` (your user folder, which no session in a project "
418
+ "writes) and name it there")
419
+ out: List[str] = []
420
+ seen = set()
421
+ for level, path, data in claude_settings.levels(project, home):
422
+ if not isinstance(data, dict):
423
+ continue
424
+ hooks = data.get("hooks") if isinstance(data.get("hooks"), dict) else {}
425
+ if hooks.get("PermissionRequest"):
426
+ out.append(f" NOTE: the {level} settings ({path}) have a PermissionRequest hook: it "
427
+ "can answer the prompts phiward's hook asks (code files, writes outside "
428
+ "the sandbox's folders) without you; know what it allows")
429
+ for where, command in _settings_commands(data):
430
+ if hook_form({"type": "command", "command": command}):
431
+ continue # phiward's own
432
+ for f in _script_files(command, project, home):
433
+ real = os.path.realpath(f)
434
+ key = pathid.fold(real)
435
+ if key in seen:
436
+ continue
437
+ seen.add(key)
438
+ if not any((key + "/").startswith(w) for w in writable):
439
+ continue
440
+ out.append(f" WARNING: {where} in the {level} settings runs {real} with your "
441
+ "rights, and a session in this project can write it, its shell too: "
442
+ + step)
443
+ return out
444
+
445
+
446
+ def code_root_lines(project: str, home: str) -> List[str]:
447
+ """doctor's lines for the code Claude Code runs that a session in `project` can write, its
448
+ shell too (`claude_settings.writable_code_roots`: a skill linked in from the project)."""
449
+ out = []
450
+ roots, notes = claude_settings.code_root_report(project, home)
451
+ if len(roots) > 3:
452
+ out.append(f" WARNING: Claude Code runs {len(roots)} folders as code that a session in "
453
+ "this project can write, its shell too (linked in from "
454
+ + ", ".join(v for _r, v in roots[:3]) + ", ...): open sessions in a folder "
455
+ "that holds none of them")
456
+ else:
457
+ for real, via in roots:
458
+ out.append(f" WARNING: Claude Code runs {real} as code (through the link {via}), "
459
+ "and a session in this project can write it, its shell too: replace the "
460
+ f"link with a copy of {real} (then edit the copy outside such sessions)")
461
+ said = {
462
+ "tree": lambda r, v: (f"Claude Code runs {r} as code" + (f" (through {v})" if v else "")
463
+ + ", which holds too many entries: the links inside it are not "
464
+ "checked; " + ("replace the link with a copy without "
465
+ "`node_modules` or `.git`" if v else
466
+ "move `node_modules` and `.git` out of it")),
467
+ "total": lambda r, v: (f"Claude Code runs {r} as code" + (f" (through {v})" if v else "")
468
+ + ", and its code folders hold too many entries in all for the "
469
+ "links in it to be checked: move the biggest linked skill out"),
470
+ "wide": lambda r, v: (f"the link {v} leads to {r}, which holds your home folder or your "
471
+ "user config folder: Claude Code would run all of it as code; "
472
+ "remove the link"),
473
+ "holds": lambda r, v: (f"the link {v} leads to {r}, which holds this project: Claude Code "
474
+ "may run anything in it as code, so every write here is asked "
475
+ "or refused; remove the link"),
476
+ }
477
+ for why in ("holds", "wide", "tree", "total"):
478
+ group = [(r, v) for w, r, v in notes if w == why]
479
+ if len(group) > 3:
480
+ out.append(f" WARNING: {len(group)} such links ({', '.join(v or r for r, v in group[:3])}"
481
+ f", ...): " + said[why](group[0][0], group[0][1]).split(": ", 1)[-1]
482
+ if why in ("wide", "holds") else
483
+ f" WARNING: {len(group)} code folders hold too many entries for their "
484
+ "links to be checked (" + ", ".join(r for r, _v in group[:3])
485
+ + ", ...): move `node_modules` and `.git` out of them")
486
+ else:
487
+ out += [f" WARNING: {said[why](r, v)}" for r, v in group]
488
+ return out
489
+
490
+
491
+ def path_risk_lines(project: str, home: str) -> List[str]:
492
+ """doctor's lines for `path_risks`, with this shell's PATH (Claude Code's, when it is started
493
+ from here)."""
494
+ from phiward import mcp_config
495
+ lines = []
496
+ for name, prog, n in path_risks(project, home, os.environ.get("PATH", "")):
497
+ lines.append(f" WARNING: MCP server {mcp_config.shown(name)} names "
498
+ f"`{mcp_config.shown(prog)}` without its path, and PATH has {n} folder(s) the "
499
+ "agent can write ahead of "
500
+ "the real one (a project's `.venv/bin`, a relative entry, a folder the "
501
+ "sandbox opens): Claude Code would start a file the agent put there with your "
502
+ "rights. Start Claude Code with those folders off PATH (deactivate the "
503
+ "project's environment), or give the entry the program's full path")
504
+ return lines
505
+
506
+
507
+ def mode_report(project: str, home: str, cfg: "config.Config") -> List[str]:
508
+ """Which mode this session is in and which layers are on."""
509
+ from phiward import hidden
510
+ if int(os.environ.get("PHIWARD_LAUNCH_DEPTH", "0") or 0) > 0:
511
+ return [" mode: B (launch): the whole tool runs in the kernel profile"]
512
+ if wiring_state(project, home).wired:
513
+ lines = [" mode: A (a Claude Code session wired by the hook): Bash in Claude Code's "
514
+ "sandbox, file tools refused by the hook and permission rules (not the kernel)"]
515
+ else:
516
+ lines = [" mode: none: no Claude Code settings file or plugin runs phiward here (run "
517
+ "`(cd ~ && phiward install claude --user --write)`); the layers below are what it would "
518
+ "have"]
519
+ secret = [h for h in hidden.paths(None, cfg, session=True) if os.path.lexists(h)]
520
+ # the same rule as the confinement check (`_covers`: both spellings, the path and where it
521
+ # leads, as the sandbox resolves links: on macOS /tmp is /private/tmp)
522
+ deny_read = claude_settings._paths(claude_settings.levels(project, home), project, home,
523
+ None, "denyRead", deny=True)
524
+ miss = [h for h in secret if not claude_settings._covers(deny_read, h)]
525
+ lines.append(f" hidden list in the sandbox: {len(secret) - len(miss)} of {len(secret)}"
526
+ + ("" if not miss else " (WARNING: run `(cd ~ && phiward install claude --user --write)` again)"))
527
+ rules = set(_merged_rules(project, home))
528
+ want = install.permission_rules(secret, home)
529
+ have = sum(1 for r in want if r in rules)
530
+ lines.append(f" permission rules for the hidden list: {have} of {len(want)}"
531
+ + ("" if have == len(want) else " (WARNING: run `(cd ~ && phiward install claude --user --write)` again)"))
532
+ kind = hidden.non_file_tickets()
533
+ if kind:
534
+ lines.append(f" NOTE: your Kerberos tickets are kept by the system ({kind} cache, the "
535
+ "default on a Mac), not in a file, so a file list cannot hide them; a Bash "
536
+ "command in Claude Code's sandbox may reach them. Most people leave this. "
537
+ "To keep them in a file instead, run `export "
538
+ "KRB5CCNAME=FILE:/tmp/krb5cc_$(id -u)` before `kinit`, in each terminal")
539
+ from phiward import mcp_config
540
+ for why in mcp_config.problems(project, home):
541
+ lines.append(f" WARNING: an MCP config file cannot be read strictly, so its servers count "
542
+ f"as bare: {why}")
543
+ lines += path_risk_lines(project, home)
544
+ lines += code_root_lines(project, home)
545
+ lines += settings_script_lines(project, home)
546
+ lines += init_lines(project, home)
547
+ servers = [(n, w) for n, w in mcp_servers(project, home) if not n.startswith("\0")]
548
+ bare = [n for n, w in servers if not w]
549
+ if servers:
550
+ version = claude_settings.claude_version()
551
+ if version is not None and version < mcp_config.MIN_SOURCE_VERSION:
552
+ lines.append(
553
+ f" WARNING: Claude Code {claude_settings.version_text(version)} does not tell "
554
+ "the hook which server a tool belongs to (from "
555
+ f"{claude_settings.version_text(mcp_config.MIN_SOURCE_VERSION)} on): until you "
556
+ "update it, a server of the project's `.mcp.json` counts as bare, and only your "
557
+ "own config (`~/.claude.json`) can make a server wrapped")
558
+ if servers and len(bare) < len(servers):
559
+ lines.append(" NOTE: the hook trusts a server as wrapped only while it runs under a live "
560
+ "`phiward launch` (its record in ~/.phiward/launched): after `phiward mcp "
561
+ "wrap`, start Claude Code again")
562
+ if os.path.isdir(os.path.join(home, ".phiward", "sessions")):
563
+ lines.append(" NOTE: ~/.phiward/sessions is left from an older phiward and no longer "
564
+ "used; you may remove it: rm -r ~/.phiward/sessions")
565
+ can, cannot = bare_split(project, home)
566
+ if can:
567
+ lines.append(f" WARNING: {len(can)} MCP server(s) run with your full rights (not wrapped "
568
+ f"in `phiward launch --`): {', '.join(can)}. Wrap each in your own "
569
+ "terminal: " + "; ".join(f"`phiward mcp wrap {n}`" for n in can))
570
+ if cannot:
571
+ lines.append(f" WARNING: {len(cannot)} MCP server(s) run with your full rights and cannot "
572
+ "be wrapped by phiward: " + "; ".join(f"{n} ({why})" for n, why in cannot)
573
+ + ". Their command tools may make only gateway calls.")
574
+ if not bare and servers:
575
+ lines.append(f" MCP servers: {len(servers)}, all wrapped or remote")
576
+ return lines
577
+
578
+
579
+ USAGE = "usage: phiward doctor [--verbose] [--show-paths | --headless]\n"
580
+ HELP = USAGE + """
581
+ Options:
582
+ --verbose every check on its own line (by default, before Claude Code is wired, its
583
+ parts are one next step), and the detail counts
584
+ --show-paths also print the protected paths (by default only their counts)
585
+ --headless a short check before an unattended run (`claude -p`, an Agent SDK app, a
586
+ scheduled agent): exit 0 when the session would be guarded, 1 with the
587
+ reasons when not (docs/unattended.md)
588
+ -h, --help show this help
589
+
590
+ Show the config in force and whether it loads, and what may turn the guards off: the
591
+ confinement backend, the sanitizer, the broker, the pinned folders, Claude Code's settings and
592
+ MCP servers. It reads settings files and never writes them. Run it in the project folder.
593
+ The exit status is 1 when the config or the sanitizer cannot be used.
594
+
595
+ Its output may reach the model, so it shows paths only with --show-paths.
596
+ """
597
+
598
+
599
+ _INSTALL = "(cd ~ && phiward install claude --user --write)"
600
+
601
+
602
+ def _pattern_version(cfg: config.Config) -> "Optional[tuple]":
603
+ """The Claude Code version, asked for only where it changes a step: on macOS, with protected
604
+ patterns (install writes their sandbox entries from 2.1.236 on)."""
605
+ if sys.platform != "darwin" or not cfg.patterns:
606
+ return None
607
+ return claude_settings.claude_version()
608
+
609
+
610
+ def _after_install(project: str, home: str, cfg: config.Config,
611
+ hidden: list, version: "Optional[tuple]" = None) -> "Optional[claude_settings.Reason]":
612
+ """Why the shell would still not be confined once `_INSTALL` has written the user wiring
613
+ (with that reason's own step), or None: what stays is in a file install does not change (the
614
+ project's or managed settings), in a setting install never removes, or in the config."""
615
+ from phiward import install
616
+ try:
617
+ path = os.path.join(claude_settings.user_dir(home), "settings.json")
618
+ want = install.merge(claude_settings._read(path) or {},
619
+ install.wiring(cfg, version=version))
620
+ return claude_settings.confinement_reason(project, home, cfg.all_roots, cfg.patterns,
621
+ config.guard_files(), hidden=hidden,
622
+ user_data=want, version=version)
623
+ except Exception as exc: # noqa: BLE001 - doctor reports; a failure here only unfolds a line
624
+ return claude_settings.Reason(f"cannot tell ({type(exc).__name__})",
625
+ "run `phiward doctor --verbose`")
626
+
627
+
628
+ # the lines of doctor's Claude Code section whose only fix, before Claude Code is wired, is
629
+ # `_INSTALL`: one next step stands for them (`--verbose` prints them). A warning with news of
630
+ # its own (an older phiward's prefix, the network limit) is never folded.
631
+ _FOLDED = (" WARNING: no Claude Code settings file runs phiward", " mode: none:",
632
+ " hidden list in the sandbox:", " permission rules for the hidden list:",
633
+ " WARNING: sandbox confines the shell: NO", " NOTE: Claude Code's shell is not pinned",
634
+ " NOTE: no `--settings` file yet")
635
+
636
+
637
+ def main(argv: List[str]) -> int:
638
+ if argv[:1] in (["-h"], ["--help"]):
639
+ sys.stdout.write(HELP)
640
+ return 0
641
+ unknown = [a for a in argv if a not in ("--headless", "--show-paths", "--verbose", "-v")]
642
+ if unknown:
643
+ sys.stderr.write(f"doctor: unknown option {unknown[0]}\n" + HELP)
644
+ return 2
645
+ if "--headless" in argv:
646
+ return headless(os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd(),
647
+ pathid.home())
648
+ show = "--show-paths" in argv
649
+ verbose = "--verbose" in argv or "-v" in argv
650
+ if show and not sys.stdin.isatty():
651
+ # the paths are the operator's to see: an agent tool has no terminal, and what it
652
+ # runs reaches the model
653
+ print("doctor: --show-paths prints the protected paths, so it runs only in your own "
654
+ "terminal. Run `phiward doctor` without it here.", file=sys.stderr)
655
+ return 2
656
+ cwd = os.getcwd()
657
+ home = pathid.home()
658
+ cfg = config.load(cwd)
659
+ from phiward import __version__
660
+ print(f"phiward doctor (phiward {__version__})")
661
+ print(f"config files: {', '.join(cfg.files) if cfg.files else 'none'}")
662
+ if cfg.problem:
663
+ print(f"PROBLEM: {cfg.problem}")
664
+ if show and cfg.problem_detail:
665
+ print(f" detail: {cfg.problem_detail}")
666
+ print("Every guarded action is refused until this is fixed.")
667
+ return 1
668
+ if cfg.ignored:
669
+ print("NOTE: the repo config sets keys that only the user config may set; they are "
670
+ f"ignored: {', '.join(cfg.ignored)}")
671
+ print(f"protected roots: {len(cfg.roots)}, patterns: {len(cfg.patterns)}" + (
672
+ f", derived (cache, .git around a root): {len(cfg.derived_roots)}, "
673
+ f"unresolved: {cfg.unresolved}" if verbose else ""))
674
+ if show:
675
+ for p in cfg.roots + cfg.patterns + cfg.derived_roots:
676
+ print(f" {p}")
677
+ if any(r.endswith("/.git") or r.endswith(".git") for r in cfg.derived_roots):
678
+ print("NOTE: a protected root sits in a git work tree; its .git is protected too, so the "
679
+ "agent cannot use git in that repository.")
680
+ from phiward import confine
681
+ why = confine.self_test()
682
+ print(("" if why is None else "WARNING: ") + f"confinement: {confine.backend() or 'none'}: "
683
+ + ("ok" if why is None else f"NOT WORKING: {why}"))
684
+ if not cfg.has_protected_paths:
685
+ # nothing is set up yet: the one step is setup (it writes the config, wires Claude Code
686
+ # and starts the broker); the wiring and broker lines would point the other way
687
+ print("No protected paths are configured yet, so phiward protects nothing. Next step: "
688
+ "`(cd ~ && phiward setup)` (it writes the config, wires Claude Code and starts the "
689
+ "broker); then run `phiward doctor` again.")
690
+ from phiward import broker as _broker
691
+ if not _broker.read_status(config.spool_dir()):
692
+ # setup cannot fix phiward's own install: its WARNINGs still show
693
+ for line in install_lines():
694
+ print(line)
695
+ return 1 # nothing else applies yet; a running broker is reported below
696
+ from phiward.sanitize import Sanitizer, SanitizerError
697
+ try:
698
+ Sanitizer.from_config(cfg)
699
+ print(f"sanitizer: ok (packs: {', '.join(cfg.packs) or 'default'})")
700
+ except SanitizerError as exc:
701
+ print(f"PROBLEM: the sanitizer cannot start: {exc}")
702
+ return 1
703
+ rel = None
704
+ if cfg.has_protected_paths:
705
+ from phiward import paths
706
+ rel = paths.ProtectedSet(cfg.all_roots, cfg.patterns).relation(cwd)
707
+ if rel:
708
+ print(f"WARNING: this folder is {rel} a protected path: its commands are refused or "
709
+ "denied, except gateway calls (phiward run|copy). Run the agent in a project "
710
+ "folder.")
711
+ from phiward import broker
712
+ spool = config.spool_dir()
713
+ where = broker.running(spool)
714
+ print(("broker: running" + (f" ({where})" if where.startswith("on ") else "")) if where else
715
+ ("WARNING: broker: NOT RUNNING: gateway calls (phiward run|copy) fail until the operator "
716
+ "starts `phiward broker` in a terminal outside the agent, or its login "
717
+ "service (`(cd ~ && phiward broker --service --write)`)"))
718
+ elsewhere = None if broker._alive(spool) else broker.other_spool(spool)
719
+ if elsewhere:
720
+ print(f"WARNING: a broker is running with the spool {elsewhere}; this shell uses {spool} "
721
+ "(check PHIWARD_SPOOL on both sides)")
722
+ from phiward import service
723
+ dropped = service.dropped_path_entries(os.environ.get("PATH", ""))
724
+ if dropped:
725
+ print(f"NOTE: the broker does not search {len(dropped)} folder(s) of this PATH (relative, "
726
+ "writable by others, inside a project, or a folder the agent's sandbox may write: "
727
+ "a temp folder, or one in allowWrite); programs there are 'not on the "
728
+ "broker's PATH'" + (": " + ", ".join(dropped[:5]) if show else
729
+ " (`--show-paths` lists them)"))
730
+ sf = service.service_file()
731
+ try:
732
+ with open(sf, encoding="utf-8") as fh:
733
+ unit = fh.read()
734
+ except OSError:
735
+ unit = ""
736
+ if unit and service.log_folder() not in unit:
737
+ print("WARNING: the broker's login service was written by an older phiward and keeps no "
738
+ "log: run `(cd ~ && phiward broker --service --write)` again")
739
+ st = broker.read_status(spool)
740
+ if st and st.get("config") != config.user_config_path():
741
+ print(f"WARNING: the broker uses the user config {st.get('config', '(none)')}; this shell "
742
+ f"uses {config.user_config_path()} (check PHIWARD_CONFIG on both sides)")
743
+ elif st and (st.get("cache") != cfg.cache_dir or set(st.get("roots", [])) != set(cfg.user_roots)):
744
+ print("WARNING: the broker uses another cache folder or roots than this shell (check "
745
+ "XDG_CACHE_HOME on both sides, and restart the broker after a config change)")
746
+ from phiward import fsinfo, pin
747
+ if cfg.has_protected_paths:
748
+ pinned = set(pin.read_pins())
749
+ found = set(pin.pinnable(cfg))
750
+ if not os.path.exists(pin.pins_path()):
751
+ print("NOTE: no derived protected folders are pinned yet; run `phiward pin` in "
752
+ "your own terminal (it records the git folders, snapshots and other mounts "
753
+ "found now, so a file the agent plants later cannot hide them)")
754
+ elif not pin.pins_readable():
755
+ print("WARNING: pinned.toml cannot be read; nothing is pinned (run phiward pin)")
756
+ else:
757
+ if found - pinned:
758
+ print(f"WARNING: {len(found - pinned)} derived protected folder(s) are found now "
759
+ "but not pinned; check them (doctor --show-paths) and run `phiward pin`")
760
+ if pinned - found:
761
+ print(f"WARNING: {len(pinned - found)} folder(s) are pinned but not found now; "
762
+ "check them (doctor --show-paths) and drop wrong ones with `phiward pin`")
763
+ if show:
764
+ for d in sorted(found - pinned):
765
+ print(f" found, not pinned: {d}")
766
+ for d in sorted(pinned - found):
767
+ print(f" pinned but not found: {d}")
768
+ respelled = [r for r in cfg.user_roots if os.path.exists(r) and
769
+ pathid.canon(r) != os.path.realpath(r)]
770
+ if respelled:
771
+ print(f"WARNING: {len(respelled)} root(s) are written in another spelling than the file "
772
+ "system's own (letter case, Unicode form or /System/Volumes/Data); phiward "
773
+ "covers both, but write the canonical spelling (doctor --show-paths)")
774
+ if show:
775
+ for r in respelled:
776
+ print(f" {r} -> {pathid.canon(r)}")
777
+ hl = fsinfo.hardlinked_count(cfg.roots, cfg.inventory_limit) if cfg.roots else 0
778
+ if hl:
779
+ print(f"WARNING: {hl} protected file(s) have other hard links; path rules cannot cover "
780
+ "those other names (docs/threat-model.md, known gap 9)")
781
+ if any(os.path.basename(d) in fsinfo.SNAPSHOT_NAMES + tuple(cfg.snapshot_names)
782
+ for d in cfg.derived_roots):
783
+ print("NOTE: snapshot folders next to or above a root are protected too (derived roots)")
784
+ print("NOTE: protected roots are read only for gateway commands; they write only in "
785
+ "[broker] write_to folders (which may sit inside a root)")
786
+ print(f"grants: write_to folders: {len(cfg.write_to)}"
787
+ + (f" (skipped: {cfg.write_to_missing} that do not exist yet)" if cfg.write_to_missing else "")
788
+ + (f" (skipped: {cfg.write_to_linked} reached through a link; name the real folder)"
789
+ if cfg.write_to_linked else "")
790
+ + (f" (skipped: {cfg.write_to_claude} that hold a .claude folder)"
791
+ if cfg.write_to_claude else "")
792
+ + f", network: {'yes' if cfg.net else 'no'}, copy remotes: {len(cfg.remotes)}")
793
+ if show:
794
+ for p in cfg.write_to:
795
+ print(f" write_to: {p}")
796
+ if cfg.command_lists:
797
+ n = min(len(x) for x in cfg.command_lists)
798
+ print(f"programs gateway commands may run: only those in [broker] commands "
799
+ f"({n} listed)")
800
+ names = {os.path.basename(e.rstrip("/")) for lst in cfg.command_lists for e in lst
801
+ if not e.startswith("@")}
802
+ runs_code = sorted(n for n in names if config.runs_other_code(n))
803
+ if runs_code:
804
+ print(f"WARNING: {len(runs_code)} listed program(s) can run other code (an "
805
+ "interpreter, a shell, git aliases, find -exec, make and the like): with "
806
+ "them, code the agent writes can run again. List your own scripts instead")
807
+ home = pathid.home()
808
+ from phiward import broker
809
+ mine = [p for p in broker.listed_programs(cfg, broker.command_env().get("PATH", ""))
810
+ if p.startswith(home.rstrip("/") + "/")]
811
+ if mine:
812
+ print(f"NOTE: {len(mine)} listed program(s) are in your home folder (conda, "
813
+ "~/.local/bin): `(cd ~ && phiward install claude --user --write)` protects them from "
814
+ "agent writes, and the broker runs them only as you approved them. After you "
815
+ "update one, check it and run `phiward pin`, then restart the broker")
816
+ if cfg.command_lists:
817
+ from phiward import pin
818
+ bad = [line for line in pin.describe(cfg) if line.endswith(")")]
819
+ if pin.unapproved(cfg):
820
+ print(f"WARNING: {len(pin.unapproved(cfg))} listed program(s) are not approved as "
821
+ "the broker finds them: gateway commands are refused until you check them "
822
+ "and run `phiward pin` in your own terminal, then restart the broker:")
823
+ for line in bad[:20]:
824
+ print(f" {line}")
825
+ else:
826
+ print("WARNING: programs gateway commands may run: any (no [broker] commands list). Code "
827
+ "that the agent writes can run on protected data and print it encoded. Before real "
828
+ "patient data, run `(cd ~ && phiward setup)` in your own terminal and choose 1, or list your "
829
+ "programs (docs/configuration.md)")
830
+ if cfg.ssh_config:
831
+ print("copy: ssh config file " + ("set" if os.path.isfile(cfg.ssh_config) else
832
+ "set, but WARNING: it does not exist"))
833
+ if cfg.write_to or cfg.net or cfg.remotes:
834
+ print("NOTE: a grant gives code the agent chooses that capability. Against an agent you "
835
+ "do not trust, leave write_to and remotes empty and net false.")
836
+ # the operator runs doctor in the project folder; a hook gets $CLAUDE_PROJECT_DIR
837
+ project = os.environ.get("CLAUDE_PROJECT_DIR") or cwd
838
+ for line in install_lines():
839
+ print(line)
840
+ print("Claude Code:")
841
+ # before Claude Code is wired, each part's fix is the same command: one next step (each
842
+ # part is behind --verbose)
843
+ fold = not verbose and not wiring_state(project, home).wired
844
+ if fold:
845
+ print(f" WARNING: Claude Code is not wired to phiward yet. Next step, in your own "
846
+ f"terminal: `{_INSTALL}` (the hook, the sandbox and the permission rules), then "
847
+ "run doctor again. `phiward doctor --verbose` lists each part.")
848
+
849
+ def say(line="", *a, **k):
850
+ if fold and line.startswith(_FOLDED):
851
+ return
852
+ print(line, *a, **k)
853
+
854
+ for line in claude_report(project, home):
855
+ say(line)
856
+ redirect = claude_settings.project_redirects(project, home)
857
+ if redirect:
858
+ say(f" WARNING: {claude_settings.redirect_text(redirect)}: the hook refuses every "
859
+ "tool call until you fix that (it could change what the hook runs or reads).")
860
+ for r in claude_settings.git_redirects(project, home):
861
+ say(" WARNING: " + GIT_REDIRECT.format(r) + ".")
862
+ loader = claude_settings.project_loader_keys(project, home)
863
+ if loader:
864
+ say(" NOTE: this project's Claude Code settings set " + ", ".join(
865
+ "env." + k for k in loader) + ": the hooks clear them before phiward starts, but the "
866
+ "shell that starts a hook loads them first (docs/threat-model.md).")
867
+ clean = clean_start_problem()
868
+ if clean:
869
+ say(f" WARNING: {clean}.")
870
+ for line in sandbox_needs():
871
+ say(line)
872
+ for line in launch_settings_report():
873
+ say(line)
874
+ if cfg.has_protected_paths and not cfg.problem:
875
+ for line in mode_report(project, home, cfg):
876
+ say(line)
877
+ if cfg.has_protected_paths:
878
+ from phiward import hidden as _hidden
879
+ hidden_now = [h for h in _hidden.paths(None, cfg, session=True) if os.path.lexists(h)]
880
+ version = _pattern_version(cfg)
881
+ reason = claude_settings.confinement_reason(
882
+ project, home, cfg.all_roots, cfg.patterns, config.guard_files(), hidden=hidden_now,
883
+ version=version)
884
+ ok, why_not = reason is None, reason.text if reason else ""
885
+ # folded only when the next step fixes it: a cause install does not fix is shown even
886
+ # before Claude Code is wired
887
+ still = None if ok else _after_install(project, home, cfg, hidden_now, version)
888
+ fixed = still is None
889
+ # one fix, the right one: install when it would confine the shell; otherwise the step of
890
+ # what would stay after it (the same step the hook's refusal gives)
891
+ fix = ("" if ok else f". To fix it: {claude_settings.INSTALL_STEP}, or use `phiward "
892
+ "launch`." if fixed else
893
+ f". To fix it: {still.step}" + ("" if still.text == why_not else
894
+ f" ({still.text})") + ".")
895
+ show = say if ok or not fold or fixed else print
896
+ show(" sandbox confines the shell: yes" if ok else
897
+ f" WARNING: sandbox confines the shell: NO ({why_not})" +
898
+ ("; for shell commands only the hook's text check is left, which is best effort"
899
+ if cfg.shell_best_effort else
900
+ "; so the hook refuses shell commands except gateway calls") + fix)
901
+ if claude_settings._env_value(project, home, None, "CLAUDE_CODE_SHELL_PREFIX")[0] == \
902
+ config.shell_prefix_path():
903
+ say(" WARNING: env.CLAUDE_CODE_SHELL_PREFIX names the shell prefix of an older "
904
+ "phiward, which is gone: every shell command fails. Run `phiward install claude "
905
+ "--user --write` again; it removes the setting.")
906
+ say(" Claude Code's shell is /bin/bash: yes"
907
+ if claude_settings.bash_pinned(project, home) else
908
+ " NOTE: Claude Code's shell is not pinned to /bin/bash (env.CLAUDE_CODE_SHELL); "
909
+ "the hook reads commands as bash. `(cd ~ && phiward install claude --user --write)` pins it.")
910
+ blocks = [k for k in ("blockReadsOutsideWorkingDirectories", "denyInsteadOfPrompting")
911
+ if claude_settings._first(claude_settings.levels(project, home),
912
+ "permissions", k) is True]
913
+ say(" read blocking outside the project: " + (", ".join(blocks) or
914
+ "off (optional: `(cd ~ && phiward install claude --user --block-outside-reads --write)`)"))
915
+ if cfg.shell_best_effort:
916
+ say(" WARNING: [shell] best_effort is on: a shell call that Claude Code's sandbox "
917
+ "does not confine gets only the hook's text check, which is best effort "
918
+ "(docs/threat-model.md). Turn it off once the sandbox confines the shell.")
919
+ else:
920
+ say(" shell calls outside Claude Code's sandbox: refused (there only the gateway, "
921
+ "`doctor` and `check` run)")
922
+ allow = claude_settings._merged_list(claude_settings.levels(project, home), "sandbox",
923
+ "filesystem", "allowWrite")
924
+ if ok and not any(os.path.normpath(a.replace("~", home, 1)) in (spool, os.path.dirname(spool))
925
+ for a in allow):
926
+ say(" NOTE: sandbox.filesystem.allowWrite does not hold the spool folder; "
927
+ "gateway calls cannot reach the broker from the sandbox.")
928
+ for line in network_report(project, home, cfg):
929
+ say(line)
930
+ return 0
931
+
932
+
933
+ def clean_start_problem() -> Optional[str]:
934
+ """Why `phiward`, started by name as the plugin and project hooks start it (after
935
+ CLEAN_ENV), does not start, or None (also when it is not on PATH: that is reported on its
936
+ own). A phiward whose Python needs PYTHONPATH or LD_LIBRARY_PATH (a module Python, a
937
+ checkout) stops there, and every tool call is refused."""
938
+ import shutil
939
+ import subprocess
940
+ if not shutil.which("phiward") or not os.access("/bin/sh", os.X_OK):
941
+ return None
942
+ try:
943
+ r = subprocess.run(["/bin/sh", "-c", install.CLEAN_ENV + "exec phiward --help >/dev/null"],
944
+ capture_output=True, text=True, timeout=30, stdin=subprocess.DEVNULL)
945
+ except (OSError, subprocess.TimeoutExpired) as exc:
946
+ return f"phiward could not be started the way the hooks start it ({type(exc).__name__})"
947
+ if r.returncode == 0:
948
+ return None
949
+ gone = sorted(k for k, v in os.environ.items() if install.cleared(k, v))
950
+ return ("phiward does not start once the hooks clear " +
951
+ (", ".join(gone) if gone else "the Python and loader variables") +
952
+ f" (exit {r.returncode}), so the hooks refuse every tool call. Install phiward with "
953
+ "`uv tool install` or `pipx`, whose Python needs none of them (docs/setup.md)")
954
+
955
+
956
+ GIT_REDIRECT = ("git takes this repository's config and hooks from a folder the agent can write "
957
+ "({}): git, which Claude Code runs outside its sandbox, would run what the agent "
958
+ "puts there. If you did not set this up, remove that file and the folder it "
959
+ "names")
960
+
961
+
962
+ def headless_problems(project: str, home: str) -> List[str]:
963
+ """Why an unattended Claude Code run in `project` would not be guarded, or []."""
964
+ from phiward import broker, hidden
965
+ cfg = config.load(project)
966
+ if cfg.problem:
967
+ return [f"the phiward config cannot be used: {cfg.problem}"]
968
+ if not cfg.has_protected_paths:
969
+ return ["no protected paths are configured: run `(cd ~ && phiward setup)` in your own "
970
+ "terminal"]
971
+ out: List[str] = [f"{t} is missing: the hooks need it to clear the Python and loader "
972
+ "variables, so they refuse every call" for t in install.CLEAN_TOOLS
973
+ if not os.access(t, os.X_OK)]
974
+ clean = clean_start_problem()
975
+ if clean:
976
+ out.append(clean)
977
+ redirect = claude_settings.project_redirects(project, home)
978
+ if redirect:
979
+ out.append(claude_settings.redirect_text(redirect) + " (the hook refuses every call)")
980
+ out += [GIT_REDIRECT.format(r) for r in claude_settings.git_redirects(project, home)]
981
+ wiring = wiring_state(project, home)
982
+ out += wiring.problems
983
+ out += [ln.strip()[len("WARNING: "):] for ln in code_root_lines(project, home)]
984
+ out += [ln.strip()[len("WARNING: "):] for ln in settings_script_lines(project, home)
985
+ if ln.strip().startswith("WARNING: ")]
986
+ if wiring.wired and not wiring.isolated:
987
+ out.append("the user settings do not run the isolated hook on every tool group; "
988
+ "the plugin's and project hooks run phiward by name, so a project's env.PATH "
989
+ "can replace them. Run `(cd ~ && phiward install claude --user --write)`")
990
+ secret = [h for h in hidden.paths(None, cfg, session=True) if os.path.lexists(h)]
991
+ rules = set(_merged_rules(project, home))
992
+ missing = [r for r in install.permission_rules(list(cfg.all_roots) + secret, home)
993
+ if r not in rules]
994
+ if missing:
995
+ out.append(f"{len(missing)} permission deny rule(s) for protected and hidden paths are "
996
+ "missing (the file tools' second check)")
997
+ reason = claude_settings.confinement_reason(project, home, cfg.all_roots, cfg.patterns,
998
+ config.guard_files(), hidden=secret,
999
+ version=_pattern_version(cfg))
1000
+ if reason is not None:
1001
+ out.append(f"the shell is not confined by Claude Code's sandbox ({reason.text}); to fix "
1002
+ f"it: {reason.step}")
1003
+ out += [x.strip().replace("WARNING: ", "") for x in sandbox_needs()]
1004
+ can, cannot = bare_split(project, home)
1005
+ if can:
1006
+ out.append(f"{len(can)} MCP server(s) run with your full rights, unwrapped: "
1007
+ + ", ".join(can) + " (`phiward mcp wrap NAME` in your own terminal)")
1008
+ if cannot:
1009
+ out.append(f"{len(cannot)} MCP server(s) run with your full rights and cannot be wrapped: "
1010
+ + "; ".join(f"{n} ({why})" for n, why in cannot)
1011
+ + " (their command tools may make only gateway calls)")
1012
+ if not broker.running(config.spool_dir()):
1013
+ out.append("the broker is not running (gateway calls would fail)")
1014
+ return out
1015
+
1016
+
1017
+ def headless(project: str, home: str) -> int:
1018
+ problems = headless_problems(project, home)
1019
+ if not problems:
1020
+ print("headless: ready (wired, sandboxed, broker running). Run `claude -p` "
1021
+ "without --bare; an Agent SDK app loads the user settings or passes "
1022
+ "`phiward install claude --json` as its settings.")
1023
+ return 0
1024
+ print("headless: NOT READY")
1025
+ for p in problems:
1026
+ print(f" - {p}")
1027
+ return 1
1028
+
1029
+
1030
+ def sandbox_needs(platform: str = sys.platform, run=None) -> List[str]:
1031
+ """What Claude Code's own sandbox needs on Linux (bubblewrap 0.4 or newer, and socat). With
1032
+ failIfUnavailable, a missing one stops Claude Code at start."""
1033
+ import re
1034
+ import shutil
1035
+ import subprocess
1036
+ if not platform.startswith("linux"):
1037
+ return []
1038
+ from phiward import service
1039
+ out = []
1040
+ # only on PATH folders the agent cannot write (as the broker's service looks): a planted
1041
+ # `bwrap` must not answer for the real one, nor run here
1042
+ safe = ":".join(service._safe_path_entries(os.environ.get("PATH", "")))
1043
+ found = {p: shutil.which(p, path=safe) for p in ("bwrap", "socat")}
1044
+ missing = [p for p, f in found.items() if f is None]
1045
+ if missing:
1046
+ out.append(f" WARNING: Claude Code's sandbox needs {' and '.join(missing)} on the PATH: "
1047
+ "with sandbox.failIfUnavailable (which install sets) Claude Code stops at "
1048
+ "start without it. Install it with the system's package manager, or without "
1049
+ "admin rights in a conda environment (`socat` from conda-forge), and put its "
1050
+ "bin folder on the PATH before you start Claude Code (not a folder the "
1051
+ "agent's sandbox may write, such as one in allowWrite; sandbox.socatPath "
1052
+ "and bwrapPath are read only from managed settings).")
1053
+ if "bwrap" not in missing:
1054
+ run = run or (lambda cmd, **k: subprocess.run(cmd, **k))
1055
+ try:
1056
+ r = run([found["bwrap"], "--version"], capture_output=True, text=True, timeout=10)
1057
+ m = re.search(r"(\d+)\.(\d+)", r.stdout or "")
1058
+ except (OSError, subprocess.SubprocessError):
1059
+ m = None
1060
+ if not m or (int(m.group(1)), int(m.group(2))) < (0, 4):
1061
+ out.append(" WARNING: Claude Code's sandbox needs bubblewrap 0.4 or newer; `bwrap "
1062
+ "--version` gave " + (m.group(0) if m else "nothing it could read") + ".")
1063
+ return out
1064
+
1065
+
1066
+ def launch_settings_report() -> List[str]:
1067
+ """The `claude --settings` file that makes the sandbox admin-required (install writes it)."""
1068
+ path = config.launch_settings_path()
1069
+ try:
1070
+ with open(path, encoding="utf-8") as fh:
1071
+ data = json.load(fh)
1072
+ except FileNotFoundError:
1073
+ return [f" NOTE: no `--settings` file yet: `(cd ~ && phiward install claude --user --write)` writes "
1074
+ f"{path}; start Claude Code with `claude --settings {path}`, so a repository's "
1075
+ "settings cannot loosen the sandbox."]
1076
+ except (OSError, ValueError):
1077
+ data = None
1078
+ sb = data.get("sandbox") if isinstance(data, dict) else None
1079
+ want = install.LAUNCH_SETTINGS["sandbox"]
1080
+ if not isinstance(sb, dict) or any(sb.get(k) != v for k, v in want.items()):
1081
+ return [f" WARNING: {path} does not set " + ", ".join(
1082
+ f"sandbox.{k}: {json.dumps(v)}" for k, v in want.items()) +
1083
+ ". Run `(cd ~ && phiward install claude --user --write)` again."]
1084
+ return [f" --settings file: {path}. Start Claude Code with `claude --settings {path}`; "
1085
+ "doctor cannot tell whether this session was started with it."]
1086
+
1087
+
1088
+ def network_report(project: Optional[str], home: str, cfg: config.Config) -> List[str]:
1089
+ """The network of shell commands in Claude Code sessions. Claude Code honours
1090
+ `strictAllowlist` only from the user and managed settings, and then ignores a repository's
1091
+ allowed domains; the allowlist is `allowedDomains` plus `WebFetch(domain:...)` allow rules."""
1092
+ trusted = [lv for lv in claude_settings.levels(project, home) if lv[0] in ("managed", "user")]
1093
+ strict = claude_settings._first(trusted, "sandbox", "network", "strictAllowlist") is True
1094
+ if not strict:
1095
+ if cfg.network_limit:
1096
+ return [" WARNING: [network] limit is set, but Claude Code's user settings do not set "
1097
+ "sandbox.network.strictAllowlist: shell commands reach any host. Run "
1098
+ "`(cd ~ && phiward install claude --user --write)`."]
1099
+ return [" network for shell commands: open (any host; see [network] in "
1100
+ "docs/configuration.md)"]
1101
+ hosts = set(claude_settings._merged_list(trusted, "sandbox", "network", "allowedDomains"))
1102
+ for _lvl, _path, data in trusted:
1103
+ allow = ((data or {}).get("permissions") or {}).get("allow") or []
1104
+ for rule in allow if isinstance(allow, list) else []:
1105
+ if isinstance(rule, str) and rule.startswith("WebFetch(domain:") and rule.endswith(")"):
1106
+ hosts.add(rule[len("WebFetch(domain:"):-1])
1107
+ n = len(hosts)
1108
+ out = [f" network for shell commands: limited to {n} host{'' if n == 1 else 's'}"
1109
+ + (f" ({', '.join(sorted(hosts)[:5])}{', ...' if n > 5 else ''})" if hosts else
1110
+ " (none)")
1111
+ + "; WebFetch and MCP servers are not limited by it; each listed host is a way out"]
1112
+ # every level, the project's too: a command outside the sandbox has no network limit
1113
+ every = claude_settings.levels(project, home)
1114
+ if claude_settings._first(every, "sandbox", "enabled") is not True \
1115
+ or claude_settings._merged_list(every, "sandbox", "excludedCommands"):
1116
+ out.append(" WARNING: the network limit does not hold for every command: the sandbox is "
1117
+ "off or sandbox.excludedCommands is set (a project's settings can do this); "
1118
+ "excluded commands reach any host.")
1119
+ if cfg.network_limit:
1120
+ extra = sorted(set(claude_settings._merged_list(trusted, "sandbox", "network",
1121
+ "allowedDomains"))
1122
+ - set(cfg.allowed_domains))
1123
+ if extra:
1124
+ out.append(f" NOTE: {len(extra)} host(s) in Claude Code's user settings are not in "
1125
+ "[network] allowed_domains (install only adds hosts): remove them from "
1126
+ "sandbox.network.allowedDomains in ~/.claude/settings.json if you no "
1127
+ "longer want them.")
1128
+ return out
1129
+
1130
+
1131
+ if __name__ == "__main__":
1132
+ sys.exit(main(sys.argv[1:]))