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.
- phiward/__init__.py +8 -0
- phiward/__main__.py +5 -0
- phiward/_toml.py +211 -0
- phiward/adapters/__init__.py +105 -0
- phiward/adapters/claude.py +429 -0
- phiward/broker.py +831 -0
- phiward/carryover.py +1613 -0
- phiward/claude_settings.py +1307 -0
- phiward/cli.py +110 -0
- phiward/config.py +936 -0
- phiward/confine.py +476 -0
- phiward/copying.py +533 -0
- phiward/core.py +105 -0
- phiward/data/agents-section.md +43 -0
- phiward/doctor.py +1132 -0
- phiward/fasthook.py +70 -0
- phiward/fsinfo.py +241 -0
- phiward/gateway.py +159 -0
- phiward/githooks.py +248 -0
- phiward/guards/__init__.py +0 -0
- phiward/guards/protected_paths.py +1138 -0
- phiward/hidden.py +281 -0
- phiward/init.py +155 -0
- phiward/install.py +828 -0
- phiward/inventory.py +173 -0
- phiward/mcp.py +186 -0
- phiward/mcp_config.py +1736 -0
- phiward/names.py +5 -0
- phiward/packs/dates.toml +17 -0
- phiward/packs/genomics.toml +51 -0
- phiward/packs/msk.toml +32 -0
- phiward/pathid.py +403 -0
- phiward/pathmatch.py +98 -0
- phiward/paths.py +942 -0
- phiward/pin.py +214 -0
- phiward/procinfo.py +73 -0
- phiward/remote.py +448 -0
- phiward/run.py +788 -0
- phiward/safeio.py +84 -0
- phiward/sanitize.py +691 -0
- phiward/selfcheck.py +1506 -0
- phiward/service.py +321 -0
- phiward/session_note.py +86 -0
- phiward/setup_cmd.py +886 -0
- phiward/shell.py +504 -0
- phiward/wholetool.py +1463 -0
- phiward-0.2.0b1.dist-info/METADATA +147 -0
- phiward-0.2.0b1.dist-info/RECORD +53 -0
- phiward-0.2.0b1.dist-info/WHEEL +5 -0
- phiward-0.2.0b1.dist-info/entry_points.txt +3 -0
- phiward-0.2.0b1.dist-info/licenses/LICENSE +662 -0
- phiward-0.2.0b1.dist-info/licenses/NOTICE +16 -0
- phiward-0.2.0b1.dist-info/top_level.txt +1 -0
phiward/hidden.py
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
"""The one list of what no agent may read besides the protected data: credentials,
|
|
2
|
+
ticket caches and keytabs, SSH keys the ssh configs name, histories, the Trash, other tools'
|
|
3
|
+
logins, local IPC sockets. `launch` hides it from the whole tool, the gateway from every command,
|
|
4
|
+
`phiward install claude` writes it into Claude Code's sandbox and permission rules, and the hook
|
|
5
|
+
refuses it to the file tools. Standard library only: the hook imports it on every call."""
|
|
6
|
+
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
from typing import Dict, Iterator, List, Optional
|
|
10
|
+
|
|
11
|
+
from phiward import config, pathid
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _inside(p: str, folder: str) -> bool:
|
|
15
|
+
return pathid.inside(p, folder)
|
|
16
|
+
|
|
17
|
+
CREDENTIALS = (".ssh", ".aws", ".kube", ".config/gh", ".netrc", ".gnupg", ".docker/config.json",
|
|
18
|
+
".config/gcloud", ".azure", ".git-credentials", ".config/git/credentials",
|
|
19
|
+
".claude/.credentials.json", ".phiward/carryover", ".agent-guards", ".pgpass", ".npmrc", ".pypirc", ".irods",
|
|
20
|
+
".config/rclone", ".cargo/credentials", ".cargo/credentials.toml",
|
|
21
|
+
".m2/settings.xml", ".gradle/gradle.properties", ".claude", ".claude.json",
|
|
22
|
+
".vault-token", ".terraform.d", ".config/op", ".s3cfg", ".boto", ".config/hub",
|
|
23
|
+
".config/glab-cli", ".databrickscfg", ".snowsql",
|
|
24
|
+
# other agent tools' logins and the Claude app
|
|
25
|
+
".codex", ".gemini", ".config/Claude", "Library/Application Support/Claude",
|
|
26
|
+
# browser profiles: cookies and saved logins
|
|
27
|
+
"Library/Application Support/Google/Chrome", "Library/Application Support/Firefox",
|
|
28
|
+
"Library/Application Support/Microsoft Edge", "Library/Application Support/BraveSoftware",
|
|
29
|
+
"Library/Safari", "Library/Cookies", ".mozilla", ".config/google-chrome",
|
|
30
|
+
".config/chromium", ".config/BraveSoftware", ".config/microsoft-edge",
|
|
31
|
+
# what the operator typed and read: a history holds paths, names and tokens
|
|
32
|
+
".zsh_history", ".zsh_sessions", ".bash_history", ".bash_sessions", ".sh_history",
|
|
33
|
+
".python_history", ".Rhistory", ".julia/logs", ".ipython", ".lesshst", ".viminfo",
|
|
34
|
+
".psql_history", ".mysql_history", ".sqlite_history", ".node_repl_history",
|
|
35
|
+
".local/share/fish", ".local/state/nvim", ".Trash", ".local/share/Trash",
|
|
36
|
+
# macOS QuickLook thumbnails of the operator's files
|
|
37
|
+
"Library/Caches/com.apple.QuickLook.thumbnailcache",
|
|
38
|
+
# Linux thumbnails and recent-file lists; R and pip settings that hold tokens
|
|
39
|
+
".cache/thumbnails", ".thumbnails", ".local/share/recently-used.xbel",
|
|
40
|
+
".Renviron", ".config/pip", ".pip", ".local/share/jupyter/runtime",
|
|
41
|
+
# more tokens and histories
|
|
42
|
+
".cache/huggingface/token", ".huggingface", ".config/github-copilot",
|
|
43
|
+
".terraformrc", ".histfile", ".subversion/auth", ".config/sops", ".globus",
|
|
44
|
+
"Library/Keychains",
|
|
45
|
+
# research data services and container registries
|
|
46
|
+
".ncbi", ".basespace", ".synapseConfig", ".dnanexus_config", ".nextflow/secrets",
|
|
47
|
+
".apptainer", ".singularity", ".config/containers/auth.json",
|
|
48
|
+
".local/share/uv/credentials", ".kaggle",
|
|
49
|
+
# copies of Claude Code's login file that `phiward mcp wrap` keeps
|
|
50
|
+
".phiward/backups",
|
|
51
|
+
# more agent tools, database and service logins, and a shell history store
|
|
52
|
+
".copilot", ".cursor", ".my.cnf", ".mylogin.cnf", ".local/share/atuin",
|
|
53
|
+
".config/ngrok", ".gem/credentials", ".composer/auth.json",
|
|
54
|
+
".config/pypoetry/auth.toml", ".oci", ".pulumi", ".tsh", ".yarnrc.yml", ".jupyter",
|
|
55
|
+
# more browsers and apps that keep logins and cookies
|
|
56
|
+
"Library/Application Support/Chromium", "Library/Application Support/Arc",
|
|
57
|
+
"Library/Application Support/Slack", "Library/Application Support/Code",
|
|
58
|
+
".config/Code", ".config/Slack")
|
|
59
|
+
|
|
60
|
+
# what a Claude Code session itself needs from its own folder (memory, plans, skills, saved tool
|
|
61
|
+
# output): in a session that is not launched (Mode A) only its login files are hidden, not the
|
|
62
|
+
# whole folder
|
|
63
|
+
OWN_CONFIG = (".claude", ".claude.json")
|
|
64
|
+
|
|
65
|
+
def credentials(env: Dict[str, str], cfg: Optional[config.Config] = None,
|
|
66
|
+
write_to: bool = True, own_config: bool = True) -> List[str]:
|
|
67
|
+
"""What no session may read, besides the protected paths: credentials, histories, the
|
|
68
|
+
Trash, Kerberos caches and keytabs, SSH keys named outside ~/.ssh, and the gateway's
|
|
69
|
+
write_to folders (what the gateway writes there is unmasked).
|
|
70
|
+
`own_config=False` (Mode A): of Claude Code's own folder, only its login files."""
|
|
71
|
+
home = pathid.home(env)
|
|
72
|
+
names = [c for c in CREDENTIALS if own_config or c not in OWN_CONFIG]
|
|
73
|
+
out = [os.path.join(home, c) for c in names]
|
|
74
|
+
if not own_config:
|
|
75
|
+
conf = env.get("CLAUDE_CONFIG_DIR") or os.path.join(home, ".claude")
|
|
76
|
+
out += [os.path.join(conf, ".credentials.json"), os.path.join(conf, ".claude.json"),
|
|
77
|
+
os.path.join(home, ".claude.json"),
|
|
78
|
+
# the copies Claude Code keeps of its login file
|
|
79
|
+
os.path.join(conf, "backups"), os.path.join(home, ".claude.json.backup"),
|
|
80
|
+
os.path.join(conf, ".claude.json.backup")]
|
|
81
|
+
# the broker's log holds the real exit status of gateway commands
|
|
82
|
+
from phiward import service
|
|
83
|
+
out.append(service.log_folder(home))
|
|
84
|
+
out += _kerberos_caches(env)
|
|
85
|
+
out += _ssh_identity_files(env, cfg)
|
|
86
|
+
if cfg is not None and write_to:
|
|
87
|
+
out += [w for w in cfg.write_to if w not in out]
|
|
88
|
+
return out
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
_SSH_LINE = re.compile(r"^\s*(IdentityFile|CertificateFile|Include)\s*(?:=\s*|\s+)(.*?)\s*$", re.I | re.M)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _token_paths(v: str, home: str) -> List[str]:
|
|
95
|
+
"""What to hide for a configured path that may hold `%` or `${...}` tokens: the path whole
|
|
96
|
+
when it has none; else the files that match it with each token as `*`, and the folder
|
|
97
|
+
before the first token unless that is the home folder or above it (for example `~/%h`)."""
|
|
98
|
+
cut = min([i for i in (v.find("%"), v.find("${")) if i >= 0] or [-1])
|
|
99
|
+
if cut < 0:
|
|
100
|
+
return [v]
|
|
101
|
+
import glob
|
|
102
|
+
pat = re.sub(r"%[A-Za-z%]|\$\{[^}]*\}", "*", v)
|
|
103
|
+
out = [m for m in glob.glob(pat)[:256]]
|
|
104
|
+
head = os.path.dirname(v[:cut]) if "/" in v[:cut] else ""
|
|
105
|
+
if head.startswith("/") and not _inside(os.path.normpath(home), os.path.normpath(head)):
|
|
106
|
+
out.append(head)
|
|
107
|
+
return out
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _ssh_words(rest: str) -> List[str]:
|
|
111
|
+
try:
|
|
112
|
+
import shlex
|
|
113
|
+
return shlex.split(rest, comments=True)
|
|
114
|
+
except ValueError:
|
|
115
|
+
return rest.split()
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _ssh_identity_files(env: Dict[str, str], cfg: Optional[config.Config]) -> List[str]:
|
|
119
|
+
"""Keys and certificates that the operator's SSH configs name outside ~/.ssh: the
|
|
120
|
+
user's config, the system's, and the [copy] one, with their Include files."""
|
|
121
|
+
home = pathid.home(env)
|
|
122
|
+
todo = [(os.path.join(home, ".ssh", "config"), os.path.join(home, ".ssh")),
|
|
123
|
+
("/etc/ssh/ssh_config", "/etc/ssh")]
|
|
124
|
+
if cfg is not None and cfg.ssh_config:
|
|
125
|
+
todo.append((os.path.expanduser(cfg.ssh_config), os.path.join(home, ".ssh")))
|
|
126
|
+
out: List[str] = []
|
|
127
|
+
seen: set = set()
|
|
128
|
+
|
|
129
|
+
def expand(v: str) -> str:
|
|
130
|
+
v = v.replace("%d", home).replace("${HOME}", home)
|
|
131
|
+
v = re.sub(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}", lambda m: env.get(m.group(1), m.group(0)), v)
|
|
132
|
+
return os.path.join(home, v[2:]) if v.startswith("~/") else v
|
|
133
|
+
|
|
134
|
+
depth = 0
|
|
135
|
+
while todo and depth < 64:
|
|
136
|
+
depth += 1
|
|
137
|
+
f, base = todo.pop(0)
|
|
138
|
+
if f in seen:
|
|
139
|
+
continue
|
|
140
|
+
seen.add(f)
|
|
141
|
+
try:
|
|
142
|
+
with open(f, encoding="utf-8", errors="replace") as fh:
|
|
143
|
+
text = fh.read(1 << 20)
|
|
144
|
+
except OSError:
|
|
145
|
+
continue
|
|
146
|
+
for key, rest in _SSH_LINE.findall(text):
|
|
147
|
+
for v in _ssh_words(rest):
|
|
148
|
+
v = expand(v)
|
|
149
|
+
if key.lower() == "include":
|
|
150
|
+
import glob
|
|
151
|
+
pat = v if v.startswith("/") else os.path.join(base, v)
|
|
152
|
+
todo += [(g, base) for g in sorted(glob.glob(pat))[:64]]
|
|
153
|
+
continue
|
|
154
|
+
out += [os.path.normpath(x) for x in _token_paths(v, home) if x.startswith("/")]
|
|
155
|
+
return out
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _kerberos_caches(env: Dict[str, str]) -> List[str]:
|
|
159
|
+
"""Kerberos ticket caches the operator's tools use: a session that could read one could log
|
|
160
|
+
in to HPC with the operator's ticket over the open network and read protected data there
|
|
161
|
+
unmasked (operator's HPC setup). The cache KRB5CCNAME names (FILE: or DIR:), read
|
|
162
|
+
from the operator's environment before it is cleared, and the default file caches."""
|
|
163
|
+
out: List[str] = []
|
|
164
|
+
cc = env.get("KRB5CCNAME", "")
|
|
165
|
+
kind, _, rest = cc.partition(":")
|
|
166
|
+
path = rest if kind in ("FILE", "DIR") else (cc if cc.startswith("/") else "")
|
|
167
|
+
if path.startswith("/"):
|
|
168
|
+
out.append(os.path.normpath(path))
|
|
169
|
+
uid = os.getuid()
|
|
170
|
+
out += [f"/tmp/krb5cc_{uid}", f"/var/tmp/krb5cc_{uid}", f"/var/kerberos/krb5/user/{uid}"]
|
|
171
|
+
# keytabs the environment names, and the caches and keytabs krb5.conf names
|
|
172
|
+
for k in ("KRB5_KTNAME", "KRB5_CLIENT_KTNAME"):
|
|
173
|
+
v = env.get(k, "")
|
|
174
|
+
v = v.split(":", 1)[1] if v.split(":", 1)[0] in ("FILE", "WRFILE") else v
|
|
175
|
+
if v.startswith("/"):
|
|
176
|
+
out.append(os.path.normpath(v))
|
|
177
|
+
subst = {"%{uid}": str(uid), "%{euid}": str(os.geteuid()), "%{USERID}": str(uid),
|
|
178
|
+
"%{EUID}": str(os.geteuid()), "%{TEMP}": "/tmp",
|
|
179
|
+
"%{username}": env.get("USER", ""), "%{LOCALSTATEDIR}": "/var",
|
|
180
|
+
"%{LIBDIR}": "/usr/lib"}
|
|
181
|
+
for text in _krb5_confs(env):
|
|
182
|
+
for v in _KRB5_NAMES.findall(text):
|
|
183
|
+
for k, w in subst.items():
|
|
184
|
+
if w:
|
|
185
|
+
v = v.replace(k, w)
|
|
186
|
+
kind, _, rest = v.partition(":")
|
|
187
|
+
v = rest if kind in ("FILE", "DIR", "WRFILE") else v
|
|
188
|
+
home = pathid.home(env)
|
|
189
|
+
out += [os.path.normpath(x) for x in _token_paths(v, home) if x.startswith("/")]
|
|
190
|
+
return out
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
_KRB5_INCLUDE = re.compile(r"^\s*(include|includedir)\s+(\S+)", re.M)
|
|
194
|
+
_KRB5_NAMES = re.compile(r"^\s*default_(?:ccache|keytab|client_keytab)_name\s*=\s*(\S+)", re.M)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
# any file named like a Kerberos cache in the shared temp folders (macOS: /tmp is readable)
|
|
198
|
+
KRB5_CACHE_NAMES = r"krb5cc[^/]*"
|
|
199
|
+
# the same on Linux, as patterns of the session's view (/tmp is the session's own there)
|
|
200
|
+
KRB5_CACHE_PATTERNS = ("/var/tmp/krb5cc*", "/dev/shm/krb5cc*")
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
IPC_PATHS = (f"/run/user/{os.getuid()}", "/run/munge", "/run/dbus", "/var/run/docker.sock",
|
|
204
|
+
"/run/docker.sock",
|
|
205
|
+
# Kerberos tickets kept by KCM (sssd-kcm, Heimdal): a socket, not a file
|
|
206
|
+
"/run/.heim_org.h5l.kcm-socket", "/var/run/.heim_org.h5l.kcm-socket")
|
|
207
|
+
|
|
208
|
+
# Kerberos caches by name, as path patterns (pathmatch: `*` within one part): new caches are
|
|
209
|
+
# made with new names, so the hook and the gateway match the name, not a list taken at a start
|
|
210
|
+
KRB5_NAME_PATTERNS = ("/tmp/krb5cc*", "/private/tmp/krb5cc*", "/var/tmp/krb5cc*",
|
|
211
|
+
"/private/var/tmp/krb5cc*", "/dev/shm/krb5cc*")
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def paths(env: Optional[Dict[str, str]] = None, cfg: Optional[config.Config] = None,
|
|
215
|
+
session: bool = False) -> List[str]:
|
|
216
|
+
"""The hidden list as absolute paths: credentials (from the operator's environment, never a
|
|
217
|
+
request's), SSH keys and certificates the ssh configs name, local IPC sockets. Not the
|
|
218
|
+
write_to folders (the gateway writes there). `session=True` is the list for a Claude Code
|
|
219
|
+
session that is not launched (Mode A): its own folder stays usable, its login files not."""
|
|
220
|
+
env = dict(os.environ) if env is None else env
|
|
221
|
+
# write_to folders hold unmasked gateway output: hidden from a session, never from the
|
|
222
|
+
# gateway itself, which writes there
|
|
223
|
+
out = credentials(env, cfg, write_to=session, own_config=not session)
|
|
224
|
+
out += [p for p in IPC_PATHS if p not in out]
|
|
225
|
+
# the folders of `launch` sessions (their config folders hold a login and transcripts): a
|
|
226
|
+
# launch session hides the others from itself; the gateway and a Mode A session must not
|
|
227
|
+
# read them either. Not in CREDENTIALS, which `launch` uses for its own view.
|
|
228
|
+
home = pathid.home(env)
|
|
229
|
+
tools = os.path.join(home, ".phiward", "tools")
|
|
230
|
+
if tools not in out:
|
|
231
|
+
out.append(tools)
|
|
232
|
+
return out
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def non_file_tickets(env: Optional[Dict[str, str]] = None) -> str:
|
|
236
|
+
"""The Kerberos cache type when it is not a file (KEYRING, KCM, API, MEMORY), else "": a
|
|
237
|
+
file list cannot hide those."""
|
|
238
|
+
import sys
|
|
239
|
+
env = dict(os.environ) if env is None else env
|
|
240
|
+
cc = env.get("KRB5CCNAME", "")
|
|
241
|
+
if not cc:
|
|
242
|
+
# unset is the usual case: the configured default (krb5.conf), else the system's
|
|
243
|
+
cc = _default_ccache(env) or ("API:" if sys.platform == "darwin" else "FILE:")
|
|
244
|
+
kind = cc.partition(":")[0] if ":" in cc else "FILE"
|
|
245
|
+
return kind if kind in ("KEYRING", "KCM", "API", "MEMORY") else ""
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _default_ccache(env: Dict[str, str]) -> str:
|
|
249
|
+
"""`default_ccache_name` from the krb5.conf files (with include and includedir), or ""."""
|
|
250
|
+
for text in _krb5_confs(env):
|
|
251
|
+
m = re.search(r"^\s*default_ccache_name\s*=\s*(\S+)", text, re.M)
|
|
252
|
+
if m:
|
|
253
|
+
return m.group(1)
|
|
254
|
+
return ""
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _krb5_confs(env: Dict[str, str]) -> Iterator[str]:
|
|
258
|
+
"""The text of each krb5.conf file (KRB5_CONFIG, else /etc/krb5.conf), then of the files it
|
|
259
|
+
includes (include, includedir), each once, at most 64."""
|
|
260
|
+
confs = [c for c in env.get("KRB5_CONFIG", "").split(":") if c] or ["/etc/krb5.conf"]
|
|
261
|
+
seen: set = set()
|
|
262
|
+
while confs and len(seen) < 64:
|
|
263
|
+
c = confs.pop(0)
|
|
264
|
+
if c in seen:
|
|
265
|
+
continue
|
|
266
|
+
seen.add(c)
|
|
267
|
+
try:
|
|
268
|
+
with open(c, encoding="utf-8", errors="replace") as fh:
|
|
269
|
+
text = fh.read(1 << 20)
|
|
270
|
+
except OSError:
|
|
271
|
+
continue
|
|
272
|
+
yield text
|
|
273
|
+
for kind, inc in _KRB5_INCLUDE.findall(text):
|
|
274
|
+
if kind == "includedir":
|
|
275
|
+
try:
|
|
276
|
+
confs += [os.path.join(inc, n) for n in sorted(os.listdir(inc))
|
|
277
|
+
if re.fullmatch(r"[A-Za-z0-9_-]+|.+\.conf", n)]
|
|
278
|
+
except OSError:
|
|
279
|
+
pass
|
|
280
|
+
else:
|
|
281
|
+
confs.append(inc)
|
phiward/init.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""`phiward init [--root DIR]...`: set up a project for phiward in one step.
|
|
2
|
+
|
|
3
|
+
In the project folder (the top of a repository) it:
|
|
4
|
+
- adds phiward's rules to `AGENTS.md` (the "Protected data (phiward)" section), unless they are
|
|
5
|
+
there;
|
|
6
|
+
- with `--root`, adds those folders to the project's `.phiward.toml` (a repo config can add
|
|
7
|
+
protection, never remove it);
|
|
8
|
+
- writes the project's Claude Code settings (`install claude --project --no-hooks`): the sandbox
|
|
9
|
+
and permission rules that are the same for every contributor into `.claude/settings.json`, and
|
|
10
|
+
this person's own into `.claude/settings.local.json`;
|
|
11
|
+
- adds `.claude/settings.local.json` to `.gitignore`;
|
|
12
|
+
- installs the git hooks (when the folder is a git repository).
|
|
13
|
+
|
|
14
|
+
It only adds, so an agent may run it. Each contributor runs it once (it is safe to run again).
|
|
15
|
+
The hooks of each session come from the user wiring (`phiward install claude --user`).
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
import os
|
|
19
|
+
import sys
|
|
20
|
+
from typing import List
|
|
21
|
+
|
|
22
|
+
from phiward import config, pathid
|
|
23
|
+
|
|
24
|
+
USAGE = "usage: phiward init [--root DIR]...\n"
|
|
25
|
+
MARK = "## Protected data (phiward)"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _agents_text() -> str:
|
|
29
|
+
with open(os.path.join(os.path.dirname(__file__), "data", "agents-section.md"),
|
|
30
|
+
encoding="utf-8") as fh:
|
|
31
|
+
return fh.read()
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _add_agents(project: str, out: List[str]) -> None:
|
|
35
|
+
path = os.path.join(project, "AGENTS.md")
|
|
36
|
+
old = ""
|
|
37
|
+
if os.path.lexists(path):
|
|
38
|
+
if os.path.islink(path) or not os.path.isfile(path):
|
|
39
|
+
out.append("AGENTS.md: not a plain file; not changed")
|
|
40
|
+
return
|
|
41
|
+
old = _read_plain(path)
|
|
42
|
+
if MARK in old:
|
|
43
|
+
out.append("AGENTS.md: the phiward rules are there already")
|
|
44
|
+
return
|
|
45
|
+
_write_plain(path, old + ("\n" if old and not old.endswith("\n\n") else "") + _agents_text())
|
|
46
|
+
out.append("AGENTS.md: added the phiward rules")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _read_plain(path: str) -> str:
|
|
50
|
+
from phiward import safeio
|
|
51
|
+
return safeio.read_text(path) # never through a link
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _write_plain(path: str, text: str) -> None:
|
|
55
|
+
"""The whole file again, through a fresh name (`safeio.write_new`): a link or a second name
|
|
56
|
+
put there meanwhile is replaced, never written through. Its mode is kept."""
|
|
57
|
+
import stat as _stat
|
|
58
|
+
from phiward import safeio
|
|
59
|
+
try:
|
|
60
|
+
mode = _stat.S_IMODE(os.lstat(path).st_mode)
|
|
61
|
+
except OSError:
|
|
62
|
+
mode = 0o644
|
|
63
|
+
safeio.write_new(path, text, mode=mode)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _add_roots(project: str, roots: List[str], out: List[str]) -> int:
|
|
67
|
+
if not roots:
|
|
68
|
+
return 0
|
|
69
|
+
from phiward import setup_cmd
|
|
70
|
+
home = pathid.home()
|
|
71
|
+
path = os.path.join(project, config.REPO_FILE)
|
|
72
|
+
if os.path.islink(path):
|
|
73
|
+
out.append(f"{config.REPO_FILE}: a link; not changed")
|
|
74
|
+
return 2
|
|
75
|
+
try:
|
|
76
|
+
data = setup_cmd._read_existing(path) if os.path.exists(path) else {}
|
|
77
|
+
except Exception: # noqa: BLE001 - say so, change nothing
|
|
78
|
+
out.append(f"{config.REPO_FILE}: cannot be read; not changed")
|
|
79
|
+
return 2
|
|
80
|
+
have = data.setdefault("protected_paths", {}).setdefault("roots", [])
|
|
81
|
+
for r in roots:
|
|
82
|
+
full = r if r.startswith(("/", "~")) else os.path.normpath(os.path.join(project, r))
|
|
83
|
+
why = setup_cmd.check_root(full, home)
|
|
84
|
+
if why:
|
|
85
|
+
out.append(f"--root {r}: {why}; not added")
|
|
86
|
+
return 2
|
|
87
|
+
if full not in have:
|
|
88
|
+
have.append(full)
|
|
89
|
+
setup_cmd._write(path, setup_cmd.dump(data).replace(
|
|
90
|
+
"# phiward user config, written by `phiward setup`.", "# phiward repo config"))
|
|
91
|
+
out.append(f"{config.REPO_FILE}: {len(have)} protected root(s)")
|
|
92
|
+
return 0
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _add_gitignore(project: str, out: List[str]) -> None:
|
|
96
|
+
path = os.path.join(project, ".gitignore")
|
|
97
|
+
line = ".claude/settings.local.json"
|
|
98
|
+
old = ""
|
|
99
|
+
if os.path.isfile(path) and not os.path.islink(path):
|
|
100
|
+
old = _read_plain(path)
|
|
101
|
+
if line in old.splitlines():
|
|
102
|
+
out.append(".gitignore: has the personal settings line already")
|
|
103
|
+
return
|
|
104
|
+
elif os.path.lexists(path):
|
|
105
|
+
out.append(".gitignore: not a plain file; not changed")
|
|
106
|
+
return
|
|
107
|
+
_write_plain(path, old + ("" if not old or old.endswith("\n") else "\n") + line + "\n")
|
|
108
|
+
out.append(".gitignore: added .claude/settings.local.json")
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def main(argv: List[str]) -> int:
|
|
112
|
+
if argv[:1] in (["-h"], ["--help"]):
|
|
113
|
+
sys.stdout.write(USAGE + "\n" + (__doc__ or ""))
|
|
114
|
+
return 0
|
|
115
|
+
roots: List[str] = []
|
|
116
|
+
it = iter(argv)
|
|
117
|
+
for w in it:
|
|
118
|
+
if w == "--root":
|
|
119
|
+
v = next(it, "")
|
|
120
|
+
if not v:
|
|
121
|
+
sys.stderr.write(USAGE)
|
|
122
|
+
return 2
|
|
123
|
+
roots.append(v)
|
|
124
|
+
else:
|
|
125
|
+
sys.stderr.write(USAGE)
|
|
126
|
+
return 2
|
|
127
|
+
project = os.getcwd()
|
|
128
|
+
home = os.path.realpath(pathid.home())
|
|
129
|
+
if os.path.realpath(project) in ("/", home):
|
|
130
|
+
sys.stderr.write("phiward init: run it in a project folder, not in / or your home "
|
|
131
|
+
"folder.\n")
|
|
132
|
+
return 2
|
|
133
|
+
out: List[str] = []
|
|
134
|
+
_add_agents(project, out)
|
|
135
|
+
code = _add_roots(project, roots, out)
|
|
136
|
+
_add_gitignore(project, out)
|
|
137
|
+
from phiward import install
|
|
138
|
+
rc = install.main(["claude", "--project", "--no-hooks", "--write", "--yes"])
|
|
139
|
+
out.append("Claude Code project settings: " + (
|
|
140
|
+
"written" if rc == 0 else "not written (install said why, above): run "
|
|
141
|
+
"`phiward init` again here in your own terminal"))
|
|
142
|
+
if os.path.isdir(os.path.join(project, ".git")):
|
|
143
|
+
from phiward import githooks
|
|
144
|
+
g = githooks.install(project, False)
|
|
145
|
+
out.append("git hooks: " + ("installed" if g == 0 else f"not installed ({g})"))
|
|
146
|
+
else:
|
|
147
|
+
out.append("git hooks: not a git repository; skipped")
|
|
148
|
+
sys.stdout.write("\nphiward init:\n" + "".join(f" {line}\n" for line in out))
|
|
149
|
+
commit = [f for f in ("AGENTS.md", ".phiward.toml", ".gitignore", ".claude/settings.json")
|
|
150
|
+
if os.path.exists(os.path.join(project, f))
|
|
151
|
+
and not (f == ".claude/settings.json" and rc != 0)]
|
|
152
|
+
if commit:
|
|
153
|
+
sys.stdout.write("Commit " + ", ".join(commit) + "; never .claude/settings.local.json "
|
|
154
|
+
"(in a repository that is not yours: list them in .git/info/exclude).\n")
|
|
155
|
+
return code or rc
|