truthstone 0.2.0__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.
- truthstone/__init__.py +7 -0
- truthstone/adapters/__init__.py +0 -0
- truthstone/adapters/claude_code/__init__.py +1 -0
- truthstone/adapters/claude_code/forward.py +308 -0
- truthstone/adapters/claude_code/install.py +268 -0
- truthstone/adapters/claude_code/plugin.py +290 -0
- truthstone/adapters/claude_code/protocol.py +46 -0
- truthstone/adapters/claude_code/settings_scan.py +216 -0
- truthstone/adapters/claude_code/shim.py +500 -0
- truthstone/adapters/claude_code/translate.py +410 -0
- truthstone/adapters/codex/__init__.py +5 -0
- truthstone/adapters/codex/forward.py +302 -0
- truthstone/adapters/codex/forward_native.c +805 -0
- truthstone/adapters/codex/hook.py +357 -0
- truthstone/adapters/codex/install.py +260 -0
- truthstone/adapters/codex/native.py +250 -0
- truthstone/adapters/codex/patch.py +495 -0
- truthstone/adapters/codex/plugin.py +698 -0
- truthstone/adapters/codex/render.py +211 -0
- truthstone/adapters/codex/status.py +181 -0
- truthstone/adapters/codex/translate.py +453 -0
- truthstone/adapters/edits.py +85 -0
- truthstone/adapters/mcp.py +90 -0
- truthstone/adapters/registry.py +161 -0
- truthstone/bench/__init__.py +0 -0
- truthstone/bench/codex/__init__.py +24 -0
- truthstone/bench/codex/__main__.py +5 -0
- truthstone/bench/codex/acceptance.py +1041 -0
- truthstone/bench/codex/accounts.py +187 -0
- truthstone/bench/codex/agents.py +659 -0
- truthstone/bench/codex/appserver.py +215 -0
- truthstone/bench/codex/claims.py +77 -0
- truthstone/bench/codex/claude.py +881 -0
- truthstone/bench/codex/claude_sandbox.py +776 -0
- truthstone/bench/codex/cli.py +1424 -0
- truthstone/bench/codex/grader.py +763 -0
- truthstone/bench/codex/guards.py +980 -0
- truthstone/bench/codex/homes.py +220 -0
- truthstone/bench/codex/hook_recorder.py +163 -0
- truthstone/bench/codex/hook_timer.c +106 -0
- truthstone/bench/codex/leakage.py +308 -0
- truthstone/bench/codex/limits.py +215 -0
- truthstone/bench/codex/naming.py +69 -0
- truthstone/bench/codex/orchestrator.py +999 -0
- truthstone/bench/codex/plan.py +247 -0
- truthstone/bench/codex/premise.py +406 -0
- truthstone/bench/codex/regrade.py +196 -0
- truthstone/bench/codex/report.py +792 -0
- truthstone/bench/codex/scripted.py +119 -0
- truthstone/bench/codex/stats.py +208 -0
- truthstone/bench/codex/suite.py +806 -0
- truthstone/bench/codex/testedits.py +713 -0
- truthstone/bench/codex/toolchain.py +96 -0
- truthstone/bench/codex/transcript.py +650 -0
- truthstone/bench/mutation.py +306 -0
- truthstone/bench/replay.py +179 -0
- truthstone/bench/runner.py +287 -0
- truthstone/bench/tasks.py +301 -0
- truthstone/census/__init__.py +16 -0
- truthstone/census/report.py +634 -0
- truthstone/census/taxonomy.py +363 -0
- truthstone/challenge/__init__.py +6 -0
- truthstone/challenge/ledger.py +199 -0
- truthstone/challenge/renderer.py +129 -0
- truthstone/cli/__init__.py +0 -0
- truthstone/cli/main.py +1587 -0
- truthstone/complexity/__init__.py +5 -0
- truthstone/complexity/engine.py +92 -0
- truthstone/complexity/rules.py +354 -0
- truthstone/complexity/signals.py +313 -0
- truthstone/core/__init__.py +0 -0
- truthstone/core/config.py +664 -0
- truthstone/core/engine.py +1390 -0
- truthstone/core/enums.py +284 -0
- truthstone/core/events.py +109 -0
- truthstone/core/hosts.py +536 -0
- truthstone/core/metrics.py +117 -0
- truthstone/core/models.py +145 -0
- truthstone/core/observe.py +58 -0
- truthstone/core/profile.py +307 -0
- truthstone/core/rehydrate.py +162 -0
- truthstone/core/shellchanges.py +336 -0
- truthstone/core/store.py +2309 -0
- truthstone/core/taskstate.py +126 -0
- truthstone/daemon/__init__.py +0 -0
- truthstone/daemon/__main__.py +31 -0
- truthstone/daemon/app.py +509 -0
- truthstone/daemon/degraded.py +149 -0
- truthstone/daemon/lifecycle.py +291 -0
- truthstone/daemon/logs.py +237 -0
- truthstone/daemon/private_paths.py +139 -0
- truthstone/evidence/__init__.py +5 -0
- truthstone/evidence/engine.py +86 -0
- truthstone/evidence/extractors.py +327 -0
- truthstone/evidence/models.py +63 -0
- truthstone/evidence/pyanalysis.py +393 -0
- truthstone/evidence/resolvers.py +629 -0
- truthstone/intent/__init__.py +6 -0
- truthstone/intent/dead_switch.py +1124 -0
- truthstone/intent/extractor.py +261 -0
- truthstone/intent/lexicon.py +321 -0
- truthstone/intent/models.py +183 -0
- truthstone/intent/premise.py +946 -0
- truthstone/intent/premise_names.py +1497 -0
- truthstone/intent/premise_switch.py +1901 -0
- truthstone/intent/waiver.py +109 -0
- truthstone/names.py +180 -0
- truthstone/planning/__init__.py +5 -0
- truthstone/planning/feasibility.py +75 -0
- truthstone/planning/governor.py +400 -0
- truthstone/planning/integrity.py +43 -0
- truthstone/planning/spec_note.py +489 -0
- truthstone/replay.py +519 -0
- truthstone/repo/__init__.py +5 -0
- truthstone/repo/gitinfo.py +145 -0
- truthstone/repo/index.py +726 -0
- truthstone/repo/manifests.py +163 -0
- truthstone/repo/models.py +193 -0
- truthstone/repo/paths.py +131 -0
- truthstone/repo/scanner.py +223 -0
- truthstone/repo/symbols_python.py +401 -0
- truthstone/repo/symbols_ts.py +214 -0
- truthstone/util/__init__.py +0 -0
- truthstone/util/used_names.py +201 -0
- truthstone/validate/__init__.py +6 -0
- truthstone/validate/checks.py +1659 -0
- truthstone/validate/config_reads.py +506 -0
- truthstone/validate/effects.py +621 -0
- truthstone/validate/fitting.py +322 -0
- truthstone/validate/gaming.py +1365 -0
- truthstone/validate/gated_skips.py +682 -0
- truthstone/validate/js_module_level.py +826 -0
- truthstone/validate/keep_reading.py +242 -0
- truthstone/validate/modify.py +435 -0
- truthstone/validate/original_tests.py +945 -0
- truthstone/validate/premise_unmet.py +318 -0
- truthstone/validate/regressions.py +495 -0
- truthstone/validate/script_effects.py +310 -0
- truthstone/validate/secrets.py +162 -0
- truthstone/validate/shell.py +1058 -0
- truthstone/validate/signoff.py +296 -0
- truthstone/validate/spec_integrity.py +1300 -0
- truthstone/validate/testrefs.py +220 -0
- truthstone/validate/untracked_state.py +472 -0
- truthstone/validate/validator.py +285 -0
- truthstone/validate/weakened_tests.py +1512 -0
- truthstone/validate/yardstick.py +273 -0
- truthstone/verify/__init__.py +5 -0
- truthstone/verify/admitted.py +254 -0
- truthstone/verify/arbiter.py +1187 -0
- truthstone/verify/baseline.py +255 -0
- truthstone/verify/claims.py +270 -0
- truthstone/verify/commands.py +1286 -0
- truthstone/verify/completion_gate.py +764 -0
- truthstone/verify/integrity.py +274 -0
- truthstone/verify/parsers.py +887 -0
- truthstone/verify/runners.py +806 -0
- truthstone/verify/spec_bound.py +161 -0
- truthstone/verify/spec_conflict.py +906 -0
- truthstone/verify/spec_rules.py +561 -0
- truthstone/verify/spec_snapshot.py +828 -0
- truthstone/verify/static.py +72 -0
- truthstone-0.2.0.dist-info/METADATA +377 -0
- truthstone-0.2.0.dist-info/RECORD +167 -0
- truthstone-0.2.0.dist-info/WHEEL +4 -0
- truthstone-0.2.0.dist-info/entry_points.txt +4 -0
- truthstone-0.2.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
"""Claude Code *plugin* entry points.
|
|
2
|
+
|
|
3
|
+
hooks/hooks.json -> scripts/hook.sh <kind>
|
|
4
|
+
-> python -I -m truthstone.adapters.claude_code.plugin <command>
|
|
5
|
+
|
|
6
|
+
The plugin (``plugins/truthstone-claude``) is a thin launcher: it installs this package
|
|
7
|
+
into its data directory and hands every event to it, so Truthstone upgrades never require
|
|
8
|
+
editing plugin files. Per-tool events go to ``forward.py`` (one lean process per call);
|
|
9
|
+
the once-per-session and once-per-prompt work is here:
|
|
10
|
+
|
|
11
|
+
``session-start [--restart-daemon]``
|
|
12
|
+
Decide whether the plugin must stand down because Truthstone's settings-based hooks
|
|
13
|
+
already cover this session (see :func:`stand_down`), make sure the daemon runs,
|
|
14
|
+
forward the SessionStart event, and say — once, as a ``systemMessage`` — when this
|
|
15
|
+
session is not guarded.
|
|
16
|
+
``prompt``
|
|
17
|
+
Revive a dead daemon or warn once; report daemon states that guard nothing; forward
|
|
18
|
+
UserPromptSubmit.
|
|
19
|
+
``status``
|
|
20
|
+
A human-readable runtime report, for ``/truthstone:doctor``.
|
|
21
|
+
``on`` / ``off`` / ``restart-daemon``
|
|
22
|
+
Switch guarding and restart the daemon so the switch takes effect.
|
|
23
|
+
|
|
24
|
+
Stdlib-only (it imports the shim and the settings scanner, both stdlib-only): this runs
|
|
25
|
+
once per prompt and must not pay for pydantic.
|
|
26
|
+
|
|
27
|
+
Invariants, as everywhere in the adapter: never grant permissions; fail open (every path
|
|
28
|
+
exits 0, and every problem degrades to "no decision"); never fail *silently* — a session
|
|
29
|
+
that is not guarded is told so once, at the moment it starts or the moment it breaks.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
from __future__ import annotations
|
|
33
|
+
|
|
34
|
+
import contextlib
|
|
35
|
+
import json
|
|
36
|
+
import os
|
|
37
|
+
import subprocess
|
|
38
|
+
import sys
|
|
39
|
+
from pathlib import Path
|
|
40
|
+
|
|
41
|
+
from truthstone.adapters.claude_code import forward, protocol, settings_scan, shim
|
|
42
|
+
|
|
43
|
+
PROMPT_TIMEOUT_S = 8.0
|
|
44
|
+
SESSION_START_TIMEOUT_S = 15.0
|
|
45
|
+
|
|
46
|
+
UNGUARDED = (
|
|
47
|
+
"Truthstone could not start its local service, so this session is UNGUARDED. "
|
|
48
|
+
"Run /truthstone:doctor to see why. Your work continues either way."
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
# -- where things are ----------------------------------------------------------------------
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def plugin_data() -> Path | None:
|
|
56
|
+
raw = os.environ.get("CLAUDE_PLUGIN_DATA")
|
|
57
|
+
return Path(raw) if raw else None
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def project_dir(payload: dict) -> Path | None:
|
|
61
|
+
raw = os.environ.get("CLAUDE_PROJECT_DIR") or payload.get("cwd")
|
|
62
|
+
return Path(raw) if isinstance(raw, str) and raw else None
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
# -- standing down beside settings-based hooks ---------------------------------------------
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def standdown_markers(data: Path, project: Path | None) -> dict[str, Path]:
|
|
69
|
+
marks = data / "standdown"
|
|
70
|
+
out = {"user": marks / "user"}
|
|
71
|
+
if project is not None:
|
|
72
|
+
out["project"] = marks / forward.project_key(str(project))
|
|
73
|
+
return out
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def stand_down(payload: dict) -> list[tuple[str, Path]]:
|
|
77
|
+
"""Find settings-based Truthstone hooks for this session and record the result.
|
|
78
|
+
|
|
79
|
+
With both installs active, every event would be handled twice. The plugin is the one
|
|
80
|
+
that can step aside — settings hooks cannot see it — so wherever settings hooks are
|
|
81
|
+
present it writes a marker that ``forward.py`` checks on every event, and says why.
|
|
82
|
+
The markers are recomputed at every session start, so removing the old hooks is
|
|
83
|
+
picked up by the next session.
|
|
84
|
+
"""
|
|
85
|
+
data = plugin_data()
|
|
86
|
+
if data is None:
|
|
87
|
+
return []
|
|
88
|
+
project = project_dir(payload)
|
|
89
|
+
found = settings_scan.legacy_hook_files(project)
|
|
90
|
+
scopes = {scope for scope, _ in found}
|
|
91
|
+
markers = standdown_markers(data, project)
|
|
92
|
+
wanted = {"user": "user" in scopes, "project": bool(scopes & {"project", "local"})}
|
|
93
|
+
for name, path in markers.items():
|
|
94
|
+
try:
|
|
95
|
+
if wanted.get(name):
|
|
96
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
97
|
+
path.write_text(json.dumps([str(p) for _, p in found]) + "\n", encoding="utf-8")
|
|
98
|
+
else:
|
|
99
|
+
path.unlink(missing_ok=True)
|
|
100
|
+
except OSError:
|
|
101
|
+
continue
|
|
102
|
+
return found
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def standdown_message(found: list[tuple[str, Path]]) -> str:
|
|
106
|
+
fixes = []
|
|
107
|
+
for scope, path in found:
|
|
108
|
+
if scope == "user":
|
|
109
|
+
fixes.append(f"`truthstone uninstall claude --global` (removes them from {path})")
|
|
110
|
+
elif scope == "local":
|
|
111
|
+
fixes.append(f"`truthstone uninstall claude --project` in this project ({path})")
|
|
112
|
+
else:
|
|
113
|
+
fixes.append(f"remove Truthstone's hooks from {path}")
|
|
114
|
+
return (
|
|
115
|
+
"Truthstone plugin is standing by: Truthstone's settings-based hooks are also "
|
|
116
|
+
"installed, and they keep guarding this session. To switch to the plugin, run "
|
|
117
|
+
+ "; ".join(fixes)
|
|
118
|
+
+ "."
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
# -- hook commands -------------------------------------------------------------------------
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _with_notices(out: dict, notices: list[str]) -> dict:
|
|
126
|
+
if notices:
|
|
127
|
+
out = dict(out)
|
|
128
|
+
out["systemMessage"] = "\n".join(notices)
|
|
129
|
+
return out
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def session_start(payload: dict, restart: bool = False) -> dict:
|
|
133
|
+
session_id = str(payload.get("session_id") or "")
|
|
134
|
+
mode = protocol.session_mode_from_env(os.environ)
|
|
135
|
+
if mode == "disabled":
|
|
136
|
+
return {}
|
|
137
|
+
|
|
138
|
+
found = stand_down(payload)
|
|
139
|
+
if found:
|
|
140
|
+
return {"systemMessage": standdown_message(found)}
|
|
141
|
+
|
|
142
|
+
if restart:
|
|
143
|
+
restart_daemon()
|
|
144
|
+
hs = shim.ensure_daemon()
|
|
145
|
+
body = shim.health_body(hs)
|
|
146
|
+
if body is None:
|
|
147
|
+
# The prompt hook would say the same; mark it so the developer hears it once.
|
|
148
|
+
shim.notify_once(session_id)
|
|
149
|
+
return {"systemMessage": UNGUARDED}
|
|
150
|
+
|
|
151
|
+
if mode == "observe":
|
|
152
|
+
shim.register_session_mode(hs, session_id, mode)
|
|
153
|
+
notices = shim.pending_notices(body, session_id, mode)
|
|
154
|
+
return _with_notices(shim.post(hs, payload, SESSION_START_TIMEOUT_S), notices)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def prompt(payload: dict) -> dict:
|
|
158
|
+
if forward.standing_down():
|
|
159
|
+
return {}
|
|
160
|
+
session_id = str(payload.get("session_id") or "")
|
|
161
|
+
mode = protocol.session_mode_from_env(os.environ)
|
|
162
|
+
if mode == "disabled":
|
|
163
|
+
return {}
|
|
164
|
+
|
|
165
|
+
hs = shim.ensure_daemon()
|
|
166
|
+
body = shim.health_body(hs)
|
|
167
|
+
if body is None:
|
|
168
|
+
return {"systemMessage": UNGUARDED} if shim.notify_once(session_id) else {}
|
|
169
|
+
|
|
170
|
+
if mode == "observe":
|
|
171
|
+
shim.register_session_mode(hs, session_id, mode)
|
|
172
|
+
notices = shim.pending_notices(body, session_id, mode)
|
|
173
|
+
return _with_notices(shim.post(hs, payload, PROMPT_TIMEOUT_S), notices)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
# -- controls ------------------------------------------------------------------------------
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _cli(*args: str) -> subprocess.CompletedProcess:
|
|
180
|
+
"""Run this runtime's own CLI. ``-P``: the caller's cwd is the user's repository."""
|
|
181
|
+
return subprocess.run(
|
|
182
|
+
[sys.executable, "-P", "-m", "truthstone.cli.main", *args],
|
|
183
|
+
capture_output=True,
|
|
184
|
+
text=True,
|
|
185
|
+
stdin=subprocess.DEVNULL,
|
|
186
|
+
timeout=60,
|
|
187
|
+
check=False,
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def restart_daemon() -> bool:
|
|
192
|
+
if shim.health_body(shim._handshake()) is not None:
|
|
193
|
+
_cli("daemon", "stop")
|
|
194
|
+
return shim.health_body(shim.ensure_daemon()) is not None
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def switch(enabled: bool) -> int:
|
|
198
|
+
result = _cli("on" if enabled else "off")
|
|
199
|
+
if result.returncode != 0:
|
|
200
|
+
sys.stdout.write(result.stdout + result.stderr)
|
|
201
|
+
return 0
|
|
202
|
+
running = restart_daemon()
|
|
203
|
+
state = "ON — guarding" if enabled else "OFF — hooks stay installed and decide nothing"
|
|
204
|
+
sys.stdout.write(f"Truthstone is {state}.\n")
|
|
205
|
+
sys.stdout.write(
|
|
206
|
+
"This applies to every Claude Code session on this machine.\n"
|
|
207
|
+
if running
|
|
208
|
+
else "The daemon is not running; the setting applies when it next starts.\n"
|
|
209
|
+
)
|
|
210
|
+
return 0
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def status() -> int:
|
|
214
|
+
data = plugin_data()
|
|
215
|
+
write = sys.stdout.write
|
|
216
|
+
write("Truthstone plugin\n")
|
|
217
|
+
write(f" runtime {sys.executable}\n")
|
|
218
|
+
with contextlib.suppress(Exception):
|
|
219
|
+
from truthstone import __version__
|
|
220
|
+
|
|
221
|
+
write(f" version {__version__}\n")
|
|
222
|
+
if data is not None:
|
|
223
|
+
write(f" data {data}\n")
|
|
224
|
+
ready = data / "runtime.ready"
|
|
225
|
+
with contextlib.suppress(OSError):
|
|
226
|
+
lines = ready.read_text(encoding="utf-8").splitlines()
|
|
227
|
+
if len(lines) >= 3:
|
|
228
|
+
write(f" source {lines[2]}\n")
|
|
229
|
+
|
|
230
|
+
hs = shim._handshake()
|
|
231
|
+
body = shim.health_body(hs)
|
|
232
|
+
if body is None:
|
|
233
|
+
write(" daemon not running (it starts with the next session or prompt)\n")
|
|
234
|
+
else:
|
|
235
|
+
flags = [
|
|
236
|
+
label
|
|
237
|
+
for label, on in (
|
|
238
|
+
("switched off", body.get("enabled") is False),
|
|
239
|
+
("observe-only", body.get("observing") is True),
|
|
240
|
+
)
|
|
241
|
+
if on
|
|
242
|
+
]
|
|
243
|
+
suffix = f" [{', '.join(flags)}]" if flags else ""
|
|
244
|
+
write(f" daemon pid {body.get('pid')} on {hs.get('host')}:{hs.get('port')}{suffix}\n")
|
|
245
|
+
|
|
246
|
+
project = Path.cwd()
|
|
247
|
+
found = settings_scan.legacy_hook_files(project)
|
|
248
|
+
if found:
|
|
249
|
+
write(" this project the plugin is STANDING BY: settings-based hooks are installed in\n")
|
|
250
|
+
for _, path in found:
|
|
251
|
+
write(f" {path}\n")
|
|
252
|
+
else:
|
|
253
|
+
write(" this project guarded by the plugin\n")
|
|
254
|
+
return 0
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
# -- entry ---------------------------------------------------------------------------------
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def main(argv: list[str] | None = None) -> int:
|
|
261
|
+
args = list(sys.argv[1:] if argv is None else argv)
|
|
262
|
+
command = args[0] if args else ""
|
|
263
|
+
try:
|
|
264
|
+
if command in ("session-start", "prompt"):
|
|
265
|
+
payload = shim.read_payload()
|
|
266
|
+
if payload is None:
|
|
267
|
+
return 0
|
|
268
|
+
if command == "session-start":
|
|
269
|
+
out = session_start(payload, restart="--restart-daemon" in args)
|
|
270
|
+
else:
|
|
271
|
+
out = prompt(payload)
|
|
272
|
+
if out:
|
|
273
|
+
sys.stdout.write(json.dumps(out))
|
|
274
|
+
return 0
|
|
275
|
+
if command == "status":
|
|
276
|
+
return status()
|
|
277
|
+
if command in ("on", "off"):
|
|
278
|
+
return switch(command == "on")
|
|
279
|
+
if command == "restart-daemon":
|
|
280
|
+
ok = restart_daemon()
|
|
281
|
+
sys.stdout.write("daemon restarted\n" if ok else "daemon did not come back; see doctor\n")
|
|
282
|
+
return 0
|
|
283
|
+
except Exception: # noqa: BLE001 - fail open: a broken entry point must not block the agent
|
|
284
|
+
return 0
|
|
285
|
+
sys.stderr.write(f"usage: python -m {__spec__.name if __spec__ else 'plugin'} <command>\n")
|
|
286
|
+
return 0
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
if __name__ == "__main__":
|
|
290
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""Wire constants shared by the daemon-side adapter and the command-hook processes.
|
|
2
|
+
|
|
3
|
+
Stdlib-only on purpose (it imports only ``truthstone.names``, itself stdlib-only):
|
|
4
|
+
``shim.py`` and ``plugin.py`` run as hook processes and must not pull in pydantic or
|
|
5
|
+
FastAPI (that would triple their start-up cost), while ``translate.py`` runs inside the
|
|
6
|
+
daemon. Anything both sides must agree on lives here, once.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from truthstone import names
|
|
14
|
+
|
|
15
|
+
HOOK_PATH = "/hook/claude-code"
|
|
16
|
+
|
|
17
|
+
# Per-session modes (R10). A command hook sees the session's own environment; the daemon
|
|
18
|
+
# does not. The hook therefore registers ``TRUTHSTONE_DISABLE`` / ``TRUTHSTONE_OBSERVE``
|
|
19
|
+
# for its session with this pseudo-event, which the adapter consumes and never forwards
|
|
20
|
+
# to the core.
|
|
21
|
+
SESSION_MODE_EVENT = "TruthstoneSessionMode"
|
|
22
|
+
SESSION_MODE_FIELD = "truthstone_session_mode"
|
|
23
|
+
SESSION_MODES = ("disabled", "observe", "guard")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def flag(environ: Any, name: str) -> bool:
|
|
27
|
+
"""A boolean switch, honouring the same setting under a former product name."""
|
|
28
|
+
return names.env_flag(name, environ)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def session_mode_from_env(environ: Any) -> str:
|
|
32
|
+
"""The mode a developer asked for when they launched this session."""
|
|
33
|
+
if names.env_flag("TRUTHSTONE_DISABLE", environ):
|
|
34
|
+
return "disabled"
|
|
35
|
+
if names.env_flag("TRUTHSTONE_OBSERVE", environ):
|
|
36
|
+
return "observe"
|
|
37
|
+
return "guard"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def session_mode_message(session_id: str, mode: str) -> dict[str, Any]:
|
|
41
|
+
"""The registration message a command hook sends for its session."""
|
|
42
|
+
return {
|
|
43
|
+
"hook_event_name": SESSION_MODE_EVENT,
|
|
44
|
+
"session_id": session_id,
|
|
45
|
+
SESSION_MODE_FIELD: mode,
|
|
46
|
+
}
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
"""Find Truthstone in Claude Code's configuration: settings-based hooks, and the plugin.
|
|
2
|
+
|
|
3
|
+
Truthstone can reach Claude Code two ways — hooks it writes into a ``settings.json``
|
|
4
|
+
(``truthstone install claude``), or the Claude Code plugin. With both active, every event
|
|
5
|
+
would be handled twice: each tool call judged twice, each challenge rationed twice, the
|
|
6
|
+
completion gate's per-task budget spent twice. This module is how each side notices the
|
|
7
|
+
other:
|
|
8
|
+
|
|
9
|
+
* the plugin's SessionStart (``plugin.py``) checks the settings files Claude Code reads
|
|
10
|
+
for the session and stands down where settings hooks already cover it;
|
|
11
|
+
* ``truthstone install`` and ``truthstone doctor`` check the plugin's install records.
|
|
12
|
+
|
|
13
|
+
Stdlib-only: the plugin runs this in a hook process and must not import pydantic.
|
|
14
|
+
``install.py`` uses the same ownership test, so there is exactly one definition of
|
|
15
|
+
"this hook is Truthstone's".
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import json
|
|
21
|
+
import os
|
|
22
|
+
import shlex
|
|
23
|
+
from collections.abc import Mapping
|
|
24
|
+
from dataclasses import dataclass
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
from typing import Any
|
|
27
|
+
|
|
28
|
+
from truthstone import names
|
|
29
|
+
|
|
30
|
+
# The plugin's name in its manifest and marketplace entry. A product rename changes this,
|
|
31
|
+
# plugins/truthstone-claude/.claude-plugin/plugin.json and .claude-plugin/marketplace.json.
|
|
32
|
+
PLUGIN_NAME = "truthstone"
|
|
33
|
+
SHIM_MODULE = "truthstone.adapters.claude_code.shim"
|
|
34
|
+
OWNERSHIP_HEADER = "X-Truthstone"
|
|
35
|
+
MAX_SETTINGS_BYTES = 5_000_000
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def claude_config_dir(environ: Mapping[str, str] | None = None) -> Path:
|
|
39
|
+
"""Where Claude Code keeps user settings and plugins (honours ``CLAUDE_CONFIG_DIR``)."""
|
|
40
|
+
env = os.environ if environ is None else environ
|
|
41
|
+
raw = env.get("CLAUDE_CONFIG_DIR")
|
|
42
|
+
return Path(raw).expanduser() if raw else Path.home() / ".claude"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def user_settings_path(environ: Mapping[str, str] | None = None) -> Path:
|
|
46
|
+
return claude_config_dir(environ) / "settings.json"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def project_settings_paths(project: Path) -> list[tuple[str, Path]]:
|
|
50
|
+
return [
|
|
51
|
+
("project", project / ".claude" / "settings.json"),
|
|
52
|
+
("local", project / ".claude" / "settings.local.json"),
|
|
53
|
+
]
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def load_json(path: Path) -> Any:
|
|
57
|
+
"""Parsed JSON, or ``None`` when the file is missing, oversized or invalid."""
|
|
58
|
+
try:
|
|
59
|
+
if path.is_symlink() and not path.exists():
|
|
60
|
+
return None
|
|
61
|
+
if path.stat().st_size > MAX_SETTINGS_BYTES:
|
|
62
|
+
return None
|
|
63
|
+
return json.loads(path.read_text(encoding="utf-8"))
|
|
64
|
+
except (OSError, ValueError, UnicodeDecodeError):
|
|
65
|
+
return None
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
# -- ownership -----------------------------------------------------------------------------
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def command_argv(hook: dict[str, Any]) -> list[str]:
|
|
72
|
+
"""Normalize current and legacy command-hook representations for ownership checks."""
|
|
73
|
+
command = hook.get("command")
|
|
74
|
+
if not isinstance(command, str) or not command:
|
|
75
|
+
return []
|
|
76
|
+
legacy_args = hook.get("args")
|
|
77
|
+
if isinstance(legacy_args, list) and all(isinstance(arg, str) for arg in legacy_args):
|
|
78
|
+
return [command, *legacy_args]
|
|
79
|
+
try:
|
|
80
|
+
return shlex.split(command)
|
|
81
|
+
except ValueError:
|
|
82
|
+
return []
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def is_ours_hook(hook: Any) -> bool:
|
|
86
|
+
"""Identify one Truthstone settings hook without matching a user's arbitrary text.
|
|
87
|
+
|
|
88
|
+
HTTP hooks carry an explicit header marker. Command hooks are recognised by the shim
|
|
89
|
+
module plus one of its two flags; older releases emitted ``command`` + ``args`` and
|
|
90
|
+
that shape is still recognised, so reinstall/uninstall stays reversible after an
|
|
91
|
+
upgrade. A user hook that merely mentions the word "truthstone" is not ours. Hooks
|
|
92
|
+
written under a former product name are ours too (`names.variants`), so a reinstall
|
|
93
|
+
replaces them instead of duplicating them.
|
|
94
|
+
"""
|
|
95
|
+
if not isinstance(hook, dict):
|
|
96
|
+
return False
|
|
97
|
+
headers = hook.get("headers")
|
|
98
|
+
if isinstance(headers, dict) and any(headers.get(h) == "1" for h in names.variants(OWNERSHIP_HEADER)):
|
|
99
|
+
return True
|
|
100
|
+
argv = command_argv(hook)
|
|
101
|
+
shims = names.variants(SHIM_MODULE)
|
|
102
|
+
return any(shim in argv for shim in shims) and ("--ensure-daemon" in argv or "--health" in argv)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def is_ours_group(group: Any) -> bool:
|
|
106
|
+
"""Whether a Claude hook group contains an Truthstone-owned hook."""
|
|
107
|
+
if not isinstance(group, dict):
|
|
108
|
+
return False
|
|
109
|
+
hooks = group.get("hooks")
|
|
110
|
+
return isinstance(hooks, list) and any(is_ours_hook(hook) for hook in hooks)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def hooks_installed(path: Path) -> bool:
|
|
114
|
+
"""Whether this settings file carries Truthstone's settings-based hooks."""
|
|
115
|
+
data = load_json(path)
|
|
116
|
+
hooks = data.get("hooks") if isinstance(data, dict) else None
|
|
117
|
+
if not isinstance(hooks, dict):
|
|
118
|
+
return False
|
|
119
|
+
return any(
|
|
120
|
+
is_ours_group(group)
|
|
121
|
+
for groups in hooks.values()
|
|
122
|
+
if isinstance(groups, list)
|
|
123
|
+
for group in groups
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def legacy_hook_files(
|
|
128
|
+
project: Path | None, environ: Mapping[str, str] | None = None
|
|
129
|
+
) -> list[tuple[str, Path]]:
|
|
130
|
+
"""``[(scope, path)]`` for each settings file Claude Code reads that has our hooks."""
|
|
131
|
+
candidates = [("user", user_settings_path(environ))]
|
|
132
|
+
if project is not None:
|
|
133
|
+
candidates += project_settings_paths(project)
|
|
134
|
+
return [(scope, path) for scope, path in candidates if hooks_installed(path)]
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
# -- the plugin ----------------------------------------------------------------------------
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
@dataclass(frozen=True, slots=True)
|
|
141
|
+
class PluginInstall:
|
|
142
|
+
plugin_id: str
|
|
143
|
+
scope: str
|
|
144
|
+
project_path: str | None
|
|
145
|
+
install_path: str | None
|
|
146
|
+
version: str | None
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def plugin_installs(environ: Mapping[str, str] | None = None) -> list[PluginInstall]:
|
|
150
|
+
"""Install records of Truthstone's plugin, from ``installed_plugins.json``."""
|
|
151
|
+
record = load_json(claude_config_dir(environ) / "plugins" / "installed_plugins.json")
|
|
152
|
+
plugins = record.get("plugins") if isinstance(record, dict) else None
|
|
153
|
+
if not isinstance(plugins, dict):
|
|
154
|
+
return []
|
|
155
|
+
found: list[PluginInstall] = []
|
|
156
|
+
for plugin_id, entries in plugins.items():
|
|
157
|
+
# Under a former product name too: that plugin would handle every event as well.
|
|
158
|
+
if not isinstance(plugin_id, str) or plugin_id.split("@", 1)[0] not in names.variants(PLUGIN_NAME):
|
|
159
|
+
continue
|
|
160
|
+
for entry in entries if isinstance(entries, list) else [entries]:
|
|
161
|
+
if not isinstance(entry, dict):
|
|
162
|
+
continue
|
|
163
|
+
found.append(
|
|
164
|
+
PluginInstall(
|
|
165
|
+
plugin_id=plugin_id,
|
|
166
|
+
scope=str(entry.get("scope") or "user"),
|
|
167
|
+
project_path=_str_or_none(entry.get("projectPath")),
|
|
168
|
+
install_path=_str_or_none(entry.get("installPath")),
|
|
169
|
+
version=_str_or_none(entry.get("version")),
|
|
170
|
+
)
|
|
171
|
+
)
|
|
172
|
+
return found
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _str_or_none(value: Any) -> str | None:
|
|
176
|
+
return value if isinstance(value, str) and value else None
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def plugin_enabled_setting(
|
|
180
|
+
plugin_id: str, project: Path | None, environ: Mapping[str, str] | None = None
|
|
181
|
+
) -> bool | None:
|
|
182
|
+
"""The ``enabledPlugins`` value Claude Code would apply, or ``None`` if unset.
|
|
183
|
+
|
|
184
|
+
Precedence, highest first: local, project, user — the order Claude Code documents.
|
|
185
|
+
Managed settings and ``--settings`` are not visible from here.
|
|
186
|
+
"""
|
|
187
|
+
sources = [path for _, path in reversed(project_settings_paths(project))] if project else []
|
|
188
|
+
sources.append(user_settings_path(environ))
|
|
189
|
+
for path in sources:
|
|
190
|
+
data = load_json(path)
|
|
191
|
+
enabled = data.get("enabledPlugins") if isinstance(data, dict) else None
|
|
192
|
+
if isinstance(enabled, dict) and isinstance(enabled.get(plugin_id), bool):
|
|
193
|
+
return enabled[plugin_id]
|
|
194
|
+
return None
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def active_plugin_installs(
|
|
198
|
+
project: Path | None, environ: Mapping[str, str] | None = None
|
|
199
|
+
) -> list[PluginInstall]:
|
|
200
|
+
"""Plugin installs that apply to a session in ``project`` and are not disabled."""
|
|
201
|
+
active = []
|
|
202
|
+
for install in plugin_installs(environ):
|
|
203
|
+
if install.scope in ("project", "local"):
|
|
204
|
+
if project is None or not install.project_path:
|
|
205
|
+
continue
|
|
206
|
+
try:
|
|
207
|
+
scoped = Path(install.project_path).resolve()
|
|
208
|
+
here = project.resolve()
|
|
209
|
+
except OSError:
|
|
210
|
+
continue
|
|
211
|
+
if here != scoped and scoped not in here.parents:
|
|
212
|
+
continue
|
|
213
|
+
if plugin_enabled_setting(install.plugin_id, project, environ) is False:
|
|
214
|
+
continue
|
|
215
|
+
active.append(install)
|
|
216
|
+
return active
|