@allansantos-dev/smart-tool 0.9.50 → 0.9.52
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +32 -0
- package/README.md +13 -9
- package/bin/smart-tool.mjs +3 -2
- package/block_patterns.py +30 -11
- package/hook_decision.py +17 -1
- package/install.py +16 -4
- package/locales/pt-BR.json +33 -6
- package/package.json +1 -1
- package/router.py +8 -3
- package/setup_audit.py +136 -34
- package/setup_ui.py +4 -2
- package/smart_tool_daemon.py +70 -10
- package/tray.py +4 -5
- package/update_check.py +8 -3
- package/update_splash.py +36 -10
- package/version.py +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,37 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.9.52 - beta
|
|
4
|
+
|
|
5
|
+
- Actionable setup audit. Every finding of `setup_audit.py` carries an `action`: the file and edit, the command to run
|
|
6
|
+
or the sign-in step per harness. `mode=last` prints it as `- Fix: ...`, and a stored report without fixes fails loud
|
|
7
|
+
naming the `mode=run` that replaces it; the daemon also runs a new audit 120 s after it starts. The SessionStart hook
|
|
8
|
+
puts the project's counts, the top three errors and warnings with their fixes and the call that lists them all in the
|
|
9
|
+
agent's `additionalContext`, with the rule that the agent applies a fix only when the user agrees. The user gets no new
|
|
10
|
+
notice (`tests/test_setup_audit.py`, `tests/test_session_audit.py`).
|
|
11
|
+
- Redirect proposals decided by an agent: `project_manage action=redirect_proposals` lists the pending proposals ranked
|
|
12
|
+
by how many commands in the history each one would have matched; `action=redirect_decide` accepts, rejects, removes or
|
|
13
|
+
turns them into `instruct`, a new mode where the call runs and the agent gets a tip naming the `smart_search` call
|
|
14
|
+
that answers it (never the model-written reason; a background shell call gets no tip, as a background call is never
|
|
15
|
+
redirected). Decisions are marked as made by an agent in the setup screen, which
|
|
16
|
+
now also offers "Tip only" (`tests/test_block_patterns.py`, `tests/test_transparent_redirect.py`).
|
|
17
|
+
- An update now confirms the version it installed. `install.py` checks that the daemon it started reports the version
|
|
18
|
+
being installed (`/health` now carries `version`) and restores the previous version otherwise; `--expect-version`
|
|
19
|
+
refuses a package that is not the requested version before touching anything. The update screen passes the version it
|
|
20
|
+
announced and reads the installed `version.py` afterwards: it reports success only when that is the announced version,
|
|
21
|
+
and a failure names the version really installed. The tray's Update entry asks npm again on each click, so a release
|
|
22
|
+
that came out after the last check is the one installed (`tests/test_update_splash.py`, `tests/test_install_version.py`).
|
|
23
|
+
- The README and the site show the install command pinned to the current version, and `release/pages.py` refuses to
|
|
24
|
+
publish when either one does not; the installer's usage text and the README no longer say to update with `@latest`
|
|
25
|
+
(`tests/test_pages.py`).
|
|
26
|
+
|
|
27
|
+
## 0.9.51 - beta
|
|
28
|
+
|
|
29
|
+
- The automatic update installs the version the tray announced (`npx --yes @allansantos-dev/smart-tool@<version>
|
|
30
|
+
install`) instead of `@latest`. With `@latest`, npx could reuse an older package left in its cache and install that,
|
|
31
|
+
moving the install back a version. The update notices given to the user and to agent sessions ("To update now,
|
|
32
|
+
run: ...") name the same pinned command, and the update screen refuses to start without the version to install
|
|
33
|
+
instead of falling back to `@latest` (`tests/test_update_splash.py`, `tests/test_update_check.py`).
|
|
34
|
+
|
|
3
35
|
## 0.9.50 - beta
|
|
4
36
|
|
|
5
37
|
- Windows refused the setup-audit toast of a project whose path made the toast tag longer than 64 characters
|
package/README.md
CHANGED
|
@@ -17,7 +17,7 @@ registered as the `playwright` server where this machine lets a browser be drive
|
|
|
17
17
|
An optional hook routes the agent's native Grep/Glob/Read/Bash/WebSearch/WebFetch calls to these tools when they
|
|
18
18
|
are cheaper, or just tells the agent what Smart Tool would do.
|
|
19
19
|
|
|
20
|
-
**Status:** 0.9.
|
|
20
|
+
**Status:** 0.9.52 beta. Windows only. What changed in each version: [CHANGELOG.md](CHANGELOG.md).
|
|
21
21
|
|
|
22
22
|
## How it works
|
|
23
23
|
|
|
@@ -83,11 +83,12 @@ gateway such as Ollama, nothing about your code leaves the machine.
|
|
|
83
83
|
## Install
|
|
84
84
|
|
|
85
85
|
```powershell
|
|
86
|
-
npx @allansantos-dev/smart-tool@
|
|
86
|
+
npx @allansantos-dev/smart-tool@0.9.52 install
|
|
87
87
|
```
|
|
88
88
|
|
|
89
89
|
Updates install themselves, on by default: the tray checks npm when it starts (at logon) and every 24 h, and when there
|
|
90
|
-
is a newer version it runs this
|
|
90
|
+
is a newer version it runs this command with that version in place of the one above, behind its own small update
|
|
91
|
+
window, with no console window (once per
|
|
91
92
|
version; a failed version is tried again after 24 h, with the previous version kept). The window has no buttons: it shows
|
|
92
93
|
the version change, the current step and the result, and closes by itself; the command's output is kept in
|
|
93
94
|
`~/.smart-tool/data/update.log`. You are told each time: a Windows notification from the tray (newer version,
|
|
@@ -97,7 +98,7 @@ X" (or "Check for updates") on demand and an "Update automatically" switch; `SMA
|
|
|
97
98
|
automatic updates off, and the newer-version notice then carries the command to run. The interface (tray, notifications,
|
|
98
99
|
settings and projects pages, update window) is in Brazilian Portuguese or English: it follows the Windows display
|
|
99
100
|
language until you pick one with the globe button (PT/EN) at the top of the pages or the tray's "Idioma / Language"
|
|
100
|
-
submenu. Running the command by hand also updates; `~/.smart-tool` is kept. It downloads [uv](https://docs.astral.sh/uv/) (checksum
|
|
101
|
+
submenu. Running the command by hand with a newer version also updates; `~/.smart-tool` is kept. It downloads [uv](https://docs.astral.sh/uv/) (checksum
|
|
101
102
|
verified) and a private Python 3.12 into `~/.smart-tool/runtime`, with nothing added to `PATH` and, in the registry, only two per-user (HKCU) keys that make the notification buttons work, then
|
|
102
103
|
copies Smart Tool to `%LOCALAPPDATA%\Programs\SmartTool` with its own virtual environment,
|
|
103
104
|
installs the web runtime, registers a per-user Scheduled Task that starts the tray at logon and starts the daemon on
|
|
@@ -192,7 +193,9 @@ Redirects) and Maintenance (Setup audit, Startup).
|
|
|
192
193
|
listings, Glob and commands that change files run. The setup screen counts the redirects and what each session
|
|
193
194
|
did next. With **Block patterns proposed by a
|
|
194
195
|
model** on (default), the scope model reviews, in the background, bulk reads the rule could not measure and
|
|
195
|
-
proposes regex patterns, each checked against the logged calls; a pattern
|
|
196
|
+
proposes regex patterns, each checked against the logged calls; a pattern acts only after it is accepted, by you
|
|
197
|
+
on the setup screen or by an agent through `project_manage action=redirect_decide`. An accepted pattern either
|
|
198
|
+
redirects or, as **Tip only**, lets the call run and gives the agent the `smart_search` call that answers it.
|
|
196
199
|
- **Advise only**: the native tool runs; the agent receives the same advice next to the result and decides.
|
|
197
200
|
- **Off**: no routing.
|
|
198
201
|
|
|
@@ -253,12 +256,13 @@ Redirects) and Maintenance (Setup audit, Startup).
|
|
|
253
256
|
|
|
254
257
|
The agent hears about it without asking for it. `setup_audit` with `mode=last` returns the stored report for the
|
|
255
258
|
folder (or the nearest audited parent) without auditing again, and fails with what to do when none is stored. On
|
|
256
|
-
its first `smart_search` of a session, and once per folder, the agent also gets
|
|
257
|
-
|
|
258
|
-
|
|
259
|
+
its first `smart_search` of a session, and once per folder, the agent also gets a short notice when the stored
|
|
260
|
+
report holds errors or warnings: the counts, the top three findings with their fixes and the call that lists them
|
|
261
|
+
all, with the rule that a fix is applied only when you agree; a clean report adds nothing. Optionally, **Report at session
|
|
262
|
+
start** on the Setup audit page (Claude Code or Codex) moves that notice to the start of every new session: it
|
|
259
263
|
previews the exact SessionStart entry, adds it to `~/.claude/settings.json` or `~/.codex/hooks.json` only after you
|
|
260
264
|
confirm (backup first), and **Turn off** removes only that entry. Codex runs a new hook only after you approve it in
|
|
261
|
-
`/hooks`; until then the page shows "waiting for your approval" and the search keeps repeating the
|
|
265
|
+
`/hooks`; until then the page shows "waiting for your approval" and the search keeps repeating the notice. It is off by default; while it is on, the search no longer repeats the notice. The
|
|
262
266
|
hook script (`hooks/session_audit.py`) only reads the stored report from the running service and prints nothing
|
|
263
267
|
when the service is down.
|
|
264
268
|
4. **Local models** (optional): if the mcp-memory embedding sidecar is installed on the machine, its local embedder
|
package/bin/smart-tool.mjs
CHANGED
|
@@ -16,9 +16,10 @@ const UV_DIR = join(RUNTIME_DIR, `uv-${UV_VERSION}`);
|
|
|
16
16
|
const UV_EXE = join(UV_DIR, "uv.exe");
|
|
17
17
|
const PYTHON_VERSION = "3.12";
|
|
18
18
|
const PYTHON_DIR = join(RUNTIME_DIR, "python");
|
|
19
|
-
const USAGE = `Usage: npx @allansantos-dev/smart-tool install [--target DIR] [--no-start] [--skip-deps]
|
|
19
|
+
const USAGE = `Usage: npx @allansantos-dev/smart-tool@<version> install [--target DIR] [--no-start] [--skip-deps]
|
|
20
20
|
|
|
21
|
-
Installs or updates Smart Tool for this Windows user.
|
|
21
|
+
Installs or updates Smart Tool for this Windows user. To update, run it again with the version to install in place of
|
|
22
|
+
<version>: a pinned version keeps npx from reusing an older package from its cache.`;
|
|
22
23
|
|
|
23
24
|
function fail(message) {
|
|
24
25
|
throw new Failure(message);
|
package/block_patterns.py
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
"""Block patterns learned during operation: when the deterministic redirect rule lets a search or read run, the router
|
|
2
2
|
model (review_model) reviews the call in the background (the agent never waits for it) and may propose a regex for calls that should
|
|
3
3
|
go to Smart Tool. A proposal is checked (compiles, matches the call, how many logged calls it would have blocked; one
|
|
4
|
-
that blocks more than BROAD_SHARE of them is discarded) and waits for
|
|
5
|
-
|
|
4
|
+
that blocks more than BROAD_SHARE of them is discarded) and waits for a decision, in the setup screen or by an agent
|
|
5
|
+
through project_manage (redirect_proposals, redirect_decide). An accepted pattern acts from then on, deterministically,
|
|
6
|
+
after the rule's own exceptions (single files, commands changing files), in its mode: redirect sends the call to
|
|
7
|
+
Smart Tool, instruct lets it run and tells the agent which smart_search call answers it.
|
|
6
8
|
"""
|
|
7
9
|
import concurrent.futures
|
|
8
10
|
import hashlib
|
|
@@ -28,6 +30,8 @@ PATTERN_MAX_CHARS = 300
|
|
|
28
30
|
CALL_MAX_CHARS = 1500
|
|
29
31
|
# Only calls whose reach the rule cannot measure are reviewed: bulk reads (globs, xargs, -exec, loops, scripts walking
|
|
30
32
|
# folders) and paths it could not resolve. Reading a few listed files is allowed on purpose and never reviewed.
|
|
33
|
+
MODES = ("redirect", "instruct")
|
|
34
|
+
DECISIONS = {"accept": "redirect", "instruct": "instruct", "reject": None, "remove": None}
|
|
31
35
|
REVIEWED_REASONS = ("The searched path uses a variable the hook cannot resolve.", "No content search over a folder.")
|
|
32
36
|
_BULK_READ = re.compile(r"\*|\bxargs\b|-exec\b|\bfor\s+\w+\s+in\b|os\.walk|rglob|glob\(|readdirSync|readdir\(|"
|
|
33
37
|
r"walkSync|-Recurse\b|Get-ChildItem", re.IGNORECASE)
|
|
@@ -125,7 +129,8 @@ def _empty():
|
|
|
125
129
|
|
|
126
130
|
|
|
127
131
|
def load():
|
|
128
|
-
"""The stored patterns: {"accepted": [...], "proposals": [...], "rejected": [...]}
|
|
132
|
+
"""The stored patterns: {"accepted": [...], "proposals": [...], "rejected": [...]}; every accepted pattern has a
|
|
133
|
+
mode in MODES."""
|
|
129
134
|
try:
|
|
130
135
|
with open(STORE_PATH, encoding="utf-8") as stream:
|
|
131
136
|
data = json.load(stream)
|
|
@@ -133,9 +138,21 @@ def load():
|
|
|
133
138
|
return _empty()
|
|
134
139
|
if not isinstance(data, dict) or any(not isinstance(data.get(k), list) for k in _empty()):
|
|
135
140
|
raise ValueError(f"{STORE_PATH} is not a block patterns file: fix or delete it.")
|
|
141
|
+
unknown = [e.get("id") for e in data["accepted"] if e.get("mode") not in MODES]
|
|
142
|
+
if unknown:
|
|
143
|
+
raise ValueError(f"{STORE_PATH}: accepted pattern(s) {', '.join(map(str, unknown))} have no mode "
|
|
144
|
+
f"({' or '.join(MODES)}): remove and accept them again in the setup screen.")
|
|
136
145
|
return data
|
|
137
146
|
|
|
138
147
|
|
|
148
|
+
def pending(limit):
|
|
149
|
+
"""(count, proposals) waiting for a decision: the limit with the most matches among the logged calls first, then
|
|
150
|
+
the newest."""
|
|
151
|
+
proposals = load()["proposals"]
|
|
152
|
+
ranked = sorted(proposals, key=lambda e: (-(e.get("history_matches") or 0), -(e.get("proposed_at") or 0)))
|
|
153
|
+
return len(proposals), ranked[:limit]
|
|
154
|
+
|
|
155
|
+
|
|
139
156
|
def _save(data):
|
|
140
157
|
os.makedirs(os.path.dirname(STORE_PATH), exist_ok=True)
|
|
141
158
|
atomic_io.write_secret_text(STORE_PATH, json.dumps(data, indent=1, ensure_ascii=False))
|
|
@@ -309,11 +326,12 @@ def review_later(tool_name, tool_input, rule_reason, metrics_path, redact, log):
|
|
|
309
326
|
return True
|
|
310
327
|
|
|
311
328
|
|
|
312
|
-
def decide_proposals(entry_ids, action):
|
|
313
|
-
"""accept moves proposals to accepted; reject moves them to rejected;
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
329
|
+
def decide_proposals(entry_ids, action, decided_by="user"):
|
|
330
|
+
"""accept moves proposals to accepted in mode redirect, instruct in mode instruct; reject moves them to rejected;
|
|
331
|
+
remove deletes accepted patterns. decided_by (user, or agent through project_manage) is stored with the decision.
|
|
332
|
+
All ids are decided in one write, or none when any id is unknown (ValueError naming it)."""
|
|
333
|
+
if action not in DECISIONS:
|
|
334
|
+
raise ValueError(f"Invalid action: use {', '.join(DECISIONS)}.")
|
|
317
335
|
wanted = list(dict.fromkeys(entry_ids))
|
|
318
336
|
if not wanted:
|
|
319
337
|
raise ValueError("No pattern selected.")
|
|
@@ -327,9 +345,10 @@ def decide_proposals(entry_ids, action):
|
|
|
327
345
|
data[source] = [e for e in data[source] if e["id"] not in found]
|
|
328
346
|
now = time.time()
|
|
329
347
|
for entry_id in wanted:
|
|
330
|
-
if action
|
|
331
|
-
data["accepted"].append({**found[entry_id], "accepted_at": now
|
|
348
|
+
if DECISIONS[action]:
|
|
349
|
+
data["accepted"].append({**found[entry_id], "mode": DECISIONS[action], "accepted_at": now,
|
|
350
|
+
"accepted_by": decided_by})
|
|
332
351
|
elif action == "reject":
|
|
333
|
-
data["rejected"].append({**found[entry_id], "rejected_by":
|
|
352
|
+
data["rejected"].append({**found[entry_id], "rejected_by": decided_by})
|
|
334
353
|
_save(data)
|
|
335
354
|
return data
|
package/hook_decision.py
CHANGED
|
@@ -163,6 +163,16 @@ def web_message(client, tool_name, url, why):
|
|
|
163
163
|
f"{_load_hint(client, tool)} Do not fetch it through {fetchers}: that bypasses the rule.")
|
|
164
164
|
|
|
165
165
|
|
|
166
|
+
def instruct_message(client, tool_name, target, reason, cwd):
|
|
167
|
+
"""Tip for a call matching an accepted pattern in mode instruct: the call runs; the text names the smart_search
|
|
168
|
+
call that answers searches like it, with project_root from the folder the call reads."""
|
|
169
|
+
root = _search_root(target, cwd).replace("\\", "/")
|
|
170
|
+
return (f"This {tool_name} call {clean_reason(reason)}. Searches like it are answered by "
|
|
171
|
+
f'{_tool_name(client, "smart_search")}: project_root="{root}", query_identifiers = what you are looking '
|
|
172
|
+
f"for in identifier terms (plus query_comments when the project has two languages)."
|
|
173
|
+
f'{_load_hint(client, "smart_search")}')
|
|
174
|
+
|
|
175
|
+
|
|
166
176
|
def advise(reason):
|
|
167
177
|
"""Same routing advice without blocking: the agent sees it next to the tool result and decides next time."""
|
|
168
178
|
return {"hookSpecificOutput": {"hookEventName": "PreToolUse",
|
|
@@ -410,7 +420,13 @@ def _route(payload, client, web_route, cfg):
|
|
|
410
420
|
except Exception:
|
|
411
421
|
pass
|
|
412
422
|
return {"systemMessage": f"Smart Tool unavailable, routing skipped: {type(exc).__name__}"}
|
|
413
|
-
if
|
|
423
|
+
if tool_name in tool_redirect.NO_OP and tool_input.get("run_in_background"):
|
|
424
|
+
return {}
|
|
425
|
+
if decision == "instruct":
|
|
426
|
+
if not agent_has_smart_tool(payload.get("agent_type") if payload.get("agent_id") else None, cwd):
|
|
427
|
+
return {}
|
|
428
|
+
return advise(instruct_message(client, tool_name, target, reason, cwd))
|
|
429
|
+
if decision != "redirect":
|
|
414
430
|
return {}
|
|
415
431
|
terms = redirect_rule.search_terms(tool_name, tool_input)
|
|
416
432
|
arguments = {"project_root": _search_root(target, cwd), "query_identifiers": terms,
|
package/install.py
CHANGED
|
@@ -13,6 +13,7 @@ import venv
|
|
|
13
13
|
from pathlib import Path
|
|
14
14
|
|
|
15
15
|
import paths
|
|
16
|
+
import version
|
|
16
17
|
|
|
17
18
|
SOURCE = Path(__file__).resolve().parent
|
|
18
19
|
DEFAULT_TARGET = Path(os.environ.get("LOCALAPPDATA", str(Path.home() / "AppData" / "Local"))) / "Programs" / "SmartTool"
|
|
@@ -291,17 +292,23 @@ def start(target, python, pythonw):
|
|
|
291
292
|
|
|
292
293
|
|
|
293
294
|
def verify(target, python):
|
|
295
|
+
"""Checks the started daemon: it answers MCP, serves REQUIRED_TOOLS, runs the version being installed and is the
|
|
296
|
+
process of this installation. Any mismatch raises, so _update restores the previous version."""
|
|
294
297
|
script = ("import json,urllib.request,daemon_launcher; url=daemon_launcher.ensure_daemon_running(wait_seconds=30); "
|
|
298
|
+
"opener=urllib.request.build_opener(urllib.request.ProxyHandler({})); "
|
|
299
|
+
"running=json.load(opener.open(url+'/health',timeout=10)).get('version'); "
|
|
295
300
|
"body=json.dumps({'jsonrpc':'2.0','id':1,'method':'tools/list','params':{}}).encode(); "
|
|
296
301
|
"req=urllib.request.Request(url+'/mcp',data=body,method='POST',headers={'Content-Type':'application/json'}); "
|
|
297
|
-
"
|
|
298
|
-
"print(json.dumps(sorted(r['name'] for r in json.load(opener.open(req,timeout=10))['result']['tools'])))")
|
|
302
|
+
"print(json.dumps({'version':running,'tools':sorted(r['name'] for r in json.load(opener.open(req,timeout=10))['result']['tools'])}))")
|
|
299
303
|
result = subprocess.run([str(python), "-c", script], cwd=target, capture_output=True, text=True, timeout=60)
|
|
300
304
|
if result.returncode:
|
|
301
305
|
raise RuntimeError("Daemon did not respond: " + ((result.stderr or result.stdout).strip().splitlines() or ["no output"])[-1])
|
|
302
|
-
|
|
306
|
+
served = json.loads(result.stdout.strip().splitlines()[-1])
|
|
307
|
+
missing = REQUIRED_TOOLS - set(served["tools"])
|
|
303
308
|
if missing:
|
|
304
309
|
raise RuntimeError("Missing MCP tools: " + ", ".join(sorted(missing)))
|
|
310
|
+
if served["version"] != version.VERSION:
|
|
311
|
+
raise RuntimeError(f"The daemon runs version {served['version']}, not the {version.VERSION} being installed")
|
|
305
312
|
pid = json.loads(REGISTRY.read_text(encoding="utf-8"))["pid"]
|
|
306
313
|
command = powershell(f"(Get-CimInstance Win32_Process -Filter 'ProcessId = {int(pid)}').CommandLine").stdout
|
|
307
314
|
if str(target / "smart_tool_daemon.py").lower() not in command.lower():
|
|
@@ -340,14 +347,19 @@ def main():
|
|
|
340
347
|
parser.add_argument("--no-start", action="store_true", help="do not restart or check the daemon")
|
|
341
348
|
parser.add_argument("--skip-tests", action="store_true",
|
|
342
349
|
help="install without running tests/run.py (npm package, whose tests ran in CI; emergency only otherwise)")
|
|
350
|
+
parser.add_argument("--expect-version",
|
|
351
|
+
help="refuse to install unless this package is that version (the update screen passes the one it announced)")
|
|
343
352
|
args = parser.parse_args()
|
|
353
|
+
if args.expect_version and args.expect_version != version.VERSION:
|
|
354
|
+
raise SystemExit(f"This package is Smart Tool {version.VERSION}, not the {args.expect_version} requested; "
|
|
355
|
+
"nothing was changed.")
|
|
344
356
|
target = args.target.resolve()
|
|
345
357
|
if target == SOURCE:
|
|
346
358
|
raise SystemExit("The target cannot be the source folder itself.")
|
|
347
359
|
if args.skip_tests:
|
|
348
360
|
print("Tests skipped by --skip-tests.")
|
|
349
361
|
elif not (SOURCE / "tests" / "run.py").is_file():
|
|
350
|
-
raise SystemExit(f"No test suite in {SOURCE}; a packaged install runs with --skip-tests (npx @allansantos-dev/smart-tool install).")
|
|
362
|
+
raise SystemExit(f"No test suite in {SOURCE}; a packaged install runs with --skip-tests (npx @allansantos-dev/smart-tool@{version.VERSION} install).")
|
|
351
363
|
else:
|
|
352
364
|
interpreter = python_paths(target)[0] if python_paths(target)[0].is_file() else Path(sys.executable)
|
|
353
365
|
tests = subprocess.run([str(interpreter), str(SOURCE / "tests" / "run.py")], capture_output=True, text=True,
|
package/locales/pt-BR.json
CHANGED
|
@@ -324,7 +324,6 @@
|
|
|
324
324
|
"Previous": "Anterior",
|
|
325
325
|
"Next": "Próxima",
|
|
326
326
|
"(filtered from": "(filtrado de",
|
|
327
|
-
"Patterns you accepted, blocking now (": "Padrões que você aceitou, bloqueando agora (",
|
|
328
327
|
"Remove": "Remover",
|
|
329
328
|
"rejected proposal": "proposta rejeitada",
|
|
330
329
|
"not offered again.": "não serão oferecidas de novo.",
|
|
@@ -675,12 +674,10 @@
|
|
|
675
674
|
"they run concurrently and any deny wins": "rodam ao mesmo tempo e qualquer deny prevalece",
|
|
676
675
|
"skill trigger overlap and contradictions between instructions need a model (not run)": "sobreposição de gatilhos de skills e contradições entre instruções exigem um modelo (não executado)",
|
|
677
676
|
"the order between two parallel rewrites is undocumented and cannot be checked": "a ordem entre duas reescritas paralelas não é documentada e não pode ser verificada",
|
|
678
|
-
"in the agent configuration. Details without rerunning: project_manage action=setup_audit mode=last.": "na configuração dos agentes. Detalhes sem executar de novo: project_manage action=setup_audit mode=last.",
|
|
679
677
|
"{0} errors, {1} warnings, {2} notes. Snapshot {3} ({4} files read).": "{0} erros, {1} avisos, {2} notas. Instantâneo {3} ({4} arquivos lidos).",
|
|
680
678
|
"subagents without Smart Tool": "subagentes sem o Smart Tool",
|
|
681
679
|
"{0} subagent(s) list tools but none of mcp__{1}__*: {2}. Add mcp__{3}__smart_search and mcp__{4}__smart_search_result to their `tools`, or drop the `tools` line to inherit every tool.": "{0} subagente(s) listam ferramentas, mas nenhuma de mcp__{1}__*: {2}. Adicione mcp__{3}__smart_search e mcp__{4}__smart_search_result ao `tools` deles, ou remova a linha `tools` para herdar todas as ferramentas.",
|
|
682
680
|
"MCP servers and HTTP hook endpoints were not contacted (probe off)": "Os servidores MCP e os endpoints de hook HTTP não foram contatados (sondagem desligada)",
|
|
683
|
-
"Setup audit of {0} ({1} min ago): {2} errors, {3} warnings": "Auditoria da configuração de {0} (há {1} min): {2} erros, {3} avisos",
|
|
684
681
|
"{0} is not a setup audit index: fix or delete it.": "{0} não é um índice de auditoria da configuração: corrija ou apague.",
|
|
685
682
|
"Setup audit: 1 new problem in the agent configuration": "Auditoria da configuração: 1 problema novo na configuração dos agentes",
|
|
686
683
|
"Setup audit: {count} new problems in the agent configuration": "Auditoria da configuração: {count} problemas novos na configuração dos agentes",
|
|
@@ -811,7 +808,6 @@
|
|
|
811
808
|
"Accept selected ({0})": "Aceitar selecionados ({0})",
|
|
812
809
|
"Reject selected ({0})": "Recusar selecionados ({0})",
|
|
813
810
|
"(filtered from {0})": "(filtrados de {0})",
|
|
814
|
-
"Patterns you accepted, blocking now ({0})": "Padrões que você aceitou, bloqueando agora ({0})",
|
|
815
811
|
"{0} not offered again.": "{0} não será oferecida de novo.",
|
|
816
812
|
"{0} API key": "Chave de API do {0}",
|
|
817
813
|
"Create a key in your {0} account": "Crie uma chave na sua conta do {0}",
|
|
@@ -883,7 +879,14 @@
|
|
|
883
879
|
"{0} {1} (~{2} tokens)": "{0} {1} (~{2} tokens)",
|
|
884
880
|
"Checking the browsers…": "Verificando os navegadores…",
|
|
885
881
|
"View log": "Ver o log",
|
|
886
|
-
"What changed": "O que mudou"
|
|
882
|
+
"What changed": "O que mudou",
|
|
883
|
+
"Tip only, does not block": "Só dica, não bloqueia",
|
|
884
|
+
"Blocks": "Bloqueia",
|
|
885
|
+
"Decided by an agent": "Decidido por um agente",
|
|
886
|
+
"Tip only": "Só dica",
|
|
887
|
+
"Patterns you accepted (": "Padrões que você aceitou (",
|
|
888
|
+
"Patterns you accepted ({0})": "Padrões que você aceitou ({0})",
|
|
889
|
+
"{0} holds a setup audit of {1} from an older Smart Tool, whose findings have no fix: run project_manage action=setup_audit mode=run to replace it.": "{0} guarda uma auditoria da configuração de {1} feita por um Smart Tool mais antigo, cujos achados não trazem a correção: rode project_manage action=setup_audit mode=run para substituí-la."
|
|
887
890
|
},
|
|
888
891
|
"ignore": [
|
|
889
892
|
"saved msg",
|
|
@@ -920,6 +923,30 @@
|
|
|
920
923
|
"no clientInfo",
|
|
921
924
|
"{0} MiB",
|
|
922
925
|
"{0} KiB",
|
|
923
|
-
"- **{0}** [{1}] {2}: {3} ([source]({4}))"
|
|
926
|
+
"- **{0}** [{1}] {2}: {3} ([source]({4}))",
|
|
927
|
+
"That file belongs to the {0} plugin: an update overwrites the edit, so report it there too.",
|
|
928
|
+
"To bring {0} back, {1}; if it is no longer used, remove it from {2}.",
|
|
929
|
+
"check that {0} answers",
|
|
930
|
+
"run its command by hand to see the error: `{0}`",
|
|
931
|
+
"In each of the {0} files listed as evidence, add mcp__{1}__smart_search and mcp__{2}__smart_search_result to the `tools:` line of the frontmatter, or delete that line so the subagent inherits every tool.",
|
|
932
|
+
"remove the skill folders you do not use",
|
|
933
|
+
"Sign in: run /mcp in Claude Code and pick {0}.",
|
|
934
|
+
"Sign in: run `codex mcp login {0}`.",
|
|
935
|
+
"in the Claude Code and Codex configuration. Top items, each with its fix:",
|
|
936
|
+
"Read these hooks in {0}: when two of them rewrite or deny the same {1} call, narrow one matcher so they stop sharing it; when each does something different (one logs, one rewrites), nothing needs to change.",
|
|
937
|
+
"Bring names and descriptions under ~{0} characters: {1}, or shorten the longest descriptions ({2}).",
|
|
938
|
+
"Add a line `@AGENTS.md` to {0} (create the file with that line if it does not exist).",
|
|
939
|
+
"Shorten the project AGENTS.md files to under {0} bytes in total, or set project_doc_max_bytes = {1} (or more) in {2}.",
|
|
940
|
+
"Smart Tool setup audit of {0} ({1} min ago): {2} errors, {3} warnings",
|
|
941
|
+
"Rename the `name` in the frontmatter of all but one of these, or remove the copies you do not use: {0}.",
|
|
942
|
+
"Reinstall or update the {0} plugin, which is missing {1}.",
|
|
943
|
+
"Restore {0}, or delete this {1} hook from {2}.",
|
|
944
|
+
"Shorten the `description` in {0} from {1} to at most {2} characters, keeping when to use the skill at the start.",
|
|
945
|
+
"In {0}, point `@{1}` to a file that exists, or delete that line.",
|
|
946
|
+
"Keep one path to {0}: drop it from the servers {1} proxies (in {2}'s own configuration), or remove the direct '{3}' entry from {4}.",
|
|
947
|
+
"In {0}, remove `|| true`, `exit 0` and `2>/dev/null` from the command of this {1} hook so its failures show.",
|
|
948
|
+
"Register MCP server '{0}' for this agent, or delete this {1} hook from {2}.",
|
|
949
|
+
", or list the duplicated tools in disabled_tools of one of them.",
|
|
950
|
+
"Start the service that listens at {0}, or delete this {1} hook from {2}."
|
|
924
951
|
]
|
|
925
952
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@allansantos-dev/smart-tool",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.52",
|
|
4
4
|
"description": "Local MCP server that gives coding agents (Claude Code, Codex) cheaper, sharper tools than their built-in search. Windows.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "Allan Santos",
|
package/router.py
CHANGED
|
@@ -154,9 +154,10 @@ def _log_error(message):
|
|
|
154
154
|
|
|
155
155
|
|
|
156
156
|
def decide(tool_name, tool_input, cwd=None):
|
|
157
|
-
"""(decision, reason, target) for one hook call: decision is redirect
|
|
158
|
-
|
|
159
|
-
the
|
|
157
|
+
"""(decision, reason, target) for one hook call: decision is redirect, instruct (an accepted pattern in mode
|
|
158
|
+
instruct: the call runs and the agent is told the smart_search call that answers it) or allow; target is the folder
|
|
159
|
+
the redirected search would read (the session folder for an accepted pattern, None when allowed). An allowed search
|
|
160
|
+
is queued for the router model's review, which never delays the call."""
|
|
160
161
|
safe_input = tool_input if isinstance(tool_input, dict) else {}
|
|
161
162
|
mechanical = _mechanical_decision(tool_name, safe_input)
|
|
162
163
|
if mechanical:
|
|
@@ -167,6 +168,10 @@ def decide(tool_name, tool_input, cwd=None):
|
|
|
167
168
|
pattern_tool = "Bash" if tool_name in SHELL_TOOLS else tool_name
|
|
168
169
|
learned = (block_patterns.matching(pattern_tool, safe_input)
|
|
169
170
|
if decision == "allow" and block_patterns.reviewable(pattern_tool, safe_input, reason) else None)
|
|
171
|
+
if learned and learned["mode"] == "instruct":
|
|
172
|
+
reason = f"matches accepted pattern {learned['id']} (a tip chosen in Smart Tool)"
|
|
173
|
+
_log_decision(tool_name, tool_input, "allow", reason, extra={"pattern": learned["id"], "mode": "instruct"})
|
|
174
|
+
return "instruct", reason, cwd
|
|
170
175
|
if learned:
|
|
171
176
|
reason = f"accepted block pattern {learned['id']} (approved by the user in Smart Tool's setup screen)"
|
|
172
177
|
_log_decision(tool_name, tool_input, "redirect", reason, extra={"pattern": learned["id"]})
|
package/setup_audit.py
CHANGED
|
@@ -43,6 +43,9 @@ PROBE_MAX_AGE_S = 6 * 3600
|
|
|
43
43
|
SKILL_DESCRIPTION_MAX = 1536
|
|
44
44
|
SKILL_BUDGET_CHARS = 8000
|
|
45
45
|
CODEX_PROJECT_DOC_MAX = 32 * 1024
|
|
46
|
+
NOTICE_ITEMS = 3
|
|
47
|
+
NOTICE_ACTION_MAX = 360
|
|
48
|
+
REVIEW_FIRST = ("hook_overlap", "skill_budget")
|
|
46
49
|
SMART_TOOL_SERVER = "smart-tool"
|
|
47
50
|
CLAUDE_TOOLS = ("Bash", "Read", "Grep", "Glob", "LS", "Edit", "MultiEdit", "Write", "NotebookEdit", "WebFetch",
|
|
48
51
|
"WebSearch", "Task")
|
|
@@ -120,8 +123,9 @@ class _Snapshot:
|
|
|
120
123
|
return None
|
|
121
124
|
|
|
122
125
|
|
|
123
|
-
def _hooks_from(data, source, root=None):
|
|
124
|
-
"""Hook entries of a settings/hooks.json object: one dict per hook with its event, matcher and
|
|
126
|
+
def _hooks_from(data, source, file, root=None):
|
|
127
|
+
"""Hook entries of a settings/hooks.json object: one dict per hook with its event, matcher, target and the file
|
|
128
|
+
that declares it (named in the fix of a finding)."""
|
|
125
129
|
found = []
|
|
126
130
|
for event, groups in ((data or {}).get("hooks") or {}).items():
|
|
127
131
|
for group in groups if isinstance(groups, list) else []:
|
|
@@ -130,7 +134,7 @@ def _hooks_from(data, source, root=None):
|
|
|
130
134
|
found.append({"event": event, "matcher": group.get("matcher") or "", "type": hook.get("type"),
|
|
131
135
|
"command": hook.get("command"), "url": hook.get("url"),
|
|
132
136
|
"server": hook.get("server"), "tool": hook.get("tool"), "source": source,
|
|
133
|
-
"root": root})
|
|
137
|
+
"file": file, "root": root})
|
|
134
138
|
return found
|
|
135
139
|
|
|
136
140
|
|
|
@@ -236,7 +240,7 @@ def collect_claude(project, snapshot):
|
|
|
236
240
|
if data is None:
|
|
237
241
|
continue
|
|
238
242
|
settings.append({"scope": scope, "path": path, "disable_all_hooks": bool(data.get("disableAllHooks"))})
|
|
239
|
-
hooks += _hooks_from(data, f"settings:{scope}")
|
|
243
|
+
hooks += _hooks_from(data, f"settings:{scope}", path)
|
|
240
244
|
enabled.update({k: v for k, v in (data.get("enabledPlugins") or {}).items()})
|
|
241
245
|
overrides.update(data.get("skillOverrides") or {})
|
|
242
246
|
_approvals(data, approval)
|
|
@@ -270,7 +274,8 @@ def collect_claude(project, snapshot):
|
|
|
270
274
|
continue
|
|
271
275
|
name = plugin_id.split("@")[0]
|
|
272
276
|
plugins.append({"id": plugin_id, "path": root})
|
|
273
|
-
|
|
277
|
+
hook_file = os.path.join(root, "hooks", "hooks.json")
|
|
278
|
+
hooks += _hooks_from(snapshot.json(hook_file), f"plugin:{name}", hook_file, root)
|
|
274
279
|
plugin_mcp = snapshot.json(os.path.join(root, ".mcp.json")) or {}
|
|
275
280
|
mcp += _mcp_entries(plugin_mcp.get("mcpServers", plugin_mcp), f"plugin:{name}",
|
|
276
281
|
os.path.join(root, ".mcp.json"), f"plugin:{name}:", {"CLAUDE_PLUGIN_ROOT": root})
|
|
@@ -327,7 +332,7 @@ def _collect_codex_plugins(config, snapshot):
|
|
|
327
332
|
continue
|
|
328
333
|
plugins.append({"id": plugin_id, "path": root})
|
|
329
334
|
hook_file = _codex_plugin_path(manifest, "hooks", root, (os.path.join("hooks", "hooks.json"),))
|
|
330
|
-
hooks += _hooks_from(snapshot.json(hook_file) if hook_file else None, f"plugin:{name}", root)
|
|
335
|
+
hooks += _hooks_from(snapshot.json(hook_file) if hook_file else None, f"plugin:{name}", hook_file, root)
|
|
331
336
|
mcp_file = _codex_plugin_path(manifest, "mcpServers", root, (".mcp.json", "mcp.json"))
|
|
332
337
|
plugin_mcp = snapshot.json(mcp_file) if mcp_file else None
|
|
333
338
|
if plugin_mcp is None and isinstance(manifest.get("mcpServers"), dict):
|
|
@@ -345,8 +350,9 @@ def collect_codex(project, snapshot):
|
|
|
345
350
|
"""Codex's effective set for project: config.toml (MCP, hooks), hooks.json, skills, AGENTS.md chain."""
|
|
346
351
|
config = snapshot.toml(os.path.join(codex_dir(), "config.toml")) or {}
|
|
347
352
|
mcp = _mcp_entries(config.get("mcp_servers"), "user", os.path.join(codex_dir(), "config.toml"))
|
|
348
|
-
hooks = _hooks_from(snapshot.json(os.path.join(codex_dir(), "hooks.json")), "hooks.json"
|
|
349
|
-
|
|
353
|
+
hooks = _hooks_from(snapshot.json(os.path.join(codex_dir(), "hooks.json")), "hooks.json",
|
|
354
|
+
os.path.join(codex_dir(), "hooks.json"))
|
|
355
|
+
hooks += _hooks_from(config, "config.toml", os.path.join(codex_dir(), "config.toml"))
|
|
350
356
|
skills = _skills(snapshot, os.path.join(codex_dir(), "skills"), "user", recursive=True)
|
|
351
357
|
skills += _skills(snapshot, _home(".agents", "skills"), "user-agents")
|
|
352
358
|
skills += _skills(snapshot, os.path.join(project, ".agents", "skills"), "project")
|
|
@@ -375,11 +381,25 @@ def collect_codex(project, snapshot):
|
|
|
375
381
|
return {"plugins": plugins, "hooks": hooks, "mcp": mcp, "skills": skills, "instructions": instructions}
|
|
376
382
|
|
|
377
383
|
|
|
378
|
-
def _finding(check, severity, harness, subject, detail, source, evidence=()):
|
|
379
|
-
"""One finding; its id is stable for the same check, harness and subject (used to diff runs).
|
|
384
|
+
def _finding(check, severity, harness, subject, detail, source, action, evidence=()):
|
|
385
|
+
"""One finding; its id is stable for the same check, harness and subject (used to diff runs). action is the step
|
|
386
|
+
that resolves it, written so an agent can carry it out: the file and line to change, the command, or the tool
|
|
387
|
+
call. Nothing applies it on its own."""
|
|
380
388
|
key = hashlib.sha1(f"{check}\0{harness}\0{subject}".encode()).hexdigest()[:10]
|
|
381
389
|
return {"id": key, "check": check, "severity": severity, "harness": harness, "subject": subject,
|
|
382
|
-
"detail": detail, "source": source, "evidence": list(evidence)}
|
|
390
|
+
"detail": detail, "source": source, "action": action, "evidence": list(evidence)}
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def _files(paths):
|
|
394
|
+
"""Distinct file paths joined for an action text, in first-seen order."""
|
|
395
|
+
return ", ".join(dict.fromkeys(p for p in paths if p))
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def _plugin_note(hook):
|
|
399
|
+
"""Warning appended to a fix that edits a plugin's own file, which the next plugin update overwrites."""
|
|
400
|
+
if not hook["source"].startswith("plugin:"):
|
|
401
|
+
return ""
|
|
402
|
+
return f" That file belongs to the {hook['source'][7:]} plugin: an update overwrites the edit, so report it there too."
|
|
383
403
|
|
|
384
404
|
|
|
385
405
|
def _matches(matcher, tool):
|
|
@@ -401,16 +421,20 @@ def check_hook_overlap(harness, hooks, tools):
|
|
|
401
421
|
matching = [h for h in hooks if h["event"] == event and _matches(h["matcher"], tool)]
|
|
402
422
|
if len(matching) > 1:
|
|
403
423
|
key = (event, tuple(sorted(f"{h['source']} {h['type']} {h['matcher'] or '*'}" for h in matching)))
|
|
404
|
-
groups.setdefault(key, []).append(tool)
|
|
424
|
+
groups.setdefault(key, ([], [h["file"] for h in matching]))[0].append(tool)
|
|
405
425
|
doc = DOCS["claude_hooks"] if harness == "claude" else DOCS["codex_hooks"]
|
|
406
426
|
rule = ("all run in parallel; deny > defer > ask > allow, and two updatedInput rewrites have no documented order"
|
|
407
427
|
if harness == "claude" else "they run concurrently and any deny wins")
|
|
408
|
-
for (event, members), names in groups.items():
|
|
428
|
+
for (event, members), (names, files) in groups.items():
|
|
409
429
|
sources = sorted({m.split(" ")[0] for m in members})
|
|
410
430
|
findings.append(_finding("hook_overlap", "warn", harness, f"{event} on {', '.join(names)}",
|
|
411
431
|
f"{len(members)} hooks decide on the same call ({rule}): " + "; ".join(members)
|
|
412
432
|
+ (". From different sources: check they do not rewrite the same input."
|
|
413
|
-
if len(sources) > 1 else "."), doc
|
|
433
|
+
if len(sources) > 1 else "."), doc,
|
|
434
|
+
f"Read these hooks in {_files(files)}: when two of them "
|
|
435
|
+
f"rewrite or deny the same {', '.join(names)} call, narrow one matcher so they stop "
|
|
436
|
+
"sharing it; when each does something different (one logs, one rewrites), nothing "
|
|
437
|
+
"needs to change."))
|
|
414
438
|
return findings
|
|
415
439
|
|
|
416
440
|
|
|
@@ -437,21 +461,31 @@ def check_hook_targets(harness, hooks, mcp_names, probe):
|
|
|
437
461
|
if not os.path.isabs(path):
|
|
438
462
|
path = os.path.join(hook["root"], path) if hook.get("root") else None
|
|
439
463
|
if path and not os.path.exists(path):
|
|
464
|
+
fix = (f"Reinstall or update the {hook['source'][7:]} plugin, which is missing {path}."
|
|
465
|
+
if hook["source"].startswith("plugin:") else
|
|
466
|
+
f"Restore {path}, or delete this {hook['event']} hook from {hook['file']}.")
|
|
440
467
|
findings.append(_finding("hook_missing_script", "error", harness, where,
|
|
441
|
-
f"The hook runs {token}, which does not exist.", doc,
|
|
468
|
+
f"The hook runs {token}, which does not exist.", doc, fix,
|
|
469
|
+
[hook["command"]]))
|
|
442
470
|
if _SILENCED_RE.search(hook["command"]):
|
|
443
471
|
findings.append(_finding("hook_silenced", "warn", harness, where,
|
|
444
472
|
"The hook discards its errors (|| true / 2>/dev/null): when it breaks, "
|
|
445
|
-
"nothing shows.", doc,
|
|
473
|
+
"nothing shows.", doc,
|
|
474
|
+
f"In {hook['file']}, remove `|| true`, `exit 0` and `2>/dev/null` from the "
|
|
475
|
+
f"command of this {hook['event']} hook so its failures show."
|
|
476
|
+
+ _plugin_note(hook), [hook["command"]]))
|
|
446
477
|
elif hook["type"] == "mcp_tool" and hook.get("server") and hook["server"] not in mcp_names:
|
|
447
478
|
findings.append(_finding("hook_unknown_server", "error", harness, where,
|
|
448
479
|
f"The hook calls MCP server '{hook['server']}', which is not configured here.",
|
|
449
|
-
doc
|
|
480
|
+
doc, f"Register MCP server '{hook['server']}' for this agent, or delete this "
|
|
481
|
+
f"{hook['event']} hook from {hook['file']}." + _plugin_note(hook)))
|
|
450
482
|
elif hook["type"] == "http" and hook.get("url") and probe:
|
|
451
483
|
problem = _reachable(hook["url"])
|
|
452
484
|
if problem:
|
|
453
485
|
findings.append(_finding("hook_endpoint_down", "error", harness, where,
|
|
454
|
-
f"The hook posts to {hook['url']}, which does not answer: {problem}", doc
|
|
486
|
+
f"The hook posts to {hook['url']}, which does not answer: {problem}", doc,
|
|
487
|
+
f"Start the service that listens at {hook['url']}, or delete this "
|
|
488
|
+
f"{hook['event']} hook from {hook['file']}." + _plugin_note(hook)))
|
|
455
489
|
return findings
|
|
456
490
|
|
|
457
491
|
|
|
@@ -481,7 +515,10 @@ def check_agents(claude):
|
|
|
481
515
|
f"{len(blind)} subagent(s) list tools but none of mcp__{SMART_TOOL_SERVER}__*: {names}. Add "
|
|
482
516
|
f"mcp__{SMART_TOOL_SERVER}__smart_search and mcp__{SMART_TOOL_SERVER}__smart_search_result to "
|
|
483
517
|
"their `tools`, or drop the `tools` line to inherit every tool.", DOCS["claude_subagents"],
|
|
484
|
-
|
|
518
|
+
f"In each of the {len(blind)} files listed as evidence, add mcp__{SMART_TOOL_SERVER}__smart_search "
|
|
519
|
+
f"and mcp__{SMART_TOOL_SERVER}__smart_search_result to the `tools:` line of the frontmatter, or "
|
|
520
|
+
"delete that line so the subagent inherits every tool.",
|
|
521
|
+
[a["path"] for a in blind])]
|
|
485
522
|
|
|
486
523
|
|
|
487
524
|
def check_skills(harness, skills):
|
|
@@ -494,19 +531,30 @@ def check_skills(harness, skills):
|
|
|
494
531
|
if len(same) > 1:
|
|
495
532
|
findings.append(_finding("skill_name_collision", "warn", harness, name,
|
|
496
533
|
f"{len(same)} skills share the name '{name}': only one is offered.", doc,
|
|
534
|
+
f"Rename the `name` in the frontmatter of all but one of these, or remove the "
|
|
535
|
+
f"copies you do not use: {_files(s['path'] for s in same)}.",
|
|
497
536
|
[s["path"] for s in same]))
|
|
498
537
|
if harness == "claude":
|
|
499
538
|
for skill in skills:
|
|
500
539
|
if len(skill["description"]) > SKILL_DESCRIPTION_MAX:
|
|
501
540
|
findings.append(_finding("skill_description_long", "warn", harness, skill["name"],
|
|
502
541
|
f"Description of {len(skill['description'])} characters; Claude Code cuts "
|
|
503
|
-
f"each one at {SKILL_DESCRIPTION_MAX}.", doc,
|
|
542
|
+
f"each one at {SKILL_DESCRIPTION_MAX}.", doc,
|
|
543
|
+
f"Shorten the `description` in {skill['path']} from "
|
|
544
|
+
f"{len(skill['description'])} to at most {SKILL_DESCRIPTION_MAX} characters, "
|
|
545
|
+
"keeping when to use the skill at the start.", [skill["path"]]))
|
|
504
546
|
total = sum(len(s["name"]) + len(s["description"]) for s in skills)
|
|
505
547
|
if total > SKILL_BUDGET_CHARS:
|
|
548
|
+
longest = ", ".join(s["name"] for s in sorted(skills, key=lambda s: -len(s["description"]))[:5])
|
|
549
|
+
how = ('turn off the ones you do not use with "skillOverrides": {"<name>": "off"} in '
|
|
550
|
+
f"{os.path.join(endpoint_sync.claude_dir(), 'settings.json')}" if harness == "claude"
|
|
551
|
+
else "remove the skill folders you do not use")
|
|
506
552
|
findings.append(_finding("skill_budget", "warn", harness, f"{len(skills)} skills",
|
|
507
553
|
f"Names and descriptions add up to {total:,} characters, over the ~{SKILL_BUDGET_CHARS:,} "
|
|
508
554
|
"the skill list gets (Claude: 1% of a 200k context; Codex: 2% or 8,000 characters):"
|
|
509
|
-
" some skills are left out of what the model sees.", doc
|
|
555
|
+
" some skills are left out of what the model sees.", doc,
|
|
556
|
+
f"Bring names and descriptions under ~{SKILL_BUDGET_CHARS:,} characters: {how}, or "
|
|
557
|
+
f"shorten the longest descriptions ({longest})."))
|
|
510
558
|
return findings
|
|
511
559
|
|
|
512
560
|
|
|
@@ -519,7 +567,9 @@ def check_instructions(project, claude, codex):
|
|
|
519
567
|
if agents_here and not imports_agents:
|
|
520
568
|
findings.append(_finding("agents_md_not_read_by_claude", "warn", "claude", os.path.join(project, "AGENTS.md"),
|
|
521
569
|
"Codex reads AGENTS.md; Claude Code reads only CLAUDE.md (and what it imports with "
|
|
522
|
-
"@AGENTS.md), so the two agents get different instructions here.", DOCS["claude_memory"]
|
|
570
|
+
"@AGENTS.md), so the two agents get different instructions here.", DOCS["claude_memory"],
|
|
571
|
+
f"Add a line `@AGENTS.md` to {os.path.join(project, 'CLAUDE.md')} (create the file "
|
|
572
|
+
"with that line if it does not exist)."))
|
|
523
573
|
for item in claude_texts:
|
|
524
574
|
base = os.path.dirname(item["path"])
|
|
525
575
|
for target in _IMPORT_RE.findall(item["_text"]):
|
|
@@ -527,12 +577,17 @@ def check_instructions(project, claude, codex):
|
|
|
527
577
|
if not os.path.exists(path):
|
|
528
578
|
findings.append(_finding("broken_import", "error", "claude", f"{item['path']} @{target}",
|
|
529
579
|
"Imported file does not exist: that part of the instructions never loads.",
|
|
530
|
-
DOCS["claude_memory"],
|
|
580
|
+
DOCS["claude_memory"],
|
|
581
|
+
f"In {item['path']}, point `@{target}` to a file that exists, or delete that "
|
|
582
|
+
"line.", [item["path"]]))
|
|
531
583
|
total = sum(i["bytes"] for i in codex["instructions"] if i["kind"] == "project")
|
|
532
584
|
if total > CODEX_PROJECT_DOC_MAX:
|
|
533
585
|
findings.append(_finding("codex_agents_truncated", "error", "codex", project,
|
|
534
586
|
f"Project AGENTS.md chain is {total:,} bytes; Codex reads {CODEX_PROJECT_DOC_MAX:,} "
|
|
535
587
|
"(project_doc_max_bytes) and drops the rest.", DOCS["codex_agents_md"],
|
|
588
|
+
f"Shorten the project AGENTS.md files to under {CODEX_PROJECT_DOC_MAX:,} bytes in "
|
|
589
|
+
f"total, or set project_doc_max_bytes = {total} (or more) in "
|
|
590
|
+
f"{os.path.join(codex_dir(), 'config.toml')}.",
|
|
536
591
|
[i["path"] for i in codex["instructions"]]))
|
|
537
592
|
return findings
|
|
538
593
|
|
|
@@ -672,6 +727,7 @@ def check_mcp(harness, entries, results):
|
|
|
672
727
|
"""Unhealthy servers, and tools offered twice (same name, or a proxy re-exposing a directly registered server)."""
|
|
673
728
|
findings, tools_by_server = [], {}
|
|
674
729
|
doc = DOCS["claude_mcp"] if harness == "claude" else DOCS["mcp_lifecycle"]
|
|
730
|
+
sources = {entry["name"]: entry["source"] for entry in entries}
|
|
675
731
|
for entry, result in zip(entries, results):
|
|
676
732
|
subject = f"{entry['name']} ({entry['scope']})"
|
|
677
733
|
if result is None:
|
|
@@ -682,7 +738,9 @@ def check_mcp(harness, entries, results):
|
|
|
682
738
|
"timeout": "did not answer in time; its tools were not verified"}.get(result["kind"],
|
|
683
739
|
"does not start or answer")
|
|
684
740
|
findings.append(_finding("mcp_unhealthy", severity, harness, subject,
|
|
685
|
-
f"MCP server {text}: {result['error']}", doc,
|
|
741
|
+
f"MCP server {text}: {result['error']}", doc, _mcp_fix(harness, entry,
|
|
742
|
+
result["kind"]),
|
|
743
|
+
[entry["source"]]))
|
|
686
744
|
continue
|
|
687
745
|
names = [t.get("name") for t in result["tools"] if t.get("name") not in entry["disabled_tools"]]
|
|
688
746
|
tools_by_server[entry["name"]] = set(names)
|
|
@@ -698,15 +756,33 @@ def check_mcp(harness, entries, results):
|
|
|
698
756
|
if same:
|
|
699
757
|
findings.append(_finding("mcp_duplicate_tools", "warn", harness, f"{server} and {other}",
|
|
700
758
|
f"{len(same)} tools with the same name on both servers: {', '.join(same[:6])}",
|
|
701
|
-
doc
|
|
759
|
+
doc, f"Keep one of the two: remove '{server}' from {sources[server]} or "
|
|
760
|
+
f"'{other}' from {sources[other]}"
|
|
761
|
+
+ (", or list the duplicated tools in disabled_tools of one of them."
|
|
762
|
+
if harness == "codex" else ".")))
|
|
702
763
|
if proxied:
|
|
703
764
|
findings.append(_finding("mcp_duplicate_tools", "warn", harness, f"{server} proxies {other}",
|
|
704
765
|
f"{server} re-exposes {len(proxied)} tools of {other}, which is also "
|
|
705
766
|
f"registered directly: {', '.join(proxied[:6])}. The model sees both and "
|
|
706
|
-
"pays for both descriptions.", doc
|
|
767
|
+
"pays for both descriptions.", doc,
|
|
768
|
+
f"Keep one path to {other}: drop it from the servers {server} proxies (in "
|
|
769
|
+
f"{server}'s own configuration), or remove the direct '{other}' entry from "
|
|
770
|
+
f"{sources[other]}."))
|
|
707
771
|
return findings
|
|
708
772
|
|
|
709
773
|
|
|
774
|
+
def _mcp_fix(harness, entry, kind):
|
|
775
|
+
"""The step that brings an unhealthy MCP server back: sign in, or run its command by hand to see the error, or
|
|
776
|
+
remove the entry."""
|
|
777
|
+
if kind == "auth":
|
|
778
|
+
return (f"Sign in: run /mcp in Claude Code and pick {entry['name']}." if harness == "claude"
|
|
779
|
+
else f"Sign in: run `codex mcp login {entry['name']}`.")
|
|
780
|
+
command = " ".join([entry.get("command") or ""] + entry["args"])
|
|
781
|
+
target = (f"check that {entry['url']} answers" if entry.get("url") else
|
|
782
|
+
f"run its command by hand to see the error: `{command}`")
|
|
783
|
+
return f"To bring {entry['name']} back, {target}; if it is no longer used, remove it from {entry['source']}."
|
|
784
|
+
|
|
785
|
+
|
|
710
786
|
def _public(section):
|
|
711
787
|
"""A collected section without private fields (instruction text, env and header values)."""
|
|
712
788
|
out = {}
|
|
@@ -762,12 +838,18 @@ def _report_path(project):
|
|
|
762
838
|
|
|
763
839
|
|
|
764
840
|
def last_report(project):
|
|
765
|
-
"""The last stored report of project, or None when it was never audited.
|
|
841
|
+
"""The last stored report of project, or None when it was never audited. A report whose findings carry no
|
|
842
|
+
action was written by an older Smart Tool: it raises, naming the run that replaces it."""
|
|
843
|
+
path = _report_path(project)
|
|
766
844
|
try:
|
|
767
|
-
with open(
|
|
768
|
-
|
|
845
|
+
with open(path, encoding="utf-8") as stream:
|
|
846
|
+
report = json.load(stream)
|
|
769
847
|
except FileNotFoundError:
|
|
770
848
|
return None
|
|
849
|
+
if any("action" not in finding for finding in report["findings"]):
|
|
850
|
+
raise ValueError(f"{path} holds a setup audit of {report['project']} from an older Smart Tool, whose "
|
|
851
|
+
"findings have no fix: run project_manage action=setup_audit mode=run to replace it.")
|
|
852
|
+
return report
|
|
771
853
|
|
|
772
854
|
|
|
773
855
|
def stored_for(path):
|
|
@@ -783,9 +865,20 @@ def stored_for(path):
|
|
|
783
865
|
folder = parent
|
|
784
866
|
|
|
785
867
|
|
|
868
|
+
def top_findings(report, count=NOTICE_ITEMS):
|
|
869
|
+
"""The errors and warnings of report most worth acting on first: errors, then a fix over a check to make
|
|
870
|
+
(REVIEW_FIRST), then new ones, then the report order."""
|
|
871
|
+
order = {"error": 0, "warn": 1}
|
|
872
|
+
ranked = [(order[f["severity"]], f["check"] in REVIEW_FIRST, not f.get("new"), position, f)
|
|
873
|
+
for position, f in enumerate(report["findings"]) if f["severity"] in order]
|
|
874
|
+
return [row[-1] for row in sorted(ranked, key=lambda row: row[:4])[:count]]
|
|
875
|
+
|
|
876
|
+
|
|
786
877
|
def session_notice(path):
|
|
787
|
-
"""
|
|
788
|
-
|
|
878
|
+
"""Context for an agent session about the stored audit of path (nothing is run): the project, the counts, the top
|
|
879
|
+
NOTICE_ITEMS findings with their fix and the exact call that lists all of them. "" when there is no stored report
|
|
880
|
+
or it holds no error or warning. Each fix changes the user's agent setup, so the agent is told to apply one when
|
|
881
|
+
the user agrees, never on its own. Stays far below the ~2,500 tokens Codex spills to disk."""
|
|
789
882
|
report = stored_for(path)
|
|
790
883
|
if report is None:
|
|
791
884
|
return ""
|
|
@@ -794,9 +887,17 @@ def session_notice(path):
|
|
|
794
887
|
return ""
|
|
795
888
|
new = sum(1 for f in report["findings"] if f.get("new") and f["severity"] in ("error", "warn"))
|
|
796
889
|
age = max(0, int((time.time() - report["checked_at"]) // 60))
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
890
|
+
lines = [f"Smart Tool setup audit of {report['project']} ({age} min ago): {summary['error']} errors, "
|
|
891
|
+
f"{summary['warn']} warnings" + (f", {new} new" if new else "") + " in the Claude Code and Codex "
|
|
892
|
+
"configuration. Top items, each with its fix:"]
|
|
893
|
+
for number, finding in enumerate(top_findings(report), 1):
|
|
894
|
+
lines.append(f"{number}. [{finding['harness']}] {finding['severity']} {finding['check']}: "
|
|
895
|
+
f"{finding['subject'][:120]}. Fix: {finding['action'][:NOTICE_ACTION_MAX]}")
|
|
896
|
+
root = report["project"].replace("\\", "/")
|
|
897
|
+
lines.append(f'All findings with their fixes: project_manage action=setup_audit mode=last project_root="{root}"; '
|
|
898
|
+
"after a fix, mode=run checks again. These fixes change the user's agent setup: apply one when the "
|
|
899
|
+
"user agrees.")
|
|
900
|
+
return "\n".join(lines)
|
|
800
901
|
|
|
801
902
|
|
|
802
903
|
def index():
|
|
@@ -975,6 +1076,7 @@ def markdown(report):
|
|
|
975
1076
|
mark = {"error": "ERROR", "warn": "WARN", "info": "NOTE"}[finding["severity"]]
|
|
976
1077
|
lines.append(f"- **{mark}** [{finding['harness']}] {finding['subject']}: {finding['detail']} "
|
|
977
1078
|
f"([source]({finding['source']}))" + (" *(new)*" if finding.get("new") else ""))
|
|
1079
|
+
lines.append(f" - Fix: {finding['action']}")
|
|
978
1080
|
for side in ("claude", "codex"):
|
|
979
1081
|
servers = [m for m in report[side]["mcp"] if "tools" in m]
|
|
980
1082
|
if servers:
|
package/setup_ui.py
CHANGED
|
@@ -1600,6 +1600,8 @@ function patternRow(item, actions, selectable) {
|
|
|
1600
1600
|
buttons.style.marginTop = "0";
|
|
1601
1601
|
for (const [decision, label] of actions) buttons.appendChild(button(label, "small", () => decidePatterns([item.id], decision, label)));
|
|
1602
1602
|
const meta = node("div", "pattern-meta");
|
|
1603
|
+
if (!selectable) meta.appendChild(node("span", "pattern-mode", item.mode === "instruct" ? "Tip only, does not block" : "Blocks"));
|
|
1604
|
+
if (item.accepted_by === "agent") meta.appendChild(node("span", "pattern-mode", "Decided by an agent"));
|
|
1603
1605
|
meta.append(reach, buttons);
|
|
1604
1606
|
const main = node("div");
|
|
1605
1607
|
main.append(body, meta);
|
|
@@ -1652,7 +1654,7 @@ function renderPatterns(patterns) {
|
|
|
1652
1654
|
accept.disabled = reject.disabled = !count;
|
|
1653
1655
|
bulk.append(selectPage, accept, reject);
|
|
1654
1656
|
const list = node("ul", "pattern-list");
|
|
1655
|
-
for (const item of view.rows) list.appendChild(patternRow(item, [["accept", "Accept"], ["reject", "Reject"]], true));
|
|
1657
|
+
for (const item of view.rows) list.appendChild(patternRow(item, [["accept", "Accept"], ["instruct", "Tip only"], ["reject", "Reject"]], true));
|
|
1656
1658
|
if (!view.rows.length) list.appendChild(node("li", "hint", "No proposal matches the filter."));
|
|
1657
1659
|
const pager = node("div", "actions pager");
|
|
1658
1660
|
const prev = button("Previous", "", () => { patternView.page -= 1; renderPatterns(lastPatterns); });
|
|
@@ -1669,7 +1671,7 @@ function renderPatterns(patterns) {
|
|
|
1669
1671
|
const blocking = node("details", "more");
|
|
1670
1672
|
blocking.open = patternView.open;
|
|
1671
1673
|
blocking.addEventListener("toggle", () => { patternView.open = blocking.open; });
|
|
1672
|
-
blocking.appendChild(node("summary", "", "Patterns you accepted
|
|
1674
|
+
blocking.appendChild(node("summary", "", "Patterns you accepted (" + patterns.accepted.length + ")"));
|
|
1673
1675
|
const list = node("ul", "pattern-list");
|
|
1674
1676
|
for (const item of patterns.accepted) list.appendChild(patternRow(item, [["remove", "Remove"]], false));
|
|
1675
1677
|
blocking.appendChild(list);
|
package/smart_tool_daemon.py
CHANGED
|
@@ -66,6 +66,7 @@ import research_metrics
|
|
|
66
66
|
import research_cache
|
|
67
67
|
import router
|
|
68
68
|
import setup_audit
|
|
69
|
+
import block_patterns
|
|
69
70
|
import setup_ui
|
|
70
71
|
import site_memory
|
|
71
72
|
import web_search_adapters
|
|
@@ -360,10 +361,12 @@ SERVER_INSTRUCTIONS = (
|
|
|
360
361
|
TOOLS = [
|
|
361
362
|
{
|
|
362
363
|
"name": "project_manage",
|
|
363
|
-
"description": "Manages folders and indexing. Every action takes project_root (the folder) or project_id. list gives a short line per project; status shows storage, scope and jobs. graph with symbol (function, Class.method, class name, or path::name when the name repeats) answers what an edit touches: definition, callers with line, calls, tests that reach it through static calls (depth hops, default 3) and files importing it; use it before changing a function to know what to update. affected_tests answers which tests to run after editing: every test file importing a changed file (git diff against base, default HEAD, untracked included) plus changed tests, likeliest failures first, with the command to run them and run_all when config or unanalyzed code changed. graph without symbol reads the indexed view: coverage, references and static calls in Java, Angular, Python and JS/TS/JSX/TSX; includes HTML/CSS/Markdown references and TXT/DOCX coverage; with file_path, narrows to that file's symbols, imports and calls (lists capped by limit). inspect lists the files of a view_id; with file_path, returns only that file's chunks. usage shows consumption and reuse; docs lists public functions without a docstring (Python docstring, JSDoc, Javadoc; private, nested and override functions excluded) with coverage percent, excluding tests unless include_tests=true, for documenting a project that started without it; duplicates lists duplicated functions (identical, near-identical and semantic bodies, min_similarity default 0.90; below that most pairs measured were false positives), excluding tests unless include_tests=true; fix real duplicates; only dismiss with duplicates_dismiss (finding_id, reason=false_positive|intentional, note) what is not a duplicate or is a copy kept on purpose: the finding stays hidden until the code changes, and duplicates_restore reopens it; integration shows the MCP client, hook and tool usage metrics; install_hook_preview shows the change that would install the hook redirecting Grep/Read to smart_search and WebSearch/WebFetch to web_search/web_fetch in this session's client and returns a plan_id; install_hook writes it with that plan_id and confirm=true, with a backup, only after the user approves the change; search_limits saves the project's default top_k per block ({code, test, doc}, each 1-20, total at most 20); storage shows disk usage and views; pin_view protects a view; cleanup_preview and cleanup_commit remove selected views after confirmation; compare compares two stored views, without checkout or embeddings. register adds a folder; preview checks the scope; index/rebuild update; pause/cancel keep checkpoints; resume continues; policy picks on_search/eager; scope adjusts the scope; remove deletes only the local index. setup_audit (project_root) reports what Claude Code and Codex actually load for that folder (settings layers, plugins, hooks, MCP servers, skills, CLAUDE.md/AGENTS.md) and where they collide: hooks deciding on the same tool in parallel, missing hook scripts, silenced hooks, MCP servers down or offering duplicate tools, skill name and budget problems, AGENTS.md that only Codex reads, broken @imports; what could not be checked is listed as not verified; mode=last returns the stored report instead of auditing again. Jobs via smart_search_result.",
|
|
364
|
+
"description": "Manages folders and indexing. Every action takes project_root (the folder) or project_id. list gives a short line per project; status shows storage, scope and jobs. graph with symbol (function, Class.method, class name, or path::name when the name repeats) answers what an edit touches: definition, callers with line, calls, tests that reach it through static calls (depth hops, default 3) and files importing it; use it before changing a function to know what to update. affected_tests answers which tests to run after editing: every test file importing a changed file (git diff against base, default HEAD, untracked included) plus changed tests, likeliest failures first, with the command to run them and run_all when config or unanalyzed code changed. graph without symbol reads the indexed view: coverage, references and static calls in Java, Angular, Python and JS/TS/JSX/TSX; includes HTML/CSS/Markdown references and TXT/DOCX coverage; with file_path, narrows to that file's symbols, imports and calls (lists capped by limit). inspect lists the files of a view_id; with file_path, returns only that file's chunks. usage shows consumption and reuse; docs lists public functions without a docstring (Python docstring, JSDoc, Javadoc; private, nested and override functions excluded) with coverage percent, excluding tests unless include_tests=true, for documenting a project that started without it; duplicates lists duplicated functions (identical, near-identical and semantic bodies, min_similarity default 0.90; below that most pairs measured were false positives), excluding tests unless include_tests=true; fix real duplicates; only dismiss with duplicates_dismiss (finding_id, reason=false_positive|intentional, note) what is not a duplicate or is a copy kept on purpose: the finding stays hidden until the code changes, and duplicates_restore reopens it; integration shows the MCP client, hook and tool usage metrics; install_hook_preview shows the change that would install the hook redirecting Grep/Read to smart_search and WebSearch/WebFetch to web_search/web_fetch in this session's client and returns a plan_id; install_hook writes it with that plan_id and confirm=true, with a backup, only after the user approves the change; search_limits saves the project's default top_k per block ({code, test, doc}, each 1-20, total at most 20); storage shows disk usage and views; pin_view protects a view; cleanup_preview and cleanup_commit remove selected views after confirmation; compare compares two stored views, without checkout or embeddings. register adds a folder; preview checks the scope; index/rebuild update; pause/cancel keep checkpoints; resume continues; policy picks on_search/eager; scope adjusts the scope; remove deletes only the local index. setup_audit (project_root) reports what Claude Code and Codex actually load for that folder (settings layers, plugins, hooks, MCP servers, skills, CLAUDE.md/AGENTS.md) and where they collide: hooks deciding on the same tool in parallel, missing hook scripts, silenced hooks, MCP servers down or offering duplicate tools, skill name and budget problems, AGENTS.md that only Codex reads, broken @imports; what could not be checked is listed as not verified; each finding carries its fix (the file to edit or the command to run), applied by the agent when the user agrees, never by Smart Tool; mode=last returns the stored report instead of auditing again. redirect_proposals (no project_root) lists the redirect patterns proposed from allowed searches, most matched first, with a guide; redirect_decide decides them by ids: accept, instruct (tip without blocking), reject, or remove an accepted one. Jobs via smart_search_result.",
|
|
364
365
|
"inputSchema": {
|
|
365
366
|
"type": "object", "properties": {
|
|
366
|
-
"action": {"type": "string", "enum": ["list", "status", "register", "preview", "index", "rebuild", "pause", "cancel", "resume", "watch", "scope", "remove", "relocate", "probe", "policy", "inspect", "graph", "usage", "storage", "pin_view", "cleanup_preview", "cleanup_commit", "compare", "search_limits", "integration", "install_hook_preview", "install_hook", "duplicates", "duplicates_dismiss", "duplicates_restore", "docs", "affected_tests", "setup_audit"]},
|
|
367
|
+
"action": {"type": "string", "enum": ["list", "status", "register", "preview", "index", "rebuild", "pause", "cancel", "resume", "watch", "scope", "remove", "relocate", "probe", "policy", "inspect", "graph", "usage", "storage", "pin_view", "cleanup_preview", "cleanup_commit", "compare", "search_limits", "integration", "install_hook_preview", "install_hook", "duplicates", "duplicates_dismiss", "duplicates_restore", "docs", "affected_tests", "setup_audit", "redirect_proposals", "redirect_decide"]},
|
|
368
|
+
"ids": {"type": "array", "items": {"type": "string"}, "description": "redirect_decide: proposal ids from redirect_proposals (accepted ids for remove)"},
|
|
369
|
+
"decision": {"type": "string", "enum": ["accept", "instruct", "reject", "remove"], "description": "redirect_decide: accept redirects matching calls to smart_search; instruct lets them run with a tip naming smart_search; reject discards; remove deletes an accepted pattern"},
|
|
367
370
|
"finding_id": {"type": "string"},
|
|
368
371
|
"reason": {"type": "string", "enum": ["false_positive", "intentional"]},
|
|
369
372
|
"note": {"type": "string"},
|
|
@@ -1621,22 +1624,77 @@ def _mark_notice_delivered(job_id):
|
|
|
1621
1624
|
|
|
1622
1625
|
|
|
1623
1626
|
def _pending_notices(session, client, project_root):
|
|
1624
|
-
"""[(key, text)] the session has not been told yet: the hook state (once)
|
|
1625
|
-
searched folder (once per folder, only with errors or warnings
|
|
1626
|
-
reports
|
|
1627
|
+
"""[(key, text)] the session has not been told yet: the hook state (once), the stored setup audit of the
|
|
1628
|
+
searched folder (once per folder, only with errors or warnings) and the redirect proposals waiting for a decision
|
|
1629
|
+
(once), these two not when the SessionStart audit hook already reports them at the start of the session. An
|
|
1630
|
+
unreadable audit report is logged, not raised, so a search never fails over it."""
|
|
1627
1631
|
delivered = session.get("notices_delivered") or set()
|
|
1628
1632
|
pending = []
|
|
1629
1633
|
if session["hook_notice"] and "hook" not in delivered:
|
|
1630
1634
|
pending.append(("hook", session["hook_notice"]))
|
|
1631
1635
|
pending += [(key, f"{text} Tell the user.") for key, text in _update_notices() if key not in delivered]
|
|
1632
1636
|
key = "audit:" + setup_audit.index_key(project_root)
|
|
1633
|
-
if key not in delivered and not client_hooks.audit_hook_installed(client):
|
|
1634
|
-
|
|
1637
|
+
if (key not in delivered or "proposals" not in delivered) and not client_hooks.audit_hook_installed(client):
|
|
1638
|
+
try:
|
|
1639
|
+
text = setup_audit.session_notice(project_root) if key not in delivered else ""
|
|
1640
|
+
except Exception as exc:
|
|
1641
|
+
_log(f"setup audit notice not read: {type(exc).__name__}: {exc}")
|
|
1642
|
+
text = ""
|
|
1635
1643
|
if text:
|
|
1636
1644
|
pending.append((key, text))
|
|
1645
|
+
proposals = _proposals_notice() if "proposals" not in delivered else ""
|
|
1646
|
+
if proposals:
|
|
1647
|
+
pending.append(("proposals", proposals))
|
|
1637
1648
|
return pending
|
|
1638
1649
|
|
|
1639
1650
|
|
|
1651
|
+
def _proposals_notice():
|
|
1652
|
+
"""One line for the agent when redirect proposals wait for a decision, "" when none; an unreadable store is
|
|
1653
|
+
logged, not raised, so neither a search nor a session start fails over it."""
|
|
1654
|
+
try:
|
|
1655
|
+
count, _top = block_patterns.pending(0)
|
|
1656
|
+
except Exception as exc:
|
|
1657
|
+
_log(f"redirect proposals not read: {type(exc).__name__}: {exc}")
|
|
1658
|
+
return ""
|
|
1659
|
+
if not count:
|
|
1660
|
+
return ""
|
|
1661
|
+
return (f"{count} Smart Tool redirect proposal(s) wait for a decision (no need to interrupt the user's task for "
|
|
1662
|
+
"them): list and decide them with project_manage action=redirect_proposals.")
|
|
1663
|
+
|
|
1664
|
+
|
|
1665
|
+
REDIRECT_GUIDE = (
|
|
1666
|
+
"Decide each proposal from its pattern, example and history_matches (logged calls it would have matched): "
|
|
1667
|
+
"accept (mode redirect: matching calls go to smart_search) when the pattern only matches searches or bulk reads "
|
|
1668
|
+
"over a folder that smart_search answers; instruct (the calls run and the agent gets a tip naming smart_search) "
|
|
1669
|
+
"when it also matches calls whose shell output is needed, or when unsure; reject when it matches commands that "
|
|
1670
|
+
"change files, read one known file or are not searches. Then call project_manage action=redirect_decide with ids "
|
|
1671
|
+
"and decision; remove undoes an accepted one.")
|
|
1672
|
+
|
|
1673
|
+
|
|
1674
|
+
def _redirect_action(arguments):
|
|
1675
|
+
"""redirect_proposals: the proposals waiting for a decision, most matched first, with the guide to decide them;
|
|
1676
|
+
redirect_decide: accept, instruct, reject (proposals) or remove (accepted) the given ids, recorded as decided by an
|
|
1677
|
+
agent."""
|
|
1678
|
+
if arguments["action"] == "redirect_proposals":
|
|
1679
|
+
limit = arguments.get("limit", 30)
|
|
1680
|
+
if not isinstance(limit, int) or not 1 <= limit <= 200:
|
|
1681
|
+
raise ValueError("redirect_proposals limit must be an integer from 1 to 200.")
|
|
1682
|
+
count, top = block_patterns.pending(limit)
|
|
1683
|
+
accepted = block_patterns.load()["accepted"]
|
|
1684
|
+
fields = ("id", "tool", "pattern", "reason", "example", "history_matches", "history_total")
|
|
1685
|
+
return {"pending": count, "shown": len(top),
|
|
1686
|
+
"accepted": {mode: sum(e["mode"] == mode for e in accepted) for mode in block_patterns.MODES},
|
|
1687
|
+
"proposals": [{f: entry.get(f) for f in fields} for entry in top], "guide": REDIRECT_GUIDE}
|
|
1688
|
+
ids, decision = arguments.get("ids"), arguments.get("decision")
|
|
1689
|
+
if not isinstance(ids, list) or not ids or not all(isinstance(i, str) for i in ids):
|
|
1690
|
+
raise ValueError("redirect_decide needs ids: the proposal ids listed by action=redirect_proposals.")
|
|
1691
|
+
if decision not in block_patterns.DECISIONS:
|
|
1692
|
+
raise ValueError(f"redirect_decide decision must be one of {', '.join(block_patterns.DECISIONS)}.")
|
|
1693
|
+
data = block_patterns.decide_proposals(ids, decision, decided_by="agent")
|
|
1694
|
+
return {"decided": len(set(ids)), "decision": decision, "pending": len(data["proposals"]),
|
|
1695
|
+
"accepted": {mode: sum(e["mode"] == mode for e in data["accepted"]) for mode in block_patterns.MODES}}
|
|
1696
|
+
|
|
1697
|
+
|
|
1640
1698
|
def _update_notices():
|
|
1641
1699
|
"""Update notices (updated, failed, newer version on npm); an unreadable state file is logged, not raised, so a
|
|
1642
1700
|
search never fails over it."""
|
|
@@ -1695,7 +1753,7 @@ def _smart_search_arguments(arguments):
|
|
|
1695
1753
|
if session is not None:
|
|
1696
1754
|
notices = _pending_notices(session, client, project_root)
|
|
1697
1755
|
if notices:
|
|
1698
|
-
arguments["setup_notice"] = "
|
|
1756
|
+
arguments["setup_notice"] = "\n".join(text for _key, text in notices)
|
|
1699
1757
|
arguments["setup_notice_keys"] = [key for key, _text in notices]
|
|
1700
1758
|
_metric("search", group=group, top_k=limits, query_comments=bool(comments), single_language_reason=reason)
|
|
1701
1759
|
return arguments
|
|
@@ -2006,6 +2064,8 @@ def _project_summary(project):
|
|
|
2006
2064
|
def _project_action(arguments):
|
|
2007
2065
|
if not isinstance(arguments, dict):
|
|
2008
2066
|
raise ValueError("Pass the action in a JSON object.")
|
|
2067
|
+
if arguments.get("action") in ("redirect_proposals", "redirect_decide"):
|
|
2068
|
+
return _redirect_action(arguments)
|
|
2009
2069
|
if arguments.get("action") == "setup_audit":
|
|
2010
2070
|
root = arguments.get("project_root")
|
|
2011
2071
|
if not isinstance(root, str) or not os.path.isdir(root):
|
|
@@ -4000,7 +4060,7 @@ def _session_audit_hook(handler):
|
|
|
4000
4060
|
_log(f"SessionStart audit hook without a report: {type(exc).__name__}: {exc}")
|
|
4001
4061
|
text = ""
|
|
4002
4062
|
updates = " ".join(notice for _key, notice in _update_notices())
|
|
4003
|
-
context = "
|
|
4063
|
+
context = "\n".join(part for part in (updates, text, _proposals_notice()) if part)
|
|
4004
4064
|
if not context:
|
|
4005
4065
|
return {}
|
|
4006
4066
|
output = {"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": context}}
|
|
@@ -4259,7 +4319,7 @@ class MCPHandler(BaseHTTPRequestHandler):
|
|
|
4259
4319
|
if self._reject_foreign_origin():
|
|
4260
4320
|
return
|
|
4261
4321
|
if self.path == "/health":
|
|
4262
|
-
self._write_json(200, {"status": "ok"})
|
|
4322
|
+
self._write_json(200, {"status": "ok", "version": version.VERSION})
|
|
4263
4323
|
return
|
|
4264
4324
|
if self.path == "/status":
|
|
4265
4325
|
self._write_json(200, {
|
package/tray.py
CHANGED
|
@@ -289,17 +289,16 @@ _update_busy = threading.Lock()
|
|
|
289
289
|
|
|
290
290
|
|
|
291
291
|
def _update_now(icon, item):
|
|
292
|
-
"""Menu action:
|
|
293
|
-
when there is none."""
|
|
292
|
+
"""Menu action: asks npm again for the newest version (a newer one may have come out since the last check) and
|
|
293
|
+
installs it, telling the user it is checking when no newer version was known yet, and says when there is none."""
|
|
294
294
|
if not _update_busy.acquire(blocking=False):
|
|
295
295
|
return
|
|
296
296
|
|
|
297
297
|
def run():
|
|
298
298
|
try:
|
|
299
|
-
|
|
300
|
-
if not latest:
|
|
299
|
+
if not _state["update"]:
|
|
301
300
|
_notify(icon, "Checking for updates…")
|
|
302
|
-
|
|
301
|
+
latest = update_check.newer_version()
|
|
303
302
|
if not latest:
|
|
304
303
|
_notify(icon, "Smart Tool {version} is the latest version.", version=version.VERSION)
|
|
305
304
|
return
|
package/update_check.py
CHANGED
|
@@ -20,7 +20,6 @@ import version
|
|
|
20
20
|
|
|
21
21
|
PACKAGE = "@allansantos-dev/smart-tool"
|
|
22
22
|
REGISTRY_URL = "https://registry.npmjs.org/@allansantos-dev%2Fsmart-tool/latest"
|
|
23
|
-
UPDATE_COMMAND = f"npx --yes {PACKAGE}@latest install"
|
|
24
23
|
SITE_URL = "https://allansantos-dv.github.io/smart-tool/"
|
|
25
24
|
STATE_PATH = os.path.join(paths.DATA_DIR, "update-state.json")
|
|
26
25
|
UPDATE_LOG = os.path.join(paths.DATA_DIR, "update.log")
|
|
@@ -42,6 +41,12 @@ def newer_version(timeout=10):
|
|
|
42
41
|
return latest if _parts(latest) > _parts(version.VERSION) else None
|
|
43
42
|
|
|
44
43
|
|
|
44
|
+
def update_command(target):
|
|
45
|
+
"""The npx command that installs version target, as told to the user and to agent sessions. Pinned rather than
|
|
46
|
+
`@latest`, which lets npx reuse an older package from its cache."""
|
|
47
|
+
return f"npx --yes {PACKAGE}@{target} install"
|
|
48
|
+
|
|
49
|
+
|
|
45
50
|
def env_opted_out():
|
|
46
51
|
"""SMART_TOOL_AUTO_UPDATE set to off, 0, false or no."""
|
|
47
52
|
return os.environ.get(ENV_OPT_OUT, "").strip().lower() in ("off", "0", "false", "no")
|
|
@@ -144,10 +149,10 @@ def notices(now=None):
|
|
|
144
149
|
else "automatic updates are now off")
|
|
145
150
|
found.append((f"failed:{failed}",
|
|
146
151
|
f"The automatic update of Smart Tool to {failed} failed; {version.VERSION} is still installed "
|
|
147
|
-
f"and {retry}. To update now, run: {
|
|
152
|
+
f"and {retry}. To update now, run: {update_command(failed)}"))
|
|
148
153
|
elif latest and _parts(latest) > _parts(version.VERSION):
|
|
149
154
|
how = ("the tray installs it automatically" if automatic_enabled()
|
|
150
|
-
else f"automatic updates are off (tray switch or {ENV_OPT_OUT}=off); to update, run: {
|
|
155
|
+
else f"automatic updates are off (tray switch or {ENV_OPT_OUT}=off); to update, run: {update_command(latest)}")
|
|
151
156
|
found.append((f"available:{latest}",
|
|
152
157
|
f"Smart Tool {latest} is available on npm (installed: {version.VERSION}); {how}."))
|
|
153
158
|
return found
|
package/update_splash.py
CHANGED
|
@@ -4,9 +4,11 @@ the interface language, then the result. Started by the tray (update_check.run_u
|
|
|
4
4
|
|
|
5
5
|
The install command runs with CREATE_NO_WINDOW, so it and every console program it starts (node, the installer,
|
|
6
6
|
pip, PowerShell, schtasks) share one hidden console. Its output goes to update_check.UPDATE_LOG; a failure shows the last line,
|
|
7
|
-
the log path and a Windows notification, and the installer has already restored the previous version.
|
|
7
|
+
the log path and a Windows notification, and the installer has already restored the previous version. The outcome names
|
|
8
|
+
the version read from the installed version.py after the run, not the one this process loaded before it."""
|
|
8
9
|
import os
|
|
9
10
|
import queue
|
|
11
|
+
import re
|
|
10
12
|
import subprocess
|
|
11
13
|
import sys
|
|
12
14
|
import threading
|
|
@@ -47,18 +49,32 @@ def step_for(line):
|
|
|
47
49
|
return None
|
|
48
50
|
|
|
49
51
|
|
|
50
|
-
def install_command():
|
|
51
|
-
"""argv of the update: the
|
|
52
|
+
def install_command(target):
|
|
53
|
+
"""argv of the update: the npx command a user types, through cmd.exe because npx is a .cmd script, for the version
|
|
54
|
+
the tray announced. `@latest` would let npx reuse an older package from its cache and install that instead, and
|
|
55
|
+
--expect-version makes the installer refuse a package that is not that version."""
|
|
52
56
|
npx = node_locator.which("npx.cmd")
|
|
53
57
|
if not npx:
|
|
54
58
|
raise RuntimeError(i18n.t("Node.js (npx) was not found; install Node.js and try again."))
|
|
55
|
-
return ["cmd.exe", "/d", "/c", npx, "--yes", f"{update_check.PACKAGE}@
|
|
59
|
+
return ["cmd.exe", "/d", "/c", npx, "--yes", f"{update_check.PACKAGE}@{target}", "install",
|
|
60
|
+
"--expect-version", target], npx
|
|
56
61
|
|
|
57
62
|
|
|
58
|
-
def
|
|
63
|
+
def installed_version(folder=os.path.dirname(os.path.abspath(__file__))):
|
|
64
|
+
"""VERSION as written in folder's version.py now: the installer replaces that file, so after an update it tells which
|
|
65
|
+
version is really installed. Raises when the file has no VERSION line."""
|
|
66
|
+
path = os.path.join(folder, "version.py")
|
|
67
|
+
with open(path, encoding="utf-8") as stream:
|
|
68
|
+
found = re.search(r'^VERSION = "([^"]+)"', stream.read(), re.M)
|
|
69
|
+
if not found:
|
|
70
|
+
raise RuntimeError(f"{path} has no VERSION line")
|
|
71
|
+
return found.group(1)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def run_install(lines, target):
|
|
59
75
|
"""Runs the install command hidden, puts each output line on `lines`, writes them to update_check.UPDATE_LOG and returns
|
|
60
76
|
(exit code, last non-empty line). Kills the whole process tree after TIMEOUT_S."""
|
|
61
|
-
command, npx = install_command()
|
|
77
|
+
command, npx = install_command(target)
|
|
62
78
|
os.makedirs(os.path.dirname(update_check.UPDATE_LOG), exist_ok=True)
|
|
63
79
|
last = ""
|
|
64
80
|
with open(update_check.UPDATE_LOG, "w", encoding="utf-8") as log:
|
|
@@ -150,7 +166,9 @@ class Splash:
|
|
|
150
166
|
|
|
151
167
|
def main(argv):
|
|
152
168
|
"""Shows the screen, runs the update and reports the outcome; returns the installer's exit code."""
|
|
153
|
-
|
|
169
|
+
if len(argv) < 2:
|
|
170
|
+
raise SystemExit("usage: update_splash.py <version>: the version to install, as announced by the tray")
|
|
171
|
+
target = argv[1]
|
|
154
172
|
if not _single_instance():
|
|
155
173
|
return 0
|
|
156
174
|
splash = Splash(target)
|
|
@@ -158,7 +176,7 @@ def main(argv):
|
|
|
158
176
|
|
|
159
177
|
def work():
|
|
160
178
|
try:
|
|
161
|
-
outcome["code"], outcome["last"] = run_install(lines)
|
|
179
|
+
outcome["code"], outcome["last"] = run_install(lines, target)
|
|
162
180
|
except Exception as exc:
|
|
163
181
|
outcome["code"], outcome["last"] = 1, f"{type(exc).__name__}: {exc}"
|
|
164
182
|
|
|
@@ -173,12 +191,20 @@ def main(argv):
|
|
|
173
191
|
if worker.is_alive():
|
|
174
192
|
splash.root.after(200, pump)
|
|
175
193
|
return
|
|
176
|
-
|
|
194
|
+
try:
|
|
195
|
+
installed = installed_version()
|
|
196
|
+
except (OSError, RuntimeError) as exc:
|
|
197
|
+
installed = None
|
|
198
|
+
outcome["code"], outcome["last"] = outcome["code"] or 1, f"{type(exc).__name__}: {exc}"
|
|
199
|
+
if outcome["code"] == 0 and installed == target:
|
|
177
200
|
splash.finish(True, i18n.t("Smart Tool updated"),
|
|
178
201
|
i18n.t("Version {version} is installed and running.", version=target),
|
|
179
202
|
i18n.t("This window closes by itself."))
|
|
180
203
|
return
|
|
181
|
-
|
|
204
|
+
if outcome["code"] == 0:
|
|
205
|
+
outcome["last"] = f"installed version.py says {installed}, not {target}"
|
|
206
|
+
detail = i18n.t("The update did not finish; version {version} is still installed.",
|
|
207
|
+
version=installed or version.VERSION)
|
|
182
208
|
where = i18n.t("Details in {path}", path=update_check.UPDATE_LOG)
|
|
183
209
|
splash.finish(False, i18n.t("Update not finished"), f"{detail}\n{outcome['last'][:180]}", where)
|
|
184
210
|
try:
|
package/version.py
CHANGED