@allansantos-dev/smart-tool 0.9.74 → 0.9.76

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 CHANGED
@@ -1,5 +1,30 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.9.76 - beta
4
+
5
+ - A project is only the folder where the agent session started. A new project is refused, with the reason and nothing
6
+ indexed, when its folder is a drive root, a personal folder (home, Desktop, Documents, Downloads and the OneDrive
7
+ copies), a system folder, application data, a hidden tool folder in the home folder, a build or dependency folder
8
+ (`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
9
+ resolves to the project or the repository, and a subfolder of the session's own folder resolves to that folder. Moving
10
+ 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
11
+ `cwd` (first one wins) and, when it is known, indexes only that project from the session. A folder the agent merely
12
+ navigated to never becomes a project, and a raw search of such a folder runs natively instead of being redirected.
13
+ Registered projects always pass. Copilot has no hook route, so only the folder rules apply there.
14
+ - `project_manage action=junk` lists the registered projects that were never projects (a refused folder, a folder of
15
+ projects, a subfolder of a repository or of another project); with `confirm=true` it unregisters them and deletes their
16
+ index files, never the project's own files, and writes a manifest (`junk-manifests/junk-<time>.json`). The daily
17
+ cleanup applies the same test at daemon start. Research: `docs/research/2026-11-13-projeto-de-origem-da-sessao.md`.
18
+ Tests: `tests/test_project_admission.py`.
19
+
20
+ ## 0.9.75 - beta
21
+
22
+ - The disk space card of each project marks the stale views itself: a view that is not pinned or active and was not
23
+ updated for 30 days shows "Stale" in its Protection column, and a "Stale views" total gives their size and count. The
24
+ inventory (`project_manage action=storage`) carries `stale` per view plus `stale_bytes` and `stale_after_days`, using the
25
+ same test as the daily cleanup (`project_storage.stale_view_ids`). The card's note now says the daily cleanup removes
26
+ stale views instead of "Cleanup is manual". No notification is sent for it. Tests: `tests/test_storage_auto_cleanup.py`.
27
+
3
28
  ## 0.9.74 - beta
4
29
 
5
30
  - The agent's browser (the Playwright MCP server Smart Tool registers) is marked by its User-Agent, which ends with
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.74 beta. Windows only. What changed in each version: [CHANGELOG.md](CHANGELOG.md).
20
+ **Status:** 0.9.76 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.74 install
86
+ npx @allansantos-dev/smart-tool@0.9.76 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.74 uninstall [--target DIR] [--keep-data]
393
+ npx @allansantos-dev/smart-tool@0.9.76 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/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 of projects is
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 {containers, files, bytes, errors}.
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 = {"containers": [], "files": [], "bytes": 0, "errors": []}
64
- for project in project_store.all_projects():
65
- if not os.path.isdir(project["root"]):
66
- continue
67
- try:
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 {}
@@ -433,7 +433,12 @@
433
433
  "Local counts and usage reported by the gateway. No query text is saved in this telemetry.": "Contagens locais e uso informado pelo gateway. Nenhum texto de consulta é salvo nesta telemetria.",
434
434
  "Disk space and view cleanup": "Espaço em disco e limpeza de visões",
435
435
  "Refresh inventory": "Atualizar inventário",
436
- "The active view and pinned views are protected. Cleanup is manual and removes only Smart Tool indexes and cache.": "A visão ativa e as visões fixadas são protegidas. A limpeza é manual e remove apenas índices e cache do Smart Tool.",
436
+ "The active view, pinned views and the last available view are protected. Stale views are removed by a daily cleanup; you can also remove views here. Only Smart Tool indexes and cache are removed.": "A visão ativa, as fixadas e a última disponível são protegidas. As visões obsoletas são removidas por uma limpeza diária; você também pode removê-las aqui. Só índices e cache do Smart Tool são removidos.",
437
+ "Stale views": "Visões obsoletas",
438
+ "not updated for": "sem atualização há",
439
+ "Stale: not updated for": "Obsoleta: sem atualização há",
440
+ "{0} not updated for {1} days": "{0} sem atualização há {1} dias",
441
+ "Stale: not updated for {0} days": "Obsoleta: sem atualização há {0} dias",
437
442
  "Also clear vectors no longer used by the stored generations": "Limpar também os vetores que as gerações guardadas não usam mais",
438
443
  "Preview selected cleanup": "Pré-visualizar a limpeza selecionada",
439
444
  "Confirm removal of this preview": "Confirmar a remoção desta pré-visualização",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@allansantos-dev/smart-tool",
3
- "version": "0.9.74",
3
+ "version": "0.9.76",
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)
@@ -6,7 +6,7 @@ STYLE=r'''
6
6
  HTML=r'''
7
7
  <details class="insights-panel" id="usage-panel"><summary>Usage and reuse by project and view</summary>
8
8
  <div class="insights-controls"><div><label for="usage-days">Period</label><select id="usage-days"><option value="7">7 days</option><option value="30" selected>30 days</option><option value="90">90 days</option><option value="366">1 year</option></select></div><div><label for="usage-view">View</label><select id="usage-view"><option value="">All</option></select></div><button id="usage-load">Refresh usage</button></div><p id="usage-message" class="insights-note">Local counts and usage reported by the gateway. No query text is saved in this telemetry.</p><div id="usage-summary" class="insights-summary"></div><div id="usage-table" class="insights-table-wrap"></div><div id="usage-indexing" class="insights-table-wrap"></div></details>
9
- <details class="insights-panel" id="storage-panel"><summary>Disk space and view cleanup</summary><div class="insights-controls"><button id="storage-load">Refresh inventory</button></div><p class="insights-note">The active view and pinned views are protected. Cleanup is manual and removes only Smart Tool indexes and cache.</p><div id="storage-summary" class="insights-summary"></div><div id="storage-table" class="insights-table-wrap"></div><label class="check-label"><input id="cleanup-cache" type="checkbox" checked>Also clear vectors no longer used by the stored generations</label><div class="actions"><button id="cleanup-preview" disabled>Preview selected cleanup</button></div><div id="cleanup-plan" class="cleanup-preview" hidden></div><button id="cleanup-apply" class="danger" hidden>Confirm removal of this preview</button><p id="storage-message" class="insights-note"></p></details>
9
+ <details class="insights-panel" id="storage-panel"><summary>Disk space and view cleanup</summary><div class="insights-controls"><button id="storage-load">Refresh inventory</button></div><p class="insights-note">The active view, pinned views and the last available view are protected. Stale views are removed by a daily cleanup; you can also remove views here. Only Smart Tool indexes and cache are removed.</p><div id="storage-summary" class="insights-summary"></div><div id="storage-table" class="insights-table-wrap"></div><label class="check-label"><input id="cleanup-cache" type="checkbox" checked>Also clear vectors no longer used by the stored generations</label><div class="actions"><button id="cleanup-preview" disabled>Preview selected cleanup</button></div><div id="cleanup-plan" class="cleanup-preview" hidden></div><button id="cleanup-apply" class="danger" hidden>Confirm removal of this preview</button><p id="storage-message" class="insights-note"></p></details>
10
10
  <details class="insights-panel" id="compare-panel"><summary>Compare two stored views</summary><p class="insights-note">The comparison uses the index content, with no checkout and no new embeddings. Scope differences can also show up as added or removed files.</p><button id="compare-load-views">Load views</button><div class="insights-views"><div><label for="compare-left">View A · base</label><select id="compare-left"></select></div><div><label for="compare-right">View B · compare with A</label><select id="compare-right"></select></div></div><label class="check-label"><input id="compare-relations" type="checkbox" checked>Also compare resolved references and static calls</label><div class="actions"><button id="compare-run" disabled>Compare A → B</button></div><p id="compare-message" class="insights-note"></p><div id="compare-summary" class="insights-summary"></div><div id="compare-files" class="insights-table-wrap"></div><div id="compare-graph"></div><h3 id="compare-file-title"></h3><pre id="compare-diff" class="comparison-diff"></pre></details>
11
11
  '''
12
12
  SCRIPT=r'''
@@ -20,7 +20,7 @@ window.SmartInsights=(()=>{
20
20
  function clearPlan(){plan=null;$i('cleanup-plan').hidden=true;$i('cleanup-apply').hidden=true;$i('cleanup-preview').disabled=!document.querySelector('#storage-table input[data-storage]:checked')}
21
21
  function reset(){sequence++;storage=null;comparison=null;plan=null;for(const id of ['usage-summary','usage-table','usage-indexing','storage-summary','storage-table','storage-message','compare-summary','compare-files','compare-graph','compare-file-title','compare-diff','compare-message'])$i(id).replaceChildren();$i('usage-view').replaceChildren(new Option('All',''));$i('compare-left').replaceChildren();$i('compare-right').replaceChildren();$i('compare-run').disabled=true;clearPlan();for(const id of ['usage-load','storage-load','compare-load-views'])$i(id).disabled=false;$i('usage-message').textContent='Refresh the usage of this project. The telemetry stores only counts and metadata.'}
22
22
  async function loadUsage(key,valid){const requestedDays=$i('usage-days').value,requestedView=$i('usage-view').value;const data=await api({action:'usage',project_id:key,days:Number($i('usage-days').value),...($i('usage-view').value?{view_id:$i('usage-view').value}:{})});if(!valid()||requestedDays!==$i('usage-days').value||requestedView!==$i('usage-view').value)return;const t=data.totals,old=$i('usage-view').value,views=new Map();for(const row of [...data.daily,...data.indexing])views.set(row.view_id,row.view_label);if(!old)$i('usage-view').replaceChildren(new Option('All',''),...Array.from(views,([id,label])=>new Option(label||id,id)));summary($i('usage-summary'),[['Call attempts',count(t.attempts),count(t.errors)+' with errors'],['Reported tokens',t.token_reports?count((t.prompt_tokens||0)+(t.output_tokens||0)):'Not reported',count(t.token_reports)+' of '+count(t.attempts)+' calls with data'],['Cost reported by the gateway',t.reported_usd==null?'Not reported':new Intl.NumberFormat('en-US',{style:'currency',currency:'USD',maximumFractionDigits:6}).format(t.reported_usd),count(t.price_reports)+' calls with a cost; not the full bill'],['Chunks sent / cache',count(data.indexing.reduce((s,r)=>s+r.embedded_chunks,0))+' / '+count(data.indexing.reduce((s,r)=>s+r.reused_chunks,0)),'Unchanged files are counted separately']]);$i('usage-message').textContent='Loaded period: '+data.days+' days (UTC). '+data.notes.join(' ');$i('usage-table').innerHTML=table(['Date UTC','View / step','Model','Attempts','Reported tokens','Measured characters'],data.daily.slice(0,200).map(r=>[esc(r.day),esc(r.view_label)+'<br>'+esc(phaseNames[r.purpose]||r.purpose),esc(r.model),count(r.attempts),r.token_reports?count(r.prompt_tokens+r.output_tokens):'Not reported',count(r.input_characters)]));$i('usage-indexing').innerHTML=table(['View','Indexing jobs','Chunks sent','Cache reuse','Unchanged files'],data.indexing.map(r=>[esc(r.view_label),count(r.jobs),count(r.embedded_chunks),count(r.reused_chunks),count(r.unchanged_files)]))}
23
- function renderStorage(data){storage=data;clearPlan();summary($i('storage-summary'),[['SQLite indexes',size(data.total_bytes)],['Vector cache',size(data.cache_bytes)],['Auxiliary generations',size(data.auxiliary_bytes)],['Stored views',count(data.views.length),'Active and pinned views are protected']]);$i('storage-table').innerHTML=table(['Clear','View','Space','Protection'],data.views.map(v=>[`<input type="checkbox" data-storage="${esc(v.storage_id)}" aria-label="Select ${esc(v.label)} for cleanup" ${v.protected?'disabled':''}>`,esc(v.label)+'<br><small>'+esc(v.commit?.slice(0,10)||'Commit not recorded')+'</small>',size(v.bytes),esc(v.protected_reason||'Can be selected')+`<br><button data-pin="${esc(v.storage_id)}" data-pinned="${v.pinned?'1':'0'}">${v.pinned?'Unpin':'Pin'}</button>`]));$i('storage-message').textContent=data.views.length?'Choose the old views and check the preview before removing.':'No stored views in this project.';clearPlan()}
23
+ function renderStorage(data){storage=data;clearPlan();summary($i('storage-summary'),[['SQLite indexes',size(data.total_bytes)],['Vector cache',size(data.cache_bytes)],['Auxiliary generations',size(data.auxiliary_bytes)],['Stored views',count(data.views.length),'Active and pinned views are protected'],['Stale views',size(data.stale_bytes),count(data.views.filter(v=>v.stale).length)+' not updated for '+data.stale_after_days+' days']]);$i('storage-table').innerHTML=table(['Clear','View','Space','Protection'],data.views.map(v=>[`<input type="checkbox" data-storage="${esc(v.storage_id)}" aria-label="Select ${esc(v.label)} for cleanup" ${v.protected?'disabled':''}>`,esc(v.label)+'<br><small>'+esc(v.commit?.slice(0,10)||'Commit not recorded')+'</small>',size(v.bytes),esc(v.protected_reason||(v.stale?'Stale: not updated for '+data.stale_after_days+' days':'Can be selected'))+`<br><button data-pin="${esc(v.storage_id)}" data-pinned="${v.pinned?'1':'0'}">${v.pinned?'Unpin':'Pin'}</button>`]));$i('storage-message').textContent=data.views.length?'Choose the old views and check the preview before removing.':'No stored views in this project.';clearPlan()}
24
24
  async function loadStorage(key,valid){const data=await api({action:'storage',project_id:key});if(valid())renderStorage(data)}
25
25
  $i('usage-load').onclick=()=>run($i('usage-load'),loadUsage);$i('usage-days').onchange=()=>run($i('usage-load'),loadUsage);$i('usage-view').onchange=()=>run($i('usage-load'),loadUsage);$i('storage-load').onclick=()=>run($i('storage-load'),loadStorage);
26
26
  $i('storage-table').onchange=clearPlan;$i('cleanup-cache').onchange=clearPlan;
@@ -36,7 +36,20 @@ def _stamp(path):
36
36
  stat=os.stat(path);return [stat.st_size,stat.st_mtime_ns,stat.st_ino]
37
37
 
38
38
 
39
- def inventory(project):
39
+ def _is_stale(row,now):
40
+ return not row['protected'] and bool(row.get('updated_at')) and now-row['updated_at']>STALE_VIEW_S
41
+
42
+
43
+ def _view_files(storage_id,assets):
44
+ """Paths of a view's database and its `.previous` and `.building-*` generations."""
45
+ stem=storage_id[:-8]
46
+ return [path for name,path in assets.items() if name==storage_id or re.fullmatch(re.escape(stem)+r'(?:\.previous|\.building-[a-f0-9]+)\.sqlite3',name)]
47
+
48
+
49
+ def inventory(project,now=None):
50
+ """Disk use of the project's indexes and vector cache, one row per stored view; `stale` marks the unprotected
51
+ views the daily cleanup removes."""
52
+ now=time.time() if now is None else now
40
53
  root=project['root'];views=index_inventory.views(root);assets=_assets(root)
41
54
  active=indexer.existing_db_path(root)
42
55
  for view in views:view['current']=bool(active and os.path.normcase(view['path'])==os.path.normcase(active))
@@ -46,12 +59,13 @@ def inventory(project):
46
59
  for view in views:
47
60
  row={**view,'storage_id':Path(view['path']).name,'pinned':view['view_id'] in pins}
48
61
  row['protected_reason']='Active view' if view['current'] else 'Pinned view' if row['pinned'] else 'Last available view; the active branch has no index' if view['path']==fallback else ''
49
- row['protected']=bool(row['protected_reason']);rows.append(row)
62
+ row['protected']=bool(row['protected_reason']);row['stale']=_is_stale(row,now);rows.append(row)
50
63
  total=sum(os.path.getsize(path) for path in assets.values())
51
64
  cache_path=Path(indexer.INDEX_DIR)/(project_identity.project_id(root)+'.vectors.sqlite3')
52
65
  return {'views':rows,'total_bytes':total,'cache_bytes':cache_path.stat().st_size if cache_path.exists() else 0,
53
66
  'auxiliary_bytes':max(0,total-sum(v['bytes'] for v in rows)-(cache_path.stat().st_size if cache_path.exists() else 0)),
54
- 'cleanup':'manual','source_files_untouched':True}
67
+ 'stale_bytes':sum(os.path.getsize(path) for v in rows if v['stale'] for path in _view_files(v['storage_id'],assets)),'stale_after_days':STALE_VIEW_S//86400,
68
+ 'source_files_untouched':True}
55
69
 
56
70
 
57
71
  def pin(project,storage_id,pinned):
@@ -98,7 +112,7 @@ def preview(project,storage_ids,clear_cache=True):
98
112
  if row['protected']:raise ValueError(row['label']+': '+row['protected_reason']+'.')
99
113
  selected.append(row)
100
114
  stem=storage_id[:-8]
101
- removed.extend(path for name,path in assets.items() if name==storage_id or re.fullmatch(re.escape(stem)+r'(?:\.previous|\.building-[a-f0-9]+)\.sqlite3',name))
115
+ removed.extend(_view_files(storage_id,assets))
102
116
  if '.v-' in stem:
103
117
  scope=Path(index_scope.SCOPE_DIR)/(stem+'.scope.json')
104
118
  if scope.is_file():removed.append(str(scope))
@@ -121,8 +135,7 @@ def preview(project,storage_ids,clear_cache=True):
121
135
  def stale_view_ids(project,now=None):
122
136
  """Storage ids of the views of `project` that are not protected and were last updated over STALE_VIEW_S ago."""
123
137
  now=time.time() if now is None else now
124
- return [v['storage_id'] for v in inventory(project)['views']
125
- if not v['protected'] and v.get('updated_at') and now-v['updated_at']>STALE_VIEW_S]
138
+ return [v['storage_id'] for v in inventory(project,now)['views'] if v['stale']]
126
139
 
127
140
 
128
141
  def auto_cleanup(project,now=None):
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
- if tool not in WEB_TOOLS or not isinstance(arguments, dict):
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:
@@ -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; 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 = project_identity.display_root(arguments["project_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(lambda: [p["root"] for p in project_store.all_projects() if p.get("root")], _log)
4875
+ audit = setup_audit.Scheduler(_audited_roots, _log)
4839
4876
  audit.start()
4840
4877
  try:
4841
4878
  server.serve_forever()
package/version.py CHANGED
@@ -1,7 +1,7 @@
1
1
  """Single source of the Smart Tool version and of the User-Agent sent to public APIs."""
2
2
  import re
3
3
 
4
- VERSION = "0.9.74"
4
+ VERSION = "0.9.76"
5
5
  _CONTACT_RE = re.compile(r"^(?:[^\s@()<>;]+@[^\s@()<>;]+\.[^\s@()<>;]+|https?://[^\s()<>;]+)$")
6
6
 
7
7