@allansantos-dev/smart-tool 0.9.80 → 0.9.82
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 +129 -0
- package/NOTICE +1 -1
- package/README.md +59 -14
- package/agent_redirect.py +32 -0
- package/autostart.py +32 -25
- package/browser_bridge.py +320 -0
- package/browser_control.py +76 -39
- package/browser_service_client.py +1 -7
- package/client_hooks.py +42 -41
- package/code_graph.py +56 -15
- package/code_graph_java.mjs +21 -12
- package/code_health.py +19 -12
- package/code_impact.py +1 -1
- package/codex_config.py +3 -0
- package/config.py +35 -0
- package/daemon_launcher.py +37 -5
- package/doc_candidates.py +63 -0
- package/doc_check.py +9 -3
- package/doc_extras.py +2 -3
- package/doc_insights.py +26 -2
- package/doc_prose.py +59 -11
- package/doc_registry.py +241 -0
- package/doc_scope.py +205 -39
- package/doc_turn.py +205 -0
- package/doc_validate.py +52 -9
- package/document_read.py +4 -2
- package/dossier.py +40 -5
- package/edit_shape.py +119 -0
- package/endpoint_sync.py +3 -21
- package/engine_home.py +95 -0
- package/hook_call.py +132 -0
- package/hook_decision.py +337 -23
- package/hooks/pretool_router.py +36 -29
- package/hooks/turn_end.py +40 -0
- package/index_views.py +5 -0
- package/install.py +90 -36
- package/install_runtime.py +24 -10
- package/lazy_mcp_proxy.py +10 -9
- package/link_check.py +69 -0
- package/local_embedder.py +9 -2
- package/locales/pt-BR.json +72 -4
- package/model_breaker.py +6 -5
- package/model_client.py +1 -1
- package/model_health.py +24 -6
- package/notice_action.py +9 -0
- package/package.json +2 -2
- package/pr_comment.py +94 -0
- package/pr_impact.py +216 -35
- package/process_limits.py +17 -3
- package/project_admission.py +17 -15
- package/project_identity.py +19 -1
- package/project_scan.py +98 -0
- package/removed_callers.py +146 -0
- package/scout_access.py +48 -0
- package/setup_ui.py +33 -4
- package/shell_reads.py +67 -0
- package/smart_tool_daemon.py +149 -39
- package/tray.py +60 -9
- package/update_splash.py +2 -2
- package/venv_launch.py +67 -0
- package/version.py +1 -1
- package/web_adapters/node/engine-home.mjs +42 -0
- package/web_adapters/node/package-lock.json +13 -0
- package/web_adapters/node/package.json +1 -0
- package/web_document_graph.py +12 -1
package/hook_decision.py
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
"""Decisão do PreToolUse e do PostToolUse do Smart Tool, tomada dentro do daemon já aquecido.
|
|
2
2
|
|
|
3
|
-
O Claude Code
|
|
4
|
-
|
|
3
|
+
O Claude Code e o Codex chamam as rotas POST /hooks/pretool, /hooks/posttool e /hooks/subagent-start pelo hook de
|
|
4
|
+
comando `hooks/pretool_router.py`, que lê o endereço do daemon no arquivo de execução a cada chamada, espera um
|
|
5
|
+
reinício e só repassa o payload (`hook_call`).
|
|
5
6
|
|
|
6
7
|
Uma busca nativa que a regra redireciona, e WebFetch/WebSearch, não são negadas: o Smart Tool responde no lugar e o
|
|
7
8
|
texto volta como saída da própria chamada (`tool_redirect`). INVARIANTE: a saída do PreToolUse é `{}`, `updatedInput`
|
|
@@ -12,9 +13,12 @@ consulta legível nunca é negada: é respondida no contexto (`_answer_in_place`
|
|
|
12
13
|
não altera permissão.
|
|
13
14
|
"""
|
|
14
15
|
import os
|
|
16
|
+
import subprocess
|
|
17
|
+
import time
|
|
15
18
|
import uuid
|
|
16
19
|
|
|
17
20
|
import affected_tests
|
|
21
|
+
import agent_redirect
|
|
18
22
|
import code_graph
|
|
19
23
|
import code_impact
|
|
20
24
|
import comment_check
|
|
@@ -23,17 +27,23 @@ import credential_check
|
|
|
23
27
|
import dependency_notice
|
|
24
28
|
import doc_check
|
|
25
29
|
import doc_scope
|
|
30
|
+
import dossier
|
|
26
31
|
import duplicates
|
|
27
32
|
import edit_preview
|
|
33
|
+
import edit_shape
|
|
28
34
|
import index_profile
|
|
29
35
|
import index_scope
|
|
30
36
|
import layer_check
|
|
37
|
+
import link_check
|
|
31
38
|
import endpoint_sync
|
|
32
39
|
import project_admission
|
|
33
40
|
import project_store
|
|
34
41
|
import redirect_rule
|
|
42
|
+
import removed_callers
|
|
35
43
|
import requester
|
|
36
44
|
import router
|
|
45
|
+
import scout_access
|
|
46
|
+
import shell_reads
|
|
37
47
|
import tool_redirect
|
|
38
48
|
|
|
39
49
|
WEB_TOOLS = ("WebSearch", "WebFetch")
|
|
@@ -47,6 +57,13 @@ SINGLE_LANGUAGE_REASON = "redirected native search: its pattern is the only quer
|
|
|
47
57
|
EDIT_TOOLS = ("Edit", "MultiEdit", "Write", "apply_patch")
|
|
48
58
|
MAX_DOC_FINDINGS = 5
|
|
49
59
|
MAX_DUPLICATE_FINDINGS = 3
|
|
60
|
+
MAX_DECISION_FUNCTIONS = 3
|
|
61
|
+
DECISION_TIMEOUT_MS = 300
|
|
62
|
+
MAX_SHELL_REVIEW_FILES = 20
|
|
63
|
+
MAX_REVIEW_BYTES = 1_000_000
|
|
64
|
+
# FAT keeps two-second timestamps: a file the call wrote can look older than the call.
|
|
65
|
+
MTIME_SLACK_S = 2.0
|
|
66
|
+
SHELL_START_TTL_S = 3600
|
|
50
67
|
SMART_TOOL_SERVER = "smart-tool"
|
|
51
68
|
SMART_SEARCH_TOOL = f"mcp__{SMART_TOOL_SERVER}__smart_search"
|
|
52
69
|
REASON_MAX_CHARS = 200
|
|
@@ -292,6 +309,26 @@ def _layer_lines(findings):
|
|
|
292
309
|
"if this one is intended, go ahead.")
|
|
293
310
|
|
|
294
311
|
|
|
312
|
+
def _callers_lines(answers):
|
|
313
|
+
lines = []
|
|
314
|
+
for answer in answers:
|
|
315
|
+
resigned = "changed" in answer
|
|
316
|
+
for item in answer["findings"][:MAX_DOC_FINDINGS]:
|
|
317
|
+
same = f" A function named {item['name'].rpartition('.')[2]} also exists in {', '.join(item['also_defined_in'])}." \
|
|
318
|
+
if item["also_defined_in"] else ""
|
|
319
|
+
sites = removed_callers.sites_text(item)
|
|
320
|
+
lines.append(f"`{item['name']}` ({item['path']}) has a new signature after this edit and is called from {sites} "
|
|
321
|
+
f"outside this file: check that the callers pass what it takes now.{same}" if resigned else
|
|
322
|
+
f"`{item['name']}` ({item['path']}) is gone after this edit but is still called from "
|
|
323
|
+
f"{sites}: update the callers or keep the name.{same}")
|
|
324
|
+
if not answer["findings"]:
|
|
325
|
+
names = ", ".join(f"`{name}`" for name in answer["changed" if resigned else "removed"])
|
|
326
|
+
lines.append(f"no caller of {names}, whose signature changed, was found." if resigned else
|
|
327
|
+
f"no caller of the removed {names} was found.")
|
|
328
|
+
notes = " ".join(dict.fromkeys(answer["note"] for answer in answers if answer["note"]))
|
|
329
|
+
return "Smart Tool callers: " + " ".join(lines) + (f" {notes}" if notes else "")
|
|
330
|
+
|
|
331
|
+
|
|
295
332
|
def _credential_lines(findings):
|
|
296
333
|
lines = [f"{rel}:{item['line']} looks like a {item['kind']}" for rel, item in findings[:MAX_DOC_FINDINGS]]
|
|
297
334
|
if len(findings) > MAX_DOC_FINDINGS:
|
|
@@ -300,15 +337,106 @@ def _credential_lines(findings):
|
|
|
300
337
|
"variable or a secret store. If it is a fake value for a test, go ahead.")
|
|
301
338
|
|
|
302
339
|
|
|
303
|
-
def
|
|
340
|
+
def _cycle_lines(findings):
|
|
341
|
+
"""The note that names the import cycles an edit's added imports close.
|
|
342
|
+
|
|
343
|
+
Parameters: findings (list of (rel, item)) the `edit_shape.added_cycles` items with the file that was edited.
|
|
344
|
+
Returns: str, one sentence per import, cut at MAX_DOC_FINDINGS.
|
|
345
|
+
"""
|
|
346
|
+
lines = [f"{rel}:{item['line']} now imports `{item['imports']}`, which already leads back to it "
|
|
347
|
+
f"({' -> '.join([rel, *item['chain']])}): the import closes a cycle" for rel, item in findings[:MAX_DOC_FINDINGS]]
|
|
348
|
+
if len(findings) > MAX_DOC_FINDINGS:
|
|
349
|
+
lines.append(f"{len(findings) - MAX_DOC_FINDINGS} more import(s) in the same situation")
|
|
350
|
+
return ("Smart Tool cycles: " + "; ".join(lines) + ". Move what both files need into a third module, or import it where "
|
|
351
|
+
"it is used; if the cycle is intended, go ahead.")
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def _history_lines(hotspots, coupled):
|
|
355
|
+
"""The note that names the hotspots among the edited files and the files that usually change with them.
|
|
356
|
+
|
|
357
|
+
Parameters: hotspots, coupled (lists) the two lists of `edit_shape.history_findings`.
|
|
358
|
+
Returns: str, one sentence per file, cut at MAX_DOC_FINDINGS.
|
|
359
|
+
"""
|
|
360
|
+
lines = [f"`{item['path']}` is a hotspot of the project (rank {item['rank']}, {item['commits']} commits): keep the edit "
|
|
361
|
+
"small and run its tests" for item in hotspots]
|
|
362
|
+
lines += [f"`{item['path']}` usually changes with `{item['with']}` ({item['shared']} shared commits, {item['degree']}%) "
|
|
363
|
+
"and is not in this edit: check whether it needs the same change" for item in coupled]
|
|
364
|
+
if len(lines) > MAX_DOC_FINDINGS:
|
|
365
|
+
lines[MAX_DOC_FINDINGS:] = [f"{len(lines) - MAX_DOC_FINDINGS} more file(s) in the same situation"]
|
|
366
|
+
return "Smart Tool history: " + "; ".join(lines) + "."
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def _link_lines(broken, unchecked):
|
|
370
|
+
"""The link notes: the links that point to nothing, and the ones that could not be checked with the reason."""
|
|
371
|
+
parts = []
|
|
372
|
+
if broken:
|
|
373
|
+
lines = [f"{rel}:{item['line']} points to `{item['link']}`, which does not exist" for rel, item in broken[:MAX_DOC_FINDINGS]]
|
|
374
|
+
if len(broken) > MAX_DOC_FINDINGS:
|
|
375
|
+
lines.append(f"{len(broken) - MAX_DOC_FINDINGS} more link(s) in the same situation")
|
|
376
|
+
parts.append("Smart Tool links: " + "; ".join(lines) + ". Fix the path, or create the file if it is coming next.")
|
|
377
|
+
if unchecked:
|
|
378
|
+
lines = [f"{rel}{':' + str(item['line']) if item['line'] else ''}{' `' + item['link'] + '`' if item['link'] else ''} "
|
|
379
|
+
f"({item['why']})" for rel, item in unchecked[:MAX_DOC_FINDINGS]]
|
|
380
|
+
if len(unchecked) > MAX_DOC_FINDINGS:
|
|
381
|
+
lines.append(f"{len(unchecked) - MAX_DOC_FINDINGS} more not checked")
|
|
382
|
+
parts.append("Smart Tool links not checked: " + "; ".join(lines) + ".")
|
|
383
|
+
return parts
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def _decision_lines(found):
|
|
389
|
+
"""The note that names the decisions recorded about the touched functions, each note once.
|
|
390
|
+
|
|
391
|
+
Parameters: found (list of (rel, function name, hits)) the functions with a note and their `dossier.notes_about` hits.
|
|
392
|
+
Returns: str, empty when every note was already said.
|
|
393
|
+
"""
|
|
394
|
+
seen, sentences = set(), []
|
|
395
|
+
for rel, name, hits in found:
|
|
396
|
+
fresh = [hit for hit in hits if hit["id"] not in seen]
|
|
397
|
+
seen.update(hit["id"] for hit in fresh)
|
|
398
|
+
if fresh:
|
|
399
|
+
sentences.append(f"`{name}` ({rel}) is named in " + "; ".join(f"`{hit['id']}` {hit['title']}" for hit in fresh))
|
|
400
|
+
return "Smart Tool decision notes: " + ". ".join(sentences) + ". Read them before changing what they record." \
|
|
401
|
+
if sentences else ""
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def _decision_findings(root, rel, touched, failures):
|
|
405
|
+
"""The recorded decisions about the touched functions of one file, looked up in the project's notes (not its commit
|
|
406
|
+
messages: reading them runs a `git log` the budget cannot cut) within `DECISION_TIMEOUT_MS` each.
|
|
407
|
+
|
|
408
|
+
Parameters: root (str) project folder; rel (str) path of the file relative to it; touched (list) the functions
|
|
409
|
+
`doc_check.written` found touched; failures (list) where a search that fails or is cut adds its line.
|
|
410
|
+
Returns: list of (rel, function name, hits) for the functions that a note or commit message names.
|
|
411
|
+
"""
|
|
412
|
+
found = []
|
|
413
|
+
for function in touched:
|
|
414
|
+
try:
|
|
415
|
+
answer = dossier.notes_about(root, rel, function["name"], timeout_ms=DECISION_TIMEOUT_MS, history=False)
|
|
416
|
+
except (OSError, ValueError, RuntimeError) as exc:
|
|
417
|
+
failures.append(f"Smart Tool decision notes check skipped: {exc}")
|
|
418
|
+
break
|
|
419
|
+
line = f"Smart Tool decision notes search cut: {'; '.join(answer['reasons'])}"
|
|
420
|
+
if answer["reasons"] and line not in failures:
|
|
421
|
+
failures.append(line)
|
|
422
|
+
if answer["hits"]:
|
|
423
|
+
found.append((rel, function["name"], answer["hits"]))
|
|
424
|
+
return found
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def _edit_review(payload, doc_mode, duplicate_mode, dependency_mode, comment_mode="off", layer_mode="off",
|
|
428
|
+
link_mode="off", decision_mode="off"):
|
|
304
429
|
"""Checks of an edit before it runs. Docstrings follow doc_mode, in code files of registered projects only (tests,
|
|
305
430
|
docs and files outside a project are left out, as in the docs coverage): missing ones deny the edit in require mode and become a reminder in remind mode; a
|
|
306
431
|
documented function whose signature changed always gets a reminder. Comments the edit adds in the wrong place
|
|
307
432
|
(see comment_check) follow comment_mode in the same files: require denies, remind adds context. Copies of indexed
|
|
308
433
|
functions follow duplicate_mode and only add context, never deny. An edit of a package.json, requirements*.txt or go.mod follows dependency_mode: advisories
|
|
309
|
-
of the added or changed dependencies are added as context, never a denial.
|
|
434
|
+
of the added or changed dependencies are added as context, never a denial. Local links an edit of an HTML or Markdown
|
|
435
|
+
file adds or changes follow link_mode: missing targets and links that cannot be checked are added as context. The notes
|
|
436
|
+
and commit messages that name a touched function follow decision_mode and only add context."""
|
|
310
437
|
with code_graph.pending_scope():
|
|
311
|
-
return _edit_review_scoped(payload, doc_mode, duplicate_mode, dependency_mode, comment_mode, layer_mode
|
|
438
|
+
return _edit_review_scoped(payload, doc_mode, duplicate_mode, dependency_mode, comment_mode, layer_mode, link_mode,
|
|
439
|
+
decision_mode)
|
|
312
440
|
|
|
313
441
|
|
|
314
442
|
def _dependency_part(before, after, ecosystem):
|
|
@@ -324,25 +452,66 @@ def _dependency_part(before, after, ecosystem):
|
|
|
324
452
|
return f"{dependency_notice.PREFIX}dependency check skipped: {exc}"
|
|
325
453
|
|
|
326
454
|
|
|
327
|
-
def
|
|
328
|
-
"""The
|
|
329
|
-
|
|
455
|
+
def _history_findings(edited, failures):
|
|
456
|
+
"""The hotspot and change-partner facts of the edited files, per project, from the cached history only.
|
|
457
|
+
|
|
458
|
+
Parameters: edited (dict) project folder -> project-relative paths of the edit; failures (list) where a failed lookup
|
|
459
|
+
adds its line.
|
|
460
|
+
Returns: tuple (hotspots, coupled) as `edit_shape.history_findings` lists, over every project of the edit.
|
|
461
|
+
"""
|
|
462
|
+
hotspots, coupled = [], []
|
|
463
|
+
for root, rels in edited.items():
|
|
464
|
+
try:
|
|
465
|
+
found = edit_shape.history_findings(root, rels)
|
|
466
|
+
except (ValueError, RuntimeError, OSError) as exc:
|
|
467
|
+
failures.append(f"Smart Tool history check skipped: {exc}")
|
|
468
|
+
continue
|
|
469
|
+
hotspots += found["hotspots"]
|
|
470
|
+
coupled += found["coupled"]
|
|
471
|
+
return hotspots, coupled
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
def _review_changes(changes, doc_mode, duplicate_mode, dependency_mode, comment_mode, layer_mode="off", link_mode="off",
|
|
475
|
+
decision_mode="off", shape=False):
|
|
476
|
+
"""The checks of an edit over (path, before, after) triples: docstrings, comments, documentation anchors, copies,
|
|
477
|
+
dependency advisories, local links, layers and the decisions recorded about the touched functions, each following its mode.
|
|
478
|
+
With `shape`, two more notes read only the cached code graph and history: the import cycle an added Python import
|
|
479
|
+
closes and the hotspots or usual change partners among the edited files.
|
|
330
480
|
|
|
331
|
-
Parameters: changes (iterable of (absolute path, text before or None, text after)); the
|
|
481
|
+
Parameters: changes (iterable of (absolute path, text before or None, text after)); the modes (`off` skips a check);
|
|
482
|
+
shape (bool) whether the cycle and history notes run: the edit hook asks for them, a review of a finished diff does not
|
|
483
|
+
(`pr_impact` reports both from the whole graph and history).
|
|
332
484
|
Returns: tuple (message parts, doc findings, comment findings); the parts are empty when nothing is worth saying.
|
|
333
485
|
"""
|
|
334
486
|
doc_findings, scope_findings, duplicate_findings, failures, dependency_parts = [], [], [], [], []
|
|
335
|
-
comment_findings, layer_findings, credential_findings = [], [], []
|
|
487
|
+
comment_findings, layer_findings, credential_findings, caller_answers = [], [], [], []
|
|
488
|
+
broken_links, unchecked_links = [], []
|
|
489
|
+
decision_findings, decisions_asked = [], 0
|
|
490
|
+
cycle_findings, edited_files = [], {}
|
|
336
491
|
for path, before, after in changes:
|
|
337
492
|
root = _project_of(path)
|
|
338
493
|
rel = os.path.relpath(os.path.realpath(path), os.path.realpath(root)).replace(os.sep, "/") if root else os.path.basename(path)
|
|
494
|
+
if shape and root:
|
|
495
|
+
edited_files.setdefault(root, []).append(rel)
|
|
339
496
|
credential_findings += [(rel, item) for item in credential_check.review(before, after)]
|
|
497
|
+
if link_mode != "off":
|
|
498
|
+
try:
|
|
499
|
+
found = link_check.review(path, before, after)
|
|
500
|
+
broken_links += [(rel, item) for item in found["broken"]]
|
|
501
|
+
unchecked_links += [(rel, item) for item in found["unchecked"]]
|
|
502
|
+
except (ValueError, RuntimeError, OSError) as exc:
|
|
503
|
+
failures.append(f"Smart Tool links check skipped: {exc}")
|
|
340
504
|
ecosystem = dependency_notice.ecosystem_of(path)
|
|
341
505
|
if dependency_mode != "off" and ecosystem:
|
|
342
506
|
dependency_parts += [part for part in (_dependency_part(before, after, ecosystem),) if part]
|
|
343
507
|
continue
|
|
344
508
|
if not doc_check.supported(path):
|
|
345
509
|
continue
|
|
510
|
+
if shape and root:
|
|
511
|
+
try:
|
|
512
|
+
cycle_findings += [(rel, item) for item in edit_shape.added_cycles(root, rel, before, after)]
|
|
513
|
+
except (ValueError, RuntimeError, OSError) as exc:
|
|
514
|
+
failures.append(f"Smart Tool cycles check skipped: {exc}")
|
|
346
515
|
edited = doc_check.written(path, before, after)
|
|
347
516
|
profile = index_profile.current((index_scope.load_scope(root) or {}).get("profile")) if root else None
|
|
348
517
|
if doc_mode != "off" and root and index_profile.kind(rel, profile) == "code":
|
|
@@ -364,12 +533,30 @@ def _review_changes(changes, doc_mode, duplicate_mode, dependency_mode, comment_
|
|
|
364
533
|
layer_findings += [(rel, item) for item in layer_check.review(root, rel, before, after, edited)]
|
|
365
534
|
except (ValueError, RuntimeError, OSError) as exc:
|
|
366
535
|
failures.append(f"Smart Tool layers check skipped: {exc}")
|
|
536
|
+
if decision_mode != "off" and root and index_profile.kind(rel, profile) == "code":
|
|
537
|
+
asked = edited["touched"][:MAX_DECISION_FUNCTIONS - decisions_asked]
|
|
538
|
+
decisions_asked += len(asked)
|
|
539
|
+
decision_findings += _decision_findings(root, rel, asked, failures)
|
|
540
|
+
if root:
|
|
541
|
+
try:
|
|
542
|
+
for review, key in ((removed_callers.review, "removed"), (removed_callers.signature_review, "changed")):
|
|
543
|
+
answer = review(root, rel, before, after)
|
|
544
|
+
if answer["findings"] or answer[key] and answer["note"]:
|
|
545
|
+
caller_answers.append(answer)
|
|
546
|
+
except (ValueError, RuntimeError, OSError) as exc:
|
|
547
|
+
failures.append(f"Smart Tool callers check skipped: {exc}")
|
|
548
|
+
hotspots, coupled = _history_findings(edited_files, failures)
|
|
367
549
|
parts = ([_doc_lines(doc_findings)] if doc_findings else []) + \
|
|
368
550
|
([_comment_lines(comment_findings)] if comment_findings else []) + \
|
|
369
551
|
([_scope_lines(scope_findings)] if scope_findings else []) + \
|
|
370
552
|
([_duplicate_lines(duplicate_findings)] if duplicate_findings else []) + \
|
|
371
553
|
([_layer_lines(layer_findings)] if layer_findings else []) + \
|
|
372
|
-
([
|
|
554
|
+
([_cycle_lines(cycle_findings)] if cycle_findings else []) + \
|
|
555
|
+
([_decision_lines(decision_findings)] if decision_findings else []) + \
|
|
556
|
+
([_callers_lines(caller_answers)] if caller_answers else []) + \
|
|
557
|
+
([_credential_lines(credential_findings)] if credential_findings else []) + \
|
|
558
|
+
([_history_lines(hotspots, coupled)] if hotspots or coupled else []) + \
|
|
559
|
+
_link_lines(broken_links, unchecked_links) + failures + dependency_parts
|
|
373
560
|
return parts, doc_findings, comment_findings
|
|
374
561
|
|
|
375
562
|
|
|
@@ -380,16 +567,115 @@ def review_diff(changes, cfg):
|
|
|
380
567
|
Returns: str, the hook's message for the whole set; empty when every check is quiet or off.
|
|
381
568
|
"""
|
|
382
569
|
modes = (config.doc_mode(cfg), config.duplicate_mode(cfg), config.dependency_mode(cfg), config.comment_mode(cfg),
|
|
383
|
-
config.layer_mode(cfg))
|
|
570
|
+
config.layer_mode(cfg), config.link_mode(cfg), config.decision_mode(cfg))
|
|
384
571
|
with code_graph.pending_scope():
|
|
385
572
|
return " ".join(_review_changes(changes, *modes)[0])
|
|
386
573
|
|
|
387
574
|
|
|
388
|
-
def
|
|
575
|
+
def file_changes(root, base, rels):
|
|
576
|
+
"""The (path, text before, text after) triples `review_diff` takes, for the text files among `rels`.
|
|
577
|
+
|
|
578
|
+
Parameters: root (str) folder the paths are relative to; base (str) git revision holding the text before; rels (iterable
|
|
579
|
+
of str) forward-slash paths relative to root.
|
|
580
|
+
Returns: list of (absolute path, text at base or None for a file new since base, current text); a file that cannot be
|
|
581
|
+
read as UTF-8, is over MAX_REVIEW_BYTES or is gone is left out.
|
|
582
|
+
"""
|
|
583
|
+
triples = []
|
|
584
|
+
for rel in rels:
|
|
585
|
+
full = os.path.join(root, *rel.split("/"))
|
|
586
|
+
try:
|
|
587
|
+
if os.path.getsize(full) > MAX_REVIEW_BYTES:
|
|
588
|
+
continue
|
|
589
|
+
with open(full, encoding="utf-8") as stream:
|
|
590
|
+
after = stream.read()
|
|
591
|
+
except (OSError, UnicodeDecodeError):
|
|
592
|
+
continue
|
|
593
|
+
try:
|
|
594
|
+
before = affected_tests._git(root, "show", f"{base}:./{rel}")
|
|
595
|
+
except ValueError:
|
|
596
|
+
before = None
|
|
597
|
+
triples.append((full, before, after))
|
|
598
|
+
return triples
|
|
599
|
+
|
|
600
|
+
|
|
601
|
+
_SHELL_STARTS = {}
|
|
602
|
+
|
|
603
|
+
|
|
604
|
+
def note_shell_start(payload):
|
|
605
|
+
"""Records when a shell call (Bash, PowerShell) starts, by its tool_use_id: the PostToolUse payload carries no start
|
|
606
|
+
time and no snapshot, so this is what tells the files the call wrote from the ones that were already changed."""
|
|
607
|
+
if not isinstance(payload, dict) or payload.get("tool_name") not in tool_redirect.NO_OP or not payload.get("tool_use_id"):
|
|
608
|
+
return
|
|
609
|
+
now = time.time()
|
|
610
|
+
for old in [key for key, at in _SHELL_STARTS.items() if now - at > SHELL_START_TTL_S]:
|
|
611
|
+
_SHELL_STARTS.pop(old, None)
|
|
612
|
+
_SHELL_STARTS[payload["tool_use_id"]] = now
|
|
613
|
+
|
|
614
|
+
|
|
615
|
+
def _in_git_repository(folder):
|
|
616
|
+
"""Whether folder or one of its parents holds a `.git` entry (a folder, or a file for a worktree or submodule)."""
|
|
617
|
+
folder = os.path.abspath(folder)
|
|
618
|
+
while True:
|
|
619
|
+
if os.path.exists(os.path.join(folder, ".git")):
|
|
620
|
+
return True
|
|
621
|
+
parent = os.path.dirname(folder)
|
|
622
|
+
if parent == folder:
|
|
623
|
+
return False
|
|
624
|
+
folder = parent
|
|
625
|
+
|
|
626
|
+
|
|
627
|
+
def _shell_review(payload):
|
|
628
|
+
"""PostToolUse notes for the files a shell call wrote (`sed -i`, a redirection, `npm install`): the files git shows
|
|
629
|
+
changed since HEAD, tracked or not, whose modification time is not older than the call's start (see
|
|
630
|
+
`note_shell_start`), through the same checks as `review_diff`. A file the user or another tool changed before the
|
|
631
|
+
call is left out. Anything that stops the review, a git failure included, comes back as a note.
|
|
632
|
+
|
|
633
|
+
Parameters: payload (dict) the PostToolUse payload of the call.
|
|
634
|
+
Returns: the hook output, `{}` when there is nothing to say.
|
|
635
|
+
"""
|
|
636
|
+
started = _SHELL_STARTS.pop(payload["tool_use_id"], None)
|
|
637
|
+
cwd = payload.get("cwd")
|
|
638
|
+
cfg = config.load_config()
|
|
639
|
+
modes = (config.doc_mode(cfg), config.duplicate_mode(cfg), config.dependency_mode(cfg), config.comment_mode(cfg),
|
|
640
|
+
config.layer_mode(cfg), config.link_mode(cfg), config.decision_mode(cfg))
|
|
641
|
+
if set(modes) == {"off"}:
|
|
642
|
+
return {}
|
|
643
|
+
if not isinstance(cwd, str) or not os.path.isdir(cwd) or not _in_git_repository(cwd):
|
|
644
|
+
return {}
|
|
645
|
+
if started is None:
|
|
646
|
+
return _shell_note("the start of this call was not recorded, so the files it wrote cannot be told apart")
|
|
647
|
+
try:
|
|
648
|
+
changed = affected_tests._changes(cwd, "HEAD")
|
|
649
|
+
written = sorted(rel for rel, found in changed.items() if found["status"] != "deleted"
|
|
650
|
+
and _written_since(os.path.join(cwd, *rel.split("/")), started - MTIME_SLACK_S))
|
|
651
|
+
notes = review_diff(file_changes(cwd, "HEAD", written[:MAX_SHELL_REVIEW_FILES]), cfg)
|
|
652
|
+
except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as exc:
|
|
653
|
+
return _shell_note(str(exc))
|
|
654
|
+
if len(written) > MAX_SHELL_REVIEW_FILES:
|
|
655
|
+
notes += f" {len(written) - MAX_SHELL_REVIEW_FILES} more changed file(s) were not reviewed."
|
|
656
|
+
notes = notes.strip()
|
|
657
|
+
return {"hookSpecificOutput": {"hookEventName": "PostToolUse", "additionalContext": notes}} if notes else {}
|
|
658
|
+
|
|
659
|
+
|
|
660
|
+
def _written_since(path, moment):
|
|
661
|
+
"""Whether path was modified at or after moment (seconds since the epoch); a file that cannot be read was not."""
|
|
662
|
+
try:
|
|
663
|
+
return os.stat(path).st_mtime >= moment
|
|
664
|
+
except OSError:
|
|
665
|
+
return False
|
|
666
|
+
|
|
667
|
+
|
|
668
|
+
def _shell_note(reason):
|
|
669
|
+
return {"hookSpecificOutput": {"hookEventName": "PostToolUse",
|
|
670
|
+
"additionalContext": f"Smart Tool shell review skipped: {reason}"}}
|
|
671
|
+
|
|
672
|
+
|
|
673
|
+
def _edit_review_scoped(payload, doc_mode, duplicate_mode, dependency_mode, comment_mode="off", layer_mode="off",
|
|
674
|
+
link_mode="off", decision_mode="off"):
|
|
389
675
|
"""`_edit_review` inside one `code_graph.pending_scope`, so the pending-changes scan runs once per review."""
|
|
390
676
|
parts, doc_findings, comment_findings = _review_changes(
|
|
391
677
|
edit_preview.preview(payload.get("tool_name"), payload.get("tool_input"), payload.get("cwd")),
|
|
392
|
-
doc_mode, duplicate_mode, dependency_mode, comment_mode, layer_mode)
|
|
678
|
+
doc_mode, duplicate_mode, dependency_mode, comment_mode, layer_mode, link_mode, decision_mode, shape=True)
|
|
393
679
|
if not parts:
|
|
394
680
|
return {}
|
|
395
681
|
message = " ".join(parts)
|
|
@@ -404,20 +690,22 @@ def _edit_review_scoped(payload, doc_mode, duplicate_mode, dependency_mode, comm
|
|
|
404
690
|
|
|
405
691
|
def decide(payload, client, web_route, jobs):
|
|
406
692
|
"""Hook output for one PreToolUse payload: edits follow doc_mode (require | remind | off) and duplicate_mode
|
|
407
|
-
(warn | off) and dependency_mode (warn | off), and every edit review also notes credentials the edit writes, the other tools follow hook_mode (redirect | advise | off). In redirect mode the Smart Tool call that
|
|
693
|
+
(warn | off) and dependency_mode (warn | off) and decision_mode (warn | off), and every edit review also notes credentials the edit writes, the other tools follow hook_mode (redirect | advise | off). In redirect mode the Smart Tool call that
|
|
408
694
|
replaces a redirected one starts in `jobs` under the call's tool_use_id (see `_redirect`); only a search whose
|
|
409
695
|
query cannot be built, or a client that sends no tool_use_id, is denied with the exact call to make, and never in a
|
|
410
696
|
subagent whose tool list has no Smart Tool MCP tool: it has nothing to switch to."""
|
|
411
697
|
cfg = config.load_config()
|
|
698
|
+
note_shell_start(payload)
|
|
412
699
|
if isinstance(payload, dict):
|
|
413
700
|
requester.note_origin(payload.get("session_id"), payload.get("cwd"))
|
|
414
701
|
if isinstance(payload, dict) and payload.get("tool_name") in EDIT_TOOLS:
|
|
415
|
-
doc_mode, duplicate_mode, dependency_mode, comment_mode, layer_mode = (
|
|
702
|
+
doc_mode, duplicate_mode, dependency_mode, comment_mode, layer_mode, link_mode, decision_mode = (
|
|
416
703
|
config.doc_mode(cfg), config.duplicate_mode(cfg), config.dependency_mode(cfg), config.comment_mode(cfg),
|
|
417
|
-
config.layer_mode(cfg))
|
|
418
|
-
if "off" == doc_mode == duplicate_mode == dependency_mode == comment_mode == layer_mode:
|
|
704
|
+
config.layer_mode(cfg), config.link_mode(cfg), config.decision_mode(cfg))
|
|
705
|
+
if "off" == doc_mode == duplicate_mode == dependency_mode == comment_mode == layer_mode == link_mode == decision_mode:
|
|
419
706
|
return {}
|
|
420
|
-
return _edit_review(payload, doc_mode, duplicate_mode, dependency_mode, comment_mode, layer_mode
|
|
707
|
+
return _edit_review(payload, doc_mode, duplicate_mode, dependency_mode, comment_mode, layer_mode, link_mode,
|
|
708
|
+
decision_mode)
|
|
421
709
|
if isinstance(payload, dict) and str(payload.get("tool_name")).startswith(f"mcp__{SMART_TOOL_SERVER}__"):
|
|
422
710
|
if payload["tool_name"] == SMART_SEARCH_TOOL:
|
|
423
711
|
router.CLIENT.set(client)
|
|
@@ -426,12 +714,14 @@ def decide(payload, client, web_route, jobs):
|
|
|
426
714
|
requester.note_hook(payload["tool_name"].removeprefix(f"mcp__{SMART_TOOL_SERVER}__"), payload.get("tool_input"),
|
|
427
715
|
payload.get("session_id"), payload.get("cwd"))
|
|
428
716
|
return {}
|
|
717
|
+
if isinstance(payload, dict) and payload.get("tool_name") in agent_redirect.LAUNCH_TOOLS:
|
|
718
|
+
return _launch_decision(payload, config.hook_mode(cfg))
|
|
429
719
|
mode = config.hook_mode(cfg)
|
|
430
720
|
if mode == "off" or not isinstance(payload, dict):
|
|
431
721
|
return {}
|
|
432
722
|
plan = _route(payload, client, web_route, cfg)
|
|
433
723
|
if "kind" not in plan:
|
|
434
|
-
return plan
|
|
724
|
+
return plan or _shell_read_tip(payload)
|
|
435
725
|
if mode == "advise":
|
|
436
726
|
return advise(plan["message"])
|
|
437
727
|
if plan["kind"] and payload.get("tool_use_id"):
|
|
@@ -441,6 +731,30 @@ def decide(payload, client, web_route, jobs):
|
|
|
441
731
|
return _answer_in_place(payload, client, plan, jobs)
|
|
442
732
|
|
|
443
733
|
|
|
734
|
+
def _shell_read_tip(payload):
|
|
735
|
+
"""The tip that goes with the third source file read through the shell in a session (`shell_reads`), `{}` otherwise
|
|
736
|
+
and where smart_scout is not callable."""
|
|
737
|
+
if payload.get("tool_name") != "Bash":
|
|
738
|
+
return {}
|
|
739
|
+
tool_input = payload.get("tool_input") if isinstance(payload.get("tool_input"), dict) else {}
|
|
740
|
+
message = shell_reads.note(payload.get("session_id"), tool_input.get("command"), payload.get("cwd"))
|
|
741
|
+
if message is None or not agent_has_smart_tool(payload.get("agent_type") if payload.get("agent_id") else None,
|
|
742
|
+
payload.get("cwd")) or not scout_access.callable_in(payload):
|
|
743
|
+
return {}
|
|
744
|
+
return advise(message)
|
|
745
|
+
|
|
746
|
+
|
|
747
|
+
def _launch_decision(payload, mode):
|
|
748
|
+
"""A subagent launch that `agent_redirect` matches carries the smart_scout call to make as a tip in redirect and
|
|
749
|
+
advise modes (the launch always runs); nothing in off mode, where the launching agent has no Smart Tool and where
|
|
750
|
+
smart_scout is not callable without a permission prompt (see `scout_access`)."""
|
|
751
|
+
message = agent_redirect.reason(payload) if mode != "off" else None
|
|
752
|
+
if message is None or not agent_has_smart_tool(payload.get("agent_type") if payload.get("agent_id") else None,
|
|
753
|
+
payload.get("cwd")) or not scout_access.callable_in(payload):
|
|
754
|
+
return {}
|
|
755
|
+
return advise(message)
|
|
756
|
+
|
|
757
|
+
|
|
444
758
|
def _start_job(payload, client, plan, jobs, key):
|
|
445
759
|
"""Starts the Smart Tool call of a redirected one under key (web calls carry the requester of the hook)."""
|
|
446
760
|
who = requester.CURRENT.set(requester.from_hook(client, payload)) if payload["tool_name"] in WEB_TOOLS else None
|
|
@@ -523,8 +837,8 @@ def _log_served(client, payload):
|
|
|
523
837
|
|
|
524
838
|
def after(payload, client, jobs):
|
|
525
839
|
"""PostToolUse output: the call's own response with the Smart Tool answer started for its tool_use_id in the field
|
|
526
|
-
the model reads (`updatedToolOutput`)
|
|
527
|
-
|
|
840
|
+
the model reads (`updatedToolOutput`); for a shell call with no such answer, the notes of `_shell_review` on the files
|
|
841
|
+
it wrote; else `{}` (the native output stays)."""
|
|
528
842
|
if not isinstance(payload, dict) or not payload.get("tool_use_id"):
|
|
529
843
|
return {}
|
|
530
844
|
key, tool_name = payload["tool_use_id"], payload.get("tool_name")
|
|
@@ -532,7 +846,7 @@ def after(payload, client, jobs):
|
|
|
532
846
|
jobs.forget(key)
|
|
533
847
|
output = tool_redirect.output_for(tool_name, payload.get("tool_response"), text) if text else None
|
|
534
848
|
if output is None:
|
|
535
|
-
return {}
|
|
849
|
+
return _shell_review(payload) if tool_name in tool_redirect.NO_OP else {}
|
|
536
850
|
_log_served(client, payload)
|
|
537
851
|
return {"hookSpecificOutput": {"hookEventName": "PostToolUse", "updatedToolOutput": output}}
|
|
538
852
|
|
package/hooks/pretool_router.py
CHANGED
|
@@ -1,46 +1,53 @@
|
|
|
1
1
|
#!/usr/bin/env python3
|
|
2
|
-
"""
|
|
3
|
-
|
|
4
|
-
|
|
2
|
+
"""Command hook of Claude Code and Codex: thin client that forwards the payload to the Smart Tool daemon
|
|
3
|
+
(`--route pretool|posttool|subagent-start`), where the decision runs already warm (`hook_decision.py`). The daemon
|
|
4
|
+
address comes from its run file on every call, a restart is waited out with backoff (`hook_call`), and a daemon that
|
|
5
|
+
stays unreachable fails open: the call runs, neutral output and one plain message the first time.
|
|
5
6
|
"""
|
|
6
7
|
import json
|
|
7
8
|
import os
|
|
8
9
|
import sys
|
|
9
|
-
import urllib.parse
|
|
10
|
-
import urllib.request
|
|
11
|
-
|
|
12
|
-
sys.stdin.reconfigure(encoding="utf-8")
|
|
13
|
-
sys.stdout.reconfigure(encoding="utf-8")
|
|
14
10
|
|
|
15
11
|
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
|
|
16
|
-
import
|
|
12
|
+
import hook_call
|
|
13
|
+
|
|
14
|
+
EVENTS = {"pretool": "PreToolUse", "posttool": "PostToolUse", "subagent-start": "SubagentStart"}
|
|
15
|
+
|
|
17
16
|
|
|
18
|
-
|
|
19
|
-
|
|
17
|
+
def _arg(argv, name):
|
|
18
|
+
return argv[argv.index(name) + 1] if name in argv and argv.index(name) + 1 < len(argv) else ""
|
|
20
19
|
|
|
21
20
|
|
|
22
|
-
def
|
|
23
|
-
|
|
24
|
-
|
|
21
|
+
def run(argv, raw):
|
|
22
|
+
"""The JSON object the hook prints for the payload `raw` (bytes) under the command line `argv`."""
|
|
23
|
+
route = _arg(argv, "--route")
|
|
24
|
+
if route not in EVENTS:
|
|
25
|
+
return {"systemMessage": hook_call.message(
|
|
26
|
+
"command", "this hook entry is from an older Smart Tool version (no --route)",
|
|
27
|
+
"The call ran without Smart Tool routing.", "Install the hooks again from the Smart Tool setup screen.")}
|
|
28
|
+
output, failure = hook_call.call(route, raw, _arg(argv, "--client"))
|
|
29
|
+
if failure is None:
|
|
30
|
+
return output
|
|
31
|
+
tool = ""
|
|
32
|
+
try:
|
|
33
|
+
tool = json.loads(raw or b"{}").get("tool_name") or ""
|
|
34
|
+
except ValueError:
|
|
35
|
+
pass
|
|
36
|
+
effect = f"The {tool + ' ' if tool else ''}call was let through without Smart Tool routing."
|
|
37
|
+
return {"systemMessage": hook_call.message(EVENTS[route], failure, effect)}
|
|
25
38
|
|
|
26
39
|
|
|
27
40
|
def main():
|
|
41
|
+
"""Reads the payload from stdin and prints the hook's JSON answer; any failure prints a message and lets the call run."""
|
|
42
|
+
sys.stdout.reconfigure(encoding="utf-8")
|
|
28
43
|
raw = sys.stdin.buffer.read()
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
request = urllib.request.Request(f"{base}/hooks/pretool?{urllib.parse.urlencode({'client': _client()})}",
|
|
36
|
-
data=raw, headers={"Content-Type": "application/json"}, method="POST")
|
|
37
|
-
with urllib.request.urlopen(request, timeout=TIMEOUT_S) as response:
|
|
38
|
-
output = json.loads(response.read() or b"{}")
|
|
39
|
-
print(json.dumps(output if isinstance(output, dict) else {}, ensure_ascii=False))
|
|
44
|
+
try:
|
|
45
|
+
output = run(sys.argv[1:], raw)
|
|
46
|
+
except Exception as exc:
|
|
47
|
+
output = {"systemMessage": hook_call.message(
|
|
48
|
+
"command", f"the hook failed ({type(exc).__name__}: {exc})", "The call was let through.")}
|
|
49
|
+
print(json.dumps(output, ensure_ascii=False))
|
|
40
50
|
|
|
41
51
|
|
|
42
52
|
if __name__ == "__main__":
|
|
43
|
-
|
|
44
|
-
main()
|
|
45
|
-
except BaseException:
|
|
46
|
-
print("{}")
|
|
53
|
+
main()
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Stop hook of Claude Code (type command): forwards the payload to the Smart Tool daemon (POST /hooks/stop), whose
|
|
3
|
+
address it reads on every call from the run file the daemon writes (`hook_call`), and prints the daemon's answer (a block
|
|
4
|
+
with the docstrings to review, or nothing). A continuation (stop_hook_active) exits at once without calling the daemon.
|
|
5
|
+
A restart is waited out; a daemon that stays unreachable prints one plain message and the step stays pending.
|
|
6
|
+
"""
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import sys
|
|
10
|
+
|
|
11
|
+
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
|
|
12
|
+
import hook_call
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def run(raw):
|
|
16
|
+
"""The JSON object the hook prints for the Stop payload `raw` (bytes); {} for a continuation or an empty answer."""
|
|
17
|
+
if json.loads(raw or b"{}").get("stop_hook_active"):
|
|
18
|
+
return {}
|
|
19
|
+
output, failure = hook_call.call("stop", raw)
|
|
20
|
+
if failure is None:
|
|
21
|
+
return output
|
|
22
|
+
return {"systemMessage": hook_call.message(
|
|
23
|
+
"Stop", failure, "The end-of-turn documentation step did not run and its work stays pending.")}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def main():
|
|
27
|
+
"""Reads the Stop payload from stdin and prints the answer when it is not empty; a failure prints a message."""
|
|
28
|
+
sys.stdout.reconfigure(encoding="utf-8")
|
|
29
|
+
raw = sys.stdin.buffer.read()
|
|
30
|
+
try:
|
|
31
|
+
output = run(raw)
|
|
32
|
+
except Exception as exc:
|
|
33
|
+
output = {"systemMessage": hook_call.message(
|
|
34
|
+
"Stop", f"the hook failed ({type(exc).__name__}: {exc})", "The end-of-turn documentation step did not run.")}
|
|
35
|
+
if output:
|
|
36
|
+
print(json.dumps(output, ensure_ascii=False))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
if __name__ == "__main__":
|
|
40
|
+
main()
|
package/index_views.py
CHANGED
|
@@ -73,6 +73,11 @@ def _validated(key):
|
|
|
73
73
|
return old[1] if time.monotonic()-old[0] < 1 else None
|
|
74
74
|
|
|
75
75
|
|
|
76
|
+
def cached_view(root):
|
|
77
|
+
"""The view `describe` holds for `root` while it is still the current one, else None; checks by stat and never runs git."""
|
|
78
|
+
return _validated(project_identity.canonical_root(project_identity.display_root(root)))
|
|
79
|
+
|
|
80
|
+
|
|
76
81
|
def describe(root, fresh=False):
|
|
77
82
|
"""Git view of `root`. `fresh` asks for a check, not for a new resolution: a cached Git view whose stamp (HEAD, index,
|
|
78
83
|
logs/HEAD, packed-refs, the ref file) did not move is still the current one and costs no git process. Concurrent
|