@allansantos-dev/smart-tool 0.9.82 → 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.
package/hook_decision.py CHANGED
@@ -424,6 +424,44 @@ def _decision_findings(root, rel, touched, failures):
424
424
  return found
425
425
 
426
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
+
427
465
  def _edit_review(payload, doc_mode, duplicate_mode, dependency_mode, comment_mode="off", layer_mode="off",
428
466
  link_mode="off", decision_mode="off"):
429
467
  """Checks of an edit before it runs. Docstrings follow doc_mode, in code files of registered projects only (tests,
@@ -690,7 +728,7 @@ def _edit_review_scoped(payload, doc_mode, duplicate_mode, dependency_mode, comm
690
728
 
691
729
  def decide(payload, client, web_route, jobs):
692
730
  """Hook output for one PreToolUse payload: edits follow doc_mode (require | remind | off) and duplicate_mode
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
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
694
732
  replaces a redirected one starts in `jobs` under the call's tool_use_id (see `_redirect`); only a search whose
695
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
696
734
  subagent whose tool list has no Smart Tool MCP tool: it has nothing to switch to."""
@@ -706,6 +744,9 @@ def decide(payload, client, web_route, jobs):
706
744
  return {}
707
745
  return _edit_review(payload, doc_mode, duplicate_mode, dependency_mode, comment_mode, layer_mode, link_mode,
708
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
709
750
  if isinstance(payload, dict) and str(payload.get("tool_name")).startswith(f"mcp__{SMART_TOOL_SERVER}__"):
710
751
  if payload["tool_name"] == SMART_SEARCH_TOOL:
711
752
  router.CLIENT.set(client)
@@ -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()
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@allansantos-dev/smart-tool",
3
- "version": "0.9.82",
3
+ "version": "0.9.83",
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",
@@ -0,0 +1,125 @@
1
+ """A Markdown draft for the next release, built without a model from facts the project already holds: the commit
2
+ subjects since a base, the public functions the diff touches with their caller and test counts, the decision notes that
3
+ name them and the documentation entries the diff leaves out of date. The sections come from the builders of
4
+ `pr_impact`; every line is a commit subject, a name or a count read from the project, never written text. Nothing is
5
+ published or written.
6
+ """
7
+ import affected_tests
8
+ import doc_check
9
+ import pr_impact
10
+
11
+ DEFAULT_LIMIT = 30
12
+ CALLBACK_SUFFIX = " (callback"
13
+
14
+
15
+ def _base(root, base):
16
+ """The revision the draft starts from.
17
+
18
+ Parameters: root (str) project folder; base (str or None) a tag, branch or commit, the latest tag of the history of
19
+ HEAD when None.
20
+ Returns: str the revision.
21
+ Raises: ValueError when the folder is not a git repository, no tag exists for the default, or the base is not a commit.
22
+ """
23
+ affected_tests._git(root, "rev-parse", "--git-dir")
24
+ if base is None:
25
+ try:
26
+ return affected_tests._git(root, "describe", "--tags", "--abbrev=0").strip()
27
+ except ValueError as exc:
28
+ raise ValueError(f"The repository has no tag to start from ({exc}). Pass base: a tag, branch or commit.") from None
29
+ if not isinstance(base, str) or not base.strip() or base.startswith("-"):
30
+ raise ValueError("base must be a git tag, branch or commit.")
31
+ try:
32
+ affected_tests._git(root, "rev-parse", "--verify", "--quiet", f"{base}^{{commit}}")
33
+ except ValueError:
34
+ raise ValueError(f"base {base!r} is not a commit of this repository.") from None
35
+ return base
36
+
37
+
38
+ def _commits(root, base, limit):
39
+ """Hash and subject of the commits reachable from HEAD and not from the base, newest first.
40
+
41
+ Returns: tuple (list of {"hash", "subject"} up to `limit`, int total).
42
+ """
43
+ rows = [line.partition("\0")[::2] for line in
44
+ affected_tests._git(root, "log", "--format=%h%x00%s", f"{base}..HEAD").splitlines() if line]
45
+ return [{"hash": short, "subject": subject} for short, subject in rows[:limit]], len(rows)
46
+
47
+
48
+ def _public(label):
49
+ """Whether a `path::name` label names a public function: no segment of the name is private (a leading `_` that is not a
50
+ dunder, or `#`)."""
51
+ qualified = label.rpartition("::")[2].split("(")[0]
52
+ return all(doc_check._public_name(part) and not part.startswith("#") for part in qualified.split("."))
53
+
54
+
55
+ def _commit_lines(commits, total, base):
56
+ """The Markdown section of the commit subjects."""
57
+ if not total:
58
+ return ["### Commits", "", f"No commit since {base}.", ""]
59
+ lines = [f"### Commits ({total})", ""] + [f"- {item['hash']} {item['subject']}" for item in commits]
60
+ if total > len(commits):
61
+ lines.append(f"- ... and {total - len(commits)} more commit(s)")
62
+ return lines + [""]
63
+
64
+
65
+ def _function_lines(base, shown, hidden, callers):
66
+ """The Markdown section of the touched public functions with their caller and test counts."""
67
+ lines = ["### Public functions touched and who calls them", "", f"Diff of {base} against the working tree.", ""]
68
+ if not shown:
69
+ return lines + ["No public function is touched by the diff.", ""]
70
+ lines += ["| Function | Callers | Tests |", "|---|---|---|"]
71
+ for label in shown:
72
+ reached = callers[label]
73
+ lines.append(f"| `{label}` | not in the graph | - |" if reached is None
74
+ else f"| `{label}` | {reached[1]} | {reached[2] or 'none'} |")
75
+ return lines + (["", f"{hidden} more public function(s) not listed."] if hidden else []) + [""]
76
+
77
+
78
+ def _decision_lines(shown, decisions, note):
79
+ """The Markdown section of the decision notes that name a touched function, from `pr_impact._decisions`."""
80
+ lines = ["### Decision notes of the touched functions", ""]
81
+ lines += [f"- `{label}`: `{hit['id']}` {hit['title']}" for label, hits in decisions.items() for hit in hits]
82
+ if not decisions:
83
+ lines.append("No decision note or commit message names a touched public function." if shown
84
+ else "No public function is touched, so no decision note was searched.")
85
+ return lines + ([note] if note else []) + [""]
86
+
87
+
88
+ def _stale_lines(stale, note, limit):
89
+ """The Markdown section of the documentation entries the diff leaves out of date, from `pr_impact._stale`."""
90
+ lines = ["### Documentation left out of date", ""]
91
+ if note:
92
+ return lines + [note, ""]
93
+ if not stale:
94
+ return lines + ["No documented entry in the changed files is out of date.", ""]
95
+ lines += [f"- `{f['id']}`: {f['issue'].replace('_', ' ')} ({f['file']}:{f['line']})" for f in stale[:limit]]
96
+ if len(stale) > limit:
97
+ lines.append(f"- ... and {len(stale) - limit} more")
98
+ return lines + [""]
99
+
100
+
101
+ def draft(root, base=None, limit=DEFAULT_LIMIT, view_id=None):
102
+ """The release notes draft since a base.
103
+
104
+ Parameters: root (str) project folder; base (str or None) tag, branch or commit the draft starts from, the latest tag
105
+ when None; limit (int) rows in each list; view_id (str or None) index view.
106
+ Returns: dict {"base", "markdown" (headed `## Draft since <base>`), "commits": [{"hash", "subject"}], "commit_total",
107
+ "functions": [path::name shown], "callers": {path::name: caller count}, "decisions", "stale_anchors", "stale_note"}.
108
+ Raises: ValueError when the folder is not a git repository, there is no tag and no base was given, or the base is not a
109
+ commit; RuntimeError when the code graph cannot be built.
110
+ """
111
+ base = _base(root, base)
112
+ changes = affected_tests.affected(root, base, pr_impact.ALL_ROWS, view_id)
113
+ touched = list(dict.fromkeys(label.partition(CALLBACK_SUFFIX)[0] for label in changes["touched_functions"]))
114
+ public = [label for label in touched if _public(label)]
115
+ shown = public[:limit]
116
+ callers = {label: pr_impact._callers(root, label, view_id) for label in shown}
117
+ decisions, decisions_note = pr_impact._decisions(root, shown)
118
+ stale, stale_note = pr_impact._stale(root, view_id, set(changes["changed"]["code"]))
119
+ commits, total = _commits(root, base, limit)
120
+ lines = [f"## Draft since {base}", ""] + _commit_lines(commits, total, base)
121
+ lines += _function_lines(base, shown, len(public) - len(shown), callers)
122
+ lines += _decision_lines(shown, decisions, decisions_note) + _stale_lines(stale, stale_note, limit)
123
+ return {"base": base, "markdown": "\n".join(lines).rstrip("\n") + "\n", "commits": commits, "commit_total": total,
124
+ "functions": shown, "callers": {label: reached[1] if reached else 0 for label, reached in callers.items()},
125
+ "decisions": decisions, "stale_anchors": stale[:limit], "stale_note": stale_note}
@@ -0,0 +1,95 @@
1
+ """What renaming a function leaves behind, asked before the rename: where it is defined, who calls it (the calls the
2
+ graph resolved and the calls it left unresolved under that name), the tests that reach it, the files that import its
3
+ module, the anchors of the generated documents and the lines of the README and `docs` text that name it. Nothing is
4
+ written; the lists are the places an agent edits or checks after changing the name.
5
+ """
6
+ import posixpath
7
+
8
+ import code_graph
9
+ import code_impact
10
+ import doc_scope
11
+ import dossier
12
+ import project_scan
13
+ import removed_callers
14
+
15
+ DEFAULT_LIMIT = 30
16
+ TEST_DEPTH = 3
17
+ DOC_EXTENSIONS = (".md", ".rst", ".txt", ".html")
18
+ MAX_LINE_CHARS = 160
19
+ NOTE = ("A rename also needs a text search of the old name for what static analysis cannot see: strings, dynamic access "
20
+ "and names built at run time.")
21
+
22
+
23
+ def _is_doc(rel):
24
+ """Whether a tracked file is a README or sits in a `docs` folder, outside the generated documents (their anchors are
25
+ listed apart)."""
26
+ if rel.startswith(doc_scope.DOCS_DIR + "/") or not rel.lower().endswith(DOC_EXTENSIONS):
27
+ return False
28
+ return posixpath.basename(rel).upper().startswith("README") or "docs" in rel.split("/")[:-1]
29
+
30
+
31
+ def _unresolved_calls(data, definitions, limit):
32
+ """Calls the graph could not resolve whose expression can mean one of the definitions, as `removed_callers` reads them.
33
+
34
+ Returns: tuple (list of {"path", "line", "expression"} up to `limit`, int total).
35
+ """
36
+ found = {}
37
+ for definition in definitions:
38
+ short = definition["name"].rpartition(".")[2]
39
+ stem = posixpath.splitext(posixpath.basename(definition["path"]))[0]
40
+ for call in data.get("unresolved") or []:
41
+ if removed_callers._names(call["expression"], short, stem, "." in definition["name"]):
42
+ found[(call["path"], call["line"], call["expression"])] = None
43
+ rows = [{"path": path, "line": line, "expression": expression} for path, line, expression in sorted(found)]
44
+ return rows[:limit], len(rows)
45
+
46
+
47
+ def _mentions(root, definitions, limit):
48
+ """Lines of the tracked README and `docs` text that name a definition: `path::name`, `module.name` or `Owner.name`,
49
+ the name in backticks, or a compound name on its own (`dossier.mention_test`, which keeps a single plain word out).
50
+
51
+ Returns: tuple (list of {"path", "line", "text"} up to `limit`, int total).
52
+ Raises: ValueError when git cannot list the folder.
53
+ """
54
+ tests = [dossier.mention_test(item["path"], item["name"]) for item in definitions]
55
+ literals = [f"{item['path']}::{item['name']}" for item in definitions]
56
+ quoted = [f"`{item['name'].rpartition('.')[2]}`" for item in definitions]
57
+ quoted += [text[:-1] + "(" for text in quoted]
58
+ found, total = [], 0
59
+ for rel, text in project_scan.tracked_texts(root, DOC_EXTENSIONS):
60
+ if text is None or not _is_doc(rel):
61
+ continue
62
+ for number, line in enumerate(text.splitlines(), 1):
63
+ if any(test(line) for test in tests) or any(literal in line for literal in literals) \
64
+ or any(mark in line for mark in quoted):
65
+ total += 1
66
+ if len(found) < limit:
67
+ found.append({"path": rel, "line": number, "text": line.strip()[:MAX_LINE_CHARS]})
68
+ return found, total
69
+
70
+
71
+ def preview(root, symbol, view_id=None, limit=DEFAULT_LIMIT):
72
+ """Everything a rename of one function touches.
73
+
74
+ Parameters: root (str) project folder; symbol (str) function, `Class.method`, class or `path::name`; view_id (str or
75
+ None) index view; limit (int) rows in each list.
76
+ Returns: dict {"symbol", "definitions": [{"name", "kind", "path", "lines"}], "callers": [{"function", "path", "line"}],
77
+ "unresolved_calls": [{"path", "line", "expression"}], "tests", "imported_by": [path], "doc_anchors": [{"file", "line",
78
+ "id", "level", "current"}], "doc_mentions": [{"path", "line", "text"}], "counts": {list: total}, "doc_scope": str
79
+ ("" when docs/scope exists, otherwise why no anchor could be listed), "note": str}.
80
+ Raises: ValueError when the symbol is not found (with the closest names), the folder is not a git repository or a page of
81
+ docs/scope is in an older format; RuntimeError when the code graph cannot be built.
82
+ """
83
+ found = code_impact.impact(root, symbol, view_id, TEST_DEPTH, limit)
84
+ data = code_graph.build_current(root, view_id, shared=True)
85
+ unresolved, unresolved_total = _unresolved_calls(data, found["definitions"], limit)
86
+ mentions, mentions_total = _mentions(root, found["definitions"], limit)
87
+ anchored = doc_scope.anchors(root, symbol, view_id)
88
+ anchors = anchored["anchors"]
89
+ counts = {**found["counts"], "unresolved_calls": unresolved_total, "doc_anchors": len(anchors),
90
+ "doc_mentions": mentions_total}
91
+ counts.pop("calls")
92
+ return {"symbol": found["symbol"], "definitions": found["definitions"], "callers": found["callers"],
93
+ "unresolved_calls": unresolved, "tests": found["tests"], "imported_by": found["imported_by"],
94
+ "doc_anchors": anchors[:limit], "doc_mentions": mentions, "counts": counts,
95
+ "doc_scope": anchored.get("guidance", ""), "note": f"{found['note']} {NOTE}"}
package/requester.py CHANGED
@@ -13,7 +13,7 @@ import json
13
13
  import threading
14
14
  import time
15
15
 
16
- WEB_TOOLS = ("web_search", "web_fetch")
16
+ WEB_TOOLS = ("web_search", "web_fetch", "web_fetch_many")
17
17
  PROJECT_TOOLS = ("smart_search", "smart_scout", "project_manage")
18
18
  NOTE_TTL_S = 60
19
19
  MAX_NOTES = 256