contextgate-core 0.6.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.
- contextgate_core/__init__.py +48 -0
- contextgate_core/ab_compare.py +566 -0
- contextgate_core/bridge.py +345 -0
- contextgate_core/cli.py +560 -0
- contextgate_core/data_contracts.py +89 -0
- contextgate_core/downstream.py +165 -0
- contextgate_core/eval_retrieval.py +173 -0
- contextgate_core/gate.py +430 -0
- contextgate_core/gate_bench.py +148 -0
- contextgate_core/gateway.py +442 -0
- contextgate_core/hook.py +116 -0
- contextgate_core/ledger.py +228 -0
- contextgate_core/mcp_server.py +291 -0
- contextgate_core/pipeline.py +1756 -0
- contextgate_core/protocol.py +112 -0
- contextgate_core/py.typed +0 -0
- contextgate_core/registry.py +109 -0
- contextgate_core/repo_indexer.py +1128 -0
- contextgate_core/token_audit.py +242 -0
- contextgate_core-0.6.0.dist-info/METADATA +426 -0
- contextgate_core-0.6.0.dist-info/RECORD +25 -0
- contextgate_core-0.6.0.dist-info/WHEEL +5 -0
- contextgate_core-0.6.0.dist-info/entry_points.txt +5 -0
- contextgate_core-0.6.0.dist-info/licenses/LICENSE +21 -0
- contextgate_core-0.6.0.dist-info/top_level.txt +1 -0
contextgate_core/cli.py
ADDED
|
@@ -0,0 +1,560 @@
|
|
|
1
|
+
"""
|
|
2
|
+
`smarty` CLI: bootstrap, verify and remove NLP-Smarty repo intelligence in any repository.
|
|
3
|
+
|
|
4
|
+
smarty init [--root DIR] [--dry-run] [--scope local|project] [--no-hooks] [--no-mcp] [--no-index]
|
|
5
|
+
[--agents-md [FILE]] [--python PATH]
|
|
6
|
+
smarty doctor [--root DIR]
|
|
7
|
+
smarty uninstall [--root DIR] [--dry-run] [--purge]
|
|
8
|
+
|
|
9
|
+
Guarantees: idempotent; merges (never overwrites) existing JSON config and aborts on files it cannot parse; every
|
|
10
|
+
changed pre-existing file gets a one-time `.smarty-bak` backup; `uninstall` removes only what `init` added.
|
|
11
|
+
Stdlib only; no network; no LLM.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import argparse
|
|
17
|
+
import difflib
|
|
18
|
+
import json
|
|
19
|
+
import os
|
|
20
|
+
import shlex
|
|
21
|
+
import subprocess
|
|
22
|
+
import sys
|
|
23
|
+
import time
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
# Clone-mode install root = the directory holding the root launchers (smarty_hook.py, mcp_server.py, ...); the package sits inside it.
|
|
27
|
+
HOME = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
28
|
+
SERVER_NAME = "nlp-smarty"
|
|
29
|
+
# Each entry is recognised in BOTH install modes: a clone registers `<home>/smarty_hook.py`, a pip install registers `-m contextgate_core.hook`.
|
|
30
|
+
HOOK_MARK = ("smarty_hook.py", "contextgate_core.hook")
|
|
31
|
+
INDEX_MARK = ("repo_indexer.py", "contextgate_core.repo_indexer")
|
|
32
|
+
MCP_MARK = ("mcp_server.py", "contextgate_core.mcp_server")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _mentions(marks: tuple[str, ...], text: str) -> bool:
|
|
36
|
+
return any(m in text for m in marks)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class Launch:
|
|
40
|
+
"""How the hook, the index refresh and the MCP server are started.
|
|
41
|
+
|
|
42
|
+
clone mode: `<python> <home>/smarty_hook.py` (root launchers next to the package; also what existing installs use)
|
|
43
|
+
installed mode: `<python> -m contextgate_core.hook` (pip install: there are no root launchers)
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
def __init__(self, python: str, home: str) -> None:
|
|
47
|
+
self.python, self.home = python, home
|
|
48
|
+
self.clone = os.path.exists(os.path.join(home, HOOK_MARK[0]))
|
|
49
|
+
|
|
50
|
+
def argv(self, which: tuple[str, ...]) -> list[str]:
|
|
51
|
+
return [self.python, os.path.join(self.home, which[0])] if self.clone else [self.python, "-m", which[1]]
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def mcp_command(self) -> tuple[str, list[str]]:
|
|
55
|
+
argv = self.argv(MCP_MARK)
|
|
56
|
+
return argv[0], argv[1:]
|
|
57
|
+
|
|
58
|
+
BEGIN, END = "<!-- smarty:begin -->", "<!-- smarty:end -->"
|
|
59
|
+
CARTRIDGE = f"""{BEGIN}
|
|
60
|
+
## NLP-Smarty repo intelligence (auto-managed; edit outside these markers only)
|
|
61
|
+
- MCP tools `smarty_get_context`, `smarty_find_symbol`, `smarty_repo_map`, `smarty_get_slice` query a local symbol index: use them before grepping or reading whole files.
|
|
62
|
+
- A `<retrieved_context>` block may be injected before your turn. It is lexical retrieval and can be incomplete; verify with grep if unsure.
|
|
63
|
+
- The index lives in `.smarty/` (gitignored). Do not edit it.
|
|
64
|
+
{END}
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class InitError(Exception):
|
|
69
|
+
pass
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
# ── file helpers ──────────────────────────────────────────────────────────────
|
|
73
|
+
def _read(path: str) -> str | None:
|
|
74
|
+
try:
|
|
75
|
+
with open(path, encoding="utf-8") as f:
|
|
76
|
+
return f.read()
|
|
77
|
+
except FileNotFoundError:
|
|
78
|
+
return None
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _load_json(path: str) -> dict[str, Any] | None:
|
|
82
|
+
raw = _read(path)
|
|
83
|
+
if raw is None:
|
|
84
|
+
return None
|
|
85
|
+
try:
|
|
86
|
+
data = json.loads(raw) if raw.strip() else {}
|
|
87
|
+
except ValueError as exc:
|
|
88
|
+
raise InitError(f"{path} is not valid JSON ({exc}); refusing to modify it. Fix or remove it and retry.")
|
|
89
|
+
if not isinstance(data, dict):
|
|
90
|
+
raise InitError(f"{path} must contain a JSON object; refusing to modify it.")
|
|
91
|
+
return data
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _dump(data: dict[str, Any]) -> str:
|
|
95
|
+
return json.dumps(data, indent=2) + "\n"
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _canon(path: str) -> str:
|
|
99
|
+
"""Follow symlinks (e.g. CLAUDE.md -> AGENTS.md) so we edit the target instead of replacing the link."""
|
|
100
|
+
return os.path.realpath(path) if os.path.islink(path) else path
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class Plan:
|
|
104
|
+
"""Collects file writes so --dry-run and real runs share one code path."""
|
|
105
|
+
|
|
106
|
+
def __init__(self) -> None:
|
|
107
|
+
self.writes: dict[str, tuple[str | None, str | None]] = {} # path -> (old, new); new None = delete
|
|
108
|
+
self.notes: list[str] = []
|
|
109
|
+
|
|
110
|
+
def write(self, path: str, new: str | None) -> None:
|
|
111
|
+
path = _canon(path)
|
|
112
|
+
old = self.writes[path][0] if path in self.writes else _read(path)
|
|
113
|
+
self.writes[path] = (old, new)
|
|
114
|
+
|
|
115
|
+
def current(self, path: str) -> str | None:
|
|
116
|
+
path = _canon(path)
|
|
117
|
+
return self.writes[path][1] if path in self.writes else _read(path)
|
|
118
|
+
|
|
119
|
+
def changed(self) -> list[str]:
|
|
120
|
+
return [p for p, (o, n) in self.writes.items() if o != n]
|
|
121
|
+
|
|
122
|
+
def show(self) -> None:
|
|
123
|
+
for p in self.changed():
|
|
124
|
+
old, new = self.writes[p]
|
|
125
|
+
print(f"\n--- {p} ({'delete' if new is None else 'create' if old is None else 'modify'})")
|
|
126
|
+
diff = difflib.unified_diff((old or "").splitlines(), (new or "").splitlines(), "before", "after", lineterm="", n=1)
|
|
127
|
+
for line in diff:
|
|
128
|
+
print(" " + line)
|
|
129
|
+
|
|
130
|
+
def apply(self, root: str, backup: bool = True) -> None:
|
|
131
|
+
git_dir = os.path.join(root, ".git") + os.sep
|
|
132
|
+
for p in self.changed():
|
|
133
|
+
old, new = self.writes[p]
|
|
134
|
+
if new is None:
|
|
135
|
+
os.remove(p)
|
|
136
|
+
continue
|
|
137
|
+
os.makedirs(os.path.dirname(p) or ".", exist_ok=True)
|
|
138
|
+
if backup and old is not None and not p.startswith(git_dir):
|
|
139
|
+
_backup(root, p, old)
|
|
140
|
+
tmp = p + ".smarty-tmp"
|
|
141
|
+
with open(tmp, "w", encoding="utf-8") as f:
|
|
142
|
+
f.write(new)
|
|
143
|
+
os.replace(tmp, p)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _backup(root: str, path: str, content: str) -> None:
|
|
147
|
+
"""One-time pre-change copy under .smarty/backups/ (gitignored; never clutters the working tree)."""
|
|
148
|
+
d = os.path.join(root, ".smarty")
|
|
149
|
+
bp = os.path.join(d, "backups", os.path.relpath(path, root).replace(os.sep, "__"))
|
|
150
|
+
if os.path.exists(bp):
|
|
151
|
+
return
|
|
152
|
+
os.makedirs(os.path.dirname(bp), exist_ok=True)
|
|
153
|
+
gi = os.path.join(d, ".gitignore")
|
|
154
|
+
if not os.path.exists(gi):
|
|
155
|
+
with open(gi, "w") as f:
|
|
156
|
+
f.write("*\n")
|
|
157
|
+
with open(bp, "w", encoding="utf-8") as f:
|
|
158
|
+
f.write(content)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
# ── settings (hooks) ──────────────────────────────────────────────────────────
|
|
162
|
+
def _hooks_of(settings: dict, event: str) -> list:
|
|
163
|
+
hooks = settings.get("hooks", {})
|
|
164
|
+
if not isinstance(hooks, dict):
|
|
165
|
+
raise InitError("'hooks' in settings must be an object")
|
|
166
|
+
groups = hooks.get(event, [])
|
|
167
|
+
if not isinstance(groups, list):
|
|
168
|
+
raise InitError(f"'hooks.{event}' in settings must be a list")
|
|
169
|
+
return groups
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _has_marker(settings: dict, event: str, marker: tuple[str, ...]) -> bool:
|
|
173
|
+
for g in _hooks_of(settings, event):
|
|
174
|
+
for h in (g.get("hooks", []) if isinstance(g, dict) else []):
|
|
175
|
+
if isinstance(h, dict) and _mentions(marker, str(h.get("command", ""))):
|
|
176
|
+
return True
|
|
177
|
+
return False
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _add_hook(settings: dict, event: str, command: str, timeout: int) -> None:
|
|
181
|
+
_hooks_of(settings, event) # structure check
|
|
182
|
+
settings.setdefault("hooks", {}).setdefault(event, []).append(
|
|
183
|
+
{"hooks": [{"type": "command", "command": command, "timeout": timeout}]})
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _strip_marker(settings: dict, event: str, marker: tuple[str, ...]) -> bool:
|
|
187
|
+
groups = _hooks_of(settings, event)
|
|
188
|
+
changed = False
|
|
189
|
+
keep = []
|
|
190
|
+
for g in groups:
|
|
191
|
+
if isinstance(g, dict) and isinstance(g.get("hooks"), list):
|
|
192
|
+
inner = [h for h in g["hooks"] if not (isinstance(h, dict) and _mentions(marker, str(h.get("command", ""))))]
|
|
193
|
+
if len(inner) != len(g["hooks"]):
|
|
194
|
+
changed = True
|
|
195
|
+
if inner:
|
|
196
|
+
keep.append({**g, "hooks": inner})
|
|
197
|
+
else:
|
|
198
|
+
keep.append(g)
|
|
199
|
+
if changed:
|
|
200
|
+
if keep:
|
|
201
|
+
settings["hooks"][event] = keep
|
|
202
|
+
else:
|
|
203
|
+
settings["hooks"].pop(event, None)
|
|
204
|
+
if not settings["hooks"]:
|
|
205
|
+
settings.pop("hooks")
|
|
206
|
+
return changed
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _settings_paths(root: str) -> dict[str, str]:
|
|
210
|
+
d = os.path.join(root, ".claude")
|
|
211
|
+
return {"project": os.path.join(d, "settings.json"), "local": os.path.join(d, "settings.local.json")}
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _plan_hooks(plan: Plan, root: str, scope: str, python: str, home: str) -> None:
|
|
215
|
+
paths = _settings_paths(root)
|
|
216
|
+
loaded = {k: _load_json(p) for k, p in paths.items()}
|
|
217
|
+
launch = Launch(python, home)
|
|
218
|
+
hook_cmd = " ".join(shlex.quote(x) for x in launch.argv(HOOK_MARK))
|
|
219
|
+
index_cmd = (" ".join(shlex.quote(x) for x in launch.argv(INDEX_MARK)) +
|
|
220
|
+
" --root \"$CLAUDE_PROJECT_DIR\" index >/dev/null 2>&1 || true")
|
|
221
|
+
target_path = paths[scope]
|
|
222
|
+
target = loaded[scope] if loaded[scope] is not None else {}
|
|
223
|
+
before = json.dumps(target, sort_keys=True)
|
|
224
|
+
for event, marker, cmd, timeout in (("UserPromptSubmit", HOOK_MARK, hook_cmd, 10),
|
|
225
|
+
("SessionStart", INDEX_MARK, index_cmd, 30)):
|
|
226
|
+
where = [k for k, s in loaded.items() if s and _has_marker(s, event, marker)]
|
|
227
|
+
if where:
|
|
228
|
+
plan.notes.append(f"{event} hook already configured in {paths[where[0]]} - left as is")
|
|
229
|
+
else:
|
|
230
|
+
_add_hook(target, event, cmd, timeout)
|
|
231
|
+
if json.dumps(target, sort_keys=True) != before:
|
|
232
|
+
plan.write(target_path, _dump(target))
|
|
233
|
+
if scope == "local":
|
|
234
|
+
_plan_git_exclude(plan, root, os.path.join(".claude", "settings.local.json"))
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _plan_git_exclude(plan: Plan, root: str, rel: str) -> None:
|
|
238
|
+
"""Keep machine-specific local settings out of commits via .git/info/exclude (never edits .gitignore)."""
|
|
239
|
+
if not os.path.isdir(os.path.join(root, ".git")):
|
|
240
|
+
return
|
|
241
|
+
ignored = subprocess.run(["git", "-C", root, "check-ignore", "-q", rel], capture_output=True).returncode == 0
|
|
242
|
+
if ignored:
|
|
243
|
+
return
|
|
244
|
+
ex = os.path.join(root, ".git", "info", "exclude")
|
|
245
|
+
cur = plan.current(ex) or ""
|
|
246
|
+
if rel not in cur.split("\n"):
|
|
247
|
+
plan.write(ex, cur + ("" if cur.endswith("\n") or not cur else "\n") + rel + "\n")
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
# ── MCP ───────────────────────────────────────────────────────────────────────
|
|
251
|
+
def _plan_mcp(plan: Plan, root: str, python: str, home: str, scope: str) -> None:
|
|
252
|
+
path = os.path.join(root, ".mcp.json")
|
|
253
|
+
data = _load_json(path)
|
|
254
|
+
cfg = data if data is not None else {}
|
|
255
|
+
servers = cfg.get("mcpServers", {})
|
|
256
|
+
if not isinstance(servers, dict):
|
|
257
|
+
raise InitError(".mcp.json 'mcpServers' must be an object")
|
|
258
|
+
existing = servers.get(SERVER_NAME)
|
|
259
|
+
if existing is not None:
|
|
260
|
+
if _mentions(MCP_MARK, json.dumps(existing)):
|
|
261
|
+
plan.notes.append(f"MCP server '{SERVER_NAME}' already in .mcp.json - left as is")
|
|
262
|
+
else:
|
|
263
|
+
plan.notes.append(f"WARNING: .mcp.json already has an unrelated '{SERVER_NAME}' server - not touching it")
|
|
264
|
+
else:
|
|
265
|
+
command, args = Launch(python, home).mcp_command
|
|
266
|
+
servers[SERVER_NAME] = {"command": command, "args": args, "env": {"SMARTY_ROOT": "."}}
|
|
267
|
+
cfg["mcpServers"] = servers
|
|
268
|
+
plan.write(path, _dump(cfg))
|
|
269
|
+
plan.notes.append(".mcp.json contains machine-specific absolute paths; avoid committing it (or share a relative one)")
|
|
270
|
+
# approval so the server starts without a prompt
|
|
271
|
+
sp = _settings_paths(root)[scope]
|
|
272
|
+
cur = plan.current(sp)
|
|
273
|
+
try:
|
|
274
|
+
s = json.loads(cur) if cur and cur.strip() else {}
|
|
275
|
+
except ValueError as exc:
|
|
276
|
+
raise InitError(f"{sp} is not valid JSON ({exc}); refusing to modify it.")
|
|
277
|
+
if not isinstance(s, dict) or not isinstance(s.get("enabledMcpjsonServers", []), list):
|
|
278
|
+
raise InitError(f"{sp}: unexpected structure for 'enabledMcpjsonServers'")
|
|
279
|
+
approved = s.setdefault("enabledMcpjsonServers", [])
|
|
280
|
+
if SERVER_NAME not in approved and existing is None:
|
|
281
|
+
approved.append(SERVER_NAME)
|
|
282
|
+
plan.write(sp, _dump(s))
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
# ── cartridge (static AGENTS.md/CLAUDE.md block) ──────────────────────────────
|
|
286
|
+
def _cartridge_target(root: str, name: str) -> str:
|
|
287
|
+
if name != "AUTO":
|
|
288
|
+
return os.path.join(root, name)
|
|
289
|
+
for n in ("CLAUDE.md", "AGENTS.md"):
|
|
290
|
+
if os.path.exists(os.path.join(root, n)):
|
|
291
|
+
return os.path.join(root, n)
|
|
292
|
+
return os.path.join(root, "AGENTS.md")
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def _with_block(text: str | None) -> str:
|
|
296
|
+
text = text or ""
|
|
297
|
+
if BEGIN in text and END in text:
|
|
298
|
+
a, b = text.index(BEGIN), text.index(END) + len(END)
|
|
299
|
+
return text[:a] + CARTRIDGE.rstrip("\n") + text[b:]
|
|
300
|
+
return text + ("" if not text or text.endswith("\n\n") else "\n" if text.endswith("\n") else "\n\n") + CARTRIDGE
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _without_block(text: str) -> str:
|
|
304
|
+
if BEGIN not in text or END not in text:
|
|
305
|
+
return text
|
|
306
|
+
a, b = text.index(BEGIN), text.index(END) + len(END)
|
|
307
|
+
out = (text[:a].rstrip("\n") + "\n" + text[b:].lstrip("\n")) if text[:a].strip() else text[b:].lstrip("\n")
|
|
308
|
+
return out
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
# ── commands ──────────────────────────────────────────────────────────────────
|
|
312
|
+
def _resolve_root(arg: str) -> str:
|
|
313
|
+
root = os.path.abspath(arg)
|
|
314
|
+
if not os.path.isdir(root):
|
|
315
|
+
raise InitError(f"root is not a directory: {root}")
|
|
316
|
+
return root
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _preflight(home: str, explicit: bool = False) -> None:
|
|
320
|
+
if explicit or os.path.exists(os.path.join(home, HOOK_MARK[0])): # clone mode (an explicit --home is always treated as one): every launcher and the package must be there
|
|
321
|
+
missing = [f for f in (HOOK_MARK[0], INDEX_MARK[0], MCP_MARK[0], "contextgate_core/pipeline.py") if not os.path.exists(os.path.join(home, f))]
|
|
322
|
+
if missing:
|
|
323
|
+
raise InitError(f"NLP-Smarty install at {home} is missing: {', '.join(missing)} (use --home)")
|
|
324
|
+
return
|
|
325
|
+
import importlib.util # installed mode: the package itself must provide the entry points
|
|
326
|
+
|
|
327
|
+
missing = [m for m in ("hook", "repo_indexer", "mcp_server", "pipeline") if importlib.util.find_spec(f"contextgate_core.{m}") is None]
|
|
328
|
+
if missing:
|
|
329
|
+
raise InitError(f"the contextgate_core package is missing modules: {', '.join(missing)}")
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def cmd_init(a: argparse.Namespace) -> int:
|
|
333
|
+
t0 = time.perf_counter()
|
|
334
|
+
root, home = _resolve_root(a.root), os.path.abspath(a.home or HOME)
|
|
335
|
+
_preflight(home, a.home is not None)
|
|
336
|
+
python = os.path.abspath(a.python) if a.python else sys.executable
|
|
337
|
+
if not os.path.isfile(python):
|
|
338
|
+
raise InitError(f"python interpreter not found: {python}")
|
|
339
|
+
plan = Plan()
|
|
340
|
+
if not os.path.isdir(os.path.join(root, ".git")):
|
|
341
|
+
plan.notes.append("not a git repository: only a plain directory walk will be indexed (no .gitignore awareness)")
|
|
342
|
+
if not a.no_hooks:
|
|
343
|
+
_plan_hooks(plan, root, a.scope, python, home)
|
|
344
|
+
if not a.no_mcp:
|
|
345
|
+
_plan_mcp(plan, root, python, home, a.scope)
|
|
346
|
+
if a.agents_md:
|
|
347
|
+
tgt = _cartridge_target(root, a.agents_md)
|
|
348
|
+
new = _with_block(plan.current(tgt))
|
|
349
|
+
if new != plan.current(tgt):
|
|
350
|
+
plan.write(tgt, new)
|
|
351
|
+
changed = plan.changed()
|
|
352
|
+
if a.dry_run:
|
|
353
|
+
print(f"[dry-run] would change {len(changed)} file(s) under {root}")
|
|
354
|
+
plan.show()
|
|
355
|
+
else:
|
|
356
|
+
plan.apply(root)
|
|
357
|
+
for p in changed:
|
|
358
|
+
print(f" wrote {os.path.relpath(p, root)}")
|
|
359
|
+
if not changed:
|
|
360
|
+
print(" nothing to change (already configured)")
|
|
361
|
+
for n in plan.notes:
|
|
362
|
+
print(f" note: {n}")
|
|
363
|
+
if not a.no_index and not a.dry_run:
|
|
364
|
+
os.environ.setdefault("SMARTY_LIGHT_TOKENS", "1")
|
|
365
|
+
from . import repo_indexer as ri # noqa: WPS433
|
|
366
|
+
|
|
367
|
+
st = ri.refresh(root)
|
|
368
|
+
info = ri.stats(root)
|
|
369
|
+
print(f" indexed {info['files']} files / {info['symbols']} symbols "
|
|
370
|
+
f"({st['reparsed']} parsed, {st['unchanged']} unchanged)")
|
|
371
|
+
if not a.dry_run:
|
|
372
|
+
print(f"done in {time.perf_counter() - t0:.2f}s - run `smarty doctor` to verify; restart Claude Code to load hooks/MCP")
|
|
373
|
+
return 0
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def _check(name: str, ok: bool, detail: str = "") -> bool:
|
|
377
|
+
print(f" [{'PASS' if ok else 'FAIL'}] {name}{(' - ' + detail) if detail else ''}")
|
|
378
|
+
return ok
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def cmd_doctor(a: argparse.Namespace) -> int:
|
|
382
|
+
root, home = _resolve_root(a.root), os.path.abspath(a.home or HOME)
|
|
383
|
+
print(f"smarty doctor: {root}")
|
|
384
|
+
ok = True
|
|
385
|
+
try:
|
|
386
|
+
_preflight(home, a.home is not None)
|
|
387
|
+
ok &= _check("install files present" if Launch(sys.executable, home).clone else "contextgate_core package present", True, home)
|
|
388
|
+
except InitError as exc:
|
|
389
|
+
return 1 if not _check("install files present", False, str(exc)) else 0
|
|
390
|
+
s = {k: _load_json(p) or {} for k, p in _settings_paths(root).items()}
|
|
391
|
+
for event, mark in (("UserPromptSubmit", HOOK_MARK), ("SessionStart", INDEX_MARK)):
|
|
392
|
+
ok &= _check(f"{event} hook registered", any(_has_marker(v, event, mark) for v in s.values()))
|
|
393
|
+
mcp = _load_json(os.path.join(root, ".mcp.json")) or {}
|
|
394
|
+
ok &= _check("MCP server registered", _mentions(MCP_MARK, json.dumps(mcp.get("mcpServers", {}).get(SERVER_NAME, {}))))
|
|
395
|
+
env = {**os.environ, "CLAUDE_PROJECT_DIR": root}
|
|
396
|
+
ev = json.dumps({"session_id": "doctor", "prompt": "how does the prompt cache lookup work", "cwd": root})
|
|
397
|
+
launch = Launch(sys.executable, home)
|
|
398
|
+
p = subprocess.run(launch.argv(HOOK_MARK), input=ev, capture_output=True, text=True,
|
|
399
|
+
env=env, timeout=60)
|
|
400
|
+
ok &= _check("hook smoke test (fail-open, valid output)", p.returncode == 0 and
|
|
401
|
+
(p.stdout == "" or "hookSpecificOutput" in json.loads(p.stdout)), f"exit={p.returncode}")
|
|
402
|
+
sess = os.path.join(root, ".smarty", "sessions", "doctor.json")
|
|
403
|
+
if os.path.exists(sess):
|
|
404
|
+
os.remove(sess)
|
|
405
|
+
msgs = "\n".join(json.dumps(m) for m in (
|
|
406
|
+
{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}},
|
|
407
|
+
{"jsonrpc": "2.0", "id": 2, "method": "tools/list"})) + "\n"
|
|
408
|
+
p = subprocess.run(launch.argv(MCP_MARK), input=msgs, capture_output=True, text=True,
|
|
409
|
+
env={**env, "SMARTY_ROOT": root}, timeout=60, cwd=home if launch.clone else root)
|
|
410
|
+
try:
|
|
411
|
+
tools = [t["name"] for t in json.loads(p.stdout.splitlines()[-1])["result"]["tools"]]
|
|
412
|
+
except (ValueError, KeyError, IndexError):
|
|
413
|
+
tools = []
|
|
414
|
+
ok &= _check("MCP handshake + tools/list", "smarty_get_context" in tools, f"{len(tools)} tools")
|
|
415
|
+
os.environ.setdefault("SMARTY_LIGHT_TOKENS", "1")
|
|
416
|
+
from . import repo_indexer as ri # noqa: WPS433
|
|
417
|
+
|
|
418
|
+
info = ri.stats(root) if os.path.isdir(os.path.join(root, ".smarty")) else {"files": 0, "symbols": 0}
|
|
419
|
+
ok &= _check("index built", info["files"] > 0, f"{info['files']} files, {info['symbols']} symbols")
|
|
420
|
+
print("all checks passed" if ok else "some checks FAILED")
|
|
421
|
+
return 0 if ok else 1
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
def cmd_audit(a: argparse.Namespace) -> int:
|
|
425
|
+
from . import token_audit # noqa: WPS433
|
|
426
|
+
|
|
427
|
+
return token_audit.main(a.audit_args)
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def _delegate(module: str, args: list[str]) -> int:
|
|
431
|
+
import importlib
|
|
432
|
+
|
|
433
|
+
return importlib.import_module(f"contextgate_core.{module}").main(args)
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def cmd_serve(a: argparse.Namespace) -> int:
|
|
437
|
+
return _delegate("gateway", a.rest)
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def cmd_stats(a: argparse.Namespace) -> int:
|
|
441
|
+
return _delegate("ledger", a.rest)
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def cmd_bench(a: argparse.Namespace) -> int:
|
|
445
|
+
return _delegate("gate_bench", a.rest)
|
|
446
|
+
|
|
447
|
+
|
|
448
|
+
def cmd_uninstall(a: argparse.Namespace) -> int:
|
|
449
|
+
root = _resolve_root(a.root)
|
|
450
|
+
plan = Plan()
|
|
451
|
+
for path in _settings_paths(root).values():
|
|
452
|
+
s = _load_json(path)
|
|
453
|
+
if s is None:
|
|
454
|
+
continue
|
|
455
|
+
for event, mark in (("UserPromptSubmit", HOOK_MARK), ("SessionStart", INDEX_MARK)):
|
|
456
|
+
_strip_marker(s, event, mark)
|
|
457
|
+
ap = s.get("enabledMcpjsonServers")
|
|
458
|
+
if isinstance(ap, list) and SERVER_NAME in ap:
|
|
459
|
+
ap.remove(SERVER_NAME)
|
|
460
|
+
if not ap:
|
|
461
|
+
s.pop("enabledMcpjsonServers")
|
|
462
|
+
new = _dump(s) if s else None
|
|
463
|
+
if new != _read(path):
|
|
464
|
+
plan.write(path, new)
|
|
465
|
+
mp = os.path.join(root, ".mcp.json")
|
|
466
|
+
m = _load_json(mp)
|
|
467
|
+
if m and isinstance(m.get("mcpServers"), dict) and _mentions(MCP_MARK, json.dumps(m["mcpServers"].get(SERVER_NAME, {}))):
|
|
468
|
+
del m["mcpServers"][SERVER_NAME]
|
|
469
|
+
if not m["mcpServers"]:
|
|
470
|
+
m.pop("mcpServers")
|
|
471
|
+
plan.write(mp, _dump(m) if m else None)
|
|
472
|
+
seen: list[str] = []
|
|
473
|
+
for name in ("CLAUDE.md", "AGENTS.md", "agents.md"):
|
|
474
|
+
p = os.path.join(root, name)
|
|
475
|
+
if not os.path.isfile(p) or any(os.path.samefile(p, q) for q in seen):
|
|
476
|
+
continue # also dedupes case-insensitive filesystems and symlinks
|
|
477
|
+
seen.append(p)
|
|
478
|
+
t = _read(p)
|
|
479
|
+
if t and BEGIN in t and END in t:
|
|
480
|
+
rest = _without_block(t)
|
|
481
|
+
plan.write(p, rest if rest.strip() else None) # file held only our block -> it was ours
|
|
482
|
+
changed = plan.changed()
|
|
483
|
+
if a.dry_run:
|
|
484
|
+
print(f"[dry-run] would change {len(changed)} file(s)")
|
|
485
|
+
plan.show()
|
|
486
|
+
return 0
|
|
487
|
+
plan.apply(root, backup=False)
|
|
488
|
+
claude_dir = os.path.join(root, ".claude")
|
|
489
|
+
if os.path.isdir(claude_dir) and not os.listdir(claude_dir):
|
|
490
|
+
os.rmdir(claude_dir)
|
|
491
|
+
for p in changed:
|
|
492
|
+
print(f" {'removed' if plan.writes[p][1] is None else 'updated'} {os.path.relpath(p, root)}")
|
|
493
|
+
if a.purge:
|
|
494
|
+
import shutil
|
|
495
|
+
|
|
496
|
+
d = os.path.join(root, ".smarty")
|
|
497
|
+
if os.path.isdir(d):
|
|
498
|
+
shutil.rmtree(d)
|
|
499
|
+
print(" removed .smarty/")
|
|
500
|
+
print("uninstalled" if changed or a.purge else "nothing to remove")
|
|
501
|
+
return 0
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
505
|
+
ap = argparse.ArgumentParser(prog="smarty", description=__doc__.split("\n")[1])
|
|
506
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
507
|
+
|
|
508
|
+
def common(p: argparse.ArgumentParser) -> None:
|
|
509
|
+
p.add_argument("--root", default=".", help="target repository (default: cwd)")
|
|
510
|
+
p.add_argument("--home", default=None, help=argparse.SUPPRESS) # explicit => must be a complete clone install
|
|
511
|
+
|
|
512
|
+
i = sub.add_parser("init", help="register hooks + MCP server, build the index")
|
|
513
|
+
common(i)
|
|
514
|
+
i.add_argument("--dry-run", action="store_true", help="show diffs, write nothing")
|
|
515
|
+
i.add_argument("--scope", choices=("local", "project"), default="local",
|
|
516
|
+
help="where new hooks go: .claude/settings.local.json (default, machine-specific) or settings.json")
|
|
517
|
+
i.add_argument("--python", help="interpreter for hooks/MCP (default: the one running smarty)")
|
|
518
|
+
i.add_argument("--no-hooks", action="store_true")
|
|
519
|
+
i.add_argument("--no-mcp", action="store_true")
|
|
520
|
+
i.add_argument("--no-index", action="store_true")
|
|
521
|
+
i.add_argument("--agents-md", nargs="?", const="AUTO", default=None, metavar="FILE",
|
|
522
|
+
help="append a static marker-fenced cartridge to CLAUDE.md/AGENTS.md (or FILE)")
|
|
523
|
+
i.set_defaults(fn=cmd_init)
|
|
524
|
+
d = sub.add_parser("doctor", help="verify an install end to end")
|
|
525
|
+
common(d)
|
|
526
|
+
d.set_defaults(fn=cmd_doctor)
|
|
527
|
+
au = sub.add_parser("audit", help="where do your agent sessions' tokens go? (reads Claude Code transcripts)")
|
|
528
|
+
au.add_argument("audit_args", nargs=argparse.REMAINDER, help="passed to token_audit (see: python token_audit.py -h)")
|
|
529
|
+
au.set_defaults(fn=cmd_audit)
|
|
530
|
+
for name, fn, helptext in (("serve", cmd_serve, "OpenAI-compatible gateway proxy (see: python gateway.py -h)"),
|
|
531
|
+
("stats", cmd_stats, "savings ledger report (see: python ledger.py -h)"),
|
|
532
|
+
("bench", cmd_bench, "replay recorded requests through the gate offline (see: python gate_bench.py -h)")):
|
|
533
|
+
sp = sub.add_parser(name, help=helptext)
|
|
534
|
+
sp.add_argument("rest", nargs=argparse.REMAINDER)
|
|
535
|
+
sp.set_defaults(fn=fn)
|
|
536
|
+
u = sub.add_parser("uninstall", help="remove what init added")
|
|
537
|
+
common(u)
|
|
538
|
+
u.add_argument("--dry-run", action="store_true")
|
|
539
|
+
u.add_argument("--purge", action="store_true", help="also delete the .smarty/ index")
|
|
540
|
+
u.set_defaults(fn=cmd_uninstall)
|
|
541
|
+
return ap
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
DELEGATED = {"serve": "gateway", "stats": "ledger", "bench": "gate_bench", "audit": "token_audit"}
|
|
545
|
+
|
|
546
|
+
|
|
547
|
+
def main(argv: list[str] | None = None) -> int:
|
|
548
|
+
argv = sys.argv[1:] if argv is None else argv
|
|
549
|
+
if argv and argv[0] in DELEGATED: # hand the rest to the module untouched (argparse REMAINDER breaks on a leading option)
|
|
550
|
+
return _delegate(DELEGATED[argv[0]], argv[1:])
|
|
551
|
+
a = build_parser().parse_args(argv)
|
|
552
|
+
try:
|
|
553
|
+
return a.fn(a)
|
|
554
|
+
except InitError as exc:
|
|
555
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
556
|
+
return 2
|
|
557
|
+
|
|
558
|
+
|
|
559
|
+
if __name__ == "__main__":
|
|
560
|
+
sys.exit(main())
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
from dataclasses import dataclass, field
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
@dataclass
|
|
6
|
+
class TokenBudget:
|
|
7
|
+
"""
|
|
8
|
+
Step 1: Token-Aware Budgeting contract.
|
|
9
|
+
Per-section token budgets. NOTE: max_total_tokens is advisory; it is not
|
|
10
|
+
enforced as a total ceiling on the compiled payload.
|
|
11
|
+
"""
|
|
12
|
+
max_total_tokens: int = 512
|
|
13
|
+
core_query_budget: int = 120
|
|
14
|
+
context_budget: int = 160
|
|
15
|
+
history_budget: int = 80
|
|
16
|
+
tools_budget: int = 60
|
|
17
|
+
few_shot_budget: int = 90
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class RawRequest:
|
|
22
|
+
text: str
|
|
23
|
+
task_hint: str = "" # optional caller-supplied intent hint
|
|
24
|
+
context_chunks: list[str] = field(default_factory=list) # Step 3: external RAG chunks to prune via MMR
|
|
25
|
+
conversation_history: list[dict[str, str]] = field(default_factory=list) # Step 7: [{"role": "user"|"assistant", "content": "..."}]
|
|
26
|
+
token_budget: TokenBudget = field(default_factory=TokenBudget) # Step 1: token-aware budget
|
|
27
|
+
compression_intensity: str = "AUTO" # Step 8: "AUTO" | "LIGHT" | "MEDIUM" | "AGGRESSIVE"
|
|
28
|
+
enable_cache: bool = True # Step 6: deterministic prompt cache toggle
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class OptimizationTrace:
|
|
33
|
+
# Step 9: Comprehensive Before & After Token Measurements (Words + BPE Subword Tokens)
|
|
34
|
+
raw_token_count: int = 0
|
|
35
|
+
optimized_token_count: int = 0
|
|
36
|
+
query_token_savings_pct: float = 0.0
|
|
37
|
+
raw_bpe_tokens: int = 0
|
|
38
|
+
optimized_bpe_tokens: int = 0
|
|
39
|
+
query_bpe_savings_pct: float = 0.0
|
|
40
|
+
unoptimized_payload_token_count: int = 0
|
|
41
|
+
compiled_payload_token_count: int = 0
|
|
42
|
+
payload_token_savings_pct: float = 0.0
|
|
43
|
+
tool_schema_tokens_saved: int = 0
|
|
44
|
+
|
|
45
|
+
# Per-Section Token Breakdown & Context Pruning Stats
|
|
46
|
+
compressed_query_text: str = ""
|
|
47
|
+
total_context_chunks: int = 0
|
|
48
|
+
raw_context_tokens: int = 0
|
|
49
|
+
pruned_context_tokens: int = 0
|
|
50
|
+
context_token_savings_pct: float = 0.0
|
|
51
|
+
raw_history_tokens: int = 0
|
|
52
|
+
pruned_history_tokens: int = 0
|
|
53
|
+
raw_tools_tokens: int = 0
|
|
54
|
+
compressed_tools_tokens: int = 0
|
|
55
|
+
raw_examples_tokens: int = 0
|
|
56
|
+
selected_examples_tokens: int = 0
|
|
57
|
+
|
|
58
|
+
# Routing & Extraction Audit
|
|
59
|
+
detected_intent: str = ""
|
|
60
|
+
secondary_intents: list[str] = field(default_factory=list)
|
|
61
|
+
intent_confidence: float = 0.0
|
|
62
|
+
compression_intensity_used: str = "LIGHT"
|
|
63
|
+
pruning_strategy_used: str = "MMR+BM25+TFIDF"
|
|
64
|
+
|
|
65
|
+
# Transformation Details & Step-by-Step Stage Audit Logs
|
|
66
|
+
stripped_tokens: list[str] = field(default_factory=list)
|
|
67
|
+
normalized_phrases: list[str] = field(default_factory=list)
|
|
68
|
+
injected_example_ids: list[str] = field(default_factory=list)
|
|
69
|
+
injected_tool_ids: list[str] = field(default_factory=list)
|
|
70
|
+
kept_context_indices: list[int] = field(default_factory=list)
|
|
71
|
+
kept_history_turns: int = 0
|
|
72
|
+
extracted_entities: dict[str, Any] = field(default_factory=dict)
|
|
73
|
+
negations: list[str] = field(default_factory=list)
|
|
74
|
+
stage_logs: list[str] = field(default_factory=list)
|
|
75
|
+
|
|
76
|
+
# Step 6: Caching & Telemetry
|
|
77
|
+
cache_hit: bool = False
|
|
78
|
+
cache_type: str = "NONE" # "NONE" | "CANONICAL_EXACT" | "SIMHASH_NEAR"
|
|
79
|
+
cache_key: str = ""
|
|
80
|
+
simhash_signature: str = ""
|
|
81
|
+
latency_ms: float = 0.0
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@dataclass
|
|
85
|
+
class CompiledPrompt:
|
|
86
|
+
payload: str # final XML/Markdown string for downstream agent
|
|
87
|
+
trace: OptimizationTrace
|
|
88
|
+
status: str = "OK" # "OK" | "NEEDS_CLARIFICATION" | "INSUFFICIENT_CONTEXT"
|
|
89
|
+
clarification_request: str = ""
|