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.
Files changed (167) hide show
  1. truthstone/__init__.py +7 -0
  2. truthstone/adapters/__init__.py +0 -0
  3. truthstone/adapters/claude_code/__init__.py +1 -0
  4. truthstone/adapters/claude_code/forward.py +308 -0
  5. truthstone/adapters/claude_code/install.py +268 -0
  6. truthstone/adapters/claude_code/plugin.py +290 -0
  7. truthstone/adapters/claude_code/protocol.py +46 -0
  8. truthstone/adapters/claude_code/settings_scan.py +216 -0
  9. truthstone/adapters/claude_code/shim.py +500 -0
  10. truthstone/adapters/claude_code/translate.py +410 -0
  11. truthstone/adapters/codex/__init__.py +5 -0
  12. truthstone/adapters/codex/forward.py +302 -0
  13. truthstone/adapters/codex/forward_native.c +805 -0
  14. truthstone/adapters/codex/hook.py +357 -0
  15. truthstone/adapters/codex/install.py +260 -0
  16. truthstone/adapters/codex/native.py +250 -0
  17. truthstone/adapters/codex/patch.py +495 -0
  18. truthstone/adapters/codex/plugin.py +698 -0
  19. truthstone/adapters/codex/render.py +211 -0
  20. truthstone/adapters/codex/status.py +181 -0
  21. truthstone/adapters/codex/translate.py +453 -0
  22. truthstone/adapters/edits.py +85 -0
  23. truthstone/adapters/mcp.py +90 -0
  24. truthstone/adapters/registry.py +161 -0
  25. truthstone/bench/__init__.py +0 -0
  26. truthstone/bench/codex/__init__.py +24 -0
  27. truthstone/bench/codex/__main__.py +5 -0
  28. truthstone/bench/codex/acceptance.py +1041 -0
  29. truthstone/bench/codex/accounts.py +187 -0
  30. truthstone/bench/codex/agents.py +659 -0
  31. truthstone/bench/codex/appserver.py +215 -0
  32. truthstone/bench/codex/claims.py +77 -0
  33. truthstone/bench/codex/claude.py +881 -0
  34. truthstone/bench/codex/claude_sandbox.py +776 -0
  35. truthstone/bench/codex/cli.py +1424 -0
  36. truthstone/bench/codex/grader.py +763 -0
  37. truthstone/bench/codex/guards.py +980 -0
  38. truthstone/bench/codex/homes.py +220 -0
  39. truthstone/bench/codex/hook_recorder.py +163 -0
  40. truthstone/bench/codex/hook_timer.c +106 -0
  41. truthstone/bench/codex/leakage.py +308 -0
  42. truthstone/bench/codex/limits.py +215 -0
  43. truthstone/bench/codex/naming.py +69 -0
  44. truthstone/bench/codex/orchestrator.py +999 -0
  45. truthstone/bench/codex/plan.py +247 -0
  46. truthstone/bench/codex/premise.py +406 -0
  47. truthstone/bench/codex/regrade.py +196 -0
  48. truthstone/bench/codex/report.py +792 -0
  49. truthstone/bench/codex/scripted.py +119 -0
  50. truthstone/bench/codex/stats.py +208 -0
  51. truthstone/bench/codex/suite.py +806 -0
  52. truthstone/bench/codex/testedits.py +713 -0
  53. truthstone/bench/codex/toolchain.py +96 -0
  54. truthstone/bench/codex/transcript.py +650 -0
  55. truthstone/bench/mutation.py +306 -0
  56. truthstone/bench/replay.py +179 -0
  57. truthstone/bench/runner.py +287 -0
  58. truthstone/bench/tasks.py +301 -0
  59. truthstone/census/__init__.py +16 -0
  60. truthstone/census/report.py +634 -0
  61. truthstone/census/taxonomy.py +363 -0
  62. truthstone/challenge/__init__.py +6 -0
  63. truthstone/challenge/ledger.py +199 -0
  64. truthstone/challenge/renderer.py +129 -0
  65. truthstone/cli/__init__.py +0 -0
  66. truthstone/cli/main.py +1587 -0
  67. truthstone/complexity/__init__.py +5 -0
  68. truthstone/complexity/engine.py +92 -0
  69. truthstone/complexity/rules.py +354 -0
  70. truthstone/complexity/signals.py +313 -0
  71. truthstone/core/__init__.py +0 -0
  72. truthstone/core/config.py +664 -0
  73. truthstone/core/engine.py +1390 -0
  74. truthstone/core/enums.py +284 -0
  75. truthstone/core/events.py +109 -0
  76. truthstone/core/hosts.py +536 -0
  77. truthstone/core/metrics.py +117 -0
  78. truthstone/core/models.py +145 -0
  79. truthstone/core/observe.py +58 -0
  80. truthstone/core/profile.py +307 -0
  81. truthstone/core/rehydrate.py +162 -0
  82. truthstone/core/shellchanges.py +336 -0
  83. truthstone/core/store.py +2309 -0
  84. truthstone/core/taskstate.py +126 -0
  85. truthstone/daemon/__init__.py +0 -0
  86. truthstone/daemon/__main__.py +31 -0
  87. truthstone/daemon/app.py +509 -0
  88. truthstone/daemon/degraded.py +149 -0
  89. truthstone/daemon/lifecycle.py +291 -0
  90. truthstone/daemon/logs.py +237 -0
  91. truthstone/daemon/private_paths.py +139 -0
  92. truthstone/evidence/__init__.py +5 -0
  93. truthstone/evidence/engine.py +86 -0
  94. truthstone/evidence/extractors.py +327 -0
  95. truthstone/evidence/models.py +63 -0
  96. truthstone/evidence/pyanalysis.py +393 -0
  97. truthstone/evidence/resolvers.py +629 -0
  98. truthstone/intent/__init__.py +6 -0
  99. truthstone/intent/dead_switch.py +1124 -0
  100. truthstone/intent/extractor.py +261 -0
  101. truthstone/intent/lexicon.py +321 -0
  102. truthstone/intent/models.py +183 -0
  103. truthstone/intent/premise.py +946 -0
  104. truthstone/intent/premise_names.py +1497 -0
  105. truthstone/intent/premise_switch.py +1901 -0
  106. truthstone/intent/waiver.py +109 -0
  107. truthstone/names.py +180 -0
  108. truthstone/planning/__init__.py +5 -0
  109. truthstone/planning/feasibility.py +75 -0
  110. truthstone/planning/governor.py +400 -0
  111. truthstone/planning/integrity.py +43 -0
  112. truthstone/planning/spec_note.py +489 -0
  113. truthstone/replay.py +519 -0
  114. truthstone/repo/__init__.py +5 -0
  115. truthstone/repo/gitinfo.py +145 -0
  116. truthstone/repo/index.py +726 -0
  117. truthstone/repo/manifests.py +163 -0
  118. truthstone/repo/models.py +193 -0
  119. truthstone/repo/paths.py +131 -0
  120. truthstone/repo/scanner.py +223 -0
  121. truthstone/repo/symbols_python.py +401 -0
  122. truthstone/repo/symbols_ts.py +214 -0
  123. truthstone/util/__init__.py +0 -0
  124. truthstone/util/used_names.py +201 -0
  125. truthstone/validate/__init__.py +6 -0
  126. truthstone/validate/checks.py +1659 -0
  127. truthstone/validate/config_reads.py +506 -0
  128. truthstone/validate/effects.py +621 -0
  129. truthstone/validate/fitting.py +322 -0
  130. truthstone/validate/gaming.py +1365 -0
  131. truthstone/validate/gated_skips.py +682 -0
  132. truthstone/validate/js_module_level.py +826 -0
  133. truthstone/validate/keep_reading.py +242 -0
  134. truthstone/validate/modify.py +435 -0
  135. truthstone/validate/original_tests.py +945 -0
  136. truthstone/validate/premise_unmet.py +318 -0
  137. truthstone/validate/regressions.py +495 -0
  138. truthstone/validate/script_effects.py +310 -0
  139. truthstone/validate/secrets.py +162 -0
  140. truthstone/validate/shell.py +1058 -0
  141. truthstone/validate/signoff.py +296 -0
  142. truthstone/validate/spec_integrity.py +1300 -0
  143. truthstone/validate/testrefs.py +220 -0
  144. truthstone/validate/untracked_state.py +472 -0
  145. truthstone/validate/validator.py +285 -0
  146. truthstone/validate/weakened_tests.py +1512 -0
  147. truthstone/validate/yardstick.py +273 -0
  148. truthstone/verify/__init__.py +5 -0
  149. truthstone/verify/admitted.py +254 -0
  150. truthstone/verify/arbiter.py +1187 -0
  151. truthstone/verify/baseline.py +255 -0
  152. truthstone/verify/claims.py +270 -0
  153. truthstone/verify/commands.py +1286 -0
  154. truthstone/verify/completion_gate.py +764 -0
  155. truthstone/verify/integrity.py +274 -0
  156. truthstone/verify/parsers.py +887 -0
  157. truthstone/verify/runners.py +806 -0
  158. truthstone/verify/spec_bound.py +161 -0
  159. truthstone/verify/spec_conflict.py +906 -0
  160. truthstone/verify/spec_rules.py +561 -0
  161. truthstone/verify/spec_snapshot.py +828 -0
  162. truthstone/verify/static.py +72 -0
  163. truthstone-0.2.0.dist-info/METADATA +377 -0
  164. truthstone-0.2.0.dist-info/RECORD +167 -0
  165. truthstone-0.2.0.dist-info/WHEEL +4 -0
  166. truthstone-0.2.0.dist-info/entry_points.txt +4 -0
  167. 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