@allansantos-dev/smart-tool 0.9.16 → 0.9.17
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.
- package/CHANGELOG.md +9 -0
- package/README.md +11 -1
- package/client_hooks.py +122 -4
- package/hooks/session_audit.py +39 -0
- package/install.py +5 -4
- package/package.json +1 -1
- package/setup_audit.py +29 -0
- package/setup_ui.py +73 -1
- package/smart_tool_daemon.py +54 -5
- package/version.py +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.9.17 - beta
|
|
4
|
+
|
|
5
|
+
- The agent learns the setup audit result without asking for it. On its first `smart_search` of a session, once per
|
|
6
|
+
folder, it gets one short line when the stored audit has errors or warnings (nothing when clean, nothing is run).
|
|
7
|
+
`project_manage action=setup_audit mode=last` returns the stored report without auditing again.
|
|
8
|
+
- Optional **Report at session start (Claude Code)** on the Setup audit page: off by default; it previews the exact
|
|
9
|
+
SessionStart entry, writes it to Claude Code's settings after you confirm (backup first), and **Turn off** removes
|
|
10
|
+
only that entry. While it is on, the search no longer repeats the line.
|
|
11
|
+
|
|
3
12
|
## 0.9.16 - beta
|
|
4
13
|
|
|
5
14
|
- New setup screen. It opens on an **Overview** that checks everything Smart Tool needs on this machine (model
|
package/README.md
CHANGED
|
@@ -15,7 +15,7 @@ registered as the `playwright` server where this machine lets a browser be drive
|
|
|
15
15
|
An optional hook routes the agent's native Grep/Glob/Read/Bash/WebSearch/WebFetch calls to these tools when they
|
|
16
16
|
are cheaper, or just tells the agent what Smart Tool would do.
|
|
17
17
|
|
|
18
|
-
**Status:** 0.9.
|
|
18
|
+
**Status:** 0.9.17 beta. Windows only. What changed in each version: [CHANGELOG.md](CHANGELOG.md).
|
|
19
19
|
|
|
20
20
|
## How it works
|
|
21
21
|
|
|
@@ -173,6 +173,16 @@ Redirects) and Maintenance (Setup audit, Startup).
|
|
|
173
173
|
and their result reused for 6 hours; Run now always contacts them again), and the setup screen's **Setup audit**
|
|
174
174
|
panel shows each project's last report: findings by severity, what is new, what was resolved, the tokens each MCP
|
|
175
175
|
server's tools cost and what was not verified.
|
|
176
|
+
|
|
177
|
+
The agent hears about it without asking for it. `setup_audit` with `mode=last` returns the stored report for the
|
|
178
|
+
folder (or the nearest audited parent) without auditing again, and fails with what to do when none is stored. On
|
|
179
|
+
its first `smart_search` of a session, and once per folder, the agent also gets one short line (under 100 tokens)
|
|
180
|
+
when the stored report holds errors or warnings; a clean report adds nothing. Optionally, **Report at session
|
|
181
|
+
start (Claude Code)** on the Setup audit page moves that line to the start of every new session: it previews the
|
|
182
|
+
exact SessionStart entry, adds it to `~/.claude/settings.json` only after you confirm (backup first), and **Turn
|
|
183
|
+
off** removes only that entry. It is off by default; while it is on, the search no longer repeats the line. The
|
|
184
|
+
hook script (`hooks/session_audit.py`) only reads the stored report from the running service and prints nothing
|
|
185
|
+
when the service is down.
|
|
176
186
|
4. **Local models** (optional): if the mcp-memory embedding sidecar is installed on the machine, its local embedder
|
|
177
187
|
can serve as a fallback (or preferred) embedding model.
|
|
178
188
|
5. **Web search providers** work without keys on their free public tiers; add your own key for more volume. Set your
|
package/client_hooks.py
CHANGED
|
@@ -10,6 +10,10 @@ import endpoint_sync
|
|
|
10
10
|
|
|
11
11
|
HOOK_SCRIPT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "hooks", "pretool_router.py")
|
|
12
12
|
MARKER = "pretool_router.py"
|
|
13
|
+
AUDIT_SCRIPT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "hooks", "session_audit.py")
|
|
14
|
+
AUDIT_MARKER = "session_audit.py"
|
|
15
|
+
AUDIT_MATCHER = "startup|resume|clear"
|
|
16
|
+
AUDIT_TIMEOUT_S = 10
|
|
13
17
|
HTTP_PATH = "/hooks/pretool"
|
|
14
18
|
HTTP_TIMEOUT_S = 15
|
|
15
19
|
HOME = os.path.expanduser("~")
|
|
@@ -202,6 +206,8 @@ def preview(client_info):
|
|
|
202
206
|
|
|
203
207
|
|
|
204
208
|
def install(client_info, token, confirm):
|
|
209
|
+
"""Writes the redirect hook for client_info's client with a backup; needs the `preview` token of this session
|
|
210
|
+
(10 min) and confirm=True. Returns {client, installed, changed, file, backup}."""
|
|
205
211
|
planned = _PREVIEWS.pop(token or "", None)
|
|
206
212
|
client, spec, path, data, groups, entry = _plan(client_info)
|
|
207
213
|
if confirm is not True or not planned or planned["client"] != client or time.time() - planned["at"] > PREVIEW_TTL_S:
|
|
@@ -209,6 +215,14 @@ def install(client_info, token, confirm):
|
|
|
209
215
|
if installed(client):
|
|
210
216
|
return {"client": client, "installed": True, "changed": False, "file": path}
|
|
211
217
|
groups.append(entry)
|
|
218
|
+
backup = _write_checked(path, data, lambda: installed(client), "The hook")
|
|
219
|
+
return {"client": client, "installed": True, "changed": True, "file": path, "backup": backup,
|
|
220
|
+
"after_install": spec.get("after_install")}
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _write_checked(path, data, verify, what):
|
|
224
|
+
"""Writes data as JSON to path through a temp file after a timestamped backup; when verify() fails on the written
|
|
225
|
+
file, restores the backup (or removes the new file) and raises. Returns the backup path (None for a new file)."""
|
|
212
226
|
backup = None
|
|
213
227
|
if os.path.exists(path):
|
|
214
228
|
backup = f"{path}.smart-tool-backup-{time.strftime('%Y%m%d-%H%M%S')}"
|
|
@@ -218,9 +232,113 @@ def install(client_info, token, confirm):
|
|
|
218
232
|
with open(temporary, "w", encoding="utf-8") as stream:
|
|
219
233
|
json.dump(data, stream, indent=2, ensure_ascii=False)
|
|
220
234
|
os.replace(temporary, path)
|
|
221
|
-
if not
|
|
235
|
+
if not verify():
|
|
222
236
|
if backup:
|
|
223
237
|
shutil.copy2(backup, path)
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
238
|
+
else:
|
|
239
|
+
os.remove(path)
|
|
240
|
+
raise RuntimeError(f"{what} does not appear in {path} after writing; the file was restored.")
|
|
241
|
+
return backup
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _audit_hook(hook):
|
|
245
|
+
return isinstance(hook, dict) and AUDIT_MARKER in str(hook.get("command", ""))
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _audit_ours(group):
|
|
249
|
+
return isinstance(group, dict) and isinstance(group.get("hooks"), list) and any(map(_audit_hook, group["hooks"]))
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _audit_entry():
|
|
253
|
+
return {"matcher": AUDIT_MATCHER,
|
|
254
|
+
"hooks": [{"type": "command", "command": f"{_shell_safe(sys.executable)} {_shell_safe(AUDIT_SCRIPT)}",
|
|
255
|
+
"timeout": AUDIT_TIMEOUT_S}]}
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _audit_plan():
|
|
259
|
+
"""(path, data, groups) of Claude Code's settings with our SessionStart entry already removed from groups."""
|
|
260
|
+
path = os.path.realpath(CLIENTS["claude"]["files"][0])
|
|
261
|
+
try:
|
|
262
|
+
with open(path, encoding="utf-8") as stream:
|
|
263
|
+
data = json.load(stream)
|
|
264
|
+
except FileNotFoundError:
|
|
265
|
+
data = {}
|
|
266
|
+
if not isinstance(data, dict) or not isinstance(data.setdefault("hooks", {}), dict):
|
|
267
|
+
raise ValueError(f"{path} does not have the expected format (object with 'hooks'); nothing was changed.")
|
|
268
|
+
groups = data["hooks"].setdefault("SessionStart", [])
|
|
269
|
+
if not isinstance(groups, list):
|
|
270
|
+
raise ValueError(f"{path}: hooks.SessionStart is not a list; nothing was changed.")
|
|
271
|
+
kept = []
|
|
272
|
+
for group in groups:
|
|
273
|
+
if not _audit_ours(group):
|
|
274
|
+
kept.append(group)
|
|
275
|
+
continue
|
|
276
|
+
others = [hook for hook in group["hooks"] if not _audit_hook(hook)]
|
|
277
|
+
if others:
|
|
278
|
+
kept.append({**group, "hooks": others})
|
|
279
|
+
groups[:] = kept
|
|
280
|
+
return path, data, groups
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def audit_state():
|
|
284
|
+
"""The SessionStart audit hook in Claude Code's settings: `current` (our entry equals this version's), `outdated`
|
|
285
|
+
(an entry of ours that differs) or `missing`."""
|
|
286
|
+
path = CLIENTS["claude"]["files"][0]
|
|
287
|
+
try:
|
|
288
|
+
with open(path, encoding="utf-8") as stream:
|
|
289
|
+
data = json.load(stream)
|
|
290
|
+
except FileNotFoundError:
|
|
291
|
+
return "missing"
|
|
292
|
+
groups = ((data.get("hooks") or {}).get("SessionStart") or []) if isinstance(data, dict) else []
|
|
293
|
+
found = [group for group in groups if _audit_ours(group)] if isinstance(groups, list) else []
|
|
294
|
+
if not found:
|
|
295
|
+
return "missing"
|
|
296
|
+
return "current" if _audit_entry() in found else "outdated"
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def audit_hook_installed(client):
|
|
300
|
+
"""The Claude Code session-start audit report is on, so a search need not repeat it. An unreadable settings file
|
|
301
|
+
counts as off here; `audit_state` raises for it on the setup screen."""
|
|
302
|
+
if client != "claude":
|
|
303
|
+
return False
|
|
304
|
+
try:
|
|
305
|
+
return audit_state() == "current"
|
|
306
|
+
except (OSError, ValueError):
|
|
307
|
+
return False
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def audit_preview():
|
|
311
|
+
"""The change that turns the SessionStart audit report on in Claude Code, with a token for `audit_install`."""
|
|
312
|
+
path, _data, _groups = _audit_plan()
|
|
313
|
+
entry = _audit_entry()
|
|
314
|
+
if audit_state() == "current":
|
|
315
|
+
return {"installed": True, "file": path, "change": None}
|
|
316
|
+
token = secrets.token_urlsafe(12)
|
|
317
|
+
_PREVIEWS[token] = {"client": "audit", "at": time.time()}
|
|
318
|
+
return {"installed": False, "file": path, "event": "SessionStart", "change": entry, "token": token,
|
|
319
|
+
"expires_s": PREVIEW_TTL_S}
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def audit_install(token, confirm):
|
|
323
|
+
"""Writes the SessionStart audit entry into Claude Code's settings with a backup; needs the `audit_preview` token
|
|
324
|
+
(10 min) and confirm=True. Returns {installed, changed, file, backup}."""
|
|
325
|
+
planned = _PREVIEWS.pop(token or "", None)
|
|
326
|
+
if confirm is not True or not planned or planned["client"] != "audit" or time.time() - planned["at"] > PREVIEW_TTL_S:
|
|
327
|
+
raise ValueError("Turning the audit report on requires the preview token (valid for 10 min) and confirm=true.")
|
|
328
|
+
path, data, groups = _audit_plan()
|
|
329
|
+
if audit_state() == "current":
|
|
330
|
+
return {"installed": True, "changed": False, "file": path}
|
|
331
|
+
groups.append(_audit_entry())
|
|
332
|
+
backup = _write_checked(path, data, lambda: audit_state() == "current", "The audit hook")
|
|
333
|
+
return {"installed": True, "changed": True, "file": path, "backup": backup}
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def audit_remove():
|
|
337
|
+
"""Takes only our SessionStart entry out of Claude Code's settings (after a backup); nothing else is touched."""
|
|
338
|
+
path, data, groups = _audit_plan()
|
|
339
|
+
if audit_state() == "missing":
|
|
340
|
+
return {"installed": False, "changed": False, "file": path}
|
|
341
|
+
if not groups:
|
|
342
|
+
del data["hooks"]["SessionStart"]
|
|
343
|
+
backup = _write_checked(path, data, lambda: audit_state() == "missing", "The removal")
|
|
344
|
+
return {"installed": False, "changed": True, "file": path, "backup": backup}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""SessionStart hook of Claude Code (opt-in, from the setup screen): forwards the payload to the Smart Tool daemon
|
|
3
|
+
(POST /hooks/session-audit) and prints its answer, the stored setup audit notice of the session folder as additional
|
|
4
|
+
context. Never starts the daemon or an audit: daemon down or any error means empty output, so a session start is
|
|
5
|
+
never delayed or blocked.
|
|
6
|
+
"""
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import sys
|
|
10
|
+
import urllib.request
|
|
11
|
+
|
|
12
|
+
sys.stdin.reconfigure(encoding="utf-8")
|
|
13
|
+
sys.stdout.reconfigure(encoding="utf-8")
|
|
14
|
+
|
|
15
|
+
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
|
|
16
|
+
import daemon_launcher
|
|
17
|
+
|
|
18
|
+
TIMEOUT_S = 5
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def main():
|
|
22
|
+
"""Posts the SessionStart payload read from stdin to the running daemon and prints its JSON answer if not empty."""
|
|
23
|
+
raw = sys.stdin.buffer.read()
|
|
24
|
+
base = daemon_launcher.daemon_url_if_up()
|
|
25
|
+
if not base:
|
|
26
|
+
return
|
|
27
|
+
request = urllib.request.Request(f"{base}/hooks/session-audit", data=raw,
|
|
28
|
+
headers={"Content-Type": "application/json"}, method="POST")
|
|
29
|
+
with urllib.request.urlopen(request, timeout=TIMEOUT_S) as response:
|
|
30
|
+
output = json.loads(response.read() or b"{}")
|
|
31
|
+
if output:
|
|
32
|
+
print(json.dumps(output, ensure_ascii=False))
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
if __name__ == "__main__":
|
|
36
|
+
try:
|
|
37
|
+
main()
|
|
38
|
+
except BaseException:
|
|
39
|
+
pass
|
package/install.py
CHANGED
|
@@ -17,7 +17,8 @@ import paths
|
|
|
17
17
|
SOURCE = Path(__file__).resolve().parent
|
|
18
18
|
DEFAULT_TARGET = Path(os.environ.get("LOCALAPPDATA", str(Path.home() / "AppData" / "Local"))) / "Programs" / "SmartTool"
|
|
19
19
|
TASK_NAME = "SmartTool-Tray"
|
|
20
|
-
ENTRY_SCRIPTS = ("tray.py", "smart_tool_daemon.py", "pretool_router.py")
|
|
20
|
+
ENTRY_SCRIPTS = ("tray.py", "smart_tool_daemon.py", "pretool_router.py", "session_audit.py")
|
|
21
|
+
HOOK_SCRIPTS = ("pretool_router.py", "session_audit.py")
|
|
21
22
|
STARTUP_SCRIPT = Path(os.environ.get("APPDATA", str(Path.home() / "AppData" / "Roaming"))) / "Microsoft" / "Windows" / \
|
|
22
23
|
"Start Menu" / "Programs" / "Startup" / "SmartTool-Tray.vbs"
|
|
23
24
|
MANIFEST = ".install-manifest.json"
|
|
@@ -65,7 +66,7 @@ def _processes():
|
|
|
65
66
|
|
|
66
67
|
def _script_folder(script):
|
|
67
68
|
path = Path(script)
|
|
68
|
-
return path.parent.parent if path.name
|
|
69
|
+
return path.parent.parent if path.name in HOOK_SCRIPTS else path.parent
|
|
69
70
|
|
|
70
71
|
|
|
71
72
|
def _same_folder(path, folder):
|
|
@@ -79,7 +80,7 @@ def _same_folder(path, folder):
|
|
|
79
80
|
def stop_processes(target):
|
|
80
81
|
def running():
|
|
81
82
|
return [pid for pid, line in _processes() for script in _script_paths(line)
|
|
82
|
-
if Path(script).name
|
|
83
|
+
if Path(script).name not in HOOK_SCRIPTS and _same_folder(_script_folder(script), target)]
|
|
83
84
|
|
|
84
85
|
for pid in running():
|
|
85
86
|
powershell(f"Stop-Process -Id {pid} -Force -ErrorAction SilentlyContinue")
|
|
@@ -169,7 +170,7 @@ def other_installs(target):
|
|
|
169
170
|
def _repointed(text, folder, target):
|
|
170
171
|
"""text with each spelling of folder found in front of an entry script (long, 8.3 or mixed) replaced by target."""
|
|
171
172
|
for script in set(_script_paths(text)):
|
|
172
|
-
cut = len(Path(script).name) + 1 + (len("hooks") + 1 if Path(script).name
|
|
173
|
+
cut = len(Path(script).name) + 1 + (len("hooks") + 1 if Path(script).name in HOOK_SCRIPTS else 0)
|
|
173
174
|
spelled = script[:-cut]
|
|
174
175
|
if _same_folder(Path(spelled), folder):
|
|
175
176
|
text = text.replace(spelled, target.as_posix() if "/" in spelled else str(target))
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@allansantos-dev/smart-tool",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.17",
|
|
4
4
|
"description": "Local MCP server that gives coding agents (Claude Code, Codex) cheaper, sharper tools than their built-in search. Windows.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "Allan Santos",
|
package/setup_audit.py
CHANGED
|
@@ -671,6 +671,35 @@ def last_report(project):
|
|
|
671
671
|
return None
|
|
672
672
|
|
|
673
673
|
|
|
674
|
+
def stored_for(path):
|
|
675
|
+
"""The last stored report of path or of its nearest audited ancestor folder, or None when none was audited."""
|
|
676
|
+
folder = os.path.abspath(path)
|
|
677
|
+
while True:
|
|
678
|
+
report = last_report(folder)
|
|
679
|
+
if report is not None:
|
|
680
|
+
return report
|
|
681
|
+
parent = os.path.dirname(folder)
|
|
682
|
+
if parent == folder:
|
|
683
|
+
return None
|
|
684
|
+
folder = parent
|
|
685
|
+
|
|
686
|
+
|
|
687
|
+
def session_notice(path):
|
|
688
|
+
"""One short line for the agent about the stored audit of path (nothing is run), or "" when there is no stored
|
|
689
|
+
report or it holds no error or warning."""
|
|
690
|
+
report = stored_for(path)
|
|
691
|
+
if report is None:
|
|
692
|
+
return ""
|
|
693
|
+
summary = report["summary"]
|
|
694
|
+
if not summary["error"] and not summary["warn"]:
|
|
695
|
+
return ""
|
|
696
|
+
new = sum(1 for f in report["findings"] if f.get("new") and f["severity"] in ("error", "warn"))
|
|
697
|
+
age = max(0, int((time.time() - report["checked_at"]) // 60))
|
|
698
|
+
return (f"Setup audit of {report['project']} ({age} min ago): {summary['error']} errors, {summary['warn']} "
|
|
699
|
+
f"warnings" + (f", {new} new" if new else "") + " in the agent configuration. Details without rerunning: "
|
|
700
|
+
"project_manage action=setup_audit mode=last.")
|
|
701
|
+
|
|
702
|
+
|
|
674
703
|
def index():
|
|
675
704
|
"""{project: {summary, new, resolved, checked_at, trigger}} of every audited project (the periodic summary)."""
|
|
676
705
|
try:
|
package/setup_ui.py
CHANGED
|
@@ -261,11 +261,21 @@ def handle_integration_save(body):
|
|
|
261
261
|
def handle_audit(body):
|
|
262
262
|
"""Setup audit panel: `index` lists the registered projects with their last audit summary; `report` returns the
|
|
263
263
|
last stored report of one of them; `run` audits it now (MCP servers contacted unless probe is false). Only
|
|
264
|
-
registered project folders are accepted.
|
|
264
|
+
registered project folders are accepted. The opt-in session-start report in Claude Code: `hook_state`,
|
|
265
|
+
`hook_preview` (the exact entry and a token), `hook_install` (with that token, after a backup) and `hook_remove`
|
|
266
|
+
(only Smart Tool's entry, after a backup)."""
|
|
265
267
|
if not isinstance(body, dict):
|
|
266
268
|
raise SetupError("Invalid request.")
|
|
267
269
|
roots = sorted({p["root"] for p in project_store.all_projects() if p.get("root")}, key=str.casefold)
|
|
268
270
|
try:
|
|
271
|
+
if body.get("action") == "hook_state":
|
|
272
|
+
return {"state": client_hooks.audit_state(), "file": client_hooks.CLIENTS["claude"]["files"][0]}
|
|
273
|
+
if body.get("action") == "hook_preview":
|
|
274
|
+
return client_hooks.audit_preview()
|
|
275
|
+
if body.get("action") == "hook_install":
|
|
276
|
+
return client_hooks.audit_install(body.get("token"), True)
|
|
277
|
+
if body.get("action") == "hook_remove":
|
|
278
|
+
return client_hooks.audit_remove()
|
|
269
279
|
if body.get("action") == "index":
|
|
270
280
|
stored = setup_audit.index()
|
|
271
281
|
found = {root: stored[setup_audit.index_key(root)] for root in roots if setup_audit.index_key(root) in stored}
|
|
@@ -714,6 +724,17 @@ _PAGE_TEMPLATE = """<!doctype html>
|
|
|
714
724
|
<section class="page" data-page="audit" aria-labelledby="h-audit" hidden>
|
|
715
725
|
<header class="page-head"><h2 id="h-audit" tabindex="-1">Setup audit</h2>
|
|
716
726
|
<p>What Claude Code and Codex load for a project, and where they collide: hooks deciding on the same tool at once, hooks or MCP servers that do not work, tools offered twice, skills and instructions one agent never sees. It runs on its own for the registered projects and never changes anything.</p></header>
|
|
727
|
+
<div class="card">
|
|
728
|
+
<div class="card-head"><h3>Report at session start (Claude Code)</h3><span class="pill" id="audit-hook-pill" data-tone="busy">Checking</span></div>
|
|
729
|
+
<p class="lede">Off by default. When on, every new Claude Code session starts with one short line about the stored audit of its folder (errors and warnings only, nothing runs). It adds a SessionStart entry to <span class="mono" id="audit-hook-file"></span>, written after a backup, and turning it off removes only that entry. Without it, the agent gets the same line once, on its first search.</p>
|
|
730
|
+
<div class="actions"><button type="button" class="primary" id="btn-audit-hook-on" hidden>Turn on</button><button type="button" id="btn-audit-hook-off" hidden>Turn off</button></div>
|
|
731
|
+
<div id="audit-hook-confirm" hidden>
|
|
732
|
+
<p class="hint" id="audit-hook-where"></p>
|
|
733
|
+
<pre class="mono" id="audit-hook-preview"></pre>
|
|
734
|
+
<div class="actions"><button type="button" class="primary" id="btn-audit-hook-write">Write it</button><button type="button" id="btn-audit-hook-cancel">Cancel</button></div>
|
|
735
|
+
</div>
|
|
736
|
+
<div class="msg" id="audit-hook-msg" role="status"></div>
|
|
737
|
+
</div>
|
|
717
738
|
<div class="card">
|
|
718
739
|
<div class="field"><label for="sel-audit-project">Project</label>
|
|
719
740
|
<select id="sel-audit-project"></select>
|
|
@@ -1716,6 +1737,56 @@ async function loadAudit() {
|
|
|
1716
1737
|
}
|
|
1717
1738
|
renderOverview();
|
|
1718
1739
|
}
|
|
1740
|
+
async function loadAuditHook() {
|
|
1741
|
+
try {
|
|
1742
|
+
const hook = await post("/setup/audit", { action: "hook_state" });
|
|
1743
|
+
$("audit-hook-file").textContent = hook.file;
|
|
1744
|
+
const on = hook.state === "current";
|
|
1745
|
+
const pillEl = $("audit-hook-pill");
|
|
1746
|
+
pillEl.textContent = on ? "On" : hook.state === "outdated" ? "Outdated" : "Off";
|
|
1747
|
+
pillEl.dataset.tone = on ? "ok" : hook.state === "outdated" ? "warn" : "idle";
|
|
1748
|
+
$("btn-audit-hook-on").hidden = on;
|
|
1749
|
+
$("btn-audit-hook-on").textContent = hook.state === "outdated" ? "Update" : "Turn on";
|
|
1750
|
+
$("btn-audit-hook-off").hidden = hook.state === "missing";
|
|
1751
|
+
} catch (error) {
|
|
1752
|
+
setMsg("audit-hook-msg", "error", "Session-start report state unavailable: " + error.message);
|
|
1753
|
+
}
|
|
1754
|
+
}
|
|
1755
|
+
$("btn-audit-hook-on").addEventListener("click", async () => {
|
|
1756
|
+
setMsg("audit-hook-msg", "", "Preparing the change…");
|
|
1757
|
+
try {
|
|
1758
|
+
const plan = await post("/setup/audit", { action: "hook_preview" });
|
|
1759
|
+
setMsg("audit-hook-msg", "", "");
|
|
1760
|
+
$("audit-hook-where").textContent = "Adds this entry under " + plan.event + " in " + plan.file + ".";
|
|
1761
|
+
$("audit-hook-preview").textContent = JSON.stringify(plan.change, null, 2);
|
|
1762
|
+
$("audit-hook-confirm").hidden = false;
|
|
1763
|
+
$("btn-audit-hook-write").onclick = async () => {
|
|
1764
|
+
$("btn-audit-hook-write").disabled = true;
|
|
1765
|
+
try {
|
|
1766
|
+
const result = await post("/setup/audit", { action: "hook_install", token: plan.token });
|
|
1767
|
+
$("audit-hook-confirm").hidden = true;
|
|
1768
|
+
await loadAuditHook();
|
|
1769
|
+
setMsg("audit-hook-msg", "ok", "Turned on. Backup: " + (result.backup || "none, the file was new") + ".");
|
|
1770
|
+
} catch (error) {
|
|
1771
|
+
setMsg("audit-hook-msg", "error", error.message);
|
|
1772
|
+
} finally {
|
|
1773
|
+
$("btn-audit-hook-write").disabled = false;
|
|
1774
|
+
}
|
|
1775
|
+
};
|
|
1776
|
+
} catch (error) {
|
|
1777
|
+
setMsg("audit-hook-msg", "error", error.message);
|
|
1778
|
+
}
|
|
1779
|
+
});
|
|
1780
|
+
$("btn-audit-hook-cancel").addEventListener("click", () => { $("audit-hook-confirm").hidden = true; });
|
|
1781
|
+
$("btn-audit-hook-off").addEventListener("click", async () => {
|
|
1782
|
+
try {
|
|
1783
|
+
const result = await post("/setup/audit", { action: "hook_remove" });
|
|
1784
|
+
await loadAuditHook();
|
|
1785
|
+
setMsg("audit-hook-msg", "ok", "Turned off. Backup: " + (result.backup || "none") + ".");
|
|
1786
|
+
} catch (error) {
|
|
1787
|
+
setMsg("audit-hook-msg", "error", error.message);
|
|
1788
|
+
}
|
|
1789
|
+
});
|
|
1719
1790
|
$("sel-audit-project").addEventListener("change", () => showAudit($("sel-audit-project").value));
|
|
1720
1791
|
$("btn-audit-run").addEventListener("click", async () => {
|
|
1721
1792
|
const run = $("btn-audit-run");
|
|
@@ -1739,6 +1810,7 @@ loadIntegration();
|
|
|
1739
1810
|
loadAutostart();
|
|
1740
1811
|
loadProviders();
|
|
1741
1812
|
loadAudit();
|
|
1813
|
+
loadAuditHook();
|
|
1742
1814
|
setInterval(refreshStatus, 15000);
|
|
1743
1815
|
</script>
|
|
1744
1816
|
</body>
|
package/smart_tool_daemon.py
CHANGED
|
@@ -327,7 +327,7 @@ SERVER_INSTRUCTIONS = (
|
|
|
327
327
|
TOOLS = [
|
|
328
328
|
{
|
|
329
329
|
"name": "project_manage",
|
|
330
|
-
"description": "Manages folders and indexing. Every action takes project_root (the folder) or project_id. list gives a short line per project; status shows storage, scope and jobs. graph with symbol (function, Class.method, class name, or path::name when the name repeats) answers what an edit touches: definition, callers with line, calls, tests that reach it through static calls (depth hops, default 3) and files importing it; use it before changing a function to know what to update. affected_tests answers which tests to run after editing: every test file importing a changed file (git diff against base, default HEAD, untracked included) plus changed tests, likeliest failures first, with the command to run them and run_all when config or unanalyzed code changed. graph without symbol reads the indexed view: coverage, references and static calls in Java, Angular, Python and JS/TS/JSX/TSX; includes HTML/CSS/Markdown references and TXT/DOCX coverage; with file_path, narrows to that file's symbols, imports and calls (lists capped by limit). inspect lists the files of a view_id; with file_path, returns only that file's chunks. usage shows consumption and reuse; docs lists public functions without a docstring (Python docstring, JSDoc, Javadoc; private, nested and override functions excluded) with coverage percent, excluding tests unless include_tests=true, for documenting a project that started without it; duplicates lists duplicated functions (identical, near-identical and semantic bodies, min_similarity default 0.90; below that most pairs measured were false positives), excluding tests unless include_tests=true; fix real duplicates; only dismiss with duplicates_dismiss (finding_id, reason=false_positive|intentional, note) what is not a duplicate or is a copy kept on purpose: the finding stays hidden until the code changes, and duplicates_restore reopens it; integration shows the MCP client, hook and tool usage metrics; install_hook_preview shows the change that would install the hook redirecting Grep/Read to smart_search and WebSearch/WebFetch to web_search/web_fetch in this session's client and returns a plan_id; install_hook writes it with that plan_id and confirm=true, with a backup, only after the user approves the change; search_limits saves the project's default top_k per block ({code, test, doc}, each 1-20, total at most 20); storage shows disk usage and views; pin_view protects a view; cleanup_preview and cleanup_commit remove selected views after confirmation; compare compares two stored views, without checkout or embeddings. register adds a folder; preview checks the scope; index/rebuild update; pause/cancel keep checkpoints; resume continues; policy picks on_search/eager; scope adjusts the scope; remove deletes only the local index. setup_audit (project_root) reports what Claude Code and Codex actually load for that folder (settings layers, plugins, hooks, MCP servers, skills, CLAUDE.md/AGENTS.md) and where they collide: hooks deciding on the same tool in parallel, missing hook scripts, silenced hooks, MCP servers down or offering duplicate tools, skill name and budget problems, AGENTS.md that only Codex reads, broken @imports; what could not be checked is listed as not verified. Jobs via smart_search_result.",
|
|
330
|
+
"description": "Manages folders and indexing. Every action takes project_root (the folder) or project_id. list gives a short line per project; status shows storage, scope and jobs. graph with symbol (function, Class.method, class name, or path::name when the name repeats) answers what an edit touches: definition, callers with line, calls, tests that reach it through static calls (depth hops, default 3) and files importing it; use it before changing a function to know what to update. affected_tests answers which tests to run after editing: every test file importing a changed file (git diff against base, default HEAD, untracked included) plus changed tests, likeliest failures first, with the command to run them and run_all when config or unanalyzed code changed. graph without symbol reads the indexed view: coverage, references and static calls in Java, Angular, Python and JS/TS/JSX/TSX; includes HTML/CSS/Markdown references and TXT/DOCX coverage; with file_path, narrows to that file's symbols, imports and calls (lists capped by limit). inspect lists the files of a view_id; with file_path, returns only that file's chunks. usage shows consumption and reuse; docs lists public functions without a docstring (Python docstring, JSDoc, Javadoc; private, nested and override functions excluded) with coverage percent, excluding tests unless include_tests=true, for documenting a project that started without it; duplicates lists duplicated functions (identical, near-identical and semantic bodies, min_similarity default 0.90; below that most pairs measured were false positives), excluding tests unless include_tests=true; fix real duplicates; only dismiss with duplicates_dismiss (finding_id, reason=false_positive|intentional, note) what is not a duplicate or is a copy kept on purpose: the finding stays hidden until the code changes, and duplicates_restore reopens it; integration shows the MCP client, hook and tool usage metrics; install_hook_preview shows the change that would install the hook redirecting Grep/Read to smart_search and WebSearch/WebFetch to web_search/web_fetch in this session's client and returns a plan_id; install_hook writes it with that plan_id and confirm=true, with a backup, only after the user approves the change; search_limits saves the project's default top_k per block ({code, test, doc}, each 1-20, total at most 20); storage shows disk usage and views; pin_view protects a view; cleanup_preview and cleanup_commit remove selected views after confirmation; compare compares two stored views, without checkout or embeddings. register adds a folder; preview checks the scope; index/rebuild update; pause/cancel keep checkpoints; resume continues; policy picks on_search/eager; scope adjusts the scope; remove deletes only the local index. setup_audit (project_root) reports what Claude Code and Codex actually load for that folder (settings layers, plugins, hooks, MCP servers, skills, CLAUDE.md/AGENTS.md) and where they collide: hooks deciding on the same tool in parallel, missing hook scripts, silenced hooks, MCP servers down or offering duplicate tools, skill name and budget problems, AGENTS.md that only Codex reads, broken @imports; what could not be checked is listed as not verified; mode=last returns the stored report instead of auditing again. Jobs via smart_search_result.",
|
|
331
331
|
"inputSchema": {
|
|
332
332
|
"type": "object", "properties": {
|
|
333
333
|
"action": {"type": "string", "enum": ["list", "status", "register", "preview", "index", "rebuild", "pause", "cancel", "resume", "watch", "scope", "remove", "relocate", "probe", "policy", "inspect", "graph", "usage", "storage", "pin_view", "cleanup_preview", "cleanup_commit", "compare", "search_limits", "integration", "install_hook_preview", "install_hook", "duplicates", "duplicates_dismiss", "duplicates_restore", "docs", "affected_tests", "setup_audit"]},
|
|
@@ -349,6 +349,7 @@ TOOLS = [
|
|
|
349
349
|
"left_view":{"type":"string"},"right_view":{"type":"string"},"relations":{"type":"boolean"},
|
|
350
350
|
"update_mode": {"type": "string", "enum": ["on_search", "eager"]},
|
|
351
351
|
"view_id": {"type": "string"}, "file_path": {"type": "string"},
|
|
352
|
+
"mode": {"type": "string", "enum": ["run", "last"], "default": "run", "description": "setup_audit: run audits now; last reads the stored report (the service audits registered projects every 30 minutes) without running anything, and fails when none is stored"},
|
|
352
353
|
"probe": {"type": "boolean", "default": True, "description": "setup_audit: start/call each MCP server (initialize + tools/list); false reads configs only"},
|
|
353
354
|
"base": {"type": "string", "default": "HEAD", "description": "affected_tests: git revision the changes are compared with (HEAD = uncommitted work; main or origin/main for a branch)"},
|
|
354
355
|
"symbol": {"type": "string", "description": "graph: function, Class.method, class name or path::name to get its callers, calls, tests and importers"},
|
|
@@ -1299,8 +1300,25 @@ def _mark_notice_delivered(job_id):
|
|
|
1299
1300
|
session, _client = _session_client()
|
|
1300
1301
|
with _JOBS_LOCK:
|
|
1301
1302
|
job = _jobs.get(job_id) or {}
|
|
1302
|
-
|
|
1303
|
-
|
|
1303
|
+
keys = (job.get("arguments") or {}).get("setup_notice_keys")
|
|
1304
|
+
if session and job.get("status") == "done" and keys:
|
|
1305
|
+
session.setdefault("notices_delivered", set()).update(keys)
|
|
1306
|
+
|
|
1307
|
+
|
|
1308
|
+
def _pending_notices(session, client, project_root):
|
|
1309
|
+
"""[(key, text)] the session has not been told yet: the hook state (once) and the stored setup audit of the
|
|
1310
|
+
searched folder (once per folder, only with errors or warnings, and not when the SessionStart audit hook already
|
|
1311
|
+
reports it at the start of the session)."""
|
|
1312
|
+
delivered = session.get("notices_delivered") or set()
|
|
1313
|
+
pending = []
|
|
1314
|
+
if session["hook_notice"] and "hook" not in delivered:
|
|
1315
|
+
pending.append(("hook", session["hook_notice"]))
|
|
1316
|
+
key = "audit:" + setup_audit.index_key(project_root)
|
|
1317
|
+
if key not in delivered and not client_hooks.audit_hook_installed(client):
|
|
1318
|
+
text = setup_audit.session_notice(project_root)
|
|
1319
|
+
if text:
|
|
1320
|
+
pending.append((key, text))
|
|
1321
|
+
return pending
|
|
1304
1322
|
|
|
1305
1323
|
|
|
1306
1324
|
def _smart_search_arguments(arguments):
|
|
@@ -1348,8 +1366,11 @@ def _smart_search_arguments(arguments):
|
|
|
1348
1366
|
state = client_hooks.status(client)
|
|
1349
1367
|
_metric("hook_status", installed=state["installed"], client_name=state["name"], error=state["error"])
|
|
1350
1368
|
session["hook_notice"] = client_hooks.notice(state) or ""
|
|
1351
|
-
if session is not None
|
|
1352
|
-
|
|
1369
|
+
if session is not None:
|
|
1370
|
+
notices = _pending_notices(session, client, project_root)
|
|
1371
|
+
if notices:
|
|
1372
|
+
arguments["setup_notice"] = " ".join(text for _key, text in notices)
|
|
1373
|
+
arguments["setup_notice_keys"] = [key for key, _text in notices]
|
|
1353
1374
|
_metric("search", group=group, top_k=limits, query_comments=bool(comments), single_language_reason=reason)
|
|
1354
1375
|
return arguments
|
|
1355
1376
|
|
|
@@ -1493,6 +1514,16 @@ def _project_action(arguments):
|
|
|
1493
1514
|
root = arguments.get("project_root")
|
|
1494
1515
|
if not isinstance(root, str) or not os.path.isdir(root):
|
|
1495
1516
|
raise ValueError("setup_audit needs project_root: the folder whose Claude Code and Codex setup to audit.")
|
|
1517
|
+
mode = arguments.get("mode", "run")
|
|
1518
|
+
if mode not in ("run", "last"):
|
|
1519
|
+
raise ValueError("setup_audit mode must be run (audit now) or last (read the stored report).")
|
|
1520
|
+
if mode == "last":
|
|
1521
|
+
report = setup_audit.stored_for(root)
|
|
1522
|
+
if report is None:
|
|
1523
|
+
raise ValueError(f"No stored setup audit covers {root}: call setup_audit with mode=run once "
|
|
1524
|
+
"(the service also audits registered projects every 30 minutes).")
|
|
1525
|
+
return {"summary": report["summary"], "snapshot_key": report["snapshot_key"],
|
|
1526
|
+
"checked_at": report["checked_at"], "stored": True, "report": setup_audit.markdown(report)}
|
|
1496
1527
|
report = setup_audit.run(root, probe=arguments.get("probe", True) is not False)
|
|
1497
1528
|
return {"summary": report["summary"], "snapshot_key": report["snapshot_key"],
|
|
1498
1529
|
"report": setup_audit.markdown(report)}
|
|
@@ -3355,6 +3386,21 @@ def _pretool_hook(handler):
|
|
|
3355
3386
|
return output
|
|
3356
3387
|
|
|
3357
3388
|
|
|
3389
|
+
def _session_audit_hook(handler):
|
|
3390
|
+
"""SessionStart output for the audit report hook: the stored audit notice of the session's folder as
|
|
3391
|
+
additionalContext, or `{}` when nothing is stored or it holds no error or warning. Never runs an audit."""
|
|
3392
|
+
try:
|
|
3393
|
+
payload = json.loads(handler._read_body(HOOK_MAX_BODY_BYTES) or b"{}")
|
|
3394
|
+
cwd = payload.get("cwd")
|
|
3395
|
+
text = setup_audit.session_notice(cwd) if isinstance(cwd, str) and os.path.isdir(cwd) else ""
|
|
3396
|
+
except Exception as exc:
|
|
3397
|
+
_log(f"SessionStart audit hook without a report: {type(exc).__name__}: {exc}")
|
|
3398
|
+
return {}
|
|
3399
|
+
if not text:
|
|
3400
|
+
return {}
|
|
3401
|
+
return {"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": text}}
|
|
3402
|
+
|
|
3403
|
+
|
|
3358
3404
|
_TOOL_HANDLERS = {
|
|
3359
3405
|
"web_fetch": _handle_web_fetch,
|
|
3360
3406
|
"project_manage": _handle_project_manage,
|
|
@@ -3663,6 +3709,9 @@ class MCPHandler(BaseHTTPRequestHandler):
|
|
|
3663
3709
|
if urllib.parse.urlsplit(self.path).path == "/hooks/pretool":
|
|
3664
3710
|
self._write_json(200, _pretool_hook(self))
|
|
3665
3711
|
return
|
|
3712
|
+
if urllib.parse.urlsplit(self.path).path == "/hooks/session-audit":
|
|
3713
|
+
self._write_json(200, _session_audit_hook(self))
|
|
3714
|
+
return
|
|
3666
3715
|
save = _SETUP_SAVES.get(self.path)
|
|
3667
3716
|
if save:
|
|
3668
3717
|
self._post_setup(save)
|
package/version.py
CHANGED