@allansantos-dev/smart-tool 0.9.69 → 0.9.71
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 +29 -0
- package/README.md +16 -7
- package/bin/smart-tool.mjs +9 -3
- package/browser_control.py +17 -11
- package/client_hooks.py +34 -0
- package/endpoint_sync.py +22 -4
- package/index_views.py +2 -0
- package/install.py +2 -1
- package/package.json +35 -35
- package/paths.py +39 -0
- package/project_scheduler.py +11 -7
- package/setup_audit.py +19 -3
- package/smart_tool_daemon.py +63 -10
- package/uninstall.py +144 -0
- package/version.py +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,34 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.9.71 - beta
|
|
4
|
+
|
|
5
|
+
- `npx @allansantos-dev/smart-tool@0.9.71 uninstall [--target DIR] [--keep-data]` (`python uninstall.py`): silent uninstall that
|
|
6
|
+
removes what the install and the agent-side setup added: tray and daemon, logon task, Smart Tool's hook entries
|
|
7
|
+
(`client_hooks.remove`, `audit_remove`), the `smart-tool` MCP entry (`endpoint_sync.unregister`) and the `playwright`
|
|
8
|
+
entry Smart Tool registered (`browser_control.unregister`), the program folder and `~/.smart-tool`. Projects are never
|
|
9
|
+
touched; the exit code is 1 when a step fails. Tests: `tests/test_uninstall.py`.
|
|
10
|
+
- `install.py` and `uninstall.py` refuse to run (`paths.refuse_overridden_folders`) when USERPROFILE or LOCALAPPDATA differ from the
|
|
11
|
+
folders Windows reports, because the logon task, the process table and the registry they act on are shared with the real
|
|
12
|
+
installation. The release gate runs the tests that read `.github` from the repository, not from the installed copy.
|
|
13
|
+
|
|
14
|
+
- A redirected search (the hook that answers the agent's Grep/Read) no longer waits behind an index update of the same
|
|
15
|
+
project: it answers from the last ready index plus the files read from disk, so a reindex never makes the hook fail.
|
|
16
|
+
Searches and index updates are counted apart (a queue of one never rejects the other; the message names which is
|
|
17
|
+
full), and a search waiting for a folder runs before the index updates queued for it. Tests:
|
|
18
|
+
`tests/test_interactive_priority.py`, `tests/test_warm_search.py`.
|
|
19
|
+
- `setup_audit` reads the MCP servers a Claude Code plugin declares in `.claude-plugin/plugin.json` (inline object or a path
|
|
20
|
+
to a JSON file), not only its `.mcp.json`: 23 `hook_unknown_server` errors reported for a plugin whose hooks call its own
|
|
21
|
+
server were false findings. Tests: `tests/test_setup_audit.py`.
|
|
22
|
+
|
|
23
|
+
## 0.9.70 - beta
|
|
24
|
+
|
|
25
|
+
- `project_manage list` no longer fails as a whole when a registered folder was deleted inside a Git repository (a removed
|
|
26
|
+
worktree): that project shows as `unavailable` with "The project folder no longer exists", and `status` on it says so.
|
|
27
|
+
- A search of a folder that holds other registered projects names each one (files indexed, `project_root` to search it),
|
|
28
|
+
because each keeps its own index and its files are not in the outer results. `project_manage status` with a path inside a
|
|
29
|
+
registered project answers for the deepest project that holds it and returns `resolved_from`.
|
|
30
|
+
Tests: `tests/test_nested_projects.py`, `tests/test_agent_efficiency.py`.
|
|
31
|
+
|
|
3
32
|
## 0.9.69 - beta
|
|
4
33
|
|
|
5
34
|
- `smart_search` answers leaner by default: `detail=compact` cuts each excerpt to whole lines within 240 characters (was 500)
|
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.71 beta. Windows only. What changed in each version: [CHANGELOG.md](CHANGELOG.md).
|
|
21
21
|
|
|
22
22
|
## How it works
|
|
23
23
|
|
|
@@ -83,7 +83,7 @@ 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@0.9.
|
|
86
|
+
npx @allansantos-dev/smart-tool@0.9.71 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
|
|
@@ -381,11 +381,20 @@ fails to load is listed in the setup screen with its error and does not affect t
|
|
|
381
381
|
|
|
382
382
|
## Uninstall
|
|
383
383
|
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
384
|
+
```powershell
|
|
385
|
+
npx @allansantos-dev/smart-tool@0.9.71 uninstall [--target DIR] [--keep-data]
|
|
386
|
+
```
|
|
387
|
+
|
|
388
|
+
It asks nothing and opens no window. It stops the tray and the daemon, removes the logon task, the hook entries of Smart
|
|
389
|
+
Tool in `~/.claude/settings.json` and `~/.codex/hooks.json` (other hooks stay), the `smart-tool` MCP entry and the
|
|
390
|
+
`playwright` entry Smart Tool registered (one you registered yourself stays) in Claude Code and Codex, the program
|
|
391
|
+
folder (`%LOCALAPPDATA%\Programs\SmartTool`), the old copies beside it, and `~/.smart-tool` (settings, indexes, saved
|
|
392
|
+
keys; `--keep-data` keeps it). Your projects are never touched. The Camoufox browser cache in
|
|
393
|
+
`%LOCALAPPDATA%\camoufox` is left in place: other tools use it too. The exit code is 0 when everything is gone (or was
|
|
394
|
+
never there) and 1 when a step failed, with each failure named on stderr; running it again retries. Turning off "Start
|
|
395
|
+
automatically" in the setup screen also removes the two per-user registry keys of the notification buttons
|
|
396
|
+
(`HKCU\Software\Classes\smart-tool-action` and `HKCU\Software\Classes\AppUserModelId\SmartTool.Notifications`); the
|
|
397
|
+
uninstall removes them too, and they come back the next time a notification is shown.
|
|
389
398
|
|
|
390
399
|
## License
|
|
391
400
|
|
package/bin/smart-tool.mjs
CHANGED
|
@@ -20,7 +20,12 @@ const USAGE = `Usage: npx @allansantos-dev/smart-tool@<version> install [--targe
|
|
|
20
20
|
|
|
21
21
|
Installs or updates Smart Tool for this Windows user. To update, run it again with the version to install in place of
|
|
22
22
|
<version>: a pinned version keeps npx from reusing an older package from its cache. For a version published minutes
|
|
23
|
-
ago, add --prefer-online before the package name so npm asks the registry instead of its cached version list
|
|
23
|
+
ago, add --prefer-online before the package name so npm asks the registry instead of its cached version list.
|
|
24
|
+
|
|
25
|
+
Usage: npx @allansantos-dev/smart-tool@<version> uninstall [--target DIR] [--keep-data]
|
|
26
|
+
|
|
27
|
+
Removes Smart Tool silently (no prompts): the program folder, autostart, the agent hooks, the MCP registrations and
|
|
28
|
+
~/.smart-tool (kept with --keep-data). Your projects are never touched. Exit code 0 when everything is gone, 1 when a step failed.`;
|
|
24
29
|
|
|
25
30
|
function fail(message) {
|
|
26
31
|
throw new Failure(message);
|
|
@@ -84,7 +89,7 @@ async function main() {
|
|
|
84
89
|
console.log(JSON.parse(readFileSync(join(PACKAGE_DIR, "package.json"), "utf8")).version);
|
|
85
90
|
return;
|
|
86
91
|
}
|
|
87
|
-
if (command !== "install") {
|
|
92
|
+
if (command !== "install" && command !== "uninstall") {
|
|
88
93
|
console.log(USAGE);
|
|
89
94
|
process.exitCode = command === undefined || command === "--help" || command === "-h" ? 0 : 1;
|
|
90
95
|
return;
|
|
@@ -96,7 +101,8 @@ async function main() {
|
|
|
96
101
|
return;
|
|
97
102
|
}
|
|
98
103
|
const python = ensurePython();
|
|
99
|
-
const
|
|
104
|
+
const script = command === "install" ? ["install.py", "--skip-tests"] : ["uninstall.py"];
|
|
105
|
+
const installer = spawnSync(python, [join(PACKAGE_DIR, script[0]), ...script.slice(1), ...rest], {
|
|
100
106
|
stdio: "inherit",
|
|
101
107
|
cwd: PACKAGE_DIR,
|
|
102
108
|
env: { ...process.env, PYTHONUTF8: "1", PYTHONIOENCODING: "utf-8" },
|
package/browser_control.py
CHANGED
|
@@ -323,15 +323,6 @@ def register_command(client, command):
|
|
|
323
323
|
raise ValueError(f"Client without MCP registration: {client!r}")
|
|
324
324
|
|
|
325
325
|
|
|
326
|
-
def remove_command(client):
|
|
327
|
-
"""Official CLI command that removes the server registered by register_command."""
|
|
328
|
-
if client == "claude":
|
|
329
|
-
return ["claude", "mcp", "remove", SERVER, "--scope", "user"]
|
|
330
|
-
if client == "codex":
|
|
331
|
-
return ["codex", "mcp", "remove", SERVER]
|
|
332
|
-
raise ValueError(f"Client without MCP registration: {client!r}")
|
|
333
|
-
|
|
334
|
-
|
|
335
326
|
def status():
|
|
336
327
|
"""Last outcome per client: {"claude": {"state": "registered"|"unavailable"|"kept"|"undenied", "reason", "at"}}."""
|
|
337
328
|
try:
|
|
@@ -374,7 +365,22 @@ def _remove(client):
|
|
|
374
365
|
if client == "codex":
|
|
375
366
|
codex_config.remove_server(_codex_config(), SERVER)
|
|
376
367
|
else:
|
|
377
|
-
endpoint_sync.run_cli(remove_command(client))
|
|
368
|
+
endpoint_sync.run_cli(endpoint_sync.remove_command(client, SERVER))
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def unregister(client):
|
|
372
|
+
"""Takes the `playwright` MCP server Smart Tool registered (and, in Claude Code, its DENIED_TOOLS rules) out of the
|
|
373
|
+
client; a server the user registered is kept. Raises RuntimeError when it is still registered afterwards. Returns
|
|
374
|
+
a sentence saying what was done."""
|
|
375
|
+
if status().get(client, {}).get("state") not in ("registered", "undenied"):
|
|
376
|
+
return f"{client}: no {SERVER} server of Smart Tool's"
|
|
377
|
+
if registered().get(client):
|
|
378
|
+
_remove(client)
|
|
379
|
+
if registered().get(client):
|
|
380
|
+
raise RuntimeError(f"The {SERVER} server of {client} is still registered after removing it.")
|
|
381
|
+
if client == "claude":
|
|
382
|
+
set_claude_deny(False)
|
|
383
|
+
return f"{client}: {SERVER} server removed"
|
|
378
384
|
|
|
379
385
|
|
|
380
386
|
def ensure(client, log=None):
|
|
@@ -411,7 +417,7 @@ def ensure(client, log=None):
|
|
|
411
417
|
try:
|
|
412
418
|
_remove(client)
|
|
413
419
|
except (OSError, RuntimeError, ValueError) as removal:
|
|
414
|
-
return _record(client, "undenied", f"remove it with `{' '.join(remove_command(client))}`: {problem} "
|
|
420
|
+
return _record(client, "undenied", f"remove it with `{' '.join(endpoint_sync.remove_command(client, SERVER))}`: {problem} "
|
|
415
421
|
f"and removing it failed ({removal})"[:300], log)
|
|
416
422
|
return _record(client, "unavailable", f"{problem}, so the server was removed"[:300], log)
|
|
417
423
|
except (OSError, RuntimeError, ValueError) as exc:
|
package/client_hooks.py
CHANGED
|
@@ -284,6 +284,40 @@ def install(client_info, token, confirm):
|
|
|
284
284
|
"after_install": spec.get("after_install")}
|
|
285
285
|
|
|
286
286
|
|
|
287
|
+
def remove(client):
|
|
288
|
+
"""Takes every redirect hook entry of ours (PreToolUse, and the PostToolUse of Claude Code) out of the client's hooks
|
|
289
|
+
file after a backup; other hooks stay, in Codex at the approval of their new index. Returns {client, changed, file,
|
|
290
|
+
backup}."""
|
|
291
|
+
path = os.path.realpath(CLIENTS[client]["files"][0])
|
|
292
|
+
try:
|
|
293
|
+
with open(path, encoding="utf-8") as stream:
|
|
294
|
+
data = json.load(stream)
|
|
295
|
+
except FileNotFoundError:
|
|
296
|
+
return {"client": client, "changed": False, "file": path, "backup": None}
|
|
297
|
+
hooks = data.get("hooks") if isinstance(data, dict) else None
|
|
298
|
+
if not isinstance(hooks, dict):
|
|
299
|
+
raise ValueError(f"{path} does not have the expected format (object with 'hooks'); nothing was changed.")
|
|
300
|
+
moved = {}
|
|
301
|
+
spec = CLIENTS[client]
|
|
302
|
+
for event in (spec["event"], *(["PostToolUse"] if spec.get("post_matcher") else [])):
|
|
303
|
+
groups = hooks.get(event)
|
|
304
|
+
if not isinstance(groups, list) or not any(_ours(group) for group in groups):
|
|
305
|
+
continue
|
|
306
|
+
kept = _without_ours(groups)
|
|
307
|
+
moved[event] = (list(groups), kept)
|
|
308
|
+
if kept:
|
|
309
|
+
hooks[event] = kept
|
|
310
|
+
else:
|
|
311
|
+
del hooks[event]
|
|
312
|
+
if not moved:
|
|
313
|
+
return {"client": client, "changed": False, "file": path, "backup": None}
|
|
314
|
+
backup = _write_checked(path, data, lambda: inspect(client, trust=False)["state"] == "missing", "The removal")
|
|
315
|
+
if client == "codex":
|
|
316
|
+
for event, (before, kept) in moved.items():
|
|
317
|
+
record_codex_trust(_codex_trust(event, before, kept))
|
|
318
|
+
return {"client": client, "changed": True, "file": path, "backup": backup}
|
|
319
|
+
|
|
320
|
+
|
|
287
321
|
def _write_checked(path, data, verify, what):
|
|
288
322
|
"""Writes data as JSON to path through a temp file after a timestamped backup; when verify() fails on the written
|
|
289
323
|
file, restores the backup (or removes the new file) and raises. Returns the backup path (None for a new file)."""
|
package/endpoint_sync.py
CHANGED
|
@@ -130,12 +130,12 @@ def register_command(client, base):
|
|
|
130
130
|
raise ValueError(f"Client without MCP registration: {client!r}")
|
|
131
131
|
|
|
132
132
|
|
|
133
|
-
def remove_command(client):
|
|
134
|
-
"""Official CLI command that removes
|
|
133
|
+
def remove_command(client, server=SERVER):
|
|
134
|
+
"""Official CLI command that removes an MCP server a client holds (default: the smart-tool one)."""
|
|
135
135
|
if client == "claude":
|
|
136
|
-
return ["claude", "mcp", "remove",
|
|
136
|
+
return ["claude", "mcp", "remove", server, "--scope", "user"]
|
|
137
137
|
if client == "codex":
|
|
138
|
-
return ["codex", "mcp", "remove",
|
|
138
|
+
return ["codex", "mcp", "remove", server]
|
|
139
139
|
raise ValueError(f"Client without MCP registration: {client!r}")
|
|
140
140
|
|
|
141
141
|
|
|
@@ -164,6 +164,24 @@ def register(client, base):
|
|
|
164
164
|
return " ".join(command)
|
|
165
165
|
|
|
166
166
|
|
|
167
|
+
def unregister(client):
|
|
168
|
+
"""Removes the client's smart-tool MCP entry the way `register` made it (Claude Code through its CLI, Codex by
|
|
169
|
+
editing its table) and checks it is gone. Nothing runs when the client holds no entry. Returns what was done."""
|
|
170
|
+
if not registrations().get(client):
|
|
171
|
+
return f"nothing to remove: {client} holds no {SERVER} entry"
|
|
172
|
+
if client == "codex":
|
|
173
|
+
path = os.path.join(codex_dir(), "config.toml")
|
|
174
|
+
codex_config.remove_server(path, SERVER)
|
|
175
|
+
done = f"edited {path}: removed [mcp_servers.{SERVER}]"
|
|
176
|
+
else:
|
|
177
|
+
command = remove_command(client)
|
|
178
|
+
run_cli(command)
|
|
179
|
+
done = " ".join(command)
|
|
180
|
+
if registrations().get(client):
|
|
181
|
+
raise RuntimeError(f"{done} finished, but the {SERVER} entry is still in the client's configuration.")
|
|
182
|
+
return done
|
|
183
|
+
|
|
184
|
+
|
|
167
185
|
def cli_folders():
|
|
168
186
|
"""Where the native installers of the clients put their CLI, for a PATH that does not list them."""
|
|
169
187
|
home, local, roaming = os.path.expanduser("~"), os.environ.get("LOCALAPPDATA"), os.environ.get("APPDATA")
|
package/index_views.py
CHANGED
|
@@ -96,6 +96,8 @@ def _resolve(root, key):
|
|
|
96
96
|
view = {'root': key, 'git': False, 'view_id': 'workspace', 'label': 'Folder without Git',
|
|
97
97
|
'branch': None, 'commit': None}
|
|
98
98
|
if _git_marker(root):
|
|
99
|
+
if not os.path.isdir(root):
|
|
100
|
+
raise FileNotFoundError(f'The project folder no longer exists: {root}. Relocate or remove the project.')
|
|
99
101
|
if not shutil.which('git'):
|
|
100
102
|
raise RuntimeError('This folder contains Git, but the git executable is not available.')
|
|
101
103
|
paths = _run(root, 'rev-parse', '--path-format=absolute', '--show-toplevel', '--absolute-git-dir', '--git-common-dir').splitlines()
|
package/install.py
CHANGED
|
@@ -33,7 +33,7 @@ DEPENDENCY_STAMP = ".dependencies.sha256"
|
|
|
33
33
|
REGISTRY = Path(paths.DATA_DIR) / "daemon.json"
|
|
34
34
|
BLOCKED = {"__pycache__", ".token-guard", ".git", ".pytest_cache", ".data", ".artifacts", ".claude", ".vscode",
|
|
35
35
|
".impeccable", "tests", "sessions", "results", "dist", "node_modules", ".node-runtime", ".venv",
|
|
36
|
-
".scratch", ".memory", "docs", "reports", "site", "design", "release", "npm", ".github", "AGENTS.md", "CLAUDE.md", "DESIGN.md", "PRODUCT.md", "install.py", ".gitignore", ".gitattributes", MANIFEST}
|
|
36
|
+
".scratch", ".memory", "docs", "reports", "site", "design", "release", "npm", ".github", "AGENTS.md", "CLAUDE.md", "DESIGN.md", "PRODUCT.md", "install.py", "uninstall.py", ".gitignore", ".gitattributes", MANIFEST}
|
|
37
37
|
PACKAGE_ONLY = {"bin", "package.json", ".npmignore"}
|
|
38
38
|
REQUIRED_TOOLS = {"smart_search", "smart_search_result", "web_search", "project_manage"}
|
|
39
39
|
_OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
|
@@ -408,6 +408,7 @@ def main():
|
|
|
408
408
|
if args.expect_version and args.expect_version != version.VERSION:
|
|
409
409
|
raise SystemExit(f"This package is Smart Tool {version.VERSION}, not the {args.expect_version} requested; "
|
|
410
410
|
"nothing was changed.")
|
|
411
|
+
paths.refuse_overridden_folders("install")
|
|
411
412
|
target = args.target.resolve()
|
|
412
413
|
if target == SOURCE:
|
|
413
414
|
raise SystemExit("The target cannot be the source folder itself.")
|
package/package.json
CHANGED
|
@@ -1,35 +1,35 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@allansantos-dev/smart-tool",
|
|
3
|
-
"version": "0.9.
|
|
4
|
-
"description": "Local MCP server that gives coding agents (Claude Code, Codex) cheaper, sharper tools than their built-in search. Windows.",
|
|
5
|
-
"license": "Apache-2.0",
|
|
6
|
-
"author": "Smart Tool contributors",
|
|
7
|
-
"homepage": "https://allansantos-dv.github.io/smart-tool/",
|
|
8
|
-
"repository": {
|
|
9
|
-
"type": "git",
|
|
10
|
-
"url": "git+https://github.com/AllanSantos-DV/smart-tool-dist.git"
|
|
11
|
-
},
|
|
12
|
-
"keywords": [
|
|
13
|
-
"mcp",
|
|
14
|
-
"claude-code",
|
|
15
|
-
"codex",
|
|
16
|
-
"semantic-search",
|
|
17
|
-
"web-search",
|
|
18
|
-
"coding-agent"
|
|
19
|
-
],
|
|
20
|
-
"bin": {
|
|
21
|
-
"smart-tool": "bin/smart-tool.mjs"
|
|
22
|
-
},
|
|
23
|
-
"os": [
|
|
24
|
-
"win32"
|
|
25
|
-
],
|
|
26
|
-
"cpu": [
|
|
27
|
-
"x64"
|
|
28
|
-
],
|
|
29
|
-
"engines": {
|
|
30
|
-
"node": ">=18"
|
|
31
|
-
},
|
|
32
|
-
"publishConfig": {
|
|
33
|
-
"access": "public"
|
|
34
|
-
}
|
|
35
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "@allansantos-dev/smart-tool",
|
|
3
|
+
"version": "0.9.71",
|
|
4
|
+
"description": "Local MCP server that gives coding agents (Claude Code, Codex) cheaper, sharper tools than their built-in search. Windows.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"author": "Smart Tool contributors",
|
|
7
|
+
"homepage": "https://allansantos-dv.github.io/smart-tool/",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/AllanSantos-DV/smart-tool-dist.git"
|
|
11
|
+
},
|
|
12
|
+
"keywords": [
|
|
13
|
+
"mcp",
|
|
14
|
+
"claude-code",
|
|
15
|
+
"codex",
|
|
16
|
+
"semantic-search",
|
|
17
|
+
"web-search",
|
|
18
|
+
"coding-agent"
|
|
19
|
+
],
|
|
20
|
+
"bin": {
|
|
21
|
+
"smart-tool": "bin/smart-tool.mjs"
|
|
22
|
+
},
|
|
23
|
+
"os": [
|
|
24
|
+
"win32"
|
|
25
|
+
],
|
|
26
|
+
"cpu": [
|
|
27
|
+
"x64"
|
|
28
|
+
],
|
|
29
|
+
"engines": {
|
|
30
|
+
"node": ">=18"
|
|
31
|
+
},
|
|
32
|
+
"publishConfig": {
|
|
33
|
+
"access": "public"
|
|
34
|
+
}
|
|
35
|
+
}
|
package/paths.py
CHANGED
|
@@ -4,3 +4,42 @@ import os
|
|
|
4
4
|
|
|
5
5
|
HOME_DIR = os.path.join(os.path.expanduser("~"), ".smart-tool")
|
|
6
6
|
DATA_DIR = os.path.join(HOME_DIR, "data")
|
|
7
|
+
|
|
8
|
+
_KNOWN_FOLDERS = {"USERPROFILE": "{5E6C858F-0E22-4760-9AFE-EA3317B67173}",
|
|
9
|
+
"LOCALAPPDATA": "{F1B32785-6FBA-4FCF-9D55-7B8E7F157091}"}
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _windows_folder(folder_id):
|
|
13
|
+
"""The folder Windows itself reports for a known-folder id; it does not follow environment variables."""
|
|
14
|
+
import ctypes
|
|
15
|
+
import uuid
|
|
16
|
+
guid = uuid.UUID(folder_id)
|
|
17
|
+
raw = (ctypes.c_byte * 16).from_buffer_copy(guid.bytes_le)
|
|
18
|
+
out = ctypes.c_wchar_p()
|
|
19
|
+
if ctypes.windll.shell32.SHGetKnownFolderPath(ctypes.byref(raw), 0, None, ctypes.byref(out)) != 0:
|
|
20
|
+
raise OSError(f"Windows did not report the known folder {folder_id}.")
|
|
21
|
+
try:
|
|
22
|
+
return out.value
|
|
23
|
+
finally:
|
|
24
|
+
ctypes.windll.ole32.CoTaskMemFree(out)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def overridden_folders():
|
|
28
|
+
"""USERPROFILE and LOCALAPPDATA values that differ from the folders Windows reports for the user, as sentences.
|
|
29
|
+
The scheduler, the process table and the registry are machine-wide and ignore these variables, so a run under
|
|
30
|
+
redirected folders would still reach the real installation."""
|
|
31
|
+
found = []
|
|
32
|
+
for name, folder_id in _KNOWN_FOLDERS.items():
|
|
33
|
+
real, given = _windows_folder(folder_id), os.environ.get(name, "")
|
|
34
|
+
if os.path.normcase(os.path.normpath(given or real)) != os.path.normcase(os.path.normpath(real)):
|
|
35
|
+
found.append(f"{name}={given} (Windows reports {real})")
|
|
36
|
+
return found
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def refuse_overridden_folders(action):
|
|
40
|
+
"""Stops `action` (an installer or uninstaller run) before it changes anything when the user folders are redirected."""
|
|
41
|
+
found = overridden_folders()
|
|
42
|
+
if found:
|
|
43
|
+
raise SystemExit(f"Refusing to {action}: " + "; ".join(found) + ". The logon task, the running processes and the "
|
|
44
|
+
"registry are shared with the real installation, so the run would reach it. Run it with the "
|
|
45
|
+
"real user folders.")
|
package/project_scheduler.py
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
"""Fila justa entre raízes; jobs aguardando a mesma pasta não ocupam workers.
|
|
1
|
+
"""Fila justa entre raízes; jobs aguardando a mesma pasta não ocupam workers. Um job de prioridade maior passa à frente
|
|
2
|
+
dos de prioridade menor ainda na fila (o que já está rodando não é interrompido)."""
|
|
2
3
|
import collections
|
|
3
4
|
import concurrent.futures
|
|
4
5
|
import threading
|
|
@@ -15,21 +16,24 @@ class ProjectScheduler:
|
|
|
15
16
|
self._running = set()
|
|
16
17
|
self._closed = False
|
|
17
18
|
|
|
18
|
-
def submit(self, root, function, *args):
|
|
19
|
+
def submit(self, root, function, *args, priority=0):
|
|
19
20
|
key = project_identity.canonical_root(root)
|
|
20
21
|
future = concurrent.futures.Future()
|
|
21
22
|
with self._lock:
|
|
22
23
|
if self._closed:
|
|
23
24
|
raise RuntimeError("Project queue closed.")
|
|
24
|
-
self._queues.setdefault(key, collections.deque())
|
|
25
|
+
queue = self._queues.setdefault(key, collections.deque())
|
|
26
|
+
at = next((index for index, item in enumerate(queue) if item[3] < priority), len(queue))
|
|
27
|
+
queue.insert(at, (future, function, args, priority))
|
|
25
28
|
self._dispatch()
|
|
26
29
|
return future
|
|
27
30
|
|
|
28
31
|
def _dispatch(self):
|
|
29
32
|
while len(self._running) < self.workers:
|
|
30
|
-
|
|
31
|
-
if
|
|
33
|
+
waiting = [root for root in self._queues if root not in self._running]
|
|
34
|
+
if not waiting:
|
|
32
35
|
break
|
|
36
|
+
key = max(waiting, key=lambda root: self._queues[root][0][3])
|
|
33
37
|
task = self._queues[key].popleft()
|
|
34
38
|
if not self._queues[key]:
|
|
35
39
|
self._queues.pop(key)
|
|
@@ -39,7 +43,7 @@ class ProjectScheduler:
|
|
|
39
43
|
self._pool.submit(self._run, key, task)
|
|
40
44
|
|
|
41
45
|
def _run(self, key, task):
|
|
42
|
-
future, function, args = task
|
|
46
|
+
future, function, args, _priority = task
|
|
43
47
|
try:
|
|
44
48
|
if future.set_running_or_notify_cancel():
|
|
45
49
|
try:
|
|
@@ -55,7 +59,7 @@ class ProjectScheduler:
|
|
|
55
59
|
with self._lock:
|
|
56
60
|
self._closed = True
|
|
57
61
|
for queue in self._queues.values():
|
|
58
|
-
for future, _fn, _args in queue:
|
|
62
|
+
for future, _fn, _args, _priority in queue:
|
|
59
63
|
future.cancel()
|
|
60
64
|
self._queues.clear()
|
|
61
65
|
self._pool.shutdown(wait=wait, cancel_futures=True)
|
package/setup_audit.py
CHANGED
|
@@ -274,9 +274,7 @@ def collect_claude(project, snapshot):
|
|
|
274
274
|
plugins.append({"id": plugin_id, "path": root})
|
|
275
275
|
hook_file = os.path.join(root, "hooks", "hooks.json")
|
|
276
276
|
hooks += _hooks_from(snapshot.json(hook_file), f"plugin:{name}", hook_file, root)
|
|
277
|
-
|
|
278
|
-
mcp += _mcp_entries(plugin_mcp.get("mcpServers", plugin_mcp), f"plugin:{name}",
|
|
279
|
-
os.path.join(root, ".mcp.json"), f"plugin:{name}:", {"CLAUDE_PLUGIN_ROOT": root})
|
|
277
|
+
mcp += _claude_plugin_mcp(snapshot, root, name)
|
|
280
278
|
skills += [{**s, "name": f"{name}:{s['name']}"} for s in
|
|
281
279
|
_skills(snapshot, os.path.join(root, "skills"), f"plugin:{name}")]
|
|
282
280
|
instructions = []
|
|
@@ -290,6 +288,24 @@ def collect_claude(project, snapshot):
|
|
|
290
288
|
"instructions": instructions, "unapproved_mcp": unapproved}
|
|
291
289
|
|
|
292
290
|
|
|
291
|
+
def _claude_plugin_mcp(snapshot, root, name):
|
|
292
|
+
"""MCP server entries of a Claude Code plugin: its `.mcp.json`, plus the servers its manifest declares in
|
|
293
|
+
`.claude-plugin/plugin.json` (`mcpServers` as an inline object or as a path to a JSON file)."""
|
|
294
|
+
manifest_path = os.path.join(root, ".claude-plugin", "plugin.json")
|
|
295
|
+
declared = (snapshot.json(manifest_path) or {}).get("mcpServers")
|
|
296
|
+
sources = [(os.path.join(root, ".mcp.json"), None)]
|
|
297
|
+
if isinstance(declared, dict):
|
|
298
|
+
sources.append((manifest_path, declared))
|
|
299
|
+
elif isinstance(declared, str):
|
|
300
|
+
sources.append((os.path.join(root, declared), None))
|
|
301
|
+
entries = []
|
|
302
|
+
for path, inline in sources:
|
|
303
|
+
found = inline if inline is not None else (snapshot.json(path) or {})
|
|
304
|
+
entries += _mcp_entries(found.get("mcpServers", found), f"plugin:{name}", path, f"plugin:{name}:",
|
|
305
|
+
{"CLAUDE_PLUGIN_ROOT": root})
|
|
306
|
+
return entries
|
|
307
|
+
|
|
308
|
+
|
|
293
309
|
def _codex_plugin_root(market, name):
|
|
294
310
|
"""Newest installed version folder of a Codex plugin (`plugins/cache/<marketplace>/<name>/<version>/`), skipping
|
|
295
311
|
the `latest` alias unless it is all there is; None when the plugin is not in the cache."""
|
package/smart_tool_daemon.py
CHANGED
|
@@ -200,6 +200,8 @@ EDIT_INDEX_DELAY_S = 8
|
|
|
200
200
|
# p75 10.7 s).
|
|
201
201
|
SMART_SEARCH_RESULT_WAIT_S = 15
|
|
202
202
|
SMART_SEARCH_MAX_PENDING = 8
|
|
203
|
+
BACKGROUND_MAX_PENDING = 8
|
|
204
|
+
INTERACTIVE_PRIORITY = 1
|
|
203
205
|
SMART_SEARCH_EXECUTOR = project_scheduler.ProjectScheduler(workers=3)
|
|
204
206
|
_PROJECT_LOCKS = {}
|
|
205
207
|
_PROJECT_LOCKS_LOCK = threading.Lock()
|
|
@@ -369,7 +371,7 @@ SERVER_INSTRUCTIONS = (
|
|
|
369
371
|
TOOLS = [
|
|
370
372
|
{
|
|
371
373
|
"name": "project_manage",
|
|
372
|
-
"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. pr_impact (base, default HEAD; main or origin/main for a branch) returns a Markdown report of the change for a pull request: the functions the diff touches with their callers, the documentation entries it leaves out of date and the tests to run with their command; it publishes nothing. graph without symbol reads the indexed view: coverage, references and static calls in Java, Angular, Python, Go 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, Go doc comment starting with the name; private, nested and override functions excluded) with coverage percent, excluding tests unless include_tests=true, for documenting a project that started without it; docs generate=true writes the documentation scope to docs/scope in the project in three levels tied to the code: technical pages by folder (an entry per public function anchored on path::name with signature, first doc line, layer, callers, calls and tests, plus a Mermaid flow by layer), functional.md (each entry point and the functions its flow reaches, by layer) and simple.md; the prose between the prose markers is kept by regeneration; docs write_prose=true writes the empty prose blocks with the Docs model of the setup (each paragraph checked against the code first) within about 40 s and says how many are left, call it again until none is; docs check=true reports anchors whose function changed signature or is gone and broken links; docs validate=true checks every claim of docs/scope against the code (anchors, links, line numbers, callers and tests, coverage, entry points, command-line options, prose names, counts, glossary, navigation, versions) and writes docs/scope/validation.md with pass/fail per check, the evidence, a score and the verdict (generate runs it too); docs with symbol lists where that function is documented; layers declares the project's layers (ordered highest first, each with path globs and annotations): without layers it returns the saved rule or a suggestion read from folder names and annotations, with files, symbols and calls between layers (direction down or up); pass layers to preview a rule and the same layers with confirm=true to save it in the project (.smart-tool/layers.json); 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.",
|
|
374
|
+
"description": "Manages folders and indexing. Every action takes project_root (the folder) or project_id. list gives a short line per project (a project whose folder is gone shows as unavailable with the reason); status shows storage, scope and jobs, and with a path inside a registered project answers for the deepest one that holds it (resolved_from). 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. pr_impact (base, default HEAD; main or origin/main for a branch) returns a Markdown report of the change for a pull request: the functions the diff touches with their callers, the documentation entries it leaves out of date and the tests to run with their command; it publishes nothing. graph without symbol reads the indexed view: coverage, references and static calls in Java, Angular, Python, Go 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, Go doc comment starting with the name; private, nested and override functions excluded) with coverage percent, excluding tests unless include_tests=true, for documenting a project that started without it; docs generate=true writes the documentation scope to docs/scope in the project in three levels tied to the code: technical pages by folder (an entry per public function anchored on path::name with signature, first doc line, layer, callers, calls and tests, plus a Mermaid flow by layer), functional.md (each entry point and the functions its flow reaches, by layer) and simple.md; the prose between the prose markers is kept by regeneration; docs write_prose=true writes the empty prose blocks with the Docs model of the setup (each paragraph checked against the code first) within about 40 s and says how many are left, call it again until none is; docs check=true reports anchors whose function changed signature or is gone and broken links; docs validate=true checks every claim of docs/scope against the code (anchors, links, line numbers, callers and tests, coverage, entry points, command-line options, prose names, counts, glossary, navigation, versions) and writes docs/scope/validation.md with pass/fail per check, the evidence, a score and the verdict (generate runs it too); docs with symbol lists where that function is documented; layers declares the project's layers (ordered highest first, each with path globs and annotations): without layers it returns the saved rule or a suggestion read from folder names and annotations, with files, symbols and calls between layers (direction down or up); pass layers to preview a rule and the same layers with confirm=true to save it in the project (.smart-tool/layers.json); 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.",
|
|
373
375
|
"inputSchema": {
|
|
374
376
|
"type": "object", "properties": {
|
|
375
377
|
"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", "layers", "affected_tests", "pr_impact", "setup_audit", "redirect_proposals", "redirect_decide"]},
|
|
@@ -1223,6 +1225,24 @@ def _perform_smart_search(arguments, job_id):
|
|
|
1223
1225
|
return contextvars.copy_context().run(_perform_smart_search_isolated, arguments, job_id)
|
|
1224
1226
|
|
|
1225
1227
|
|
|
1228
|
+
def _nested_projects_note(root):
|
|
1229
|
+
"""Names the registered projects inside `root`: each keeps its own index, so a search of `root` does not cover
|
|
1230
|
+
their files. Returns None when there are none."""
|
|
1231
|
+
inner = project_store.nested_projects(root)
|
|
1232
|
+
if not inner:
|
|
1233
|
+
return None
|
|
1234
|
+
base = project_identity.display_root(root)
|
|
1235
|
+
parts = []
|
|
1236
|
+
for rel in inner[:8]:
|
|
1237
|
+
path = os.path.join(base, *rel.split("/"))
|
|
1238
|
+
files = indexer.info(path).get("files")
|
|
1239
|
+
parts.append(f"{rel} ({files} files): project_root=\"{path}\"" if files is not None else
|
|
1240
|
+
f"{rel} (not indexed yet): project_root=\"{path}\"")
|
|
1241
|
+
more = f" and {len(inner) - 8} more" if len(inner) > 8 else ""
|
|
1242
|
+
return (f"{len(inner)} registered project(s) inside this folder keep their own index and are not in these "
|
|
1243
|
+
f"results; search them with smart_search on their folder: {'; '.join(parts)}{more}.")
|
|
1244
|
+
|
|
1245
|
+
|
|
1226
1246
|
def _perform_smart_search_isolated(arguments, job_id):
|
|
1227
1247
|
_update_job(job_id, phase="auth")
|
|
1228
1248
|
problem = _gateway_problem()
|
|
@@ -1246,7 +1266,8 @@ def _perform_smart_search_isolated(arguments, job_id):
|
|
|
1246
1266
|
warnings.append(LOCAL_EMBEDDER_DOWN_WARNING if local_embedder.configured() and config.local_models_mode(cfg) != "off"
|
|
1247
1267
|
else LEXICAL_WARNING)
|
|
1248
1268
|
try:
|
|
1249
|
-
|
|
1269
|
+
if not arguments.get("_existing_index_only"):
|
|
1270
|
+
_prepare_project_index(arguments, job_id, cfg, token, model=model)
|
|
1250
1271
|
except ProjectJobCancelled:
|
|
1251
1272
|
raise
|
|
1252
1273
|
except Exception as exc:
|
|
@@ -1284,7 +1305,7 @@ def _perform_smart_search_isolated(arguments, job_id):
|
|
|
1284
1305
|
overlay, notice = _lag_overlay(root, lag)
|
|
1285
1306
|
source = "index+disk" if overlay else source
|
|
1286
1307
|
warnings += [text for text in (notice, _refresh_in_background(root, lag)) if text]
|
|
1287
|
-
|
|
1308
|
+
elif not arguments.get("_existing_index_only"):
|
|
1288
1309
|
try:
|
|
1289
1310
|
_prepare_project_index(arguments, job_id, cfg, token, query_vector=next(iter(vectors.values())),
|
|
1290
1311
|
model=model)
|
|
@@ -1367,12 +1388,15 @@ def _perform_smart_search_isolated(arguments, job_id):
|
|
|
1367
1388
|
_job_checkpoint(job_id)
|
|
1368
1389
|
if not any(blocks.values()):
|
|
1369
1390
|
notes.append(EMPTY_RESULT_NOTICE)
|
|
1391
|
+
nested = _nested_projects_note(root)
|
|
1392
|
+
if nested:
|
|
1393
|
+
notes.append(nested)
|
|
1370
1394
|
warning = " ".join(warnings)
|
|
1371
1395
|
if warning:
|
|
1372
1396
|
_update_job(job_id, warning=warning)
|
|
1373
1397
|
if arguments.get("_structured"):
|
|
1374
1398
|
return {"source": source if source == "cold" or vectors else "lexical index", "blocks": blocks,
|
|
1375
|
-
"warnings": warnings}
|
|
1399
|
+
"warnings": warnings + ([nested] if nested else [])}
|
|
1376
1400
|
return _grouped_yaml(index_profile.public(profile), blocks, " ".join(warnings + notes))
|
|
1377
1401
|
|
|
1378
1402
|
|
|
@@ -1484,8 +1508,12 @@ def _submit_project_job_locked(kind, arguments):
|
|
|
1484
1508
|
and value.get("status") == "pending" and value.get("request_key") == request_key), None)
|
|
1485
1509
|
if existing:
|
|
1486
1510
|
return existing, None
|
|
1487
|
-
|
|
1488
|
-
|
|
1511
|
+
interactive = kind == "smart_search"
|
|
1512
|
+
pending = sum(value.get("status") == "pending" and (value.get("kind") == "smart_search") == interactive
|
|
1513
|
+
for value in _jobs.values() if value.get("kind") in _PROJECT_KINDS)
|
|
1514
|
+
if pending >= (SMART_SEARCH_MAX_PENDING if interactive else BACKGROUND_MAX_PENDING):
|
|
1515
|
+
raise RuntimeError("Too many " + ("searches" if interactive else "index updates") +
|
|
1516
|
+
" in progress; wait for one to finish.")
|
|
1489
1517
|
payload = {"kind": kind, "project_id": project["id"], "status": "pending", "phase": "queued",
|
|
1490
1518
|
"created_at": time.time(), "request_key": request_key, "arguments": arguments,
|
|
1491
1519
|
"processed_files": None, "total_files": None, "result": None, "error": None}
|
|
@@ -1494,7 +1522,8 @@ def _submit_project_job_locked(kind, arguments):
|
|
|
1494
1522
|
project_store.update(project["id"], status="queued", last_job_id=job_id,
|
|
1495
1523
|
enabled=kind != "project_preview" or project.get("enabled", False))
|
|
1496
1524
|
try:
|
|
1497
|
-
future = SMART_SEARCH_EXECUTOR.submit(root, _run_project_job, job_id, arguments, kind
|
|
1525
|
+
future = SMART_SEARCH_EXECUTOR.submit(root, _run_project_job, job_id, arguments, kind,
|
|
1526
|
+
priority=INTERACTIVE_PRIORITY if interactive else 0)
|
|
1498
1527
|
with _JOBS_LOCK:
|
|
1499
1528
|
if not future.done():
|
|
1500
1529
|
_JOB_FUTURES[job_id] = future
|
|
@@ -2119,13 +2148,23 @@ def _with_project_id(arguments):
|
|
|
2119
2148
|
return arguments
|
|
2120
2149
|
wanted = project_identity.canonical_root(root)
|
|
2121
2150
|
match = next((p for p in project_store.all_projects() if project_identity.canonical_root(p["root"]) == wanted), None)
|
|
2122
|
-
if
|
|
2151
|
+
if match:
|
|
2152
|
+
return {**arguments, "project_id": match["id"]}
|
|
2153
|
+
inner = project_store.containing(root) if arguments.get("action") == "status" else None
|
|
2154
|
+
if not inner:
|
|
2123
2155
|
raise ValueError(f"No registered project at {root}; register it first (action=register).")
|
|
2124
|
-
return {**arguments, "project_id":
|
|
2156
|
+
return {**arguments, "project_id": inner["id"], "resolved_from": root}
|
|
2125
2157
|
|
|
2126
2158
|
|
|
2127
2159
|
def _project_summary(project):
|
|
2128
|
-
|
|
2160
|
+
"""One line of `list`. A project whose payload cannot be read (its folder was deleted, Git refuses it) is listed as
|
|
2161
|
+
unavailable with the reason, so one broken entry does not hide the others."""
|
|
2162
|
+
try:
|
|
2163
|
+
data = _project_payload(project)
|
|
2164
|
+
except Exception as exc:
|
|
2165
|
+
return {"project_id": project["id"], "name": project.get("name"), "root": project["root"],
|
|
2166
|
+
"status": "unavailable", "enabled": project.get("enabled"), "paused": project.get("paused"),
|
|
2167
|
+
"last_error": _project_error(exc)[:200]}
|
|
2129
2168
|
index = data.get("index") or {}
|
|
2130
2169
|
jobs = data.get("jobs") or []
|
|
2131
2170
|
return {"project_id": data["id"], "name": data.get("name"), "root": data["root"], "status": data.get("status"),
|
|
@@ -2325,6 +2364,9 @@ def _project_action_locked(arguments):
|
|
|
2325
2364
|
if not project:
|
|
2326
2365
|
raise ValueError("Project not registered.")
|
|
2327
2366
|
if action == "status":
|
|
2367
|
+
if arguments.get("resolved_from"):
|
|
2368
|
+
return {"project": _project_payload(project), "resolved_from": arguments["resolved_from"],
|
|
2369
|
+
"detail": "project_root is inside this registered project (the deepest one that holds it)."}
|
|
2328
2370
|
return {"project": _project_payload(project)}
|
|
2329
2371
|
if action == "search_limits":
|
|
2330
2372
|
if not isinstance(arguments.get("top_k"), dict):
|
|
@@ -4078,6 +4120,15 @@ def _cold_index_building(root):
|
|
|
4078
4120
|
and job.get("project_id") == project_id for job in _jobs.values())
|
|
4079
4121
|
|
|
4080
4122
|
|
|
4123
|
+
def _index_update_running(root):
|
|
4124
|
+
"""Whether an index update of the folder is queued or running. A search job of that folder would wait behind it in the
|
|
4125
|
+
per-folder queue, longer than a hook may wait."""
|
|
4126
|
+
project_id = project_identity.project_id(root)
|
|
4127
|
+
with _JOBS_LOCK:
|
|
4128
|
+
return any(job.get("kind") == "project_index" and job.get("status") == "pending"
|
|
4129
|
+
and job.get("project_id") == project_id for job in _jobs.values())
|
|
4130
|
+
|
|
4131
|
+
|
|
4081
4132
|
def _redirected_search(arguments):
|
|
4082
4133
|
"""smart_search text for a redirected native search, waiting up to SMART_SEARCH_SYNC_WAIT_S; raises when the search
|
|
4083
4134
|
is rejected, fails or is still running then. The hook's single_language_reason only passes the language check, it is
|
|
@@ -4087,6 +4138,8 @@ def _redirected_search(arguments):
|
|
|
4087
4138
|
checked.pop("single_language_reason", None)
|
|
4088
4139
|
if _cold_index_building(checked["project_root"]):
|
|
4089
4140
|
return f"{tool_redirect.search_notice(True)}\n{_perform_smart_search(checked, '')}"
|
|
4141
|
+
if _index_update_running(checked["project_root"]):
|
|
4142
|
+
return f"{tool_redirect.search_notice(True)}\n{_perform_smart_search({**checked, '_existing_index_only': True}, '')}"
|
|
4090
4143
|
job_id, _future = _submit_project_job("smart_search", checked)
|
|
4091
4144
|
deadline = time.monotonic() + SMART_SEARCH_SYNC_WAIT_S
|
|
4092
4145
|
payload = _smart_search_job_payload(job_id)
|
package/uninstall.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Silent uninstall: removes what install.py and the agent-side setup added, never a user's project folder.
|
|
3
|
+
|
|
4
|
+
Usage: python uninstall.py [--target DIR] [--keep-data] (npm: npx @allansantos-dev/smart-tool@<version> uninstall)
|
|
5
|
+
|
|
6
|
+
It never asks anything. Exit code 0 means everything is gone (or was never there); 1 means a step failed, each failure
|
|
7
|
+
named on stderr, and the steps that could run did run.
|
|
8
|
+
"""
|
|
9
|
+
import argparse
|
|
10
|
+
import os
|
|
11
|
+
import shutil
|
|
12
|
+
import subprocess
|
|
13
|
+
import sys
|
|
14
|
+
import time
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
import autostart
|
|
18
|
+
import browser_control
|
|
19
|
+
import client_hooks
|
|
20
|
+
import endpoint_sync
|
|
21
|
+
import install
|
|
22
|
+
import paths
|
|
23
|
+
|
|
24
|
+
CLIENTS = ("claude", "codex")
|
|
25
|
+
RUNTIME_DIR = Path(paths.HOME_DIR) / "runtime"
|
|
26
|
+
DELETE_RETRY_S = 15
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _delete(folder):
|
|
30
|
+
"""Deletes folder, retrying while a process that was just stopped still holds a file; raises the last OSError."""
|
|
31
|
+
deadline = time.monotonic() + DELETE_RETRY_S
|
|
32
|
+
while True:
|
|
33
|
+
try:
|
|
34
|
+
shutil.rmtree(folder)
|
|
35
|
+
return
|
|
36
|
+
except FileNotFoundError:
|
|
37
|
+
return
|
|
38
|
+
except OSError:
|
|
39
|
+
if time.monotonic() > deadline:
|
|
40
|
+
raise
|
|
41
|
+
time.sleep(0.5)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _inside(path, folder):
|
|
45
|
+
try:
|
|
46
|
+
return Path(path).resolve().is_relative_to(Path(folder).resolve())
|
|
47
|
+
except OSError:
|
|
48
|
+
return False
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _delete_after_exit(folders):
|
|
52
|
+
"""Windows cannot delete the interpreter that is running this script: a detached, windowless cmd removes folders
|
|
53
|
+
once the process has ended."""
|
|
54
|
+
commands = " & ".join(f'rmdir /s /q "{folder}"' for folder in folders)
|
|
55
|
+
subprocess.Popen(["cmd.exe", "/c", f"ping -n 4 127.0.0.1 >nul & {commands}"], stdin=subprocess.DEVNULL,
|
|
56
|
+
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
|
57
|
+
creationflags=subprocess.DETACHED_PROCESS | subprocess.CREATE_NO_WINDOW)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def remove_hooks():
|
|
61
|
+
"""Our hook entries (redirect and session-start) out of Claude Code's and Codex's hooks files."""
|
|
62
|
+
for client in CLIENTS:
|
|
63
|
+
for result in (client_hooks.remove(client), client_hooks.audit_remove(client)):
|
|
64
|
+
if result["changed"]:
|
|
65
|
+
print(f"Hooks removed from {result['file']} (backup {result['backup']}).")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def remove_registrations():
|
|
69
|
+
"""The smart-tool MCP entry, and the playwright one Smart Tool registered, out of each client."""
|
|
70
|
+
for client in CLIENTS:
|
|
71
|
+
print(endpoint_sync.unregister(client))
|
|
72
|
+
print(browser_control.unregister(client))
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def remove_state(keep_data):
|
|
76
|
+
"""~/.smart-tool: everything unless keep_data; the downloaded runtime always, afterwards when this very
|
|
77
|
+
interpreter runs from it."""
|
|
78
|
+
home = Path(paths.HOME_DIR)
|
|
79
|
+
if not home.is_dir():
|
|
80
|
+
return
|
|
81
|
+
pending = []
|
|
82
|
+
for entry in sorted(home.iterdir()):
|
|
83
|
+
if entry == RUNTIME_DIR:
|
|
84
|
+
if _inside(sys.executable, entry):
|
|
85
|
+
pending.append(entry)
|
|
86
|
+
else:
|
|
87
|
+
_delete(entry)
|
|
88
|
+
elif not keep_data:
|
|
89
|
+
_delete(entry) if entry.is_dir() else entry.unlink()
|
|
90
|
+
if not keep_data and not pending and not any(home.iterdir()):
|
|
91
|
+
home.rmdir()
|
|
92
|
+
if pending:
|
|
93
|
+
_delete_after_exit([home] if not keep_data else pending)
|
|
94
|
+
print(f"{pending[0]} is in use by this run; it is removed as soon as the run ends.")
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def run(target, keep_data):
|
|
98
|
+
"""Runs every step, collecting failures instead of stopping at the first. Returns the list of failure messages."""
|
|
99
|
+
failures = []
|
|
100
|
+
steps = [("stop the running Smart Tool", lambda: install.stop_processes(target)),
|
|
101
|
+
("remove the autostart", lambda: print("Autostart removed:", autostart.remove()["removed"])),
|
|
102
|
+
("remove the agent hooks", remove_hooks),
|
|
103
|
+
("remove the MCP registrations", remove_registrations)]
|
|
104
|
+
install.mark_updating(True)
|
|
105
|
+
try:
|
|
106
|
+
for name, step in steps:
|
|
107
|
+
try:
|
|
108
|
+
step()
|
|
109
|
+
except Exception as exc:
|
|
110
|
+
failures.append(f"Could not {name}: {type(exc).__name__}: {exc}")
|
|
111
|
+
if failures:
|
|
112
|
+
return failures
|
|
113
|
+
for name, step in (("delete the program folder", lambda: _delete(target)),
|
|
114
|
+
("delete the old copies beside it", lambda: install.prune_backups(target)),
|
|
115
|
+
("delete Smart Tool's state", lambda: remove_state(keep_data))):
|
|
116
|
+
try:
|
|
117
|
+
step()
|
|
118
|
+
except Exception as exc:
|
|
119
|
+
failures.append(f"Could not {name}: {type(exc).__name__}: {exc}")
|
|
120
|
+
finally:
|
|
121
|
+
if keep_data or failures:
|
|
122
|
+
install.mark_updating(False)
|
|
123
|
+
return failures
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def main():
|
|
127
|
+
parser = argparse.ArgumentParser(description="Uninstall Smart Tool silently.")
|
|
128
|
+
parser.add_argument("--target", type=Path, default=install.DEFAULT_TARGET)
|
|
129
|
+
parser.add_argument("--keep-data", action="store_true", help="keep ~/.smart-tool (settings, indexes, saved keys)")
|
|
130
|
+
args = parser.parse_args()
|
|
131
|
+
paths.refuse_overridden_folders("uninstall")
|
|
132
|
+
target = args.target.resolve()
|
|
133
|
+
if target == install.SOURCE:
|
|
134
|
+
raise SystemExit("The target cannot be the folder this script runs from.")
|
|
135
|
+
failures = run(target, args.keep_data)
|
|
136
|
+
for failure in failures:
|
|
137
|
+
print(failure, file=sys.stderr)
|
|
138
|
+
if failures:
|
|
139
|
+
raise SystemExit(1)
|
|
140
|
+
print(f"Smart Tool removed from {target}.")
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
if __name__ == "__main__":
|
|
144
|
+
main()
|
package/version.py
CHANGED