@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/CHANGELOG.md CHANGED
@@ -1,5 +1,120 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.9.83 - beta
4
+
5
+ - Commit check, opt-in: `project_manage action=commit_check` reviews the staged change (`git diff --cached`) with the
6
+ notes the edit hook gives a finished diff, and `action=commit_hook_install` writes a git `pre-commit` hook that prints
7
+ them to stderr at every commit, for edits the agent hook never saw. The hook never blocks (exit 0 always): a daemon
8
+ that is down is one line, `Smart Tool is not running, commit not reviewed`, and a check that fails is printed. It finds
9
+ the daemon through its run file, never through a port. The install refuses and changes nothing when `core.hooksPath`
10
+ is set, husky is used or a `pre-commit` that is not ours exists; `action=commit_hook_uninstall` removes only our own
11
+ hook and puts back a backed-up hook that is not ours. Tests: `tests/test_commit_check.py`.
12
+ - New tool `web_fetch_many`: up to 8 URLs with one prompt in one call. Each URL goes through the same path as
13
+ `web_fetch` (24 h cache, failure memory, browser for JavaScript pages, public addresses only, answer of the
14
+ gateway model), 4 at a time, and the reply holds one block per URL in the order given: the answer, or an `ERROR`
15
+ line with the reason, so a URL that fails (an internal address, a 404, a page without text) never hides the others
16
+ and is released to the native `WebFetch` for 10 minutes like a failed `web_fetch`. A URL repeated (same address
17
+ without the fragment) is read once; more than 8 URLs, a malformed list or an empty prompt fail the whole call before
18
+ anything is read; the call fails as a whole only when every URL failed, with the report as its text. `web_fetch` and
19
+ the redirect of the native `WebFetch` are unchanged; the tool is not a redirect target and loads on demand. Measured
20
+ before the build: in 843 turns of local Claude Code transcripts that fetched a page, 621 fetched two or more and 512 spread
21
+ them over several assistant messages (`docs/research/2026-11-21-web-fetch-many-medicao.md`). Tests:
22
+ `tests/test_web_fetch_many.py`.
23
+ - A native `Read` of a code file of a registered project now names the recorded decisions that mention its functions, as
24
+ extra context before the agent plans an edit, with the same rule as the note after an edit: the first three functions
25
+ of the file in the cached code graph, up to two notes each from `docs/research`, the backlog, `CLAUDE.md` and
26
+ `AGENTS.md`, 300 ms per function, files only (no network, no model, no git history). It reads the graph only when it
27
+ is already cached (no analysis starts and nothing waits for one) and is silent when nothing is cached, for a file that
28
+ is not code, for a file outside a project and when no note names a function; a search that fails or is cut is said.
29
+ It follows `decision_mode` (`warn`, default, or `off`), never denies and never blocks the read, whatever `hook_mode` is.
30
+ The note after an edit is unchanged. A project that installed the hook before `Read` was in its matcher is reported as
31
+ outdated by the same check as any other missing tool and rewritten by the install. About 80 to 115 ms per read on this
32
+ repository with the graph in memory. Tests: `tests/test_read_decision_notes.py`. Measurement:
33
+ `docs/research/2026-11-21-notas-de-decisao-na-leitura.md`.
34
+ - `read_document` also takes an `http://` or `https://` URL as its `path`. The file is downloaded with the `web_fetch`
35
+ download (public addresses only, every redirect hop checked, 5 MB cap), kept for 24 hours in the per-user cache folder
36
+ under a name made of a hash of the URL, and read like a local file: same page, slide and sheet ranges, same token
37
+ estimate. The answer names the URL without its query string and credentials, and the metric keeps only the extension of
38
+ the URL path. A URL of a web page fails with a pointer to `web_fetch`. Any other `path` is read exactly as before.
39
+ - `project_scan.tracked_files` is now the one place that lists the files git tracks: the affected-tests selection and the
40
+ working-tree overlay of the code graph no longer run their own `git ls-files`. Their answers do not change.
41
+ - `project_manage action=rename_preview` with `symbol` lists what a rename of a function touches, before the rename: its
42
+ definitions with file and lines, its callers with line (and the calls the graph left unresolved under that name), the
43
+ tests that reach it, the files importing its module, the anchors in `docs/scope` and the lines of README and `docs` text
44
+ that name it. Each list is capped by `limit` with the totals in `counts`; a symbol that is not found fails with the
45
+ closest names, and a project without `docs/scope` says so instead of returning an empty anchor list. Nothing is
46
+ written. Tests: `tests/test_rename_preview.py`.
47
+ - `project_manage action=release_notes` drafts the notes of the next release in Markdown, without a model, under
48
+ `## Draft since <base>`: the commit subjects since `base` (default the latest tag from `git describe --tags
49
+ --abbrev=0`; no tag and no `base` is an error), the public functions the diff touches with their caller and test counts,
50
+ the decision notes that name them and the documentation entries the diff leaves out of date, all from the builders of
51
+ `pr_impact`. Lists are capped by `limit`; every line is a commit subject, a name or a count read from the project.
52
+ Nothing is written. Tests: `tests/test_release_notes.py`.
53
+
54
+ ## 0.9.82 - beta
55
+
56
+ - The edit hook adds two lines to its note, both read from what is already cached and silent otherwise (no analysis is
57
+ started, no `git` runs): the import cycle a Python import the edit adds at module level closes in the indexed import
58
+ graph, named with its chain of files, and the hotspot (top ten by commits times lines, ten commits or more) or the file
59
+ that usually changes with an edited one and is not in the edit. Context only, never a denial. `import_cycles`,
60
+ `hotspots` and `coupled_with` keep their answers; `code_graph.cached_graph` and `doc_insights.cached_history` are the new
61
+ cache-only readers.
62
+ - The Claude Code hooks (PreToolUse, PostToolUse, SubagentStart, Stop) are command hooks now, like Codex's, instead of
63
+ `http` hooks with the daemon port written into `settings.json`. The hook reads the daemon's run file on every call and
64
+ waits out a restart with backoff (up to 10 s), so a restart or an install prints nothing; a daemon that stays
65
+ unreachable lets the call through with one plain message naming the hook, its owner, the cause and what happened to the
66
+ call, and the next calls stay silent until the daemon answers. Claude Code's own `hook failed: read ECONNRESET` and
67
+ `connect ECONNREFUSED` lines came from the http transport and could not be changed. The cost is one short process per
68
+ hooked call (about 0.2 s on this machine against 11 ms). `settings.json` holds no port, so a port change rewrites no
69
+ hook; an older entry shows as outdated until the hook is installed again (Agent rules). Codex entries pass `--route`
70
+ instead of `--post`.
71
+ - Claude Code subagents now start knowing about the Smart Tool: a SubagentStart hook (`/hooks/subagent-start`, installed
72
+ with the other hooks and removed by uninstall) tells each one that, for a question across several files, its first call
73
+ is `smart_scout`, before Grep or Read. It adds context only and never denies; `hook_mode` off says nothing. Measured in
74
+ isolation: 8 of 8 subagents used the Smart Tool with it against 4 of 8 without.
75
+ - The PreToolUse hook also covers subagent launches (`Agent`, `Task`): an Explore launch with a short, targeted prompt
76
+ carries a tip with the `smart_scout` call to make, in redirect and advise modes; the launch is never denied, and every
77
+ other launch (coding, whole-product or broad reviews, web research, other agent types) gets nothing. Off mode says
78
+ nothing, and so does a session where `smart_scout` cannot be called without a permission prompt (a mode that allows
79
+ every tool, or an allow rule for the tool, its server or `mcp__smart-tool__*`, and no deny rule).
80
+ - A third source file read through the shell (`cat`, `head`, `sed -n`) in ten minutes carries a tip to call `smart_scout`
81
+ (redirect and advise modes, no blocking; off says nothing, and only where `smart_scout` is callable). A single read is
82
+ never touched: the shell is what a known file needs and `smart_search` cannot return its exact lines. The subagent start
83
+ sentence also names `smart_search`.
84
+ - **The generated documentation format changes; regenerate `docs/scope` once.** The symbol marker of each entry now
85
+ carries body and docstring stamps next to the signature (`signature="…" body="…" docstring="…"`), so
86
+ `action=docs check=true`, the edit hook, `docs symbol=` and validation also catch a body or docstring changed under
87
+ the same signature (`body_changed`, `docstring_changed`). A page in the older format fails loud and asks to
88
+ regenerate (`action=docs generate=true`, which keeps the written prose); there is no compatibility mode. The
89
+ `code="…"` stamp of a feature's paragraph now covers the entry point and every function its flow reaches, so a
90
+ change deep in the flow marks the paragraph stale: paragraphs written before this version are reported stale once.
91
+ - Each technical entry names the features whose flow reaches it (`- Feature: [name](functional.md#…)` or
92
+ `- Feature: none`); feature sections list their functions without the old cut at 12; a new `chain` check of validation
93
+ fails when one side names a link the other does not.
94
+ - **A Claude Code hook is added**: installing the hook now also writes a `Stop` entry of type `command`
95
+ (`hooks/turn_end.py … --hook-origin=smart-tool`), which reads the daemon address from its run file on every call and
96
+ fails loud with its origin when the daemon is down. At the end of a turn in a project with a generated `docs/scope`,
97
+ the daemon rewrites without a model only the pages of the functions the turn changed (at most 20 functions and 60
98
+ chain nodes per turn, 2 attempts per function), rewrites with the docs model only the stale paragraphs of the
99
+ features they belong to (a rejected paragraph keeps its old text and is reported), proposes up to two "possible"
100
+ features from the embeddings home for a public function no entry point reaches (status candidate, never confirmed by
101
+ the embedder), and blocks the turn once with the docstrings to check against a new body. A continuation of the
102
+ session (`stop_hook_active`) exits at once. Uninstalling removes the entry.
103
+ - **A database is added**: `~/.smart-tool/data/doc_registry.db`, a per-function registry in its own SQLite file (WAL,
104
+ `synchronous=FULL`) with the stamps of the code and of its documentation, the dates, a status and the feature links.
105
+ The stamps in the pages stay the truth, so a lost registry is rebuilt from them; work a crash interrupted resumes at
106
+ daemon start, at the next end of turn and at a session's first call.
107
+ - Java: the line checks of validation take the bare method name, so Java methods (with or without parameters,
108
+ overloads included) no longer fail them, and a call through a field typed by an interface the project declares
109
+ becomes an edge to the declared method (methods inherited from a library stay unresolved).
110
+ - Tests: `tests/test_doc_chain.py`, `tests/test_code_graph_java.py`, Java cases in `tests/test_doc_validate.py`.
111
+ - `project_manage action=credentials` scans every git-tracked text file from disk and lists the file and line of each
112
+ credential shape (never the value), so a token committed earlier or sitting in a `.env` file is reported, which the
113
+ edit hook and the index (it skips `.env`, `.pem`, `.key`) cannot do. `action=links` lists the relative links in the
114
+ tracked HTML and Markdown files that point to a missing file, and the links it could not decide (root-relative,
115
+ template expressions, pages with a `<base>` element) as unchecked, not broken. Both take `limit` and write nothing.
116
+ Tests: `tests/test_project_scan.py`.
117
+
3
118
  ## 0.9.81 - beta
4
119
 
5
120
  - `pr_impact` lists the functions the diff adds that no function and no test calls (the candidates `dead_code` finds, which
package/NOTICE CHANGED
@@ -1,5 +1,5 @@
1
1
  Smart Tool
2
- Copyright 2026 Smart Tool contributors
2
+ Copyright 2026 Allan Santos
3
3
 
4
4
  Licensed under the Apache License, Version 2.0 (see LICENSE).
5
5
 
package/README.md CHANGED
@@ -8,7 +8,8 @@ A local MCP server that gives coding agents (Claude Code, Codex) cheaper, sharpe
8
8
  | `smart_scout` | Answers a question about the code with the lines that answer it: reads the candidate files inside Smart Tool and returns `path:lines` with the literal text, so the files never enter the agent's context; with a `scout_model`, a small model also writes a short answer and keeps only the lines that support it; a question about why something is as it is (why, reason, decided) also lists up to three decision notes from the notes the project keeps about its intent, as ids with one excerpt each |
9
9
  | `web_search` / `web_search_result` | Web search across several sources in parallel, in the query language and in English, with a cache shared across sessions; `depth="research"` runs a multi-round research loop |
10
10
  | `web_fetch` | Reads a known URL and returns only the answer to your prompt, written by a small model; pages are cached for 24 h. Pages over 60,000 characters are not cut: the model reads the parts closest to the prompt (needs an `embedding_model`) |
11
- | `read_document` | Reads a PDF, Word, PowerPoint, Excel, HTML, CSV or EPUB file as compact text, a range at a time: type, size, page/slide/sheet/part/chapter count and estimated tokens first, then only the units asked for (`range="3-5"`), so the file never enters the agent's context whole. Opt-in: the native Read is not redirected. Scanned PDFs fail with that reason (no OCR) |
11
+ | `web_fetch_many` | Reads up to 8 known URLs in one call with the same prompt, 4 at a time, each exactly as `web_fetch` reads it (24 h cache, browser for JavaScript pages, public addresses only). One block per URL in the order given: the answer, or an `ERROR` line with the reason, so a URL that fails never hides the others; a repeated URL is read once |
12
+ | `read_document` | Reads a PDF, Word, PowerPoint, Excel, HTML, CSV or EPUB file as compact text, a range at a time: type, size, page/slide/sheet/part/chapter count and estimated tokens first, then only the units asked for (`range="3-5"`), so the file never enters the agent's context whole. The path can also be an `http(s)` URL of a PDF, Word, PowerPoint, Excel, CSV or EPUB file: it is downloaded the way `web_fetch` downloads (public addresses only, 5 MB cap), kept for 24 hours and read with the same ranges and token estimate; a URL of a web page fails and points to `web_fetch`. Opt-in: the native Read is not redirected. Scanned PDFs fail with that reason (no OCR) |
12
13
  | `project_manage` | Registers and indexes projects, shows coverage, code maps, duplicated functions and index storage; `graph` with `symbol` tells what changing a function touches: callers, calls, the tests that reach it and the files that import it |
13
14
 
14
15
  Agents that must click, type or log in also get Microsoft's [Playwright MCP](https://github.com/microsoft/playwright-mcp),
@@ -17,7 +18,7 @@ registered as the `playwright` server where this machine lets a browser be drive
17
18
  An optional hook routes the agent's native Grep/Glob/Read/Bash/WebSearch/WebFetch calls to these tools when they
18
19
  are cheaper, or just tells the agent what Smart Tool would do.
19
20
 
20
- **Status:** 0.9.81 beta. Windows only. What changed in each version: [CHANGELOG.md](CHANGELOG.md).
21
+ **Status:** 0.9.83 beta. Windows only. What changed in each version: [CHANGELOG.md](CHANGELOG.md).
21
22
 
22
23
  ## How it works
23
24
 
@@ -84,7 +85,7 @@ gateway such as Ollama, nothing about your code leaves the machine.
84
85
  ## Install
85
86
 
86
87
  ```powershell
87
- npx @allansantos-dev/smart-tool@0.9.81 install
88
+ npx @allansantos-dev/smart-tool@0.9.83 install
88
89
  ```
89
90
 
90
91
  Updates install themselves, on by default: the tray checks npm when it starts (at logon) and every 24 h, and when there
@@ -172,10 +173,13 @@ Redirects) and Maintenance (Setup audit, Startup).
172
173
  `browser_run_code_unsafe`, which runs arbitrary JavaScript in the server process, is denied in the client
173
174
  (`permissions.deny` in `~/.claude/settings.json`, `disabled_tools` in `~/.codex/config.toml`); if it cannot be
174
175
  denied, the server is not registered. A `playwright` server you registered yourself is never touched. Remove it with
175
- `claude mcp remove playwright -s user` / `codex mcp remove playwright`. The registered command is a small stdio
176
- proxy (`lazy_mcp_proxy.py`, standard library only) that answers the handshake and the tool list from a cache the
177
- probe writes and starts the Node server on the first tool call, so a session that never opens a browser does not
178
- keep a 97 MB Node process; it ends with the session.
176
+ `claude mcp remove playwright -s user` / `codex mcp remove playwright`. Claude Code's registered command is a small
177
+ stdio proxy (`lazy_mcp_proxy.py`, standard library only) that answers the handshake and the tool list from a cache
178
+ the probe writes and starts the Node server on the first tool call, so a session that never opens a browser does
179
+ not keep a 97 MB Node process; it ends with the session. The browser tools reach Codex through the daemon URL
180
+ (`url = "<daemon>/playwright/mcp"` in `~/.codex/config.toml`, next to the smart-tool entry) instead of one proxy per
181
+ conversation thread: the daemon answers the handshake from the same cache and starts one shared Node server on the
182
+ first tool call, with a browser context of its own for each Codex thread, and stops it after an hour without calls.
179
183
 
180
184
  **Who asked for a web search**: every provider call in `~/.smart-tool/data/web-search-health.jsonl` and every
181
185
  record of `research-metrics.jsonl` made for a `web_search` carries `requester`: `client`, `mcp_session` (first 12
@@ -254,10 +258,17 @@ Redirects) and Maintenance (Setup audit, Startup).
254
258
  context read from the code, and a paragraph is written only when every name, option and version it cites exists in
255
259
  the code and it is in English; a rejected one is asked again once with the reason, then reported with its fix. A call stops after about
256
260
  40 s and says how many blocks are left. The prose can also be written by hand between the markers; regenerating keeps it, reports blocks whose module
257
- or entry point is gone, and never overwrites a file that Smart Tool did not write. Each anchor records the signature
258
- it was generated from: `action=docs check=true` lists anchors whose function changed signature or is gone, links
259
- to missing anchors and entry paragraphs written for an older body of their function (the `code="..."` stamp of the
260
- block; delete it after rewriting the paragraph by hand), `action=docs validate=true` checks every claim of `docs/scope` against the code and writes `docs/scope/validation.md`, `action=docs symbol=NAME` tells where a function is documented, and the documentation hook warns
261
+ or entry point is gone, and never overwrites a file that Smart Tool did not write. Each anchor records the signature,
262
+ body and docstring it was generated from: `action=docs check=true` lists anchors whose function changed any of the
263
+ three or is gone, links to missing anchors and entry paragraphs written for older code of their feature (the
264
+ `code="..."` stamp of the block covers the entry point and every function its flow reaches; delete it after
265
+ rewriting the paragraph by hand). Each technical entry names the features it belongs to (`Feature: ...` or
266
+ `Feature: none`) and each feature lists its functions, and validation checks that both sides agree. With the Claude
267
+ Code hook installed, a Stop hook runs the end-of-turn step: the pages of the functions the turn changed are rewritten
268
+ without a model, the stale paragraphs of their features are rewritten by the docs model, a public function no entry
269
+ point reaches gets up to two "possible" features from the embeddings home (never confirmed by it), and the agent is
270
+ asked once to check a docstring whose function body changed; a per-function registry
271
+ (`~/.smart-tool/data/doc_registry.db`) keeps that work across crashes. `action=docs validate=true` checks every claim of `docs/scope` against the code and writes `docs/scope/validation.md`, `action=docs symbol=NAME` tells where a function is documented, and the documentation hook warns
261
272
  when an edit makes a documented entry out of date. The link lives in the documents, never inside docstrings.
262
273
  The same run writes fifteen optional documents under `docs/scope/extras`, all from the graph and the git log: folder
263
274
  structure, docstring coverage per folder, module Mermaid, tests README, configuration read by the code, dependencies
@@ -288,7 +299,33 @@ Redirects) and Maintenance (Setup audit, Startup).
288
299
  riskiest to change), `dead_code` lists the functions no code calls and those only tests call (static call graph,
289
300
  candidates to read before deleting), `import_cycles` lists the groups of files that import each other, and
290
301
  `comments` lists comments in the wrong place across the code files (commented-out code, history tags, loose docs,
291
- long inline blocks), for code written before the edit hook existed. Each takes `limit` and writes nothing.
302
+ long inline blocks), for code written before the edit hook existed. `credentials` lists, per git-tracked text file
303
+ (read from disk, so `.env` files and old commits count), the file and line of each credential shape and never the
304
+ value; `links` lists the relative links in tracked HTML and Markdown files that point to a missing file, and the ones
305
+ it could not decide (root-relative, template expressions, pages with a `<base>` element) as unchecked, not broken.
306
+ Each takes `limit` and writes nothing.
307
+ **Rename preview**: `project_manage action=rename_preview symbol=...` answers, before a function is renamed, with its
308
+ definitions (file and lines), its callers with line (including calls the graph left unresolved under that name), the
309
+ tests that reach it, the files importing its module, the `path::name` anchors of `docs/scope` that would go stale and
310
+ the lines of the README and `docs` text that name it (`path::name`, `module.name`, the name in backticks, or a
311
+ compound name; a plain word alone is not counted). A symbol that is not found fails with the closest names. Static
312
+ analysis does not see strings or dynamic access, so search the old name as text too. Takes `limit`, writes nothing.
313
+ **Release notes draft**: `project_manage action=release_notes` (optional `base`, default the latest tag; no tag and no
314
+ `base` is an error) returns a Markdown section headed `## Draft since <base>` built without a model: the commit
315
+ subjects since the base, the public functions the diff touches with their caller and test counts, the decision notes
316
+ that name them and the documentation entries the diff leaves out of date, the same builders `pr_impact` uses. It
317
+ writes no prose of its own, so the agent or the maintainer words the notes from it. Takes `limit`, writes nothing.
318
+ **Commit check** (opt-in): `project_manage action=commit_check` reviews the staged change (`git diff --cached`, not the
319
+ working tree) with the notes the edit hook gives a finished diff (credentials, commented-out code, missing docstrings,
320
+ duplicates, dependency advisories, link and edit notes), so edits the agent hook never saw (an IDE, hand edits,
321
+ another agent) are reviewed before they reach the commit. `action=commit_hook_install` writes a git `pre-commit` hook
322
+ in the project that prints that review to stderr at every commit; it never blocks: the exit status is always 0, a
323
+ daemon that is down is one line (`Smart Tool is not running, commit not reviewed`) and a check that fails is
324
+ printed. The hook finds the daemon through its run file, never through a port. The install refuses, naming what it
325
+ found and changing nothing, when `core.hooksPath` is set, husky is used (a `.husky` folder or `husky` in
326
+ `package.json`) or a `pre-commit` that is not Smart Tool's exists; an older hook of ours is backed up first.
327
+ `action=commit_hook_uninstall` removes only that hook (identified by its marker line) and puts back a backed-up hook
328
+ that is not ours. In a worktree or submodule the hook goes where `git rev-parse --git-path hooks` points.
292
329
 
293
330
  **Layers on edit**: when the project has confirmed layers (`.smart-tool/layers.json`), an edit that adds a call from
294
331
  a lower layer to a function of a higher one is flagged to the agent; it never blocks. `layer_mode` in
@@ -305,6 +342,14 @@ Redirects) and Maintenance (Setup audit, Startup).
305
342
  network, no model, no git history, 300 ms per function), says when it fails or is cut, and never blocks.
306
343
  `decision_mode` in `config.json`: `warn` (default) or `off`, also on the setup screen. The measurement behind the rule is
307
344
  in `docs/research/2026-11-18-decision-notes-keyword-quality.md`.
345
+ **Recorded decisions on read**: a native `Read` of a code file of a registered project names the same notes for the
346
+ first three functions the file defines in the cached code graph, as context before the agent plans an edit. It is the
347
+ same rule and the same limits (two notes each, files only, 300 ms per function), and it adds a latency budget: the
348
+ graph is read only when it is already cached, so no analysis starts and nothing waits for one, and a project with
349
+ nothing cached, a file that is not code, a file outside a project and a file no note names get no line at all. A range
350
+ read (`offset`, `limit`) gets the note too. It follows `decision_mode` (`off` says nothing), is context only whatever
351
+ `hook_mode` says, and never blocks the read. About 80 to 115 ms per read on this repository
352
+ (`docs/research/2026-11-21-notas-de-decisao-na-leitura.md`).
308
353
 
309
354
  **Folder and layer in a search**: `smart_search folder="<path>"` (or a list) and `layer="<name>"` restrict the
310
355
  search to a folder of the project or to one of its confirmed layers, by their path globs. The filter runs before
@@ -315,6 +360,16 @@ Redirects) and Maintenance (Setup audit, Startup).
315
360
  private-key header at the start of a line); the note names the file and line, never repeats the value and never blocks, and a
316
361
  line that says it is an example is skipped.
317
362
 
363
+ **Import cycles and history on edit**: two more lines of the edit note, read only from what is already cached (the
364
+ code graph analysis and the git history the daemon holds in memory), so the hook never waits for an analysis and never
365
+ runs `git`; with nothing cached they say nothing. A Python import the edit adds at module level (an import inside a
366
+ function is the usual way to break a cycle and is skipped) that names a project file with a way back to the edited
367
+ file in the indexed import graph is flagged with the chain (`a.py -> b.py -> c.py -> a.py`). A code file in the ten
368
+ riskiest by commits times lines (the `hotspots` ranking) with at least ten commits is named a hotspot, and a file
369
+ outside the edit that usually changes in the same commits as an edited one (the `coupled_with` rule: hidden coupling
370
+ without an import between them) is named as its partner. They add context only, never block, and follow the modes of
371
+ the other edit notes (all of them `off` silences the review).
372
+
318
373
  **Dependency check on edit**: an edit of `package.json`, `requirements*.txt`, `pyproject.toml` (`project.dependencies` and `project.optional-dependencies`; Poetry tables are not read), `go.mod`, `Cargo.toml` (crates.io registry dependencies) or `pom.xml` (Maven, plain or property-resolved versions) that adds or changes a dependency lists the OSV advisory IDs of up to 5 of them (exact version, or the lower bound of `^`, `~`, `~=` and `>=`), answered from a 6 h disk cache or one 2.5 s batch call that sends only package names and versions; when OSV cannot answer, the reminder says the check was skipped and the edit goes on. `dependency_mode` in `config.json`: `warn` (default) or `off`.
319
374
 
320
375
  **PDFs** inside a project are indexed as text with `[page N]` markers (20 MiB, 300 pages and 20 s per file; a scanned, password-protected or corrupt PDF is skipped with the reason), so `smart_search` returns the page that holds a passage. **Presentations and workbooks** (`.pptx`, `.xlsx`) are indexed the
@@ -391,7 +446,11 @@ Redirects) and Maintenance (Setup audit, Startup).
391
446
  (`hooks/session_audit.py`) only asks the running service and prints nothing when the service is down.
392
447
  4. **Embedder**: the embeddings home (casa-de-embeddings, the embedding service of this machine, found through
393
448
  `~/.casa-de-embeddings/run/daemon.json`) is the default; the gateway's `embedding_model` and `rerank_model` are used
394
- only when you choose **Gateway** here, never in place of a stopped home. The home's embedder is identified by the
449
+ only when you choose **Gateway** here, never in place of a stopped home. With the home chosen, the service installs
450
+ it when it is missing, brings it to the registry's version when it is older (the engine registry's kit checks the
451
+ SHA-256 and the Ed25519 signature of the asset) and starts it, looking again once a day and ten minutes after a
452
+ failure; a home that already answers at the registry's version or newer is left alone, and when it cannot be brought
453
+ up, searches stay lexical and the warning names the reason. The home's embedder is identified by the
395
454
  `model_sha256` and `dimension` of its `/info`; a home that answers without them is reported as an error, never
396
455
  replaced silently by lexical search. Rerank goes through the home's connector to the rerank host configured in it;
397
456
  without one, results keep the hybrid order and say so. Switching the embedder re-embeds each project in the
@@ -454,7 +513,7 @@ fails to load is listed in the setup screen with its error and does not affect t
454
513
  ## Uninstall
455
514
 
456
515
  ```powershell
457
- npx @allansantos-dev/smart-tool@0.9.81 uninstall [--target DIR] [--keep-data]
516
+ npx @allansantos-dev/smart-tool@0.9.83 uninstall [--target DIR] [--keep-data]
458
517
  ```
459
518
 
460
519
  It asks nothing and opens no window. It stops the tray and the daemon, removes the logon task, the hook entries of Smart
package/affected_tests.py CHANGED
@@ -16,6 +16,7 @@ import code_graph
16
16
  import index_inventory
17
17
  import index_profile
18
18
  import index_scope
19
+ import project_scan
19
20
 
20
21
  RUN_ALL = re.compile(
21
22
  r"(^|/)(package\.json|package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|pnpm-workspace\.yaml|"
@@ -284,15 +285,15 @@ def _support(root, path):
284
285
  def _tracked_tests_outside_graph(root, parsed, profile):
285
286
  """Code test files git tracks that the graph could not analyze (over the size limits, unreadable): their imports
286
287
  are unknown, so they are selected instead of silently missing (a 1.4 MB test file covering 1,427 cases did)."""
287
- listed = subprocess.run(["git", "ls-files", "-z"], cwd=root, capture_output=True, timeout=30)
288
- if listed.returncode:
288
+ try:
289
+ tracked = project_scan.tracked_files(root)
290
+ except ValueError as exc:
291
+ if exc.__cause__:
292
+ raise
289
293
  return []
290
- tests = []
291
- for rel in listed.stdout.decode("utf-8", "replace").split("\0"):
292
- if rel and rel not in parsed and rel.lower().endswith(TEST_SOURCES) and os.path.basename(rel) != "conftest.py" \
293
- and index_profile.kind(rel, profile) == "test" and os.path.isfile(os.path.join(root, rel)):
294
- tests.append(rel)
295
- return tests
294
+ return [rel for rel in tracked
295
+ if rel not in parsed and rel.lower().endswith(TEST_SOURCES) and os.path.basename(rel) != "conftest.py"
296
+ and index_profile.kind(rel, profile) == "test"]
296
297
 
297
298
 
298
299
  def _label(symbol, by_id):
@@ -0,0 +1,32 @@
1
+ """PreToolUse tip for a subagent launch (Claude Code `Agent`/`Task`): a launch of a search-only subagent for a
2
+ targeted question carries the Smart Tool call that answers it, and every other launch (coding, whole-product
3
+ reviews, web research, custom or ambiguous types) gets nothing. The launch itself is never denied."""
4
+ import re
5
+
6
+ LAUNCH_TOOLS = frozenset({"Agent", "Task"})
7
+ SEARCH_ONLY_TYPES = frozenset({"Explore"})
8
+ MAX_PROMPT_CHARS = 1500
9
+ BROAD_SCOPE = re.compile(
10
+ r"\b(review|audit|assess|inventory|survey|broad|whole|entire|every|each file|all files|all the|across the "
11
+ r"(?:repo|repository|product|codebase|project)|revis\w*|audit\w*|invent[aá]rio|inteir[oa]|todos os|todas as|"
12
+ r"produto todo|em todo)\b", re.I)
13
+ WEB_SCOPE = re.compile(r"https?://|\b(web|internet|online|documenta[cç][aã]o oficial|official docs)\b", re.I)
14
+
15
+ LAUNCH_TIP = (
16
+ "for a search like this, call "
17
+ "mcp__smart-tool__smart_scout(project_root, question) yourself (project_root is your working directory). It reads "
18
+ "the files inside Smart Tool and returns only the lines that answer, at a fraction of the cost of a subagent.")
19
+
20
+
21
+ def reason(payload):
22
+ """The tip for a launch of a search-only subagent with a short, targeted prompt, or None when the
23
+ launch should run: another tool, another subagent type, a long prompt, a broad-scope or web-research wording."""
24
+ if not isinstance(payload, dict) or payload.get("tool_name") not in LAUNCH_TOOLS:
25
+ return None
26
+ tool_input = payload.get("tool_input") if isinstance(payload.get("tool_input"), dict) else {}
27
+ prompt = str(tool_input.get("prompt") or "")
28
+ if tool_input.get("subagent_type") not in SEARCH_ONLY_TYPES or not prompt.strip():
29
+ return None
30
+ if len(prompt) > MAX_PROMPT_CHARS or BROAD_SCOPE.search(prompt) or WEB_SCOPE.search(prompt):
31
+ return None
32
+ return LAUNCH_TIP
package/autostart.py CHANGED
@@ -1,17 +1,20 @@
1
1
  #!/usr/bin/env python3
2
2
  """Autostart do Smart Tool no logon do Windows — Tarefa Agendada por usuário (sem
3
- admin), com política `RestartOnFailure` cobrindo o SO reiniciar o processo se ele
4
- morrer. `schtasks /Create` pode ser bloqueado por política de grupo corporativa
5
- (máquina AD-joined); nesse caso cai automaticamente para um atalho na pasta Startup
6
- do usuário — sem a política de restart do Task Scheduler, mas o loop de polling do
7
- próprio `tray.py` já cobre "se cair, sobe de novo" independente do mecanismo de boot.
3
+ admin). `schtasks /Create` pode ser bloqueado por política de grupo corporativa
4
+ (máquina AD-joined); nesse caso cai automaticamente para um script na pasta Startup
5
+ do usuário. Os dois rodam o mesmo VBScript, que sobe o `tray.py` no Python base com
6
+ a venv (`venv_launch`): a Tarefa Agendada não passa variável de ambiente, e o
7
+ redirecionador da venv deixaria dois processos por bandeja. O loop de polling do
8
+ próprio `tray.py` cobre "se o daemon cair, sobe de novo".
8
9
  """
9
10
  import os
10
11
  import subprocess
11
12
  import sys
12
13
  import tempfile
13
14
 
15
+ import paths
14
16
  import toast_notice
17
+ import venv_launch
15
18
 
16
19
  TASK_NAME = os.environ.get("SMART_TOOL_TASK_NAME", "SmartTool-Tray")
17
20
  # The tray runs under pythonw (no console): schtasks without this flag flashed a console each time its menu was drawn.
@@ -52,8 +55,8 @@ def _current_user_id():
52
55
 
53
56
  def _task_xml():
54
57
  user_id = _xml_escape(_current_user_id())
55
- pythonw = _xml_escape(_pythonw_path())
56
- tray = _xml_escape(_tray_path())
58
+ wscript = _xml_escape(_wscript_path())
59
+ script = _xml_escape(_write_launch_script(_task_script_path()))
57
60
  workdir = _xml_escape(_tool_dir())
58
61
  return (
59
62
  '<?xml version="1.0" encoding="UTF-16"?>\r\n'
@@ -84,15 +87,11 @@ def _task_xml():
84
87
  ' <Enabled>true</Enabled>\r\n'
85
88
  ' <Hidden>false</Hidden>\r\n'
86
89
  ' <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>\r\n'
87
- ' <RestartOnFailure>\r\n'
88
- ' <Interval>PT1M</Interval>\r\n'
89
- ' <Count>999</Count>\r\n'
90
- ' </RestartOnFailure>\r\n'
91
90
  ' </Settings>\r\n'
92
91
  ' <Actions Context="Author">\r\n'
93
92
  ' <Exec>\r\n'
94
- f' <Command>{pythonw}</Command>\r\n'
95
- f' <Arguments>"{tray}"</Arguments>\r\n'
93
+ f' <Command>{wscript}</Command>\r\n'
94
+ f' <Arguments>//B //NoLogo "{script}"</Arguments>\r\n'
96
95
  f' <WorkingDirectory>{workdir}</WorkingDirectory>\r\n'
97
96
  ' </Exec>\r\n'
98
97
  ' </Actions>\r\n'
@@ -111,20 +110,24 @@ def _startup_script_path():
111
110
  return os.path.join(_startup_dir(), "SmartTool-Tray.vbs")
112
111
 
113
112
 
114
- def _vbs_quoted_run(pythonw, tray):
115
- # WshShell.Run monta a linha de comando com Chr(34) em vez de aspas literais —
116
- # evita ter que escapar aspas dentro de aspas tanto em Python quanto em VBScript.
117
- return f'Chr(34) & "{pythonw}" & Chr(34) & " " & Chr(34) & "{tray}" & Chr(34)'
113
+ def _task_script_path():
114
+ return os.path.join(paths.DATA_DIR, "tray-start.vbs")
115
+
116
+
117
+ def _wscript_path():
118
+ return os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32", "wscript.exe")
119
+
120
+
121
+ def _write_launch_script(path):
122
+ """Writes the VBScript that starts the tray hidden in one process and returns its path."""
123
+ os.makedirs(os.path.dirname(path), exist_ok=True)
124
+ with open(path, "w", encoding="utf-16") as f:
125
+ f.write(venv_launch.hidden_run_vbs(_pythonw_path(), _tray_path(), _tool_dir()))
126
+ return path
118
127
 
119
128
 
120
129
  def _install_startup_shortcut():
121
- os.makedirs(_startup_dir(), exist_ok=True)
122
- vbs = (
123
- 'Set shell = CreateObject("WScript.Shell")\r\n'
124
- f'shell.Run {_vbs_quoted_run(_pythonw_path(), _tray_path())}, 0, False\r\n'
125
- )
126
- with open(_startup_script_path(), "w", encoding="utf-8") as f:
127
- f.write(vbs)
130
+ _write_launch_script(_startup_script_path())
128
131
  return {"ok": True, "method": "startup_folder"}
129
132
 
130
133
 
@@ -148,7 +151,7 @@ def _task_installed():
148
151
 
149
152
 
150
153
  def install():
151
- """Tenta a Tarefa Agendada primeiro (cobre restart automático pelo SO); se
154
+ """Tenta a Tarefa Agendada primeiro; se
152
155
  `schtasks /Create` falhar por qualquer motivo (ex.: bloqueado por politica de
153
156
  grupo corporativa, `schtasks` fora do PATH, timeout), cai para o atalho de
154
157
  Startup em vez de propagar o erro."""
@@ -192,6 +195,10 @@ def remove():
192
195
  pass
193
196
  if _remove_startup_shortcut():
194
197
  removed.append("startup_folder")
198
+ try:
199
+ os.remove(_task_script_path())
200
+ except FileNotFoundError:
201
+ pass
195
202
  if sys.platform == "win32" and toast_notice.unregister():
196
203
  removed.append("toast_registry")
197
204
  return {"ok": True, "removed": removed}