@allansantos-dev/smart-tool 0.9.54 → 0.9.56

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.56 - beta
4
+
5
+ - Every command hook Smart Tool writes ends with `--hook-origin=smart-tool`: the Codex redirect hook
6
+ (`hooks/pretool_router.py --client codex`) and the session-start hook (`hooks/session_audit.py`) in Claude Code and
7
+ Codex. The command line then names its owner under the hook origin convention the other local projects follow. An
8
+ entry written by an older version shows as outdated on the setup page, and updating it or turning it off takes out
9
+ the unsigned and the signed form alike, so no second entry is left. In Codex the signed entry waits for approval in
10
+ `/hooks` like any changed hook. Claude Code's redirect hooks are HTTP entries and have no command line to sign
11
+ (`tests/test_codex_audit_hook.py`).
12
+
13
+ ## 0.9.55 - beta
14
+
15
+ - The agent learns about the problems of the project it works on, and the user is not notified about them. The first
16
+ Smart Tool call of a session in a project (`smart_search`, `smart_scout` or `project_manage` with that
17
+ `project_root`) carries, after its answer, a short note: the project, its setup audit error and warning counts, the
18
+ checks that found them and the `project_manage action=setup_audit mode=last` call that shows each one with its fix.
19
+ Once per session and project (a subfolder counts as its project); a clean or missing report adds nothing; a stored
20
+ report that cannot be read is told with its cause; nothing is fixed on its own. The tray no longer raises a Windows
21
+ notification per project for new audit findings, and the session-start hook now carries only the update notices
22
+ and the redirect proposals, so the note is not given twice (`tests/test_session_audit.py`,
23
+ `tests/test_tray_notices.py`).
24
+ - A push to `main` no longer holds the only self-hosted runner waiting for npm to list a version the tag's Release
25
+ run has not published yet: the Pages workflow checks npm once on a push and skips publishing when the version is not
26
+ listed (the Release run republishes the page), and waits only when dispatched (`tests/test_pages.py`).
27
+
3
28
  ## 0.9.54 - beta
4
29
 
5
30
  - A folder whose subfolders are projects is not indexed as one project. When it has no `.git` of its own and two or
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.54 beta. Windows only. What changed in each version: [CHANGELOG.md](CHANGELOG.md).
20
+ **Status:** 0.9.56 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.54 install
86
+ npx @allansantos-dev/smart-tool@0.9.56 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
@@ -146,7 +146,11 @@ Redirects) and Maintenance (Setup audit, Startup).
146
146
  the usage meter: it is a sidecar on your machine with no price, and its state is the **Local models** section.
147
147
  3. **Agents**: register the MCP server in Claude Code or Codex (runs their official `mcp add` command), install the
148
148
  hook and choose its behavior under **Agent rules**. A hook written by an older Smart Tool shows as outdated, with
149
- what an update changes; updating previews the entry and rewrites only Smart Tool's, after a backup.
149
+ what an update changes; updating previews the entry and rewrites only Smart Tool's, after a backup. Every
150
+ command hook it writes (the Codex redirect hook and the session-start hook) ends with
151
+ `--hook-origin=smart-tool`, so its command line names Smart Tool as its owner; an entry written before that shows
152
+ as outdated, and updating replaces it instead of adding a second one. Claude Code's redirect hooks are HTTP
153
+ entries with no command line.
150
154
 
151
155
  **Browser control** comes with the registration, and with every update for clients where smart-tool is registered:
152
156
  the official Playwright MCP (pinned in `web_adapters/node`) is registered as the `playwright` server, driving the
@@ -253,21 +257,22 @@ Redirects) and Maintenance (Setup audit, Startup).
253
257
  two minutes after it starts and then every 30 minutes (MCP servers shared by several projects are contacted once
254
258
  and their result reused for 6 hours; Run now always contacts them again), and the setup screen's **Setup audit**
255
259
  panel shows each project's last report: findings by severity, what is new, what was resolved, the tokens each MCP
256
- server's tools cost and what was not verified. When a scheduled run finds new errors or warnings, a Windows
257
- notification from the tray names the folder and up to three of them, once per finding, with a button that opens the
258
- panel; manual runs and info findings stay silent.
259
-
260
- The agent hears about it without asking for it. `setup_audit` with `mode=last` returns the stored report for the
261
- folder (or the nearest audited parent) without auditing again, and fails with what to do when none is stored. On
262
- its first `smart_search` of a session, and once per folder, the agent also gets a short notice when the stored
263
- report holds errors or warnings: the counts, the top three findings with their fixes and the call that lists them
264
- all, with the rule that a fix is applied only when you agree; a clean report adds nothing. Optionally, **Report at session
265
- start** on the Setup audit page (Claude Code or Codex) moves that notice to the start of every new session: it
266
- previews the exact SessionStart entry, adds it to `~/.claude/settings.json` or `~/.codex/hooks.json` only after you
267
- confirm (backup first), and **Turn off** removes only that entry. Codex runs a new hook only after you approve it in
268
- `/hooks`; until then the page shows "waiting for your approval" and the search keeps repeating the notice. It is off by default; while it is on, the search no longer repeats the notice. The
269
- hook script (`hooks/session_audit.py`) only reads the stored report from the running service and prints nothing
270
- when the service is down.
260
+ server's tools cost and what was not verified. It never raises a Windows notification: a project's problems are
261
+ told to the agent working in it.
262
+
263
+ The agent hears about it without asking for it. The first Smart Tool call of a session in a project
264
+ (`smart_search`, `smart_scout` or `project_manage` with that `project_root`) carries, after its answer, a short
265
+ note for the agent only: the project, its error and warning counts, the checks that found them and the call that
266
+ shows each one with its fix (`project_manage action=setup_audit mode=last project_root="<project>"`), with the rule
267
+ that a fix is applied only when you ask. It comes once per session and project (a subfolder counts as its project),
268
+ a project with a clean report or no report adds nothing, and nothing is fixed on its own. `mode=last` returns the
269
+ stored report for the folder (or the nearest audited parent) without auditing again, and fails with what to do
270
+ when none is stored. Optionally, **Report at session start** on the Setup audit page (Claude Code or Codex) starts
271
+ every new session with the update notices and the redirect proposals waiting for a decision: it previews the exact
272
+ SessionStart entry, adds it to `~/.claude/settings.json` or `~/.codex/hooks.json` only after you confirm (backup
273
+ first), and **Turn off** removes only that entry. Codex runs a new hook only after you approve it in `/hooks`;
274
+ until then the page shows "waiting for your approval". It is off by default. The hook script
275
+ (`hooks/session_audit.py`) only asks the running service and prints nothing when the service is down.
271
276
  4. **Local models** (optional): if the mcp-memory embedding sidecar is installed on the machine, its local embedder
272
277
  can serve as a fallback (or preferred) embedding model.
273
278
  5. **Web search providers** work without keys on their free public tiers; add your own key for more volume. Set your
package/client_hooks.py CHANGED
@@ -14,6 +14,8 @@ HOOK_SCRIPT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "hooks",
14
14
  MARKER = "pretool_router.py"
15
15
  AUDIT_SCRIPT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "hooks", "session_audit.py")
16
16
  AUDIT_MARKER = "session_audit.py"
17
+ # Hook origin convention shared by every project that installs hooks: a failed command hook names its owner.
18
+ HOOK_ORIGIN = "--hook-origin=smart-tool"
17
19
  AUDIT_MATCHER = "startup|resume|clear|compact|fork"
18
20
  AUDIT_TIMEOUT_S = 10
19
21
  AUDIT_CLIENTS = ("claude", "codex")
@@ -185,7 +187,8 @@ def _shell_safe(path):
185
187
 
186
188
 
187
189
  def _command(client):
188
- return f"{_shell_safe(sys.executable)} {_shell_safe(HOOK_SCRIPT)} --client {client}"
190
+ """The PreToolUse command of a client without HTTP hooks, signed with HOOK_ORIGIN at the end."""
191
+ return f"{_shell_safe(sys.executable)} {_shell_safe(HOOK_SCRIPT)} --client {client} {HOOK_ORIGIN}"
189
192
 
190
193
 
191
194
  def _handler(client, route=HTTP_PATH, timeout=HTTP_TIMEOUT_S):
@@ -282,8 +285,10 @@ def _audit_hook(hook):
282
285
 
283
286
 
284
287
  def _audit_entry():
288
+ """The SessionStart group of the session-start hook, its command signed with HOOK_ORIGIN at the end."""
285
289
  return {"matcher": AUDIT_MATCHER,
286
- "hooks": [{"type": "command", "command": f"{_shell_safe(sys.executable)} {_shell_safe(AUDIT_SCRIPT)}",
290
+ "hooks": [{"type": "command",
291
+ "command": f"{_shell_safe(sys.executable)} {_shell_safe(AUDIT_SCRIPT)} {HOOK_ORIGIN}",
287
292
  "timeout": AUDIT_TIMEOUT_S}]}
288
293
 
289
294
 
@@ -372,7 +377,8 @@ def audit_state(client="claude"):
372
377
 
373
378
 
374
379
  def audit_hook_installed(client):
375
- """The session-start audit report is on and running (Codex: approved in /hooks), so a search need not repeat it.
380
+ """The session-start hook is on and running (Codex: approved in /hooks), so a search need not repeat the redirect
381
+ proposals it already carries.
376
382
  An unreadable config file counts as off here; `audit_state` raises for it on the setup screen."""
377
383
  if client not in AUDIT_CLIENTS:
378
384
  return False
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env python3
2
2
  """SessionStart hook of Claude Code and Codex (opt-in, from the setup screen): forwards the payload to the Smart Tool daemon
3
- (POST /hooks/session-audit) and prints its answer, the stored setup audit notice of the session folder as additional
4
- context. Never starts the daemon or an audit: daemon down or any error means empty output, so a session start is
3
+ (POST /hooks/session-audit) and prints its answer: the update notices and the redirect proposals waiting for a decision
4
+ as additional context. Never starts the daemon or an audit: daemon down or any error means empty output, so a session start is
5
5
  never delayed or blocked.
6
6
  """
7
7
  import json
@@ -77,8 +77,8 @@
77
77
  "Client": "Cliente",
78
78
  "Claude Code": "Claude Code",
79
79
  "Codex": "Codex",
80
- "Off by default. When on, every new session starts with one short line about the stored audit of its folder (errors and warnings only, nothing runs). It adds a SessionStart entry to": "Desligado por padrão. Quando ligado, cada nova sessão começa com uma linha curta sobre a auditoria guardada da pasta dela (apenas erros e avisos, nada é executado). Ela adiciona uma entrada SessionStart em",
81
- ", written after a backup, and turning it off removes only that entry. Codex runs a new hook only after you approve it in /hooks. Without it, the agent gets the same line once, on its first search.": ", gravada depois de um backup; ao desligar, só essa entrada é removida. O Codex só executa um hook novo depois que você o aprova em /hooks. Sem ele, o agente recebe a mesma linha uma vez, na primeira busca.",
80
+ "Off by default. When on, every new session starts with the Smart Tool update notices (also shown to you) and the redirect proposals waiting for a decision. It adds a SessionStart entry to": "Desligado por padrão. Quando ligado, cada nova sessão começa com os avisos de atualização do Smart Tool (mostrados também a você) e as propostas de redirecionamento que esperam uma decisão. Ela adiciona uma entrada SessionStart em",
81
+ ", written after a backup, and turning it off removes only that entry. Codex runs a new hook only after you approve it in /hooks. Either way, the agent learns about a project's setup audit on its first Smart Tool call there, once per session.": ", gravada depois de um backup; ao desligar, só essa entrada é removida. O Codex só executa um hook novo depois que você o aprova em /hooks. Com ou sem ele, o agente fica sabendo da auditoria de um projeto na primeira chamada ao Smart Tool ali, uma vez por sessão.",
82
82
  "Turn on": "Ligar",
83
83
  "Turn off": "Desligar",
84
84
  "Write it": "Gravar",
@@ -679,15 +679,12 @@
679
679
  "{0} subagent(s) list tools but none of mcp__{1}__*: {2}. Add mcp__{3}__smart_search and mcp__{4}__smart_search_result to their `tools`, or drop the `tools` line to inherit every tool.": "{0} subagente(s) listam ferramentas, mas nenhuma de mcp__{1}__*: {2}. Adicione mcp__{3}__smart_search e mcp__{4}__smart_search_result ao `tools` deles, ou remova a linha `tools` para herdar todas as ferramentas.",
680
680
  "MCP servers and HTTP hook endpoints were not contacted (probe off)": "Os servidores MCP e os endpoints de hook HTTP não foram contatados (sondagem desligada)",
681
681
  "{0} is not a setup audit index: fix or delete it.": "{0} não é um índice de auditoria da configuração: corrija ou apague.",
682
- "Setup audit: 1 new problem in the agent configuration": "Auditoria da configuração: 1 problema novo na configuração dos agentes",
683
- "Setup audit: {count} new problems in the agent configuration": "Auditoria da configuração: {count} problemas novos na configuração dos agentes",
684
682
  "setup audit: {0} project(s), {1} error finding(s)": "auditoria da configuração: {0} projeto(s), {1} erro(s) encontrado(s)",
685
683
  "Not verified:": "Não verificado:",
686
684
  "Names and descriptions add up to {0} characters, over the ~{1} the skill list gets (Claude: 1% of a 200k context; Codex: 2% or 8,000 characters): some skills are left out of what the model sees.": "Os nomes e as descrições somam {0} caracteres, acima dos ~{1} que a lista de skills recebe (Claude: 1% de um contexto de 200k; Codex: 2% ou 8.000 caracteres): algumas skills ficam de fora do que o modelo vê.",
687
685
  "Codex reads AGENTS.md; Claude Code reads only CLAUDE.md (and what it imports with @AGENTS.md), so the two agents get different instructions here.": "O Codex lê o AGENTS.md; o Claude Code lê apenas o CLAUDE.md (e o que ele importa com @AGENTS.md), então os dois agentes recebem instruções diferentes aqui.",
688
686
  "Project AGENTS.md chain is {0} bytes; Codex reads {1} (project_doc_max_bytes) and drops the rest.": "A cadeia de AGENTS.md do projeto tem {0} bytes; o Codex lê {1} (project_doc_max_bytes) e descarta o resto.",
689
687
  "does not start or answer": "não inicia nem responde",
690
- "and {count} more": "e mais {count}",
691
688
  "Since the last run: {0} new, {1} resolved": "Desde a última execução: {0} novos, {1} resolvidos",
692
689
  "{0}: invalid JSON ({1})": "{0}: JSON inválido ({1})",
693
690
  "{0}: invalid TOML ({1})": "{0}: TOML inválido ({1})",
@@ -728,7 +725,6 @@
728
725
  "Don't show again": "Não mostrar de novo",
729
726
  "Switch model": "Trocar de modelo",
730
727
  "Mute 7 days": "Silenciar por 7 dias",
731
- "Open the audit": "Abrir a auditoria",
732
728
  "Projects and indexing…": "Projetos e indexação…",
733
729
  "Index a folder…": "Indexar uma pasta…",
734
730
  "Open settings": "Abrir configurações",
@@ -875,7 +871,6 @@
875
871
  "{0}{1} · {2} files": "{0}{1} · {2} arquivos",
876
872
  "({0} sites)": "({0} sites)",
877
873
  "{0} skills": "{0} skills",
878
- ", {0} new": ", {0} novos",
879
874
  "{0} {1} (~{2} tokens)": "{0} {1} (~{2} tokens)",
880
875
  "Checking the browsers…": "Verificando os navegadores…",
881
876
  "View log": "Ver o log",
@@ -889,6 +884,7 @@
889
884
  "{0} holds a setup audit of {1} from an older Smart Tool, whose findings have no fix: run project_manage action=setup_audit mode=run to replace it.": "{0} guarda uma auditoria da configuração de {1} feita por um Smart Tool mais antigo, cujos achados não trazem a correção: rode project_manage action=setup_audit mode=run para substituí-la."
890
885
  },
891
886
  "ignore": [
887
+ "and {0} more",
892
888
  "saved msg",
893
889
  "more row-more",
894
890
  "callout info",
@@ -932,12 +928,10 @@
932
928
  "remove the skill folders you do not use",
933
929
  "Sign in: run /mcp in Claude Code and pick {0}.",
934
930
  "Sign in: run `codex mcp login {0}`.",
935
- "in the Claude Code and Codex configuration. Top items, each with its fix:",
936
931
  "Read these hooks in {0}: when two of them rewrite or deny the same {1} call, narrow one matcher so they stop sharing it; when each does something different (one logs, one rewrites), nothing needs to change.",
937
932
  "Bring names and descriptions under ~{0} characters: {1}, or shorten the longest descriptions ({2}).",
938
933
  "Add a line `@AGENTS.md` to {0} (create the file with that line if it does not exist).",
939
934
  "Shorten the project AGENTS.md files to under {0} bytes in total, or set project_doc_max_bytes = {1} (or more) in {2}.",
940
- "Smart Tool setup audit of {0} ({1} min ago): {2} errors, {3} warnings",
941
935
  "Rename the `name` in the frontmatter of all but one of these, or remove the copies you do not use: {0}.",
942
936
  "Reinstall or update the {0} plugin, which is missing {1}.",
943
937
  "Restore {0}, or delete this {1} hook from {2}.",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@allansantos-dev/smart-tool",
3
- "version": "0.9.54",
3
+ "version": "0.9.56",
4
4
  "description": "Local MCP server that gives coding agents (Claude Code, Codex) cheaper, sharper tools than their built-in search. Windows.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Allan Santos",
package/setup_audit.py CHANGED
@@ -31,7 +31,6 @@ import yaml
31
31
 
32
32
  import atomic_io
33
33
  import endpoint_sync
34
- import i18n
35
34
  import paths
36
35
 
37
36
  REPORT_DIR = os.path.join(paths.DATA_DIR, "setup-audit")
@@ -43,9 +42,7 @@ PROBE_MAX_AGE_S = 6 * 3600
43
42
  SKILL_DESCRIPTION_MAX = 1536
44
43
  SKILL_BUDGET_CHARS = 8000
45
44
  CODEX_PROJECT_DOC_MAX = 32 * 1024
46
- NOTICE_ITEMS = 3
47
- NOTICE_ACTION_MAX = 360
48
- REVIEW_FIRST = ("hook_overlap", "skill_budget")
45
+ NOTICE_CHECKS = 3
49
46
  SMART_TOOL_SERVER = "smart-tool"
50
47
  CLAUDE_TOOLS = ("Bash", "Read", "Grep", "Glob", "LS", "Edit", "MultiEdit", "Write", "NotebookEdit", "WebFetch",
51
48
  "WebSearch", "Task")
@@ -865,39 +862,28 @@ def stored_for(path):
865
862
  folder = parent
866
863
 
867
864
 
868
- def top_findings(report, count=NOTICE_ITEMS):
869
- """The errors and warnings of report most worth acting on first: errors, then a fix over a check to make
870
- (REVIEW_FIRST), then new ones, then the report order."""
871
- order = {"error": 0, "warn": 1}
872
- ranked = [(order[f["severity"]], f["check"] in REVIEW_FIRST, not f.get("new"), position, f)
873
- for position, f in enumerate(report["findings"]) if f["severity"] in order]
874
- return [row[-1] for row in sorted(ranked, key=lambda row: row[:4])[:count]]
875
-
876
-
877
- def session_notice(path):
878
- """Context for an agent session about the stored audit of path (nothing is run): the project, the counts, the top
879
- NOTICE_ITEMS findings with their fix and the exact call that lists all of them. "" when there is no stored report
880
- or it holds no error or warning. Each fix changes the user's agent setup, so the agent is told to apply one when
881
- the user agrees, never on its own. Stays far below the ~2,500 tokens Codex spills to disk."""
865
+ def agent_notice(path):
866
+ """(project, text) of the short note an agent gets on its first Smart Tool call in path during a session: the
867
+ audited project, its error and warning counts, up to NOTICE_CHECKS of their checks (errors first) and the call
868
+ that shows each one with its fix (nothing is run). None when no stored report covers path or it holds no error or
869
+ warning. Each fix changes the user's agent setup, so the agent is told to apply one only when the user asks."""
882
870
  report = stored_for(path)
883
871
  if report is None:
884
- return ""
885
- summary = report["summary"]
886
- if not summary["error"] and not summary["warn"]:
887
- return ""
888
- new = sum(1 for f in report["findings"] if f.get("new") and f["severity"] in ("error", "warn"))
889
- age = max(0, int((time.time() - report["checked_at"]) // 60))
890
- lines = [f"Smart Tool setup audit of {report['project']} ({age} min ago): {summary['error']} errors, "
891
- f"{summary['warn']} warnings" + (f", {new} new" if new else "") + " in the Claude Code and Codex "
892
- "configuration. Top items, each with its fix:"]
893
- for number, finding in enumerate(top_findings(report), 1):
894
- lines.append(f"{number}. [{finding['harness']}] {finding['severity']} {finding['check']}: "
895
- f"{finding['subject'][:120]}. Fix: {finding['action'][:NOTICE_ACTION_MAX]}")
872
+ return None
873
+ errors, warnings = report["summary"]["error"], report["summary"]["warn"]
874
+ if not errors and not warnings:
875
+ return None
876
+ ranked = sorted((f for f in report["findings"] if f["severity"] in ("error", "warn")),
877
+ key=lambda f: f["severity"] != "error")
878
+ checks = list(dict.fromkeys(f["check"] for f in ranked))
879
+ named = ", ".join(checks[:NOTICE_CHECKS]) + (f" and {len(checks) - NOTICE_CHECKS} more"
880
+ if len(checks) > NOTICE_CHECKS else "")
896
881
  root = report["project"].replace("\\", "/")
897
- lines.append(f'All findings with their fixes: project_manage action=setup_audit mode=last project_root="{root}"; '
898
- "after a fix, mode=run checks again. These fixes change the user's agent setup: apply one when the "
899
- "user agrees.")
900
- return "\n".join(lines)
882
+ text = (f"Smart Tool: the project {root} has {errors} error{'' if errors == 1 else 's'} and {warnings} "
883
+ f"warning{'' if warnings == 1 else 's'} in its agent setup ({named}). To see each one with its fix, call "
884
+ f'project_manage action=setup_audit mode=last project_root="{root}". This note is for you; fix one only '
885
+ "when the user asks.")
886
+ return report["project"], text
901
887
 
902
888
 
903
889
  def index():
@@ -970,53 +956,11 @@ def _save_locked(report):
970
956
  key = index_key(report["project"])
971
957
  entry = {"project": report["project"], "summary": report["summary"], "new": len(changes.get("new", [])),
972
958
  "resolved": len(changes.get("resolved", [])), "checked_at": report["checked_at"],
973
- "trigger": report["trigger"], "snapshot_key": report["snapshot_key"],
974
- "pending": _pending_notice(data.get(key), report)}
959
+ "trigger": report["trigger"], "snapshot_key": report["snapshot_key"]}
975
960
  data[key] = entry
976
961
  _write_index(data)
977
962
 
978
963
 
979
- def _pending_notice(previous, report):
980
- """The new errors and warnings of a scheduled run not yet told to the user, added to those a former run left
981
- unannounced (by finding id). A manual run adds none: the user is looking at its result."""
982
- pending = list((previous or {}).get("pending") or [])
983
- if report["trigger"] == "schedule":
984
- known = {item["id"] for item in pending}
985
- pending += [{"id": f["id"], "severity": f["severity"], "check": f["check"], "subject": f["subject"]}
986
- for f in report["findings"]
987
- if f.get("new") and f["severity"] in ("error", "warn") and f["id"] not in known]
988
- return pending
989
-
990
-
991
- def notices_due():
992
- """[{project, errors, warnings, items}] for the projects whose scheduled audits found new errors or warnings since
993
- the last call; marks them announced, so each finding is told once (the tray toast)."""
994
- with _INDEX_LOCK:
995
- data = index()
996
- due = []
997
- for entry in data.values():
998
- pending = entry.get("pending") or []
999
- if pending:
1000
- due.append({"project": entry["project"], "errors": sum(i["severity"] == "error" for i in pending),
1001
- "warnings": sum(i["severity"] == "warn" for i in pending), "items": pending})
1002
- entry["pending"] = []
1003
- if due:
1004
- _write_index(data)
1005
- return due
1006
-
1007
-
1008
- def toast_text(row):
1009
- """(title, lines) of the toast for one `notices_due` row, in the interface language."""
1010
- total = row["errors"] + row["warnings"]
1011
- title = (i18n.t("Setup audit: 1 new problem in the agent configuration") if total == 1
1012
- else i18n.t("Setup audit: {count} new problems in the agent configuration", count=total))
1013
- lines = [os.path.basename(row["project"].rstrip("\\/")) or row["project"]]
1014
- lines += [f"{item['severity']}: {item['check']} - {item['subject']}"[:120] for item in row["items"][:3]]
1015
- if len(row["items"]) > 3:
1016
- lines.append(i18n.t("and {count} more", count=len(row["items"]) - 3))
1017
- return title, lines
1018
-
1019
-
1020
964
  class Scheduler:
1021
965
  """Periodic mode: audits every registered project whose folder exists, FIRST_RUN_DELAY_S after start and then
1022
966
  every SCHEDULE_S, one project at a time, reusing MCP probes younger than PROBE_MAX_AGE_S. projects() returns the
package/setup_ui.py CHANGED
@@ -203,13 +203,12 @@ def handle_health_get():
203
203
 
204
204
 
205
205
  def handle_notices():
206
- """What the tray should show now: the model offer (once a day until answered), models over the failure limit
207
- (once a day each) and the new errors or warnings of the scheduled setup audit (once per finding). Fetching marks
208
- them announced, so each toast is shown once per reminder period."""
206
+ """What the tray should show now: the model offer (once a day until answered) and models over the failure limit
207
+ (once a day each). Fetching marks them announced, so each toast is shown once per reminder period. A project's
208
+ setup audit is told to the agent working there (first Smart Tool call of a session), never as a toast."""
209
209
  upgrade = _checked_upgrade()
210
210
  offer = model_upgrade.due() if upgrade["state"] == "pending" else None
211
- return {"upgrade": offer, "failing": model_health.alerts_due(), "audit": setup_audit.notices_due(),
212
- "check_error": upgrade["check_error"]}
211
+ return {"upgrade": offer, "failing": model_health.alerts_due(), "check_error": upgrade["check_error"]}
213
212
 
214
213
 
215
214
  def handle_local_models_get():
@@ -828,7 +827,7 @@ __I18N__
828
827
  <div class="card">
829
828
  <div class="card-head"><h3>Report at session start</h3><span class="pill" id="audit-hook-pill" data-tone="busy">Checking</span></div>
830
829
  <div class="field"><label for="sel-audit-hook-client">Client</label><select id="sel-audit-hook-client"><option value="claude">Claude Code</option><option value="codex">Codex</option></select></div>
831
- <p class="lede">Off by default. When on, every new session starts with one short line about the stored audit of its folder (errors and warnings only, nothing runs). It adds a SessionStart entry to <span class="mono" id="audit-hook-file"></span>, written after a backup, and turning it off removes only that entry. Codex runs a new hook only after you approve it in /hooks. Without it, the agent gets the same line once, on its first search.</p>
830
+ <p class="lede">Off by default. When on, every new session starts with the Smart Tool update notices (also shown to you) and the redirect proposals waiting for a decision. It adds a SessionStart entry to <span class="mono" id="audit-hook-file"></span>, written after a backup, and turning it off removes only that entry. Codex runs a new hook only after you approve it in /hooks. Either way, the agent learns about a project's setup audit on its first Smart Tool call there, once per session.</p>
832
831
  <div class="actions"><button type="button" class="primary" id="btn-audit-hook-on" hidden>Turn on</button><button type="button" id="btn-audit-hook-off" hidden>Turn off</button></div>
833
832
  <div id="audit-hook-confirm" hidden>
834
833
  <p class="hint" id="audit-hook-where"></p>
@@ -1627,30 +1627,62 @@ def _mark_notice_delivered(job_id):
1627
1627
 
1628
1628
 
1629
1629
  def _pending_notices(session, client, project_root):
1630
- """[(key, text)] the session has not been told yet: the hook state (once), the stored setup audit of the
1631
- searched folder (once per folder, only with errors or warnings) and the redirect proposals waiting for a decision
1632
- (once), these two not when the SessionStart audit hook already reports them at the start of the session. An
1633
- unreadable audit report is logged, not raised, so a search never fails over it."""
1630
+ """[(key, text)] the session has not been told yet: the hook state (once), the update notices (once each) and the
1631
+ redirect proposals waiting for a decision (once, not when the SessionStart hook already reports them at the start
1632
+ of the session). The setup audit of the folder is not here: `_project_notice` adds it to the first Smart Tool
1633
+ call of the session in that project, whatever the tool."""
1634
1634
  delivered = session.get("notices_delivered") or set()
1635
1635
  pending = []
1636
1636
  if session["hook_notice"] and "hook" not in delivered:
1637
1637
  pending.append(("hook", session["hook_notice"]))
1638
1638
  pending += [(key, f"{text} Tell the user.") for key, text in _update_notices() if key not in delivered]
1639
- key = "audit:" + setup_audit.index_key(project_root)
1640
- if (key not in delivered or "proposals" not in delivered) and not client_hooks.audit_hook_installed(client):
1641
- try:
1642
- text = setup_audit.session_notice(project_root) if key not in delivered else ""
1643
- except Exception as exc:
1644
- _log(f"setup audit notice not read: {type(exc).__name__}: {exc}")
1645
- text = ""
1646
- if text:
1647
- pending.append((key, text))
1648
- proposals = _proposals_notice() if "proposals" not in delivered else ""
1639
+ if "proposals" not in delivered and not client_hooks.audit_hook_installed(client):
1640
+ proposals = _proposals_notice()
1649
1641
  if proposals:
1650
1642
  pending.append(("proposals", proposals))
1651
1643
  return pending
1652
1644
 
1653
1645
 
1646
+ _PROJECT_NOTICE_TOOLS = frozenset({"smart_search", "smart_scout", "project_manage"})
1647
+ _NOTICE_LOCK = threading.Lock()
1648
+
1649
+
1650
+ def _notice_root(arguments):
1651
+ """The folder a tool call is about: arguments["project_root"], or the root of the registered arguments["project_id"];
1652
+ None when the call names neither or the id is not registered."""
1653
+ if not isinstance(arguments, dict):
1654
+ return None
1655
+ if isinstance(arguments.get("project_root"), str):
1656
+ return arguments["project_root"]
1657
+ project = project_store.get(arguments["project_id"]) if isinstance(arguments.get("project_id"), str) else None
1658
+ return project["root"] if project else None
1659
+
1660
+
1661
+ def _project_notice(name, arguments):
1662
+ """The setup audit note of the project the call names (project_root or project_id) when this is the first call of
1663
+ the MCP session there (keyed by the audited project, so a subfolder does not repeat it), or "". Marks it told:
1664
+ once per session and project, in the tool answer only (the user gets no notification for it). A setup_audit call
1665
+ marks it told without the note, since its own answer already holds the findings. A stored report that cannot be
1666
+ read is told the same way, with its cause, instead of being skipped."""
1667
+ session, _client = _session_client()
1668
+ root = _notice_root(arguments)
1669
+ if session is None or name not in _PROJECT_NOTICE_TOOLS or not isinstance(root, str) or not os.path.isdir(root):
1670
+ return ""
1671
+ try:
1672
+ found = setup_audit.agent_notice(root)
1673
+ except (OSError, ValueError, KeyError) as exc:
1674
+ found = (root, f"Smart Tool could not read the setup audit of {root.replace(os.sep, '/')}: {exc}")
1675
+ if found is None:
1676
+ return ""
1677
+ key = "audit:" + setup_audit.index_key(found[0])
1678
+ with _NOTICE_LOCK:
1679
+ told = session.setdefault("notices_delivered", set())
1680
+ if key in told:
1681
+ return ""
1682
+ told.add(key)
1683
+ return "" if arguments.get("action") == "setup_audit" else found[1]
1684
+
1685
+
1654
1686
  def _proposals_notice():
1655
1687
  """One line for the agent when redirect proposals wait for a decision, "" when none; an unreadable store is
1656
1688
  logged, not raised, so neither a search nor a session start fails over it."""
@@ -4048,18 +4080,16 @@ def _pretool_hook(handler):
4048
4080
 
4049
4081
 
4050
4082
  def _session_audit_hook(handler):
4051
- """SessionStart output for the audit report hook: the stored audit notice of the session's folder as
4052
- additionalContext, and the update notices both as systemMessage (shown to the user) and as context; `{}` when
4053
- there is nothing to say. Never runs an audit."""
4083
+ """SessionStart output of the session-start hook: the update notices both as systemMessage (shown to the user) and
4084
+ as additionalContext, plus the redirect proposals waiting for a decision as context; `{}` when there is nothing to
4085
+ say. The setup audit of a project reaches the agent on its first Smart Tool call there (`_project_notice`), so it
4086
+ is told once per session and project."""
4054
4087
  try:
4055
- payload = json.loads(handler._read_body(HOOK_MAX_BODY_BYTES) or b"{}")
4056
- cwd = payload.get("cwd")
4057
- text = setup_audit.session_notice(cwd) if isinstance(cwd, str) and os.path.isdir(cwd) else ""
4058
- except Exception as exc:
4059
- _log(f"SessionStart audit hook without a report: {type(exc).__name__}: {exc}")
4060
- text = ""
4088
+ handler._read_body(HOOK_MAX_BODY_BYTES)
4089
+ except ValueError as exc:
4090
+ _log(f"SessionStart hook body refused: {exc}")
4061
4091
  updates = " ".join(notice for _key, notice in _update_notices())
4062
- context = "\n".join(part for part in (updates, text, _proposals_notice()) if part)
4092
+ context = "\n".join(part for part in (updates, _proposals_notice()) if part)
4063
4093
  if not context:
4064
4094
  return {}
4065
4095
  output = {"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": context}}
@@ -4144,6 +4174,9 @@ def _dispatch_tool_call(params, session_id=None):
4144
4174
  warning = model_health.warning_text(failures, setup_ui.setup_origin())
4145
4175
  if warning:
4146
4176
  result["content"][0]["text"] += _sanitize_text(warning)
4177
+ notice = _project_notice(name, arguments)
4178
+ if notice:
4179
+ result["content"][0]["text"] += "\n\n" + _sanitize_text(notice)
4147
4180
  return result
4148
4181
  finally:
4149
4182
  if who is not None:
package/tray.py CHANGED
@@ -26,7 +26,6 @@ import config
26
26
  import daemon_launcher
27
27
  import i18n
28
28
  import paths
29
- import setup_audit
30
29
  import toast_notice
31
30
  import update_check
32
31
  import version
@@ -156,8 +155,7 @@ def _toast(title, lines, buttons, tag):
156
155
 
157
156
 
158
157
  def _show_notices(icon, notices):
159
- """Shows a toast for each pending notice: the new-default-models offer, each model over the failure limit and each
160
- project whose scheduled setup audit found new errors or warnings."""
158
+ """Shows a toast for each pending notice: the new-default-models offer and each model over the failure limit."""
161
159
  offer = notices.get("upgrade")
162
160
  if offer:
163
161
  lines = [f"{role}: {change['current']} -> {change['new']}" for role, change in offer["changes"].items()]
@@ -175,10 +173,6 @@ def _show_notices(icon, notices):
175
173
  [(i18n.t("Switch model"), toast_notice.action_uri("open-setup", section="models")),
176
174
  (i18n.t("Mute 7 days"), toast_notice.action_uri("mute-model", model=row["model"]))],
177
175
  "model-failing:" + row["model"])
178
- for row in notices.get("audit") or []:
179
- title, lines = setup_audit.toast_text(row)
180
- _toast(title, lines, [(i18n.t("Open the audit"), toast_notice.action_uri("open-setup", section="audit"))],
181
- "setup-audit:" + row["project"])
182
176
 
183
177
 
184
178
  def _log(text):
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.54"
4
+ VERSION = "0.9.56"
5
5
  _CONTACT_RE = re.compile(r"^(?:[^\s@()<>;]+@[^\s@()<>;]+\.[^\s@()<>;]+|https?://[^\s()<>;]+)$")
6
6
 
7
7