@allansantos-dev/smart-tool 0.9.81 → 0.9.83

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/CHANGELOG.md +115 -0
  2. package/NOTICE +1 -1
  3. package/README.md +73 -14
  4. package/affected_tests.py +9 -8
  5. package/agent_redirect.py +32 -0
  6. package/autostart.py +32 -25
  7. package/browser_bridge.py +320 -0
  8. package/browser_control.py +76 -39
  9. package/browser_service_client.py +1 -7
  10. package/client_hooks.py +41 -42
  11. package/code_graph.py +66 -21
  12. package/code_graph_java.mjs +21 -12
  13. package/code_health.py +14 -9
  14. package/codex_config.py +3 -0
  15. package/commit_check.py +184 -0
  16. package/daemon_launcher.py +37 -5
  17. package/doc_candidates.py +63 -0
  18. package/doc_check.py +9 -3
  19. package/doc_extras.py +2 -3
  20. package/doc_insights.py +26 -2
  21. package/doc_prose.py +59 -11
  22. package/doc_registry.py +241 -0
  23. package/doc_scope.py +205 -39
  24. package/doc_turn.py +205 -0
  25. package/doc_validate.py +52 -9
  26. package/document_converter.py +4 -4
  27. package/document_read.py +19 -11
  28. package/document_url.py +107 -0
  29. package/edit_shape.py +119 -0
  30. package/endpoint_sync.py +3 -21
  31. package/engine_home.py +95 -0
  32. package/hook_call.py +133 -0
  33. package/hook_decision.py +142 -7
  34. package/hooks/pre_commit.py +45 -0
  35. package/hooks/pretool_router.py +36 -30
  36. package/hooks/turn_end.py +40 -0
  37. package/index_views.py +5 -0
  38. package/install.py +24 -9
  39. package/lazy_mcp_proxy.py +10 -9
  40. package/local_embedder.py +8 -1
  41. package/locales/pt-BR.json +1 -2
  42. package/model_breaker.py +6 -5
  43. package/package.json +2 -2
  44. package/process_limits.py +17 -3
  45. package/project_identity.py +19 -1
  46. package/project_scan.py +98 -0
  47. package/release_notes.py +125 -0
  48. package/rename_preview.py +95 -0
  49. package/requester.py +1 -1
  50. package/scout_access.py +48 -0
  51. package/shell_reads.py +67 -0
  52. package/smart_tool_daemon.py +245 -50
  53. package/tray.py +31 -0
  54. package/venv_launch.py +67 -0
  55. package/version.py +1 -1
  56. package/web_adapters/node/engine-home.mjs +42 -0
  57. package/web_adapters/node/package-lock.json +13 -0
  58. package/web_adapters/node/package.json +1 -0
  59. package/web_fetch_many.py +61 -0
package/hook_call.py ADDED
@@ -0,0 +1,133 @@
1
+ """Client side of every command hook that calls the Smart Tool daemon (PreToolUse, PostToolUse, SubagentStart, Stop, and the
2
+ opt-in git pre-commit).
3
+
4
+ The daemon address is read from its run file on every call, never from a port written into a settings file. A refused or
5
+ reset connection (a daemon restarting) is retried with backoff for `RESTART_WINDOW_S`, so a restart produces no message at
6
+ all; a daemon that stays unreachable fails open with one plain message, and the next calls stay silent until the daemon
7
+ answers again. Imports stay light (stdlib and the run-file reader) so a hook process starts fast.
8
+ """
9
+ import http.client
10
+ import json
11
+ import os
12
+ import socket
13
+ import time
14
+ import urllib.parse
15
+
16
+ import daemon_launcher
17
+ import paths
18
+
19
+ ORIGIN = "smart-tool"
20
+ RESTART_WINDOW_S = 10
21
+ DOWN_MEMORY_S = 60
22
+ CONNECT_TIMEOUT_S = 2
23
+ QUIET_CONNECT_TIMEOUT_S = 0.4
24
+ BACKOFF_S = (0.1, 0.2, 0.4, 0.8, 1.0)
25
+ ROUTE_TIMEOUT_S = {"pretool": 14, "posttool": 59, "subagent-start": 4, "stop": 110, "commit-check": 55}
26
+ DOWN_MARKER = os.path.join(paths.DATA_DIR, "hook-down")
27
+ LOG_NAME = "daemon.log"
28
+ RETRYABLE = (ConnectionError, http.client.RemoteDisconnected, http.client.BadStatusLine)
29
+
30
+
31
+ class Unreachable(Exception):
32
+ """The daemon could not answer: `cause` is a plain-words reason."""
33
+
34
+ def __init__(self, cause):
35
+ """`cause`: the plain-words reason the daemon could not answer."""
36
+ super().__init__(cause)
37
+ self.cause = cause
38
+
39
+
40
+ def _post(url, route, query, raw, timeout, connect_timeout):
41
+ """The JSON the daemon answered to one POST of `raw` on /hooks/<route>, or raises ConnectionError, TimeoutError,
42
+ Unreachable (an HTTP error status). A connect that times out is a ConnectionError: a closed port on Windows may
43
+ take seconds to refuse, and that is a daemon not listening, not a slow one."""
44
+ parsed = urllib.parse.urlsplit(url)
45
+ connection = http.client.HTTPConnection(parsed.hostname, parsed.port, timeout=connect_timeout)
46
+ try:
47
+ try:
48
+ connection.connect()
49
+ except socket.timeout as exc:
50
+ raise ConnectionError(f"connect timed out: {exc}") from None
51
+ connection.sock.settimeout(timeout)
52
+ suffix = f"?{urllib.parse.urlencode(query)}" if query else ""
53
+ connection.request("POST", f"/hooks/{route}{suffix}", body=raw, headers={"Content-Type": "application/json"})
54
+ response = connection.getresponse()
55
+ body = response.read()
56
+ except socket.timeout as exc:
57
+ raise TimeoutError(str(exc)) from None
58
+ except OSError as exc:
59
+ if isinstance(exc, ConnectionError):
60
+ raise
61
+ raise ConnectionError(str(exc)) from None
62
+ finally:
63
+ connection.close()
64
+ if response.status != 200:
65
+ raise Unreachable(f"answered HTTP {response.status}")
66
+ return json.loads(body or b"{}")
67
+
68
+
69
+ def _down_recently():
70
+ try:
71
+ return time.time() - os.path.getmtime(DOWN_MARKER) < DOWN_MEMORY_S
72
+ except OSError:
73
+ return False
74
+
75
+
76
+ def _note_down():
77
+ os.makedirs(paths.DATA_DIR, exist_ok=True)
78
+ with open(DOWN_MARKER, "w", encoding="utf-8") as stream:
79
+ stream.write(str(time.time()))
80
+
81
+
82
+ def _clear_down():
83
+ try:
84
+ os.remove(DOWN_MARKER)
85
+ except OSError:
86
+ pass
87
+
88
+
89
+ def call(route, raw, client="", window_s=None, sleep=time.sleep):
90
+ """`(output, first_failure)` of one hook call. `output` is the daemon's JSON answer ({} when it stayed
91
+ unreachable); `first_failure` is the cause in plain words the first time the daemon is found unreachable, None when
92
+ it answered or when an earlier call already reported the same outage."""
93
+ query = {"client": client} if client else {}
94
+ window = RESTART_WINDOW_S if window_s is None else window_s
95
+ quiet = _down_recently()
96
+ deadline = time.monotonic() + (0 if quiet else window)
97
+ attempt = 0
98
+ cause = "the daemon is not running"
99
+ while True:
100
+ info = daemon_launcher.read_registry()
101
+ try:
102
+ if info:
103
+ output = _post(info["url"], route, query, raw, ROUTE_TIMEOUT_S[route],
104
+ QUIET_CONNECT_TIMEOUT_S if quiet else CONNECT_TIMEOUT_S)
105
+ _clear_down()
106
+ return (output if isinstance(output, dict) else {}), None
107
+ cause = "the daemon is not running (no run file)"
108
+ except TimeoutError:
109
+ return {}, _report(f"the daemon did not answer within {ROUTE_TIMEOUT_S[route]} s (timed out)", quiet)
110
+ except Unreachable as exc:
111
+ return {}, _report(f"the daemon {exc.cause}", quiet)
112
+ except RETRYABLE:
113
+ cause = "the daemon is restarting or not running"
114
+ if time.monotonic() >= deadline:
115
+ return {}, _report(cause, quiet)
116
+ sleep(BACKOFF_S[min(attempt, len(BACKOFF_S) - 1)])
117
+ attempt += 1
118
+
119
+
120
+ def _report(cause, quiet):
121
+ _note_down()
122
+ return None if quiet else cause
123
+
124
+
125
+ AFTER_DOWN = ("Nothing to do: it comes back by itself and further calls stay silent until it does; if it keeps "
126
+ "happening, see {log}.")
127
+
128
+
129
+ def message(event, cause, effect, action=None):
130
+ """The one visible line of a hook that let a call through: which hook, who owns it, why, what happened to the call
131
+ and what the user does."""
132
+ action = action or AFTER_DOWN.format(log=os.path.join(paths.DATA_DIR, LOG_NAME))
133
+ return f"[hook-origin={ORIGIN}] Smart Tool (project smart-tool) {event} hook: {cause}. {effect} {action}"
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 chama as rotas POST /hooks/pretool e /hooks/posttool como hooks `type: "http"` (sem processo por
4
- chamada); o Codex usa o hook de comando `hooks/pretool_router.py`, que só repassa o payload para /hooks/pretool.
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`
@@ -17,6 +18,7 @@ import time
17
18
  import uuid
18
19
 
19
20
  import affected_tests
21
+ import agent_redirect
20
22
  import code_graph
21
23
  import code_impact
22
24
  import comment_check
@@ -28,6 +30,7 @@ import doc_scope
28
30
  import dossier
29
31
  import duplicates
30
32
  import edit_preview
33
+ import edit_shape
31
34
  import index_profile
32
35
  import index_scope
33
36
  import layer_check
@@ -39,6 +42,8 @@ import redirect_rule
39
42
  import removed_callers
40
43
  import requester
41
44
  import router
45
+ import scout_access
46
+ import shell_reads
42
47
  import tool_redirect
43
48
 
44
49
  WEB_TOOLS = ("WebSearch", "WebFetch")
@@ -332,6 +337,35 @@ def _credential_lines(findings):
332
337
  "variable or a secret store. If it is a fake value for a test, go ahead.")
333
338
 
334
339
 
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
+
335
369
  def _link_lines(broken, unchecked):
336
370
  """The link notes: the links that point to nothing, and the ones that could not be checked with the reason."""
337
371
  parts = []
@@ -390,6 +424,44 @@ def _decision_findings(root, rel, touched, failures):
390
424
  return found
391
425
 
392
426
 
427
+ def _read_functions(root, rel):
428
+ """The first MAX_DECISION_FUNCTIONS functions of a file, by line, from the cached code graph (nothing is analyzed).
429
+
430
+ Parameters: root (str) project folder; rel (str) path of the file relative to it, forward slashes.
431
+ Returns: list of {"name"} as `_decision_findings` takes them; empty while no analysis is cached.
432
+ """
433
+ data = code_graph.cached_graph(root)
434
+ symbols = sorted((item for item in (data or {}).get("symbols") or []
435
+ if item.get("path") == rel and item.get("kind") == "function"), key=lambda item: item.get("start_line") or 0)
436
+ names = list(dict.fromkeys(item["name"] for item in symbols))
437
+ return [{"name": name} for name in names[:MAX_DECISION_FUNCTIONS]]
438
+
439
+
440
+ def _read_note(payload, decision_mode):
441
+ """The recorded decisions that name the functions of a code file being read, as context for the Read (never a denial).
442
+ It reads the cached graph and the project's notes only, like the note of an edit, and is silent for a file outside
443
+ a project, a file that is not code and a project with nothing cached.
444
+
445
+ Parameters: payload (dict) the PreToolUse payload of a Read; decision_mode (str) `warn` or `off`.
446
+ Returns: the hook output, `{}` when there is nothing to say.
447
+ """
448
+ tool_input = payload.get("tool_input") if isinstance(payload.get("tool_input"), dict) else {}
449
+ path = tool_input.get("file_path")
450
+ if decision_mode == "off" or not isinstance(path, str) or not path:
451
+ return {}
452
+ path = os.path.join(payload.get("cwd") or "", path)
453
+ root = _project_of(path) if os.path.isabs(path) else None
454
+ if not root:
455
+ return {}
456
+ rel = os.path.relpath(os.path.realpath(path), os.path.realpath(root)).replace(os.sep, "/")
457
+ if index_profile.kind(rel, index_profile.current((index_scope.load_scope(root) or {}).get("profile"))) != "code":
458
+ return {}
459
+ failures = []
460
+ found = _decision_findings(root, rel, _read_functions(root, rel), failures)
461
+ parts = ([_decision_lines(found)] if found else []) + failures
462
+ return {"hookSpecificOutput": {"hookEventName": "PreToolUse", "additionalContext": " ".join(parts)}} if parts else {}
463
+
464
+
393
465
  def _edit_review(payload, doc_mode, duplicate_mode, dependency_mode, comment_mode="off", layer_mode="off",
394
466
  link_mode="off", decision_mode="off"):
395
467
  """Checks of an edit before it runs. Docstrings follow doc_mode, in code files of registered projects only (tests,
@@ -418,21 +490,47 @@ def _dependency_part(before, after, ecosystem):
418
490
  return f"{dependency_notice.PREFIX}dependency check skipped: {exc}"
419
491
 
420
492
 
493
+ def _history_findings(edited, failures):
494
+ """The hotspot and change-partner facts of the edited files, per project, from the cached history only.
495
+
496
+ Parameters: edited (dict) project folder -> project-relative paths of the edit; failures (list) where a failed lookup
497
+ adds its line.
498
+ Returns: tuple (hotspots, coupled) as `edit_shape.history_findings` lists, over every project of the edit.
499
+ """
500
+ hotspots, coupled = [], []
501
+ for root, rels in edited.items():
502
+ try:
503
+ found = edit_shape.history_findings(root, rels)
504
+ except (ValueError, RuntimeError, OSError) as exc:
505
+ failures.append(f"Smart Tool history check skipped: {exc}")
506
+ continue
507
+ hotspots += found["hotspots"]
508
+ coupled += found["coupled"]
509
+ return hotspots, coupled
510
+
511
+
421
512
  def _review_changes(changes, doc_mode, duplicate_mode, dependency_mode, comment_mode, layer_mode="off", link_mode="off",
422
- decision_mode="off"):
513
+ decision_mode="off", shape=False):
423
514
  """The checks of an edit over (path, before, after) triples: docstrings, comments, documentation anchors, copies,
424
515
  dependency advisories, local links, layers and the decisions recorded about the touched functions, each following its mode.
516
+ With `shape`, two more notes read only the cached code graph and history: the import cycle an added Python import
517
+ closes and the hotspots or usual change partners among the edited files.
425
518
 
426
- Parameters: changes (iterable of (absolute path, text before or None, text after)); the modes (`off` skips a check).
519
+ Parameters: changes (iterable of (absolute path, text before or None, text after)); the modes (`off` skips a check);
520
+ shape (bool) whether the cycle and history notes run: the edit hook asks for them, a review of a finished diff does not
521
+ (`pr_impact` reports both from the whole graph and history).
427
522
  Returns: tuple (message parts, doc findings, comment findings); the parts are empty when nothing is worth saying.
428
523
  """
429
524
  doc_findings, scope_findings, duplicate_findings, failures, dependency_parts = [], [], [], [], []
430
525
  comment_findings, layer_findings, credential_findings, caller_answers = [], [], [], []
431
526
  broken_links, unchecked_links = [], []
432
527
  decision_findings, decisions_asked = [], 0
528
+ cycle_findings, edited_files = [], {}
433
529
  for path, before, after in changes:
434
530
  root = _project_of(path)
435
531
  rel = os.path.relpath(os.path.realpath(path), os.path.realpath(root)).replace(os.sep, "/") if root else os.path.basename(path)
532
+ if shape and root:
533
+ edited_files.setdefault(root, []).append(rel)
436
534
  credential_findings += [(rel, item) for item in credential_check.review(before, after)]
437
535
  if link_mode != "off":
438
536
  try:
@@ -447,6 +545,11 @@ def _review_changes(changes, doc_mode, duplicate_mode, dependency_mode, comment_
447
545
  continue
448
546
  if not doc_check.supported(path):
449
547
  continue
548
+ if shape and root:
549
+ try:
550
+ cycle_findings += [(rel, item) for item in edit_shape.added_cycles(root, rel, before, after)]
551
+ except (ValueError, RuntimeError, OSError) as exc:
552
+ failures.append(f"Smart Tool cycles check skipped: {exc}")
450
553
  edited = doc_check.written(path, before, after)
451
554
  profile = index_profile.current((index_scope.load_scope(root) or {}).get("profile")) if root else None
452
555
  if doc_mode != "off" and root and index_profile.kind(rel, profile) == "code":
@@ -480,14 +583,17 @@ def _review_changes(changes, doc_mode, duplicate_mode, dependency_mode, comment_
480
583
  caller_answers.append(answer)
481
584
  except (ValueError, RuntimeError, OSError) as exc:
482
585
  failures.append(f"Smart Tool callers check skipped: {exc}")
586
+ hotspots, coupled = _history_findings(edited_files, failures)
483
587
  parts = ([_doc_lines(doc_findings)] if doc_findings else []) + \
484
588
  ([_comment_lines(comment_findings)] if comment_findings else []) + \
485
589
  ([_scope_lines(scope_findings)] if scope_findings else []) + \
486
590
  ([_duplicate_lines(duplicate_findings)] if duplicate_findings else []) + \
487
591
  ([_layer_lines(layer_findings)] if layer_findings else []) + \
592
+ ([_cycle_lines(cycle_findings)] if cycle_findings else []) + \
488
593
  ([_decision_lines(decision_findings)] if decision_findings else []) + \
489
594
  ([_callers_lines(caller_answers)] if caller_answers else []) + \
490
595
  ([_credential_lines(credential_findings)] if credential_findings else []) + \
596
+ ([_history_lines(hotspots, coupled)] if hotspots or coupled else []) + \
491
597
  _link_lines(broken_links, unchecked_links) + failures + dependency_parts
492
598
  return parts, doc_findings, comment_findings
493
599
 
@@ -607,7 +713,7 @@ def _edit_review_scoped(payload, doc_mode, duplicate_mode, dependency_mode, comm
607
713
  """`_edit_review` inside one `code_graph.pending_scope`, so the pending-changes scan runs once per review."""
608
714
  parts, doc_findings, comment_findings = _review_changes(
609
715
  edit_preview.preview(payload.get("tool_name"), payload.get("tool_input"), payload.get("cwd")),
610
- doc_mode, duplicate_mode, dependency_mode, comment_mode, layer_mode, link_mode, decision_mode)
716
+ doc_mode, duplicate_mode, dependency_mode, comment_mode, layer_mode, link_mode, decision_mode, shape=True)
611
717
  if not parts:
612
718
  return {}
613
719
  message = " ".join(parts)
@@ -622,7 +728,7 @@ def _edit_review_scoped(payload, doc_mode, duplicate_mode, dependency_mode, comm
622
728
 
623
729
  def decide(payload, client, web_route, jobs):
624
730
  """Hook output for one PreToolUse payload: edits follow doc_mode (require | remind | off) and duplicate_mode
625
- (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
731
+ (warn | off) and dependency_mode (warn | off) and decision_mode (warn | off), and every edit review also notes credentials the edit writes, a Read of a code file follows decision_mode too (see `_read_note`, context only), the other tools follow hook_mode (redirect | advise | off). In redirect mode the Smart Tool call that
626
732
  replaces a redirected one starts in `jobs` under the call's tool_use_id (see `_redirect`); only a search whose
627
733
  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
628
734
  subagent whose tool list has no Smart Tool MCP tool: it has nothing to switch to."""
@@ -638,6 +744,9 @@ def decide(payload, client, web_route, jobs):
638
744
  return {}
639
745
  return _edit_review(payload, doc_mode, duplicate_mode, dependency_mode, comment_mode, layer_mode, link_mode,
640
746
  decision_mode)
747
+ if isinstance(payload, dict) and payload.get("tool_name") == "Read":
748
+ routed = _route(payload, client, web_route, cfg) if config.hook_mode(cfg) != "off" else {}
749
+ return _read_note(payload, config.decision_mode(cfg)) or routed
641
750
  if isinstance(payload, dict) and str(payload.get("tool_name")).startswith(f"mcp__{SMART_TOOL_SERVER}__"):
642
751
  if payload["tool_name"] == SMART_SEARCH_TOOL:
643
752
  router.CLIENT.set(client)
@@ -646,12 +755,14 @@ def decide(payload, client, web_route, jobs):
646
755
  requester.note_hook(payload["tool_name"].removeprefix(f"mcp__{SMART_TOOL_SERVER}__"), payload.get("tool_input"),
647
756
  payload.get("session_id"), payload.get("cwd"))
648
757
  return {}
758
+ if isinstance(payload, dict) and payload.get("tool_name") in agent_redirect.LAUNCH_TOOLS:
759
+ return _launch_decision(payload, config.hook_mode(cfg))
649
760
  mode = config.hook_mode(cfg)
650
761
  if mode == "off" or not isinstance(payload, dict):
651
762
  return {}
652
763
  plan = _route(payload, client, web_route, cfg)
653
764
  if "kind" not in plan:
654
- return plan
765
+ return plan or _shell_read_tip(payload)
655
766
  if mode == "advise":
656
767
  return advise(plan["message"])
657
768
  if plan["kind"] and payload.get("tool_use_id"):
@@ -661,6 +772,30 @@ def decide(payload, client, web_route, jobs):
661
772
  return _answer_in_place(payload, client, plan, jobs)
662
773
 
663
774
 
775
+ def _shell_read_tip(payload):
776
+ """The tip that goes with the third source file read through the shell in a session (`shell_reads`), `{}` otherwise
777
+ and where smart_scout is not callable."""
778
+ if payload.get("tool_name") != "Bash":
779
+ return {}
780
+ tool_input = payload.get("tool_input") if isinstance(payload.get("tool_input"), dict) else {}
781
+ message = shell_reads.note(payload.get("session_id"), tool_input.get("command"), payload.get("cwd"))
782
+ if message is None or not agent_has_smart_tool(payload.get("agent_type") if payload.get("agent_id") else None,
783
+ payload.get("cwd")) or not scout_access.callable_in(payload):
784
+ return {}
785
+ return advise(message)
786
+
787
+
788
+ def _launch_decision(payload, mode):
789
+ """A subagent launch that `agent_redirect` matches carries the smart_scout call to make as a tip in redirect and
790
+ advise modes (the launch always runs); nothing in off mode, where the launching agent has no Smart Tool and where
791
+ smart_scout is not callable without a permission prompt (see `scout_access`)."""
792
+ message = agent_redirect.reason(payload) if mode != "off" else None
793
+ if message is None or not agent_has_smart_tool(payload.get("agent_type") if payload.get("agent_id") else None,
794
+ payload.get("cwd")) or not scout_access.callable_in(payload):
795
+ return {}
796
+ return advise(message)
797
+
798
+
664
799
  def _start_job(payload, client, plan, jobs, key):
665
800
  """Starts the Smart Tool call of a redirected one under key (web calls carry the requester of the hook)."""
666
801
  who = requester.CURRENT.set(requester.from_hook(client, payload)) if payload["tool_name"] in WEB_TOOLS else None
@@ -0,0 +1,45 @@
1
+ #!/usr/bin/env python3
2
+ """pre-commit hook of git (opt-in, written by `project_manage action=commit_hook_install`): asks the Smart Tool daemon
3
+ (POST /hooks/commit-check) to review the staged change and prints the notes to stderr. It never blocks a commit: the
4
+ exit status is always 0, a daemon that is down is one plain line, and a check that fails is printed, never silent.
5
+ The daemon address comes from its run file on every call (`hook_call`), never from a port written into the hook.
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
+ DOWN = "Smart Tool is not running, commit not reviewed"
15
+ FAILED = "Smart Tool commit check failed: "
16
+
17
+
18
+ def run(root):
19
+ """The text the hook prints for the repository at `root`: the notes of the daemon's review ("" when it found
20
+ nothing), the one line of a daemon that is down, or the reason the check could not run."""
21
+ output, failure = hook_call.call("commit-check", json.dumps({"root": root}).encode(), window_s=0)
22
+ if output.get("ok") is True:
23
+ notes = output.get("notes")
24
+ return f"Smart Tool reviewed the staged change; the commit goes ahead.\n{notes}" if notes else ""
25
+ if output.get("ok") is False:
26
+ return FAILED + str(output.get("error"))
27
+ if failure is None or "not running" in failure:
28
+ return DOWN
29
+ return FAILED + failure
30
+
31
+
32
+ def main():
33
+ """Prints what `run` says about the repository the hook runs in (git starts it at the top of the work tree); any
34
+ failure is printed and the exit status stays 0."""
35
+ sys.stderr.reconfigure(encoding="utf-8", errors="replace")
36
+ try:
37
+ text = run(os.getcwd())
38
+ except Exception as exc:
39
+ text = f"{FAILED}{type(exc).__name__}: {exc}"
40
+ if text:
41
+ print(text, file=sys.stderr)
42
+
43
+
44
+ if __name__ == "__main__":
45
+ main()
@@ -1,47 +1,53 @@
1
1
  #!/usr/bin/env python3
2
- """Hook de comando (Codex): cliente fino que repassa o payload ao daemon do Smart Tool (POST /hooks/pretool, ou
3
- /hooks/posttool com `--post`), onde a decisão roda já aquecida (`hook_decision.py`). O Claude Code chama as mesmas rotas
4
- direto, como hook `type: "http"`. Falha aberto: daemon fora do ar ou erro = saída neutra `{}`, nunca `allow`.
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 daemon_launcher
12
+ import hook_call
13
+
14
+ EVENTS = {"pretool": "PreToolUse", "posttool": "PostToolUse", "subagent-start": "SubagentStart"}
15
+
17
16
 
18
- # Above the daemon's budget for a redirected shell search (smart_tool_daemon.HOOK_SHELL_BUDGET_S), below the entry's 15 s.
19
- TIMEOUT_S = 14
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 _client():
23
- args = sys.argv[1:]
24
- return args[args.index("--client") + 1] if "--client" in args and args.index("--client") + 1 < len(args) else ""
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
- base = daemon_launcher.daemon_url_if_up()
30
- if not base:
31
- daemon_launcher.start_daemon_if_down()
32
- print(json.dumps({"systemMessage": "Smart Tool: daemon subindo, roteamento pulado nesta chamada."},
33
- ensure_ascii=False))
34
- return
35
- route = "posttool" if "--post" in sys.argv[1:] else "pretool"
36
- request = urllib.request.Request(f"{base}/hooks/{route}?{urllib.parse.urlencode({'client': _client()})}",
37
- data=raw, headers={"Content-Type": "application/json"}, method="POST")
38
- with urllib.request.urlopen(request, timeout=TIMEOUT_S) as response:
39
- output = json.loads(response.read() or b"{}")
40
- 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))
41
50
 
42
51
 
43
52
  if __name__ == "__main__":
44
- try:
45
- main()
46
- except BaseException:
47
- 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