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/githooks.py
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
"""Git hooks: `phiward git-hook pre-commit | pre-push | install [--force]`.
|
|
2
|
+
|
|
3
|
+
- pre-commit refuses a staged file inside the protected set, and any added line or file name that
|
|
4
|
+
holds an identifier (the sanitizer, in table mode, would change it).
|
|
5
|
+
- pre-push refuses a push to a protected branch (`[git] protected_branches` in the repo config).
|
|
6
|
+
- install writes small `#!/bin/sh` hooks that call this module.
|
|
7
|
+
|
|
8
|
+
Output rule: what these hooks print can reach the AI model, so they never print a line's content or
|
|
9
|
+
a raw file name. They print the sanitized name, a line number and the placeholder words (for
|
|
10
|
+
example `<SAMPLEID>`). Any internal fault refuses (exit 1): a guard bug must not let a commit
|
|
11
|
+
through silently.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import os
|
|
15
|
+
import re
|
|
16
|
+
import subprocess
|
|
17
|
+
import sys
|
|
18
|
+
from typing import List, Optional, Sequence, Tuple
|
|
19
|
+
|
|
20
|
+
from phiward import config, paths
|
|
21
|
+
|
|
22
|
+
MARKER = "# phiward managed hook"
|
|
23
|
+
HOOKS = ("pre-commit", "pre-push")
|
|
24
|
+
OVERRIDE = ("To override, the human can run `git commit --no-verify` "
|
|
25
|
+
"(only the human should use it).")
|
|
26
|
+
PUSH_OVERRIDE = "To override, the human can run `git push --no-verify`."
|
|
27
|
+
FAULT = ("phiward: the git hook failed, so the operation is refused. "
|
|
28
|
+
"Report this as a bug; the human can use --no-verify.")
|
|
29
|
+
BAD_CONFIG = ("phiward: refused: the guard configuration has a problem. "
|
|
30
|
+
"Run `phiward doctor` to see it, and fix it.")
|
|
31
|
+
USAGE = "usage: phiward git-hook pre-commit | pre-push | install [--force]"
|
|
32
|
+
HELP = USAGE + """
|
|
33
|
+
|
|
34
|
+
Commands:
|
|
35
|
+
pre-commit check the staged changes (git runs it before a commit)
|
|
36
|
+
pre-push check the branches to be pushed (git runs it before a push)
|
|
37
|
+
install write both hooks into this repository's hooks folder
|
|
38
|
+
install --force replace hooks that are there already
|
|
39
|
+
|
|
40
|
+
pre-commit refuses a staged file inside a protected folder, and an added line or file name
|
|
41
|
+
that holds an identifier. pre-push refuses a push to a protected branch
|
|
42
|
+
(`[git] protected_branches` in the repo config). The hooks never print a line's content or a
|
|
43
|
+
raw file name. If a hook fails, the operation is refused.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
_PLACEHOLDER = re.compile(r"<[A-Za-z_][A-Za-z0-9_]*>")
|
|
47
|
+
_HUNK = re.compile(rb"^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class GitError(Exception):
|
|
51
|
+
pass
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _git(args: Sequence[str], cwd: str, stdin: Optional[bytes] = None) -> bytes:
|
|
55
|
+
try:
|
|
56
|
+
proc = subprocess.run(["git"] + list(args), cwd=cwd, input=stdin,
|
|
57
|
+
stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False)
|
|
58
|
+
except OSError as exc:
|
|
59
|
+
raise GitError(type(exc).__name__)
|
|
60
|
+
if proc.returncode != 0:
|
|
61
|
+
raise GitError("git exited with %d" % proc.returncode)
|
|
62
|
+
return proc.stdout
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _toplevel(cwd: str) -> str:
|
|
66
|
+
return _git(["rev-parse", "--show-toplevel"], cwd).decode("utf-8", "surrogateescape").strip()
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _names(blob: bytes) -> List[str]:
|
|
70
|
+
return [n.decode("utf-8", "surrogateescape") for n in blob.split(b"\0") if n]
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _words(text: str) -> List[str]:
|
|
74
|
+
return _PLACEHOLDER.findall(text)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _introduced(before: str, after: str) -> str:
|
|
78
|
+
"""The sorted placeholder words the cleaning added (never any content)."""
|
|
79
|
+
new = set(_words(after)) - set(_words(before))
|
|
80
|
+
return " ".join(sorted(new or set(_words(after)))) or "<MASKED>"
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _make_sanitizer(cfg: "config.Config"):
|
|
84
|
+
from phiward.sanitize import Sanitizer
|
|
85
|
+
# With no packs configured, from_config uses the default pack: the scan always runs.
|
|
86
|
+
return Sanitizer.from_config(cfg)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _added_lines(top: str, name: str) -> List[Tuple[int, str]]:
|
|
90
|
+
"""The added lines of one staged file as (line number, text); binary files give none."""
|
|
91
|
+
out = _git(["--literal-pathspecs", "diff", "--cached", "-U0", "--no-color", "--no-ext-diff",
|
|
92
|
+
"--", name], top)
|
|
93
|
+
lines: List[Tuple[int, str]] = []
|
|
94
|
+
cur = 0
|
|
95
|
+
in_hunk = False
|
|
96
|
+
for raw in out.split(b"\n"):
|
|
97
|
+
m = _HUNK.match(raw)
|
|
98
|
+
if m:
|
|
99
|
+
cur = int(m.group(1))
|
|
100
|
+
in_hunk = True
|
|
101
|
+
continue
|
|
102
|
+
if not in_hunk or raw.startswith(b"\\"):
|
|
103
|
+
continue
|
|
104
|
+
if raw.startswith(b"+"):
|
|
105
|
+
text = raw[1:].decode("utf-8", "replace").rstrip("\r")
|
|
106
|
+
lines.append((cur, text))
|
|
107
|
+
cur += 1
|
|
108
|
+
return lines
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def pre_commit(cwd: str) -> int:
|
|
112
|
+
top = _toplevel(cwd)
|
|
113
|
+
cfg = config.load(top)
|
|
114
|
+
if cfg.problem:
|
|
115
|
+
print(BAD_CONFIG, file=sys.stderr)
|
|
116
|
+
return 1
|
|
117
|
+
try:
|
|
118
|
+
san = _make_sanitizer(cfg)
|
|
119
|
+
except Exception: # noqa: BLE001 - SanitizerError or any fault: fail closed
|
|
120
|
+
print("phiward: refused: the sanitizer could not be set up. "
|
|
121
|
+
"Run `phiward doctor` to see why.", file=sys.stderr)
|
|
122
|
+
return 1
|
|
123
|
+
pset = paths.ProtectedSet(cfg.roots, cfg.patterns)
|
|
124
|
+
staged = _names(_git(["diff", "--cached", "--name-only", "-z", "--diff-filter=ACMR"], top))
|
|
125
|
+
report: List[str] = []
|
|
126
|
+
inside = 0
|
|
127
|
+
for name in staged:
|
|
128
|
+
shown = san.clean(name)
|
|
129
|
+
if pset and pset.relation(os.path.join(top, name)) == paths.INSIDE:
|
|
130
|
+
# never the name: a repo-relative path does not match the absolute-root mask
|
|
131
|
+
inside += 1
|
|
132
|
+
continue
|
|
133
|
+
if shown != name:
|
|
134
|
+
report.append(" %s: the file name holds an identifier %s"
|
|
135
|
+
% (shown, _introduced(name, shown)))
|
|
136
|
+
for lineno, text in _added_lines(top, name):
|
|
137
|
+
cleaned = san.clean(text, table=True)
|
|
138
|
+
if cleaned != text:
|
|
139
|
+
report.append(" %s:%d: identifier %s" % (shown, lineno, _introduced(text, cleaned)))
|
|
140
|
+
if inside:
|
|
141
|
+
report.insert(0, f" {inside} staged file(s) inside a protected folder (names withheld)")
|
|
142
|
+
if not report:
|
|
143
|
+
return 0
|
|
144
|
+
print("phiward: commit refused. The staged changes hold protected data or identifiers:",
|
|
145
|
+
file=sys.stderr)
|
|
146
|
+
for line in report:
|
|
147
|
+
print(line, file=sys.stderr)
|
|
148
|
+
print(OVERRIDE, file=sys.stderr)
|
|
149
|
+
return 1
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def pre_push(cwd: str, stdin_text: str) -> int:
|
|
153
|
+
top = _toplevel(cwd)
|
|
154
|
+
cfg = config.load(top)
|
|
155
|
+
if cfg.problem:
|
|
156
|
+
print(BAD_CONFIG, file=sys.stderr)
|
|
157
|
+
return 1
|
|
158
|
+
blocked: List[str] = []
|
|
159
|
+
for line in stdin_text.splitlines():
|
|
160
|
+
parts = line.split()
|
|
161
|
+
if len(parts) < 3:
|
|
162
|
+
continue
|
|
163
|
+
remote_ref = parts[2]
|
|
164
|
+
if remote_ref.startswith("refs/heads/"):
|
|
165
|
+
branch = remote_ref[len("refs/heads/"):]
|
|
166
|
+
if branch in cfg.protected_branches and branch not in blocked:
|
|
167
|
+
blocked.append(branch)
|
|
168
|
+
if not blocked:
|
|
169
|
+
return 0
|
|
170
|
+
for b in blocked:
|
|
171
|
+
print("phiward: push refused: branch '%s' is protected." % b, file=sys.stderr)
|
|
172
|
+
print(PUSH_OVERRIDE, file=sys.stderr)
|
|
173
|
+
return 1
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _hooks_dir(top: str) -> str:
|
|
177
|
+
try:
|
|
178
|
+
custom = _git(["config", "--get", "core.hooksPath"], top).decode(
|
|
179
|
+
"utf-8", "surrogateescape").strip()
|
|
180
|
+
except GitError:
|
|
181
|
+
custom = "" # unset
|
|
182
|
+
if custom:
|
|
183
|
+
custom = os.path.expanduser(custom)
|
|
184
|
+
return os.path.normpath(custom if os.path.isabs(custom) else os.path.join(top, custom))
|
|
185
|
+
got = _git(["rev-parse", "--git-path", "hooks"], top).decode(
|
|
186
|
+
"utf-8", "surrogateescape").strip()
|
|
187
|
+
return os.path.normpath(got if os.path.isabs(got) else os.path.join(top, got))
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _script(name: str) -> str:
|
|
191
|
+
return ("#!/bin/sh\n%s\n"
|
|
192
|
+
"if command -v phiward >/dev/null 2>&1; then\n"
|
|
193
|
+
" exec phiward git-hook %s \"$@\"\n"
|
|
194
|
+
"fi\n"
|
|
195
|
+
"exec python3 -m phiward git-hook %s \"$@\"\n" % (MARKER, name, name))
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def install(cwd: str, force: bool) -> int:
|
|
199
|
+
top = _toplevel(cwd)
|
|
200
|
+
hdir = _hooks_dir(top)
|
|
201
|
+
plan: List[Tuple[str, str]] = []
|
|
202
|
+
for name in HOOKS:
|
|
203
|
+
target = os.path.join(hdir, name)
|
|
204
|
+
if os.path.lexists(target) and not force:
|
|
205
|
+
try:
|
|
206
|
+
with open(target, "r", encoding="utf-8", errors="replace") as fh:
|
|
207
|
+
ours = MARKER in fh.read()
|
|
208
|
+
except OSError:
|
|
209
|
+
ours = False
|
|
210
|
+
if not ours:
|
|
211
|
+
print("phiward: refused: %s already exists and is not ours. "
|
|
212
|
+
"Nothing was written. Use --force to replace it." % target,
|
|
213
|
+
file=sys.stderr)
|
|
214
|
+
return 1
|
|
215
|
+
plan.append((name, target))
|
|
216
|
+
os.makedirs(hdir, exist_ok=True)
|
|
217
|
+
for name, target in plan:
|
|
218
|
+
from phiward import safeio
|
|
219
|
+
safeio.write_new(target, _script(name), mode=0o755) # never through a link
|
|
220
|
+
print("phiward: wrote %s" % target)
|
|
221
|
+
return 0
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def main(argv: List[str]) -> int:
|
|
225
|
+
try:
|
|
226
|
+
if argv[:1] in (["-h"], ["--help"]):
|
|
227
|
+
print(HELP, end="")
|
|
228
|
+
return 0
|
|
229
|
+
if not argv:
|
|
230
|
+
print(USAGE, file=sys.stderr)
|
|
231
|
+
return 2
|
|
232
|
+
cmd, rest = argv[0], list(argv[1:])
|
|
233
|
+
cwd = os.getcwd()
|
|
234
|
+
if cmd == "pre-commit":
|
|
235
|
+
return pre_commit(cwd)
|
|
236
|
+
if cmd == "pre-push":
|
|
237
|
+
data = sys.stdin.buffer.read().decode("utf-8", "replace")
|
|
238
|
+
return pre_push(cwd, data)
|
|
239
|
+
if cmd == "install":
|
|
240
|
+
if any(a != "--force" for a in rest):
|
|
241
|
+
print(USAGE, file=sys.stderr)
|
|
242
|
+
return 2
|
|
243
|
+
return install(cwd, "--force" in rest)
|
|
244
|
+
print(USAGE, file=sys.stderr)
|
|
245
|
+
return 2
|
|
246
|
+
except Exception: # noqa: BLE001 - fail closed on any fault
|
|
247
|
+
print(FAULT, file=sys.stderr)
|
|
248
|
+
return 1
|
|
File without changes
|