@allansantos-dev/smart-tool 0.9.75 → 0.9.77
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 +25 -0
- package/README.md +11 -3
- package/client_hooks.py +11 -1
- package/disk_cleanup.py +56 -23
- package/hook_decision.py +15 -0
- package/locales/pt-BR.json +1 -0
- package/package.json +1 -1
- package/project_admission.py +181 -0
- package/project_store.py +2 -1
- package/requester.py +29 -1
- package/smart_tool_daemon.py +43 -6
- package/version.py +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,30 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.9.77 - beta
|
|
4
|
+
|
|
5
|
+
- The Claude Code hooks Smart Tool writes name their owner and the file that holds their port: the two HTTP hook URLs
|
|
6
|
+
carry `hook-origin=smart-tool` and `port-file=~/.smart-tool/data/daemon.json` (the daemon's own announcement), so the
|
|
7
|
+
hook audit sees the owner and a managed port instead of a literal one, and the daemon's port move rewrites the URLs
|
|
8
|
+
with the parameters kept. An older entry shows as outdated and the update rewrites it. Tests:
|
|
9
|
+
`tests/test_endpoint_sync.py`.
|
|
10
|
+
|
|
11
|
+
## 0.9.76 - beta
|
|
12
|
+
|
|
13
|
+
- A project is only the folder where the agent session started. A new project is refused, with the reason and nothing
|
|
14
|
+
indexed, when its folder is a drive root, a personal folder (home, Desktop, Documents, Downloads and the OneDrive
|
|
15
|
+
copies), a system folder, application data, a hidden tool folder in the home folder, a build or dependency folder
|
|
16
|
+
(`bin`, `obj`, `node_modules`, `.git`) or a Java home. A subfolder of a registered project or of a Git repository is never a project of its own: it
|
|
17
|
+
resolves to the project or the repository, and a subfolder of the session's own folder resolves to that folder. Moving
|
|
18
|
+
a project (`relocate`) to a refused folder is refused too, and the setup audit skips the junk projects. The daemon learns the session's folder from the hook
|
|
19
|
+
`cwd` (first one wins) and, when it is known, indexes only that project from the session. A folder the agent merely
|
|
20
|
+
navigated to never becomes a project, and a raw search of such a folder runs natively instead of being redirected.
|
|
21
|
+
Registered projects always pass. Copilot has no hook route, so only the folder rules apply there.
|
|
22
|
+
- `project_manage action=junk` lists the registered projects that were never projects (a refused folder, a folder of
|
|
23
|
+
projects, a subfolder of a repository or of another project); with `confirm=true` it unregisters them and deletes their
|
|
24
|
+
index files, never the project's own files, and writes a manifest (`junk-manifests/junk-<time>.json`). The daily
|
|
25
|
+
cleanup applies the same test at daemon start. Research: `docs/research/2026-11-13-projeto-de-origem-da-sessao.md`.
|
|
26
|
+
Tests: `tests/test_project_admission.py`.
|
|
27
|
+
|
|
3
28
|
## 0.9.75 - beta
|
|
4
29
|
|
|
5
30
|
- The disk space card of each project marks the stale views itself: a view that is not pinned or active and was not
|
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.77 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.77 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
|
|
@@ -298,6 +298,14 @@ Redirects) and Maintenance (Setup audit, Startup).
|
|
|
298
298
|
by package: a file that imports a package depends on every file of it, so a changed package selects the tests of every
|
|
299
299
|
package that imports it (`go test ./pkg ...`); the Rust documentation and duplicate hooks stay silent.
|
|
300
300
|
|
|
301
|
+
**Which folder is a project**: only the folder where the agent session started (or the Git repository that holds
|
|
302
|
+
it). A drive root, a personal folder (home, Desktop, Documents), a system folder, application data, a hidden tool
|
|
303
|
+
folder in the home folder, `bin`, `obj`, `node_modules` and a Java home are refused with the reason and nothing is
|
|
304
|
+
indexed; a subfolder of a project or of a Git repository resolves to it; when the client sends its session folder, a folder the agent only navigated to is never registered (Copilot sends none, so only the folder rules apply).
|
|
305
|
+
`project_manage action=junk` lists the registered projects that break these rules; with `confirm=true` it
|
|
306
|
+
unregisters them and deletes their index files (never the project's own files) and writes a manifest in
|
|
307
|
+
`junk-manifests`. The daemon applies the same test at start.
|
|
308
|
+
|
|
301
309
|
`project_manage` with `action=setup_audit` and a `project_root` (or `python setup_audit.py --project <folder>`)
|
|
302
310
|
reports what Claude Code and Codex actually load for that folder (settings layers, enabled plugins of both,
|
|
303
311
|
hooks, MCP servers, skills, CLAUDE.md and AGENTS.md) and where they collide: several hooks deciding on the same tool in
|
|
@@ -382,7 +390,7 @@ fails to load is listed in the setup screen with its error and does not affect t
|
|
|
382
390
|
## Uninstall
|
|
383
391
|
|
|
384
392
|
```powershell
|
|
385
|
-
npx @allansantos-dev/smart-tool@0.9.
|
|
393
|
+
npx @allansantos-dev/smart-tool@0.9.77 uninstall [--target DIR] [--keep-data]
|
|
386
394
|
```
|
|
387
395
|
|
|
388
396
|
It asks nothing and opens no window. It stops the tray and the daemon, removes the logon task, the hook entries of Smart
|
package/client_hooks.py
CHANGED
|
@@ -242,6 +242,15 @@ def _command(client):
|
|
|
242
242
|
return f"{_shell_safe(sys.executable)} {_shell_safe(HOOK_SCRIPT)} --client {client} {HOOK_ORIGIN}"
|
|
243
243
|
|
|
244
244
|
|
|
245
|
+
def _port_file():
|
|
246
|
+
"""The daemon's announcement file as `~/<path>`, the form the hook audit reads to know the URL port is managed."""
|
|
247
|
+
relative = os.path.relpath(daemon_launcher.REGISTRY_PATH, os.path.expanduser("~")).replace("\\", "/")
|
|
248
|
+
if relative.startswith(".."):
|
|
249
|
+
raise ValueError(f"The daemon announcement ({daemon_launcher.REGISTRY_PATH}) is outside the home folder; "
|
|
250
|
+
"the hook cannot name it as its port file.")
|
|
251
|
+
return f"~/{relative}"
|
|
252
|
+
|
|
253
|
+
|
|
245
254
|
def _handler(client, route=HTTP_PATH, timeout=HTTP_TIMEOUT_S):
|
|
246
255
|
"""Claude Code posts the payload straight to the warm daemon (`type: "http"`, no process per tool call); other
|
|
247
256
|
clients run the thin command that forwards to the PreToolUse route."""
|
|
@@ -249,7 +258,8 @@ def _handler(client, route=HTTP_PATH, timeout=HTTP_TIMEOUT_S):
|
|
|
249
258
|
registry = daemon_launcher.read_registry()
|
|
250
259
|
if not registry or not registry.get("url"):
|
|
251
260
|
raise ValueError("Smart Tool daemon has no registered URL; start the daemon before installing the hook.")
|
|
252
|
-
|
|
261
|
+
query = f"client={client}&hook-origin={OWNER}&port-file={_port_file()}"
|
|
262
|
+
return {"type": "http", "url": f"{registry['url']}{route}?{query}", "timeout": timeout}
|
|
253
263
|
return {"type": "command", "command": _command(client), "timeout": timeout}
|
|
254
264
|
|
|
255
265
|
|
package/disk_cleanup.py
CHANGED
|
@@ -1,18 +1,23 @@
|
|
|
1
1
|
"""Removes what Smart Tool left on disk that no registered project needs.
|
|
2
2
|
|
|
3
|
-
Runs once when the daemon starts, before the project monitor: the registry of projects (a folder
|
|
4
|
-
never one of them), write temporaries orphaned by a crash, generations under construction that stopped advancing,
|
|
3
|
+
Runs once when the daemon starts, before the project monitor: the registry of projects (a folder that is not a
|
|
4
|
+
project, see project_admission.junk_reason, is never one of them, and each removal is listed in a manifest), write temporaries orphaned by a crash, generations under construction that stopped advancing,
|
|
5
5
|
the `.previous` copies older versions kept of a replaced generation, index files of projects no longer registered,
|
|
6
6
|
and saved code-graph analyses of index views that no longer exist. Source files are never touched."""
|
|
7
|
+
import json
|
|
7
8
|
import os
|
|
8
9
|
import re
|
|
9
10
|
import time
|
|
10
11
|
|
|
11
12
|
import atomic_io
|
|
12
13
|
import indexer
|
|
14
|
+
import paths
|
|
15
|
+
import project_admission
|
|
13
16
|
import project_identity
|
|
14
17
|
import project_store
|
|
15
18
|
|
|
19
|
+
MANIFEST_DIR = os.path.join(paths.DATA_DIR, "junk-manifests")
|
|
20
|
+
|
|
16
21
|
# A generation under construction resumes where it stopped; one untouched this long belongs to a model or scope that
|
|
17
22
|
# is no longer used, and a new one reuses the cached vectors anyway.
|
|
18
23
|
STALE_BUILD_S = 7 * 86400
|
|
@@ -53,33 +58,61 @@ def remove_project_files(root, report=None):
|
|
|
53
58
|
return report
|
|
54
59
|
|
|
55
60
|
|
|
61
|
+
def junk_projects(errors=None):
|
|
62
|
+
"""The registered projects that were never projects, as [{id, root, name, reason}], read-only: nothing is
|
|
63
|
+
removed. A project whose folder cannot be listed is left out and, when `errors` is a list, reported in it."""
|
|
64
|
+
found = []
|
|
65
|
+
for project in project_store.all_projects():
|
|
66
|
+
try:
|
|
67
|
+
reason = project_admission.junk_reason(project)
|
|
68
|
+
except OSError as exc:
|
|
69
|
+
if errors is not None:
|
|
70
|
+
errors.append(f"{project['root']}: {exc}")
|
|
71
|
+
continue
|
|
72
|
+
if reason:
|
|
73
|
+
found.append({"id": project["id"], "root": project["root"], "name": project.get("name"), "reason": reason})
|
|
74
|
+
return found
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def remove_junk(entries, log=None):
|
|
78
|
+
"""Unregisters the given junk projects and deletes their index files (never the project's own files), then writes
|
|
79
|
+
a manifest of what was removed and what was kept; returns {removed, kept, files, bytes, manifest}. A project whose
|
|
80
|
+
index another process holds open is kept and listed with the reason."""
|
|
81
|
+
log = log or (lambda message: None)
|
|
82
|
+
report = {"removed": [], "kept": [], "files": 0, "bytes": 0, "manifest": None}
|
|
83
|
+
for entry in entries:
|
|
84
|
+
files = {"files": [], "bytes": 0}
|
|
85
|
+
try:
|
|
86
|
+
remove_project_files(entry["root"], files)
|
|
87
|
+
except (RuntimeError, OSError) as exc:
|
|
88
|
+
report["kept"].append({**entry, "error": str(exc)})
|
|
89
|
+
log(f"disk cleanup: {entry['root']} kept: {exc}")
|
|
90
|
+
continue
|
|
91
|
+
project_store.forget(entry["id"])
|
|
92
|
+
report["removed"].append({**entry, "index_files": files["files"], "bytes": files["bytes"]})
|
|
93
|
+
report["files"] += len(files["files"])
|
|
94
|
+
report["bytes"] += files["bytes"]
|
|
95
|
+
log(f"disk cleanup: unregistered {entry['root']}: {entry['reason']}")
|
|
96
|
+
if report["removed"] or report["kept"]:
|
|
97
|
+
os.makedirs(MANIFEST_DIR, exist_ok=True)
|
|
98
|
+
report["manifest"] = os.path.join(MANIFEST_DIR, time.strftime("junk-%Y%m%d-%H%M%S.json"))
|
|
99
|
+
atomic_io.write_text(report["manifest"], json.dumps(
|
|
100
|
+
{"removed": report["removed"], "kept": report["kept"], "source_files_touched": False}, indent=1))
|
|
101
|
+
return report
|
|
102
|
+
|
|
103
|
+
|
|
56
104
|
def sweep(extra_roots, log=None):
|
|
57
|
-
"""Removes the waste described in the module docstring and returns {
|
|
105
|
+
"""Removes the waste described in the module docstring and returns {junk, files, bytes, errors}.
|
|
58
106
|
|
|
59
107
|
extra_roots are folders that own a vector cache without being projects (the web_fetch cache). A file that
|
|
60
108
|
cannot be removed, or a registered folder that cannot be listed, is reported in errors and logged, and the sweep
|
|
61
109
|
goes on with the rest: the daemon starts its project monitor right after, so the sweep must not stop it."""
|
|
62
110
|
log = log or (lambda message: None)
|
|
63
|
-
report = {"
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
refused = project_store.container_error(project["root"])
|
|
69
|
-
except OSError as exc:
|
|
70
|
-
report["errors"].append(f"{project['root']}: {exc}")
|
|
71
|
-
log(f"disk cleanup: {project['root']} not checked as a folder of projects: {exc}")
|
|
72
|
-
continue
|
|
73
|
-
if refused:
|
|
74
|
-
try:
|
|
75
|
-
remove_project_files(project["root"], report)
|
|
76
|
-
except RuntimeError as exc:
|
|
77
|
-
report["errors"].append(str(exc))
|
|
78
|
-
log(f"disk cleanup: {project['root']} kept: {exc}")
|
|
79
|
-
continue
|
|
80
|
-
project_store.forget(project["id"])
|
|
81
|
-
report["containers"].append(project["root"])
|
|
82
|
-
log(f"disk cleanup: unregistered {refused}")
|
|
111
|
+
report = {"junk": [], "files": [], "bytes": 0, "errors": []}
|
|
112
|
+
removal = remove_junk(junk_projects(report["errors"]), log)
|
|
113
|
+
report["bytes"] += removal["bytes"]
|
|
114
|
+
report["junk"] = [{"root": e["root"], "reason": e["reason"]} for e in removal["removed"]]
|
|
115
|
+
report["errors"] += [f"{e['root']}: {e['error']}" for e in removal["kept"]]
|
|
83
116
|
owners = [p["root"] for p in project_store.all_projects()] + list(extra_roots)
|
|
84
117
|
keep = {key for root in owners for key in (project_identity.project_id(root), *project_identity.legacy_ids(root))}
|
|
85
118
|
now = time.time()
|
package/hook_decision.py
CHANGED
|
@@ -27,6 +27,7 @@ import edit_preview
|
|
|
27
27
|
import index_profile
|
|
28
28
|
import index_scope
|
|
29
29
|
import endpoint_sync
|
|
30
|
+
import project_admission
|
|
30
31
|
import project_store
|
|
31
32
|
import redirect_rule
|
|
32
33
|
import requester
|
|
@@ -132,6 +133,16 @@ def _search_root(target, cwd):
|
|
|
132
133
|
return session if session and key.startswith(os.path.normcase(session).rstrip(os.sep) + os.sep) else target
|
|
133
134
|
|
|
134
135
|
|
|
136
|
+
def _indexable(target, cwd, session_id):
|
|
137
|
+
"""Whether the folder a search reads may be a Smart Tool project for this session; when not, the native tool runs
|
|
138
|
+
untouched instead of starting an index of a folder that is not the session's project."""
|
|
139
|
+
try:
|
|
140
|
+
project_admission.admit(_search_root(target, cwd), requester.session_origin(session_id))
|
|
141
|
+
except (ValueError, OSError):
|
|
142
|
+
return False
|
|
143
|
+
return True
|
|
144
|
+
|
|
145
|
+
|
|
135
146
|
def _tool_name(client, tool):
|
|
136
147
|
return f"mcp__{SMART_TOOL_SERVER}__{tool}" if client == "claude" else f"the {tool} tool of the {SMART_TOOL_SERVER} MCP server"
|
|
137
148
|
|
|
@@ -348,6 +359,8 @@ def decide(payload, client, web_route, jobs):
|
|
|
348
359
|
query cannot be built, or a client that sends no tool_use_id, is denied with the exact call to make, and never in a
|
|
349
360
|
subagent whose tool list has no Smart Tool MCP tool: it has nothing to switch to."""
|
|
350
361
|
cfg = config.load_config()
|
|
362
|
+
if isinstance(payload, dict):
|
|
363
|
+
requester.note_origin(payload.get("session_id"), payload.get("cwd"))
|
|
351
364
|
if isinstance(payload, dict) and payload.get("tool_name") in EDIT_TOOLS:
|
|
352
365
|
doc_mode, duplicate_mode, dependency_mode, comment_mode = (
|
|
353
366
|
config.doc_mode(cfg), config.duplicate_mode(cfg), config.dependency_mode(cfg), config.comment_mode(cfg))
|
|
@@ -506,6 +519,8 @@ def _route(payload, client, web_route, cfg):
|
|
|
506
519
|
return {"systemMessage": f"Smart Tool unavailable, routing skipped: {type(exc).__name__}"}
|
|
507
520
|
if tool_name in tool_redirect.NO_OP and tool_input.get("run_in_background"):
|
|
508
521
|
return {}
|
|
522
|
+
if decision in ("instruct", "redirect") and not _indexable(target, cwd, payload.get("session_id")):
|
|
523
|
+
return {}
|
|
509
524
|
if decision == "instruct":
|
|
510
525
|
if not agent_has_smart_tool(payload.get("agent_type") if payload.get("agent_id") else None, cwd):
|
|
511
526
|
return {}
|
package/locales/pt-BR.json
CHANGED
|
@@ -860,6 +860,7 @@
|
|
|
860
860
|
"Its {0} entry does not cover {1}.": "A entrada {0} dele não cobre {1}.",
|
|
861
861
|
"It calls {0} instead of {1}.": "Ele chama {0} em vez de {1}.",
|
|
862
862
|
"Its tool list is ordered or written differently from the current one.": "A lista de ferramentas dele está em outra ordem ou escrita de outro jeito que a atual.",
|
|
863
|
+
"The daemon announcement ({0}) is outside the home folder; the hook cannot name it as its port file.": "O anúncio do daemon ({0}) está fora da pasta do usuário; o hook não consegue nomeá-lo como seu arquivo de porta.",
|
|
863
864
|
"Path contains a space and has no 8.3 short name ({0}); the hook was not installed.": "O caminho tem um espaço e não tem nome curto 8.3 ({0}); o hook não foi instalado.",
|
|
864
865
|
"{0} does not have the expected format (object with 'hooks'); nothing was changed.": "{0} não tem o formato esperado (objeto com 'hooks'); nada foi alterado.",
|
|
865
866
|
"{0} does not appear in {1} after writing; the file was restored.": "{0} não aparece em {1} depois de gravar; o arquivo foi restaurado.",
|
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.77",
|
|
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": "Smart Tool contributors",
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
"""Which folder a call may turn into a project, and which registered projects were never one.
|
|
2
|
+
|
|
3
|
+
A project is the folder where the agent session started (or the repository that holds it), never a folder an agent
|
|
4
|
+
merely navigated to: personal folders, drive roots, application data, system folders, build output and a Java home
|
|
5
|
+
are refused, a subfolder resolves to the registered project or the repository that holds it, and a session whose
|
|
6
|
+
origin is known only indexes its own project. Registered folders that break these rules are junk (`junk_reason`)."""
|
|
7
|
+
import os
|
|
8
|
+
import tempfile
|
|
9
|
+
|
|
10
|
+
import project_identity
|
|
11
|
+
import project_store
|
|
12
|
+
|
|
13
|
+
PERSONAL_NAMES = ("Desktop", "Documents", "Downloads", "Pictures", "Videos", "Music")
|
|
14
|
+
TOOL_FOLDERS = frozenset(("bin", "obj", "node_modules", ".git", "site-packages", "__pycache__"))
|
|
15
|
+
POSIX_SYSTEM = ("/usr", "/bin", "/sbin", "/etc", "/var", "/opt", "/lib", "/proc", "/sys", "/dev", "/boot")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _norm(path):
|
|
19
|
+
return os.path.normcase(os.path.abspath(path))
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _inside(path, base):
|
|
23
|
+
return path == base or path.startswith(base.rstrip(os.sep) + os.sep)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _env_folders(*names):
|
|
27
|
+
return [_norm(os.environ[name]) for name in names if os.environ.get(name)]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _personal_folders():
|
|
31
|
+
"""Home, its OneDrive roots and the standard user folders in each, compared with normcase."""
|
|
32
|
+
home = _norm(os.path.expanduser("~"))
|
|
33
|
+
bases = [home]
|
|
34
|
+
try:
|
|
35
|
+
bases += [os.path.join(home, name) for name in os.listdir(home) if name.lower().startswith("onedrive")]
|
|
36
|
+
except OSError:
|
|
37
|
+
pass
|
|
38
|
+
return {_norm(path) for base in bases for path in (base, *(os.path.join(base, name) for name in PERSONAL_NAMES))}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _system_roots():
|
|
42
|
+
roots = _env_folders("SystemRoot", "ProgramFiles", "ProgramFiles(x86)", "ProgramW6432", "ProgramData")
|
|
43
|
+
return roots if os.name == "nt" else [_norm(path) for path in POSIX_SYSTEM]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _scratch_roots():
|
|
47
|
+
"""Where tests, scratch runs and the system temporary folder live, even though they sit under application data."""
|
|
48
|
+
roots = [_norm(tempfile.gettempdir()), *_env_folders("SMART_TOOL_SCRATCH")]
|
|
49
|
+
if os.environ.get("LOCALAPPDATA"):
|
|
50
|
+
roots.append(_norm(os.path.join(os.environ["LOCALAPPDATA"], "tmp")))
|
|
51
|
+
return roots
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _is_java_home(folder):
|
|
55
|
+
for launcher in ("java.exe", "java"):
|
|
56
|
+
if os.path.isfile(os.path.join(folder, "bin", launcher)) and (
|
|
57
|
+
os.path.isfile(os.path.join(folder, "release")) or os.path.isfile(os.path.join(folder, "lib", "modules"))):
|
|
58
|
+
return True
|
|
59
|
+
return False
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _ancestors(real):
|
|
63
|
+
"""`real` and every folder above it, nearest first."""
|
|
64
|
+
current = real
|
|
65
|
+
while True:
|
|
66
|
+
yield current
|
|
67
|
+
parent = os.path.dirname(current)
|
|
68
|
+
if parent == current:
|
|
69
|
+
return
|
|
70
|
+
current = parent
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def refusal(root):
|
|
74
|
+
"""Why root cannot be a project, or None: a drive or filesystem root, a personal folder, application data, a
|
|
75
|
+
system folder, a hidden tool folder in the home folder (`~/.claude`), a build or dependency folder, the temporary
|
|
76
|
+
folder itself, or a Java home (or inside one)."""
|
|
77
|
+
real = project_identity.display_root(root)
|
|
78
|
+
norm = _norm(real)
|
|
79
|
+
scratch = _scratch_roots()
|
|
80
|
+
if os.path.dirname(real) == real:
|
|
81
|
+
return "a drive or filesystem root"
|
|
82
|
+
if norm in _personal_folders():
|
|
83
|
+
return "a personal folder, not a project"
|
|
84
|
+
if norm == scratch[0]:
|
|
85
|
+
return "the temporary folder"
|
|
86
|
+
home = _norm(os.path.expanduser("~"))
|
|
87
|
+
if _inside(norm, home) and norm != home and os.path.relpath(norm, home).split(os.sep)[0].startswith("."):
|
|
88
|
+
return "inside a tool's hidden folder in the home folder"
|
|
89
|
+
if any(_inside(norm, base) for base in _system_roots()):
|
|
90
|
+
return "a system or application folder"
|
|
91
|
+
if (any(_inside(norm, base) for base in _env_folders("APPDATA", "LOCALAPPDATA", "LOCALAPPDATA_LOW"))
|
|
92
|
+
and not any(_inside(norm, base) for base in scratch)):
|
|
93
|
+
return "application data"
|
|
94
|
+
folder = next((part for part in real.replace("\\", "/").split("/") if part.lower() in TOOL_FOLDERS), None)
|
|
95
|
+
if folder:
|
|
96
|
+
return f"a build or dependency folder ({folder})"
|
|
97
|
+
java = _env_folders("JAVA_HOME")
|
|
98
|
+
if any(_inside(norm, base) for base in java) or any(_is_java_home(path) for path in _ancestors(real)):
|
|
99
|
+
return "a Java home"
|
|
100
|
+
return None
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def repository_root(path):
|
|
104
|
+
"""The nearest folder at or above path that holds `.git` and could be a project, or None. A repository the rules
|
|
105
|
+
refuse (a dotfiles repository in the home folder) is not a project to resolve to."""
|
|
106
|
+
for folder in _ancestors(project_identity.display_root(path)):
|
|
107
|
+
if os.path.exists(os.path.join(folder, ".git")):
|
|
108
|
+
return folder if refusal(folder) is None else None
|
|
109
|
+
return None
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _registered_holding(real):
|
|
113
|
+
"""The deepest registered project that is real or holds it, ignoring registered junk."""
|
|
114
|
+
base = project_identity.canonical_root(real)
|
|
115
|
+
holding = [p for p in project_store.all_projects()
|
|
116
|
+
if (base == (root := project_identity.canonical_root(p["root"])) or base.startswith(root + os.sep))
|
|
117
|
+
and junk_reason(p) is None]
|
|
118
|
+
return max(holding, key=lambda p: len(p["root"])) if holding else None
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def resolve(path):
|
|
122
|
+
"""(root, registered): the project path belongs to, from the registry first, then the repository that holds it,
|
|
123
|
+
else the folder itself."""
|
|
124
|
+
held = _registered_holding(path)
|
|
125
|
+
if held:
|
|
126
|
+
return project_identity.display_root(held["root"]), True
|
|
127
|
+
return repository_root(path) or project_identity.display_root(path), False
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def admit(path, origin=None):
|
|
131
|
+
"""The project root a call on `path` may use. A registered project (or a folder inside one) always passes; a new
|
|
132
|
+
project must not be refused by `refusal`, and when the session's `origin` folder is known it must be that
|
|
133
|
+
session's own project. Raises ValueError naming the reason and what to do."""
|
|
134
|
+
root, registered = resolve(path)
|
|
135
|
+
if registered:
|
|
136
|
+
return root
|
|
137
|
+
reason = refusal(root)
|
|
138
|
+
if reason:
|
|
139
|
+
raise ValueError(f"Not indexing {root}: it is {reason}. A project is the folder where the session started; "
|
|
140
|
+
"pass that folder as project_root.")
|
|
141
|
+
if origin:
|
|
142
|
+
home, _held = resolve(origin)
|
|
143
|
+
home_reason = refusal(home)
|
|
144
|
+
if home_reason:
|
|
145
|
+
raise ValueError(f"Not indexing {root}: the session started in {home}, which is {home_reason}, not a "
|
|
146
|
+
"project. Start the session inside the project folder.")
|
|
147
|
+
if _inside(_norm(root), _norm(home)):
|
|
148
|
+
return home
|
|
149
|
+
raise ValueError(f"Not indexing {root}: the session started in the project {home}, and a new project is "
|
|
150
|
+
"indexed only from the session that started in it.")
|
|
151
|
+
return root
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def junk_reason(project):
|
|
155
|
+
"""Why a registered project was never a project, or None: its folder is refused by `refusal`, it holds two or
|
|
156
|
+
more projects, or it is a subfolder of a repository or of another registered project."""
|
|
157
|
+
root = project["root"]
|
|
158
|
+
if not os.path.isdir(root):
|
|
159
|
+
return None
|
|
160
|
+
reason = refusal(root)
|
|
161
|
+
if reason:
|
|
162
|
+
return reason
|
|
163
|
+
if os.path.exists(os.path.join(root, ".git")):
|
|
164
|
+
return None
|
|
165
|
+
if project_store.container_error(root):
|
|
166
|
+
return "a folder of projects"
|
|
167
|
+
outer = repository_root(os.path.dirname(root))
|
|
168
|
+
if outer:
|
|
169
|
+
return f"a subfolder of the repository {outer}"
|
|
170
|
+
base = project_identity.canonical_root(root)
|
|
171
|
+
for other in project_store.all_projects():
|
|
172
|
+
folder = project_identity.canonical_root(other["root"])
|
|
173
|
+
if base.startswith(folder + os.sep) and junk_reason_shallow(other) is None:
|
|
174
|
+
return f"a subfolder of the project {other['root']}"
|
|
175
|
+
return None
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def junk_reason_shallow(project):
|
|
179
|
+
"""`junk_reason` without the subfolder rules: whether the registered folder could be a project on its own."""
|
|
180
|
+
root = project["root"]
|
|
181
|
+
return None if not os.path.isdir(root) else refusal(root)
|
package/project_store.py
CHANGED
|
@@ -323,6 +323,7 @@ def relocate(project_id, root):
|
|
|
323
323
|
def import_known_legacy(index_dir):
|
|
324
324
|
"""Somente raízes documentadas nos registros antigos; não adivinha diretórios."""
|
|
325
325
|
import indexer
|
|
326
|
+
import project_admission
|
|
326
327
|
candidates = set()
|
|
327
328
|
for name in ("daemon.log", "daemon.log.1"):
|
|
328
329
|
try:
|
|
@@ -335,7 +336,7 @@ def import_known_legacy(index_dir):
|
|
|
335
336
|
pass
|
|
336
337
|
for root in candidates:
|
|
337
338
|
key = project_identity.project_id(root)
|
|
338
|
-
if get(key) or not indexer.existing_db_path(root):
|
|
339
|
+
if get(key) or not indexer.existing_db_path(root) or project_admission.refusal(root):
|
|
339
340
|
continue
|
|
340
341
|
register(root, watch=False)
|
|
341
342
|
update(key, enabled=True, status="migration_required", legacy_discovered=True)
|
package/requester.py
CHANGED
|
@@ -14,6 +14,7 @@ import threading
|
|
|
14
14
|
import time
|
|
15
15
|
|
|
16
16
|
WEB_TOOLS = ("web_search", "web_fetch")
|
|
17
|
+
PROJECT_TOOLS = ("smart_search", "smart_scout", "project_manage")
|
|
17
18
|
NOTE_TTL_S = 60
|
|
18
19
|
MAX_NOTES = 256
|
|
19
20
|
MAX_BOUND = 256
|
|
@@ -22,16 +23,43 @@ CURRENT = contextvars.ContextVar("requester", default=None)
|
|
|
22
23
|
_LOCK = threading.Lock()
|
|
23
24
|
_NOTES = collections.OrderedDict()
|
|
24
25
|
_BOUND = collections.OrderedDict()
|
|
26
|
+
_ORIGIN = collections.OrderedDict()
|
|
25
27
|
|
|
26
28
|
|
|
27
29
|
def _key(tool, arguments):
|
|
28
30
|
return tool + "\0" + json.dumps(arguments, sort_keys=True, ensure_ascii=False, default=str)
|
|
29
31
|
|
|
30
32
|
|
|
33
|
+
def note_origin(session_id, cwd):
|
|
34
|
+
"""Remembers the first folder a client session was seen in: the SessionStart hook's `cwd`, else the first tool
|
|
35
|
+
call's. Later folders (the agent moving about) never replace it."""
|
|
36
|
+
if not isinstance(session_id, str) or not isinstance(cwd, str) or not session_id or not cwd:
|
|
37
|
+
return
|
|
38
|
+
with _LOCK:
|
|
39
|
+
_ORIGIN.setdefault(session_id, cwd)
|
|
40
|
+
while len(_ORIGIN) > MAX_BOUND:
|
|
41
|
+
_ORIGIN.popitem(last=False)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def session_origin(session_id):
|
|
45
|
+
"""The folder the client session started in, or None when no hook of that session was seen (a client without
|
|
46
|
+
hooks, or a session whose first tool call has not reached the hook yet)."""
|
|
47
|
+
with _LOCK:
|
|
48
|
+
return _ORIGIN.get(session_id)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def origin(mcp_session):
|
|
52
|
+
"""session_origin of the client session an MCP session was bound to by claim(), or None."""
|
|
53
|
+
with _LOCK:
|
|
54
|
+
bound = _BOUND.get(mcp_session)
|
|
55
|
+
return _ORIGIN.get(bound[0]) if bound else None
|
|
56
|
+
|
|
57
|
+
|
|
31
58
|
def note_hook(tool, arguments, session_id, cwd):
|
|
32
59
|
"""Remembers who the PreToolUse hook saw about to call `tool` with `arguments` (the MCP tool name without the
|
|
33
60
|
server prefix); claim() takes it back within NOTE_TTL_S."""
|
|
34
|
-
|
|
61
|
+
note_origin(session_id, cwd)
|
|
62
|
+
if tool not in WEB_TOOLS + PROJECT_TOOLS or not isinstance(arguments, dict):
|
|
35
63
|
return
|
|
36
64
|
entry = (time.monotonic(), session_id if isinstance(session_id, str) else None, cwd if isinstance(cwd, str) else None)
|
|
37
65
|
with _LOCK:
|
package/smart_tool_daemon.py
CHANGED
|
@@ -60,6 +60,7 @@ import scout
|
|
|
60
60
|
import embedding_cache
|
|
61
61
|
import model_defaults
|
|
62
62
|
import model_health
|
|
63
|
+
import project_admission
|
|
63
64
|
import project_identity
|
|
64
65
|
import project_store
|
|
65
66
|
import project_scheduler
|
|
@@ -372,10 +373,10 @@ SERVER_INSTRUCTIONS = (
|
|
|
372
373
|
TOOLS = [
|
|
373
374
|
{
|
|
374
375
|
"name": "project_manage",
|
|
375
|
-
"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; each view carries stale (not updated for 30 days, the test of the daily cleanup that removes them) and stale_bytes sums them; 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.",
|
|
376
|
+
"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; each view carries stale (not updated for 30 days, the test of the daily cleanup that removes them) and stale_bytes sums them; 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. junk (no project_root) lists the registered projects that were never projects: a personal, system, application-data or build folder, a subfolder of a repository or of another project, a folder of projects; with confirm=true it unregisters them and deletes only their index files, and the manifest says what went. A project is the folder where the session started, so smart_search and register refuse a folder that is not a project and index a new one only from the session that started in it. Jobs via smart_search_result.",
|
|
376
377
|
"inputSchema": {
|
|
377
378
|
"type": "object", "properties": {
|
|
378
|
-
"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"]},
|
|
379
|
+
"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", "junk"]},
|
|
379
380
|
"ids": {"type": "array", "items": {"type": "string"}, "description": "redirect_decide: proposal ids from redirect_proposals (accepted ids for remove)"},
|
|
380
381
|
"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"},
|
|
381
382
|
"finding_id": {"type": "string"},
|
|
@@ -1497,8 +1498,14 @@ def _submit_project_job(kind, arguments):
|
|
|
1497
1498
|
return _submit_project_job_locked(kind, arguments)
|
|
1498
1499
|
|
|
1499
1500
|
|
|
1501
|
+
def _admitted_root(path):
|
|
1502
|
+
"""The project root a call on `path` may use (see project_admission.admit), for the session this thread serves."""
|
|
1503
|
+
session = _MCP_SESSION.get()
|
|
1504
|
+
return project_admission.admit(path, requester.origin(session) if session else None)
|
|
1505
|
+
|
|
1506
|
+
|
|
1500
1507
|
def _submit_project_job_locked(kind, arguments):
|
|
1501
|
-
root =
|
|
1508
|
+
root = _admitted_root(arguments["project_root"])
|
|
1502
1509
|
arguments = {**arguments, "project_root": root}
|
|
1503
1510
|
arguments['_requested_view'] = index_views.public(index_views.describe(root, fresh=True))
|
|
1504
1511
|
project = project_store.register(root)
|
|
@@ -2176,11 +2183,34 @@ def _project_summary(project):
|
|
|
2176
2183
|
"last_error": (data.get("last_error") or None) and str(data["last_error"])[:200]}
|
|
2177
2184
|
|
|
2178
2185
|
|
|
2186
|
+
def _audited_roots():
|
|
2187
|
+
"""The registered project folders the setup audit visits: every one that is not junk."""
|
|
2188
|
+
junk = {entry["id"] for entry in disk_cleanup.junk_projects()}
|
|
2189
|
+
return [p["root"] for p in project_store.all_projects() if p.get("root") and p["id"] not in junk]
|
|
2190
|
+
|
|
2191
|
+
|
|
2192
|
+
def _junk_action(arguments):
|
|
2193
|
+
"""`junk` lists the registered projects that were never projects (a personal or system folder, a subfolder of
|
|
2194
|
+
a repository or of another project, a folder of projects); with confirm=true it unregisters them and deletes their
|
|
2195
|
+
index files, never the project's own files, and returns the path of the manifest. A project with a running job is
|
|
2196
|
+
kept and listed."""
|
|
2197
|
+
entries = disk_cleanup.junk_projects()
|
|
2198
|
+
if arguments.get("confirm") is not True:
|
|
2199
|
+
return {"junk": entries, "detail": "Nothing was removed. Pass confirm=true to unregister these and delete "
|
|
2200
|
+
"their index files (the folders themselves are never touched); a manifest lists the result."}
|
|
2201
|
+
busy = [entry for entry in entries if _active_project_jobs(entry["id"])]
|
|
2202
|
+
report = disk_cleanup.remove_junk([entry for entry in entries if entry not in busy], _log)
|
|
2203
|
+
report["kept"] += [{**entry, "error": "A job of this project is still running."} for entry in busy]
|
|
2204
|
+
return report
|
|
2205
|
+
|
|
2206
|
+
|
|
2179
2207
|
def _project_action(arguments):
|
|
2180
2208
|
if not isinstance(arguments, dict):
|
|
2181
2209
|
raise ValueError("Pass the action in a JSON object.")
|
|
2182
2210
|
if arguments.get("action") in ("redirect_proposals", "redirect_decide"):
|
|
2183
2211
|
return _redirect_action(arguments)
|
|
2212
|
+
if arguments.get("action") == "junk":
|
|
2213
|
+
return _junk_action(arguments)
|
|
2184
2214
|
if arguments.get("action") == "setup_audit":
|
|
2185
2215
|
root = arguments.get("project_root")
|
|
2186
2216
|
if not isinstance(root, str) or not os.path.isdir(root):
|
|
@@ -2356,7 +2386,7 @@ def _project_action_locked(arguments):
|
|
|
2356
2386
|
root = arguments.get("project_root")
|
|
2357
2387
|
if not isinstance(root, str) or not os.path.isabs(root):
|
|
2358
2388
|
raise ValueError("Pass the folder's absolute path.")
|
|
2359
|
-
project = project_store.register(root)
|
|
2389
|
+
project = project_store.register(_admitted_root(root))
|
|
2360
2390
|
return {"project": _project_payload(project)}
|
|
2361
2391
|
key = arguments.get("project_id")
|
|
2362
2392
|
if not isinstance(key, str) or not re.fullmatch(r"[a-f0-9]{16}", key):
|
|
@@ -2476,6 +2506,9 @@ def _project_action_locked(arguments):
|
|
|
2476
2506
|
if not isinstance(root, str) or not os.path.isabs(root) or not os.path.isdir(root):
|
|
2477
2507
|
raise ValueError("Pass the new absolute path of an existing folder.")
|
|
2478
2508
|
root = project_identity.display_root(root)
|
|
2509
|
+
reason = project_admission.refusal(root)
|
|
2510
|
+
if reason:
|
|
2511
|
+
raise ValueError(f"Not moving the project to {root}: it is {reason}.")
|
|
2479
2512
|
new_key = project_identity.project_id(root)
|
|
2480
2513
|
if new_key == key:
|
|
2481
2514
|
return {"project": _project_payload(project)}
|
|
@@ -4208,7 +4241,9 @@ def _session_audit_hook(handler):
|
|
|
4208
4241
|
say. The setup audit of a project reaches the agent on its first Smart Tool call there (`_project_notice`), so it
|
|
4209
4242
|
is told once per session and project."""
|
|
4210
4243
|
try:
|
|
4211
|
-
handler._read_body(HOOK_MAX_BODY_BYTES)
|
|
4244
|
+
started = json.loads(handler._read_body(HOOK_MAX_BODY_BYTES) or b"{}")
|
|
4245
|
+
if isinstance(started, dict):
|
|
4246
|
+
requester.note_origin(started.get("session_id"), started.get("cwd"))
|
|
4212
4247
|
except ValueError as exc:
|
|
4213
4248
|
_log(f"SessionStart hook body refused: {exc}")
|
|
4214
4249
|
updates = " ".join(notice for _key, notice in _update_notices())
|
|
@@ -4284,6 +4319,8 @@ def _dispatch_tool_call(params, session_id=None):
|
|
|
4284
4319
|
who = None
|
|
4285
4320
|
if name in requester.WEB_TOOLS:
|
|
4286
4321
|
who = requester.CURRENT.set(requester.claim(session_id, _session_client()[1].get("name"), name, arguments))
|
|
4322
|
+
elif name in requester.PROJECT_TOOLS:
|
|
4323
|
+
requester.claim(session_id, _session_client()[1].get("name"), name, arguments)
|
|
4287
4324
|
try:
|
|
4288
4325
|
with model_health.tool_call(name) as failures:
|
|
4289
4326
|
try:
|
|
@@ -4835,7 +4872,7 @@ def main():
|
|
|
4835
4872
|
_log(f"project monitor started; {recovered} interrupted job(s) recovered")
|
|
4836
4873
|
except Exception as exc:
|
|
4837
4874
|
_log(f"project monitor unavailable: {_project_error(exc)}")
|
|
4838
|
-
audit = setup_audit.Scheduler(
|
|
4875
|
+
audit = setup_audit.Scheduler(_audited_roots, _log)
|
|
4839
4876
|
audit.start()
|
|
4840
4877
|
try:
|
|
4841
4878
|
server.serve_forever()
|
package/version.py
CHANGED