@allansantos-dev/smart-tool 0.9.61 → 0.9.66

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@allansantos-dev/smart-tool",
3
- "version": "0.9.61",
3
+ "version": "0.9.66",
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/pr_impact.py ADDED
@@ -0,0 +1,84 @@
1
+ """Impact report of a change set, in Markdown, for the description or a comment of a pull request.
2
+
3
+ It joins what Smart Tool already computes: the functions the diff touches and the tests to run (affected_tests), the
4
+ callers of each touched function (code_impact) and the documentation anchors the change leaves out of date (doc_scope).
5
+ Nothing is published: the agent pastes the report where it belongs.
6
+ """
7
+ import os
8
+
9
+ import affected_tests
10
+ import code_impact
11
+ import doc_scope
12
+
13
+ MAX_FUNCTIONS = 15
14
+ MAX_CALLERS = 8
15
+
16
+
17
+ def _callers(root, label, view_id):
18
+ """Callers of one touched function, or None when the function is new and nothing calls it yet."""
19
+ try:
20
+ found = code_impact.impact(root, label, view_id, depth=1, limit=MAX_CALLERS)
21
+ except ValueError:
22
+ return None
23
+ return found["callers"], found["counts"]["callers"]
24
+
25
+
26
+ def _stale(root, view_id, paths):
27
+ """Documentation findings that sit on the changed files, or the reason none could be computed."""
28
+ if not os.path.isdir(os.path.join(root, doc_scope.DOCS_DIR)):
29
+ return [], "docs/scope is not generated in this project; run project_manage action=docs generate=true."
30
+ found = doc_scope.check(root, view_id, limit=200)["findings"]
31
+ return [f for f in found if f["issue"] != "broken_link" and f["id"].rpartition("::")[0] in paths], None
32
+
33
+
34
+ def report(root, base="HEAD", limit=30, view_id=None):
35
+ """Impact of the changes since base.
36
+
37
+ Parameters: root (str) project folder; base (str) git revision; limit (int) rows per list; view_id (str or None).
38
+ Returns: dict with 'markdown' and the data behind it (touched, tests, stale_anchors, commands, run_all).
39
+ """
40
+ changes = affected_tests.affected(root, base, limit, view_id)
41
+ changed_code = set(changes["changed"]["code"])
42
+ touched = changes["touched_functions"][:MAX_FUNCTIONS]
43
+ callers = {label: _callers(root, label, view_id) for label in touched}
44
+ stale, stale_note = _stale(root, view_id, changed_code)
45
+ lines = [f"## Impact of the change against `{base}`", "",
46
+ f"{changes['counts']['changed_files']} changed file(s), {len(changes['touched_functions'])} touched "
47
+ f"function(s), {changes['counts']['tests']} test file(s) to run.", ""]
48
+ if changes["touched_functions"]:
49
+ lines += ["### Touched functions and who calls them", "", "| Function | Callers | Called from |", "|---|---|---|"]
50
+ for label in touched:
51
+ reached = callers[label]
52
+ if reached is None:
53
+ lines.append(f"| `{label}` | 0 | new: nothing calls it yet |")
54
+ continue
55
+ sites, total = reached
56
+ shown = ", ".join(f"`{s['function']}` ({s['path']}:{s['line']})" for s in sites)
57
+ more = f" (+{total - len(sites)} more)" if total > len(sites) else ""
58
+ lines.append(f"| `{label}` | {total} | {shown or '-'}{more} |")
59
+ if len(changes["touched_functions"]) > len(touched):
60
+ lines.append(f"\n{len(changes['touched_functions']) - len(touched)} more touched function(s) not listed.")
61
+ lines.append("")
62
+ lines += ["### Documentation left out of date", ""]
63
+ if stale_note:
64
+ lines += [stale_note, ""]
65
+ elif stale:
66
+ lines += [f"- `{f['id']}`: {f['issue'].replace('_', ' ')} ({f['file']}:{f['line']})" for f in stale]
67
+ lines += ["", "Regenerate with `project_manage action=docs generate=true` and review the prose of these entries.", ""]
68
+ else:
69
+ lines += ["No documented entry in the changed files is out of date.", ""]
70
+ lines += ["### Tests to run", ""]
71
+ if changes["tests"]:
72
+ lines += [f"- `{t['path']}`: {t['why']}" for t in changes["tests"]]
73
+ if changes.get("omitted"):
74
+ lines.append(f"- ... and {changes['omitted']['tests']} more")
75
+ lines += [""] + [f"`{c['command']}` (in `{c['cwd']}`)" if c.get("command") else f"{c['reason']} ({', '.join(c['files'])})"
76
+ for c in changes["commands"]]
77
+ else:
78
+ lines.append("No test reaches the changed code through imports or static calls.")
79
+ if changes["run_all"]:
80
+ lines += ["", "Run the whole suite: " + "; ".join(changes["run_all_reasons"]) + "."]
81
+ return {"base": base, "markdown": "\n".join(lines).rstrip("\n") + "\n", "touched": touched,
82
+ "callers": {label: (reached[1] if reached else 0) for label, reached in callers.items()},
83
+ "stale_anchors": stale, "stale_note": stale_note, "tests": changes["tests"],
84
+ "commands": changes["commands"], "run_all": changes["run_all"], "counts": changes["counts"]}
@@ -13,7 +13,7 @@ SCRIPT=r'''
13
13
  window.SmartInsights=(()=>{
14
14
  const $i=id=>document.getElementById(id);let sequence=0,storage=null,plan=null,comparison=null,compareRequest=0,diffRequest=0;
15
15
  const count=n=>Number(n||0).toLocaleString('en-US'),size=n=>n>=1048576?(n/1048576).toLocaleString('en-US',{maximumFractionDigits:2})+' MiB':(n/1024).toLocaleString('en-US',{maximumFractionDigits:1})+' KiB';
16
- const phaseNames={index_embedding:'Indexing',query_embedding:'Query',embedding_probe:'Model check',scope:'Scope',rerank:'Rerank',other:'Other step'};
16
+ const phaseNames={index_embedding:'Indexing',query_embedding:'Query',embedding_probe:'Model check',scope:'Scope',scout:'Scout',docs:'Documentation',rerank:'Rerank',other:'Other step'};
17
17
  function summary(host,rows){host.innerHTML=rows.map(([title,value,note])=>`<div><small>${esc(title)}</small><strong>${esc(value)}</strong>${note?'<small>'+esc(note)+'</small>':''}</div>`).join('')}
18
18
  function table(headers,rows){return '<table class="insights-table"><thead><tr>'+headers.map(x=>'<th>'+esc(x)+'</th>').join('')+'</tr></thead><tbody>'+rows.map(row=>'<tr>'+row.map(value=>'<td>'+value+'</td>').join('')+'</tr>').join('')+'</tbody></table>'}
19
19
  async function run(button,task){const seq=sequence,key=selected;button.disabled=true;try{await task(key,()=>seq===sequence&&key===selected)}catch(e){if(seq===sequence)message(e.message,true)}finally{if(seq===sequence)button.disabled=false}}
@@ -61,7 +61,7 @@ window.SmartMaps=(()=>{
61
61
  function clearSelection(){byId('maps-selected').textContent='Select an element';for(const id of ['maps-path','maps-state','maps-facts'])byId(id).textContent='';byId('maps-relation-title').textContent=mode==='calls'?'Static calls':'File dependencies';byId('maps-relations').replaceChildren();byId('maps-read').disabled=true}
62
62
  function reset(){++requestId;aborter?.abort();data=null;project=null;selectedNode=null;positions.clear();currentNodes=[];currentEdges=[];shown=[];shownEdges=[];globalLookup.clear();byId('maps-world').replaceChildren();byId('maps-color-legend').replaceChildren();byId('map-files').replaceChildren();byId('map-chunks').replaceChildren();byId('maps-diagnostic-list').replaceChildren();byId('map-view').replaceChildren(new Option('Current view or available legacy',''));byId('maps-folder').replaceChildren(new Option('All',''));byId('maps-symbol-picker').replaceChildren(new Option('Select…',''));byId('maps-search').value='';byId('map-info').textContent='Load the maps of this project. The analysis is local and creates no embeddings.';byId('maps-count').textContent='';byId('maps-empty').hidden=false;byId('maps-empty').textContent='Load a view to explore the three maps.';byId('load-map').disabled=false;byId('maps-popup-link').hidden=true;byId('maps-popup-link').removeAttribute('href');clearSelection()}
63
63
  async function load(view,restore=null){const key=selected,id=++requestId;aborter?.abort();aborter=new AbortController();byId('load-map').disabled=true;byId('map-info').textContent='Reading the snapshot and analyzing imports and calls…';try{const response=await fetch('/setup/projects',{method:'POST',headers:{'Content-Type':'application/json','X-Setup-Token':token},body:JSON.stringify({action:'graph',project_id:key,...(view?{view_id:view}:{})}),signal:aborter.signal});const result=await response.json();if(!response.ok)throw Error(result.error||'Could not load the maps.');if(id!==requestId||key!==selected)return;data=result;project=key;selectedNode=null;focus=false;positions.clear();byId('map-view').replaceChildren(...data.views.map(v=>new Option(v.label+(v.current?' (active)':'')+' · '+v.files+' files',v.view_id)));if(data.selected)byId('map-view').value=data.selected.view_id;byId('map-info').textContent=data.selected?`${data.selected.label} · ${data.counts.files} files · ${data.counts.parsed_files} analyzed. ${data.selected.current?'Indexed content; local changes may be pending.':'Stored snapshot. Current view: '+(data.current_view?.label||'not identified')+'.'}`:data.message;byId('maps-folder').replaceChildren(new Option('All',''),...Array.from(new Set(data.files.map(f=>f.group))).sort().map(f=>new Option(f,f)));byId('map-chunks').replaceChildren();renderDiagnostics();if(restore){byId('maps-search').value=restore.q||'';if([...byId('maps-folder').options].some(o=>o.value===restore.folder))byId('maps-folder').value=restore.folder;if(['60','120','250'].includes(restore.limit))byId('maps-limit').value=restore.limit;if(['module','status'].includes(restore.colors))byId('maps-color-mode').value=restore.colors}refreshGraph(true);if(restore?.node&&globalLookup.has(restore.node)){selectedNode=restore.node;focus=restore.focus==='1';refreshGraph(true)}}catch(e){if(e.name!=='AbortError'&&id===requestId){byId('map-info').textContent=e.message+' Use Load maps to try again.';message(e.message,true)}}finally{if(id===requestId)byId('load-map').disabled=false}}
64
- function renderDiagnostics(){const c=data.counts||{},lines=[`Local analysis of Java, Angular, Python, JavaScript/TypeScript, HTML/CSS and Markdown links. TXT and DOCX show up in coverage and in text search. ${c.parsed_files||0} of ${c.files||0} files were analyzed. Other languages and incomplete snapshots remain available in coverage.`,`${c.resolved_imports||0} resolved internal references; ${c.external_imports||0} external references; ${c.calls||0} call relations. Unresolved targets are a limited sample (${c.unresolved_calls||0} records in the analysis).`];if(data.truncated)lines.push('The analysis limits were reached. Filter by folder to explore the available part.');lines.push(...(data.diagnostics||[]).slice(0,60).map(d=>d.path+': '+d.reason));lines.push(...(data.unresolved||[]).slice(0,40).map(u=>u.path+':'+u.line+' · '+u.expression+' — '+u.reason));plainList(byId('maps-diagnostic-list'),lines)}
64
+ function renderDiagnostics(){const c=data.counts||{},lines=[`Local analysis of Java, Angular, Python, JavaScript/TypeScript, Go, HTML/CSS and Markdown links. TXT and DOCX show up in coverage and in text search. ${c.parsed_files||0} of ${c.files||0} files were analyzed. Other languages and incomplete snapshots remain available in coverage.`,`${c.resolved_imports||0} resolved internal references; ${c.external_imports||0} external references; ${c.calls||0} call relations. Unresolved targets are a limited sample (${c.unresolved_calls||0} records in the analysis).`];if(data.truncated)lines.push('The analysis limits were reached. Filter by folder to explore the available part.');lines.push(...(data.diagnostics||[]).slice(0,60).map(d=>d.path+': '+d.reason));lines.push(...(data.unresolved||[]).slice(0,40).map(u=>u.path+':'+u.line+' · '+u.expression+' — '+u.reason));plainList(byId('maps-diagnostic-list'),lines)}
65
65
  function prepare(){const files=new Map((data?.files||[]).map(f=>[f.path,f]));currentNodes=mode==='calls'?(data?.symbols||[]).map(s=>({...s,file:files.get(s.path),label:s.name==='callback'?'callback :'+s.start_line:s.name})): (data?.files||[]).map(f=>({...f,file:f,label:/^(index|styles|__init__)\./.test(f.path.split('/').pop())?f.path.split('/').slice(-2).join('/'):f.path.split('/').pop()}));globalLookup=new Map(currentNodes.map(n=>[n.id,n]));currentEdges=(mode==='calls'?data?.calls:data?.dependencies)||[];currentEdges=currentEdges.filter(e=>e.target&&globalLookup.has(e.source)&&globalLookup.has(e.target));}
66
66
  function chooseVisible(){const term=byId('maps-search').value.trim().toLocaleLowerCase(),folder=byId('maps-folder').value,limit=Number(byId('maps-limit').value);const degree=new Map();for(const e of currentEdges){degree.set(e.source,(degree.get(e.source)||0)+1);degree.set(e.target,(degree.get(e.target)||0)+1)}let list=currentNodes.filter(n=>(!folder||n.file?.group===folder)&&(!term||(n.path+' '+n.label).toLocaleLowerCase().includes(term)));if(focus&&selectedNode){const near=new Set([selectedNode]);for(const e of currentEdges){if(e.source===selectedNode)near.add(e.target);if(e.target===selectedNode)near.add(e.source)}list=currentNodes.filter(n=>near.has(n.id))}list.sort((a,b)=>mode==='coverage'?(b.lines||0)-(a.lines||0):((degree.get(b.id)||0)-(degree.get(a.id)||0)||a.path.localeCompare(b.path)));if(selectedNode&&globalLookup.has(selectedNode)&&list.some(n=>n.id===selectedNode))list=[globalLookup.get(selectedNode),...list.filter(n=>n.id!==selectedNode)];shown=list.slice(0,limit);const ids=new Set(shown.map(n=>n.id));shownEdges=currentEdges.filter(e=>ids.has(e.source)&&ids.has(e.target)).slice(0,1000);byId('maps-count').textContent=mode==='coverage'?`${shown.length} of ${list.length} files · area by lines`:`${shown.length} of ${list.length} nodes · ${shownEdges.length} visible relations${focus?' · selected neighborhood':''}`;byId('maps-empty').hidden=!!shown.length;byId('maps-empty').textContent=mode==='calls'?'No resolved functions in this selection. Check the diagnostics or choose another folder/view.':'No files match the filter.';byId('maps-symbol-picker').replaceChildren(new Option('Select…',''),...list.slice(0,1000).map(n=>new Option(n.label+' · '+n.path,n.id)));if(selectedNode)byId('maps-symbol-picker').value=selectedNode;}
67
67
  function layout(){const groups=new Map();for(const n of shown){const pathGroup=n.file?.group||'(root)',parts=pathGroup.split('/'),g=parts.slice(0,parts[0]==='src'?2:1).join('/');if(!groups.has(g))groups.set(g,[]);groups.get(g).push(n)}const sorted=[...groups].sort((a,b)=>b[1].length-a[1].length);const cols=Math.max(1,Math.ceil(Math.sqrt(sorted.length*1.4)));let i=0;for(const [group,nodes] of sorted){const step=mode==='calls'?580:440,cx=210+(i%cols)*step,cy=210+Math.floor(i/cols)*step;nodes.forEach((n,j)=>{if(!positions.has(n.id)){const ring=Math.floor(Math.sqrt(j)),angle=j*2.399963,rad=nodes.length===1?0:mode==='calls'?90+ring*105:50+ring*65;positions.set(n.id,{x:cx+Math.cos(angle)*rad,y:cy+Math.sin(angle)*rad})}});i++}}
package/redirect_rule.py CHANGED
@@ -19,6 +19,7 @@ import glob
19
19
  import os
20
20
  import re
21
21
  import shlex
22
+ import tempfile
22
23
  import time
23
24
 
24
25
  import index_scope
@@ -109,13 +110,20 @@ def count_files(path):
109
110
  return files, False
110
111
 
111
112
 
113
+ def system_temp():
114
+ """The system's temporary folder."""
115
+ return tempfile.gettempdir()
116
+
117
+
112
118
  def _in_project(target, cwd):
113
- """A registered project holds target, or target is inside the session's directory."""
119
+ """A registered project holds target, or target is inside the session's directory and not in the system's
120
+ temporary folder: a copy made there for a measurement or a build is gone soon, and the redirected smart_search
121
+ would register and index it."""
114
122
  key = os.path.normcase(os.path.abspath(target)) + os.sep
115
123
  if any(key.startswith(os.path.normcase(os.path.abspath(p["root"])).rstrip(os.sep) + os.sep)
116
124
  for p in project_store.all_projects()):
117
125
  return True
118
- return bool(cwd) and index_scope._within_root(cwd, target)
126
+ return bool(cwd) and index_scope._within_root(cwd, target) and not index_scope._within_root(system_temp(), target)
119
127
 
120
128
 
121
129
  def _has_files(target):
package/setup_ui.py CHANGED
@@ -85,6 +85,7 @@ def status_payload():
85
85
  "scope_model": cfg.get("scope_model", ""),
86
86
  "scout_model": cfg.get("scout_model", ""),
87
87
  "research_model": cfg.get("research_model", ""),
88
+ "docs_model": cfg.get("docs_model", ""),
88
89
  "research_max_iterations": cfg.get("research_max_iterations", config.DEFAULT_CONFIG["research_max_iterations"]),
89
90
  "quick_search_timeout_s": cfg.get("quick_search_timeout_s", config.DEFAULT_CONFIG["quick_search_timeout_s"]),
90
91
  "site_memory_similarity_threshold": cfg.get("site_memory_similarity_threshold", config.DEFAULT_CONFIG["site_memory_similarity_threshold"]),
@@ -140,6 +141,7 @@ def handle_models_get():
140
141
  "scope_model": cfg.get("scope_model", ""),
141
142
  "scout_model": cfg.get("scout_model", ""),
142
143
  "research_model": cfg.get("research_model", ""),
144
+ "docs_model": cfg.get("docs_model", ""),
143
145
  "research_max_iterations": cfg.get("research_max_iterations", config.DEFAULT_CONFIG["research_max_iterations"]),
144
146
  "quick_search_timeout_s": cfg.get("quick_search_timeout_s", config.DEFAULT_CONFIG["quick_search_timeout_s"]),
145
147
  "site_memory_similarity_threshold": cfg.get("site_memory_similarity_threshold", config.DEFAULT_CONFIG["site_memory_similarity_threshold"]),
@@ -252,6 +254,10 @@ def handle_integration_get():
252
254
  doc_mode, doc_error = config.doc_mode(), ""
253
255
  except ValueError as exc:
254
256
  doc_mode, doc_error = "", str(exc)
257
+ try:
258
+ comment_mode, comment_error = config.comment_mode(), ""
259
+ except ValueError as exc:
260
+ comment_mode, comment_error = "", str(exc)
255
261
  try:
256
262
  duplicate_mode, duplicate_error = config.duplicate_mode(), ""
257
263
  except ValueError as exc:
@@ -270,7 +276,8 @@ def handle_integration_get():
270
276
  stored, patterns_error = block_patterns._empty(), str(exc)
271
277
  return {"daemon_url": setup_origin(), "clients": clients, "hook_mode": mode, "hook_mode_error": mode_error,
272
278
  "hook_modes": list(config.HOOK_MODES), "doc_mode": doc_mode, "doc_mode_error": doc_error,
273
- "doc_modes": list(config.DOC_MODES), "duplicate_mode": duplicate_mode,
279
+ "doc_modes": list(config.DOC_MODES), "comment_mode": comment_mode, "comment_mode_error": comment_error,
280
+ "comment_modes": list(config.COMMENT_MODES), "duplicate_mode": duplicate_mode,
274
281
  "duplicate_mode_error": duplicate_error, "duplicate_modes": list(config.DUPLICATE_MODES),
275
282
  "dependency_mode": dependency_mode, "dependency_mode_error": dependency_error,
276
283
  "dependency_modes": list(config.DEPENDENCY_MODES),
@@ -292,9 +299,9 @@ def handle_integration_save(body):
292
299
  except (OSError, ValueError) as exc:
293
300
  raise SetupError(str(exc))
294
301
  return handle_integration_get()
295
- if isinstance(body, dict) and body.get("action") in ("hook_mode", "doc_mode", "duplicate_mode", "dependency_mode", "pattern_proposals"):
302
+ if isinstance(body, dict) and body.get("action") in ("hook_mode", "doc_mode", "comment_mode", "duplicate_mode", "dependency_mode", "pattern_proposals"):
296
303
  action = body["action"]
297
- allowed = {"hook_mode": config.HOOK_MODES, "doc_mode": config.DOC_MODES,
304
+ allowed = {"hook_mode": config.HOOK_MODES, "doc_mode": config.DOC_MODES, "comment_mode": config.COMMENT_MODES,
298
305
  "duplicate_mode": config.DUPLICATE_MODES, "dependency_mode": config.DEPENDENCY_MODES,
299
306
  "pattern_proposals": config.PATTERN_PROPOSAL_MODES}[action]
300
307
  if body.get("mode") not in allowed:
@@ -451,6 +458,7 @@ _MODEL_FIELDS = {
451
458
  "scope_model": "chat",
452
459
  "scout_model": "chat",
453
460
  "research_model": "chat",
461
+ "docs_model": "chat",
454
462
  "embedding_model": "embedding",
455
463
  "rerank_model": "rerank",
456
464
  }
@@ -783,6 +791,7 @@ __I18N__
783
791
  </div>
784
792
  <div class="field"><label for="sel-scout">Code scout (optional)</label><span class="explain">smart_scout: writes a short answer over the lines it read and keeps only the ones that answer. Empty returns the literal lines without a model.</span><input id="sel-scout" list="dl-scout" autocomplete="off" spellcheck="false"><datalist id="dl-scout"></datalist></div>
785
793
  <div class="field"><label for="sel-research">Web research</label><span class="explain">Used by web_search with depth=research. Empty uses the router model.</span><input id="sel-research" list="dl-research" autocomplete="off" spellcheck="false"><datalist id="dl-research"></datalist></div>
794
+ <div class="field"><label for="sel-docs">Docs model</label><span class="explain">Writes the prose of the generated documentation (project_manage action=docs write_prose=true); each paragraph is checked against the code before it is written.</span><input id="sel-docs" list="dl-docs" autocomplete="off" spellcheck="false"><datalist id="dl-docs"></datalist></div>
786
795
  <details class="more">
787
796
  <summary>Advanced web research limits</summary>
788
797
  <div class="pair" style="margin-top:12px">
@@ -1135,6 +1144,7 @@ async function loadModels() {
1135
1144
  fillSuggestions($("sel-scope"), data.chat, data.current.scope_model);
1136
1145
  fillSuggestions($("sel-scout"), data.chat_lightweight.length ? data.chat_lightweight : data.chat, data.current.scout_model);
1137
1146
  fillSuggestions($("sel-research"), data.chat, data.current.research_model);
1147
+ fillSuggestions($("sel-docs"), data.chat, data.current.docs_model);
1138
1148
  fillSuggestions($("sel-embedding"), data.embedding, data.current.embedding_model);
1139
1149
  fillSuggestions($("sel-rerank"), data.rerank, data.current.rerank_model);
1140
1150
  fillNumber("num-research-iterations", "research-iterations-hint", data.ranges.research_max_iterations, data.current.research_max_iterations, data.recommended.research_max_iterations, "");
@@ -1211,7 +1221,7 @@ $("btn-save-models").addEventListener("click", async () => {
1211
1221
  setMsg("models-msg", "", "Saving…");
1212
1222
  try {
1213
1223
  await post("/setup/models", {
1214
- router_model: $("sel-router").value, scope_model: $("sel-scope").value, scout_model: $("sel-scout").value, research_model: $("sel-research").value,
1224
+ router_model: $("sel-router").value, scope_model: $("sel-scope").value, scout_model: $("sel-scout").value, research_model: $("sel-research").value, docs_model: $("sel-docs").value,
1215
1225
  research_max_iterations: Number($("num-research-iterations").value), quick_search_timeout_s: Number($("num-quick-timeout").value),
1216
1226
  site_memory_similarity_threshold: Number($("num-site-memory-threshold").value),
1217
1227
  embedding_model: $("sel-embedding").value, rerank_model: $("sel-rerank").value,
@@ -1302,9 +1312,14 @@ const RULES = [
1302
1312
  ["off", "Off", "No routing; agents use their native tools as usual."]] },
1303
1313
  { key: "doc_mode", title: "Documentation on edit", applies: "Applies on the next edit.",
1304
1314
  intro: "Checks the public functions an edit touches. Private, nested and override functions are exempt, as in pydocstyle, eslint-plugin-jsdoc and Checkstyle. A documented function comes up again only when its signature changes.",
1305
- options: [["remind", "Remind", "The edit runs; the agent is told which touched functions lack a docstring.", true],
1306
- ["require", "Require", "An edit that leaves a touched function without a docstring is blocked until it adds one."],
1315
+ options: [["require", "Require", "An edit that leaves a touched function without a docstring is blocked until it adds one.", true],
1316
+ ["remind", "Remind", "The edit runs; the agent is told which touched functions lack a docstring."],
1307
1317
  ["off", "Off", "No documentation checks."]] },
1318
+ { key: "comment_mode", title: "Comments in the wrong place", applies: "Applies on the next edit.",
1319
+ intro: "Checks the comments an edit adds: commented-out code, ticket or history tags, a loose block above a function instead of its docstring, and a long block inside a function body. A short comment that says why stays allowed.",
1320
+ options: [["require", "Require", "An edit that adds a comment in the wrong place is blocked until it is fixed.", true],
1321
+ ["remind", "Remind", "The edit runs; the agent is told which comments are misplaced."],
1322
+ ["off", "Off", "No comment checks."]] },
1308
1323
  { key: "duplicate_mode", title: "Duplicate functions on edit", applies: "Applies on the next edit.",
1309
1324
  intro: "Compares the functions an edit writes with the indexed code: identical bodies, and near-identical ones with only local names changed. It never blocks.",
1310
1325
  options: [["warn", "Warn", "The edit runs; the agent is told when a function copies one already in the project.", true],
@@ -35,6 +35,7 @@ import uuid
35
35
  from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
36
36
 
37
37
  sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
38
+ import atomic_io
38
39
  import browser_control
39
40
  import capabilities
40
41
  import client_hooks
@@ -93,6 +94,8 @@ MCP_MAX_REQUEST_BYTES = 10 * 1024 * 1024
93
94
  MCP_STREAM_AFTER_S = 10
94
95
  MCP_KEEPALIVE_S = 15
95
96
  _BOUND_PORT = DEFAULT_PORT
97
+ BIND_WAIT_S = 8
98
+ BIND_RETRY_S = 0.25
96
99
 
97
100
  DDG_SEARCH_SCRIPT = web_search_adapters.DDG_SEARCH_SCRIPT
98
101
  CAMOUFOX_VENV_PYTHON = web_search_adapters.CAMOUFOX_VENV_PYTHON
@@ -366,10 +369,10 @@ SERVER_INSTRUCTIONS = (
366
369
  TOOLS = [
367
370
  {
368
371
  "name": "project_manage",
369
- "description": "Manages folders and indexing. Every action takes project_root (the folder) or project_id. list gives a short line per project; status shows storage, scope and jobs. graph with symbol (function, Class.method, class name, or path::name when the name repeats) answers what an edit touches: definition, callers with line, calls, tests that reach it through static calls (depth hops, default 3) and files importing it; use it before changing a function to know what to update. affected_tests answers which tests to run after editing: every test file importing a changed file (git diff against base, default HEAD, untracked included) plus changed tests, likeliest failures first, with the command to run them and run_all when config or unanalyzed code changed. graph without symbol reads the indexed view: coverage, references and static calls in Java, Angular, Python and JS/TS/JSX/TSX; includes HTML/CSS/Markdown references and TXT/DOCX coverage; with file_path, narrows to that file's symbols, imports and calls (lists capped by limit). inspect lists the files of a view_id; with file_path, returns only that file's chunks. usage shows consumption and reuse; docs lists public functions without a docstring (Python docstring, JSDoc, Javadoc; private, nested and override functions excluded) with coverage percent, excluding tests unless include_tests=true, for documenting a project that started without it; duplicates lists duplicated functions (identical, near-identical and semantic bodies, min_similarity default 0.90; below that most pairs measured were false positives), excluding tests unless include_tests=true; fix real duplicates; only dismiss with duplicates_dismiss (finding_id, reason=false_positive|intentional, note) what is not a duplicate or is a copy kept on purpose: the finding stays hidden until the code changes, and duplicates_restore reopens it; integration shows the MCP client, hook and tool usage metrics; install_hook_preview shows the change that would install the hook redirecting Grep/Read to smart_search and WebSearch/WebFetch to web_search/web_fetch in this session's client and returns a plan_id; install_hook writes it with that plan_id and confirm=true, with a backup, only after the user approves the change; search_limits saves the project's default top_k per block ({code, test, doc}, each 1-20, total at most 20); storage shows disk usage and views; pin_view protects a view; cleanup_preview and cleanup_commit remove selected views after confirmation; compare compares two stored views, without checkout or embeddings. register adds a folder; preview checks the scope; index/rebuild update; pause/cancel keep checkpoints; resume continues; policy picks on_search/eager; scope adjusts the scope; remove deletes only the local index. setup_audit (project_root) reports what Claude Code and Codex actually load for that folder (settings layers, plugins, hooks, MCP servers, skills, CLAUDE.md/AGENTS.md) and where they collide: hooks deciding on the same tool in parallel, missing hook scripts, silenced hooks, MCP servers down or offering duplicate tools, skill name and budget problems, AGENTS.md that only Codex reads, broken @imports; what could not be checked is listed as not verified; each finding carries its fix (the file to edit or the command to run), applied by the agent when the user agrees, never by Smart Tool; mode=last returns the stored report instead of auditing again. redirect_proposals (no project_root) lists the redirect patterns proposed from allowed searches, most matched first, with a guide; redirect_decide decides them by ids: accept, instruct (tip without blocking), reject, or remove an accepted one. Jobs via smart_search_result.",
372
+ "description": "Manages folders and indexing. Every action takes project_root (the folder) or project_id. list gives a short line per project; status shows storage, scope and jobs. graph with symbol (function, Class.method, class name, or path::name when the name repeats) answers what an edit touches: definition, callers with line, calls, tests that reach it through static calls (depth hops, default 3) and files importing it; use it before changing a function to know what to update. affected_tests answers which tests to run after editing: every test file importing a changed file (git diff against base, default HEAD, untracked included) plus changed tests, likeliest failures first, with the command to run them and run_all when config or unanalyzed code changed. pr_impact (base, default HEAD; main or origin/main for a branch) returns a Markdown report of the change for a pull request: the functions the diff touches with their callers, the documentation entries it leaves out of date and the tests to run with their command; it publishes nothing. graph without symbol reads the indexed view: coverage, references and static calls in Java, Angular, Python, Go and JS/TS/JSX/TSX; includes HTML/CSS/Markdown references and TXT/DOCX coverage; with file_path, narrows to that file's symbols, imports and calls (lists capped by limit). inspect lists the files of a view_id; with file_path, returns only that file's chunks. usage shows consumption and reuse; docs lists public functions without a docstring (Python docstring, JSDoc, Javadoc, Go doc comment starting with the name; private, nested and override functions excluded) with coverage percent, excluding tests unless include_tests=true, for documenting a project that started without it; docs generate=true writes the documentation scope to docs/scope in the project in three levels tied to the code: technical pages by folder (an entry per public function anchored on path::name with signature, first doc line, layer, callers, calls and tests, plus a Mermaid flow by layer), functional.md (each entry point and the functions its flow reaches, by layer) and simple.md; the prose between the prose markers is kept by regeneration; docs write_prose=true writes the empty prose blocks with the Docs model of the setup (each paragraph checked against the code first) within about 40 s and says how many are left, call it again until none is; docs check=true reports anchors whose function changed signature or is gone and broken links; docs validate=true checks every claim of docs/scope against the code (anchors, links, line numbers, callers and tests, coverage, entry points, command-line options, prose names, counts, glossary, navigation, versions) and writes docs/scope/validation.md with pass/fail per check, the evidence, a score and the verdict (generate runs it too); docs with symbol lists where that function is documented; layers declares the project's layers (ordered highest first, each with path globs and annotations): without layers it returns the saved rule or a suggestion read from folder names and annotations, with files, symbols and calls between layers (direction down or up); pass layers to preview a rule and the same layers with confirm=true to save it in the project (.smart-tool/layers.json); duplicates lists duplicated functions (identical, near-identical and semantic bodies, min_similarity default 0.90; below that most pairs measured were false positives), excluding tests unless include_tests=true; fix real duplicates; only dismiss with duplicates_dismiss (finding_id, reason=false_positive|intentional, note) what is not a duplicate or is a copy kept on purpose: the finding stays hidden until the code changes, and duplicates_restore reopens it; integration shows the MCP client, hook and tool usage metrics; install_hook_preview shows the change that would install the hook redirecting Grep/Read to smart_search and WebSearch/WebFetch to web_search/web_fetch in this session's client and returns a plan_id; install_hook writes it with that plan_id and confirm=true, with a backup, only after the user approves the change; search_limits saves the project's default top_k per block ({code, test, doc}, each 1-20, total at most 20); storage shows disk usage and views; pin_view protects a view; cleanup_preview and cleanup_commit remove selected views after confirmation; compare compares two stored views, without checkout or embeddings. register adds a folder; preview checks the scope; index/rebuild update; pause/cancel keep checkpoints; resume continues; policy picks on_search/eager; scope adjusts the scope; remove deletes only the local index. setup_audit (project_root) reports what Claude Code and Codex actually load for that folder (settings layers, plugins, hooks, MCP servers, skills, CLAUDE.md/AGENTS.md) and where they collide: hooks deciding on the same tool in parallel, missing hook scripts, silenced hooks, MCP servers down or offering duplicate tools, skill name and budget problems, AGENTS.md that only Codex reads, broken @imports; what could not be checked is listed as not verified; each finding carries its fix (the file to edit or the command to run), applied by the agent when the user agrees, never by Smart Tool; mode=last returns the stored report instead of auditing again. redirect_proposals (no project_root) lists the redirect patterns proposed from allowed searches, most matched first, with a guide; redirect_decide decides them by ids: accept, instruct (tip without blocking), reject, or remove an accepted one. Jobs via smart_search_result.",
370
373
  "inputSchema": {
371
374
  "type": "object", "properties": {
372
- "action": {"type": "string", "enum": ["list", "status", "register", "preview", "index", "rebuild", "pause", "cancel", "resume", "watch", "scope", "remove", "relocate", "probe", "policy", "inspect", "graph", "usage", "storage", "pin_view", "cleanup_preview", "cleanup_commit", "compare", "search_limits", "integration", "install_hook_preview", "install_hook", "duplicates", "duplicates_dismiss", "duplicates_restore", "docs", "affected_tests", "setup_audit", "redirect_proposals", "redirect_decide"]},
375
+ "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"]},
373
376
  "ids": {"type": "array", "items": {"type": "string"}, "description": "redirect_decide: proposal ids from redirect_proposals (accepted ids for remove)"},
374
377
  "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"},
375
378
  "finding_id": {"type": "string"},
@@ -379,6 +382,15 @@ TOOLS = [
379
382
  "min_similarity": {"type": "number", "minimum": 0.5, "maximum": 1, "default": 0.9,
380
383
  "description": "Semantic cutoff for duplicates; keep 0.90: below it most pairs were false positives in measurement"},
381
384
  "include_tests": {"type": "boolean", "default": False},
385
+ "generate": {"type": "boolean", "default": False, "description": "docs: write the documentation scope to docs/scope, keeping the prose already written"},
386
+ "check": {"type": "boolean", "default": False, "description": "docs: report documentation anchors out of date with the code"},
387
+ "validate": {"type": "boolean", "default": False, "description": "docs: check every claim of docs/scope against the code and write the pass/fail report docs/scope/validation.md"},
388
+ "write_prose": {"type": "boolean", "default": False, "description": "docs: write the empty prose blocks of docs/scope with the Docs model, then regenerate and validate"},
389
+ "layers": {"type": "array", "description": "layers: the rule, highest layer first", "items": {
390
+ "type": "object", "additionalProperties": False, "required": ["name"], "properties": {
391
+ "name": {"type": "string"},
392
+ "paths": {"type": "array", "items": {"type": "string"}, "description": "globs relative to the project root, e.g. internal/handler/**"},
393
+ "annotations": {"type": "array", "items": {"type": "string"}, "description": "e.g. @RestController, @app.route"}}}},
382
394
  "limit": {"type": "integer", "minimum": 1, "maximum": 200, "default": 30},
383
395
  "days": {"type":"integer","minimum":1,"maximum":366},
384
396
  "top_k": {"type": "object", "additionalProperties": False, "properties": {
@@ -393,7 +405,7 @@ TOOLS = [
393
405
  "mode": {"type": "string", "enum": ["run", "last"], "default": "run", "description": "setup_audit: run audits now; last reads the stored report (the service audits registered projects every 30 minutes) without running anything, and fails when none is stored"},
394
406
  "probe": {"type": "boolean", "default": True, "description": "setup_audit: start/call each MCP server (initialize + tools/list); false reads configs only"},
395
407
  "base": {"type": "string", "default": "HEAD", "description": "affected_tests: git revision the changes are compared with (HEAD = uncommitted work; main or origin/main for a branch)"},
396
- "symbol": {"type": "string", "description": "graph: function, Class.method, class name or path::name to get its callers, calls, tests and importers"},
408
+ "symbol": {"type": "string", "description": "graph: function, Class.method, class name or path::name to get its callers, calls, tests and importers; docs: where that function is documented"},
397
409
  "depth": {"type": "integer", "minimum": 1, "maximum": 4, "default": 3, "description": "graph with symbol: call hops searched for tests"},
398
410
  "project_root": {"type": "string"}, "project_id": {"type": "string"},
399
411
  "job_id": {"type": "string"}, "watch": {"type": "boolean"},
@@ -2126,7 +2138,7 @@ def _project_action(arguments):
2126
2138
  action = arguments.get("action", "list")
2127
2139
  if action == "probe":
2128
2140
  return _probe_index_models()
2129
- if action in ('graph','compare','duplicates','duplicates_dismiss','duplicates_restore','docs','affected_tests'):
2141
+ if action in ('graph','compare','duplicates','duplicates_dismiss','duplicates_restore','docs','layers','affected_tests','pr_impact'):
2130
2142
  # Análise somente leitura pode demorar; não prende o lock global de ações.
2131
2143
  key=arguments.get('project_id')
2132
2144
  if not isinstance(key,str) or not re.fullmatch(r'[a-f0-9]{16}',key):
@@ -2138,11 +2150,39 @@ def _project_action(arguments):
2138
2150
  return _find_duplicates(project['root'], arguments, project.get('dismissed_duplicates') or {})
2139
2151
  if action=='docs':
2140
2152
  import doc_check
2153
+ import doc_scope
2141
2154
  include_tests=arguments.get('include_tests',False)
2142
- if type(include_tests) is not bool:
2143
- raise ValueError('include_tests must be true or false.')
2155
+ generate,check,symbol=arguments.get('generate',False),arguments.get('check',False),arguments.get('symbol')
2156
+ validate,write_prose=arguments.get('validate',False),arguments.get('write_prose',False)
2157
+ for name,value in (('include_tests',include_tests),('generate',generate),('check',check),('validate',validate),('write_prose',write_prose)):
2158
+ if type(value) is not bool:
2159
+ raise ValueError(f'{name} must be true or false.')
2160
+ if generate+check+validate+write_prose+(symbol is not None)+include_tests>1:
2161
+ raise ValueError('docs takes one of generate=true, check=true, validate=true, write_prose=true, symbol or include_tests=true.')
2144
2162
  limit=_parse_bounded_int(arguments.get('limit'),default=30,min_v=1,max_v=200,field_name='limit')
2163
+ if generate:
2164
+ return doc_scope.generate(project['root'],arguments.get('view_id'),limit)
2165
+ if check:
2166
+ return doc_scope.check(project['root'],arguments.get('view_id'),limit)
2167
+ if validate:
2168
+ import doc_validate
2169
+ return doc_validate.validate(project['root'],arguments.get('view_id'),limit)
2170
+ if write_prose:
2171
+ problem=_gateway_problem()
2172
+ if problem:
2173
+ raise RuntimeError(f'{problem} The prose is written by the Docs model through the gateway; no block was written.')
2174
+ import doc_prose
2175
+ return doc_prose.write(project['root'],arguments.get('view_id'),limit)
2176
+ if symbol is not None:
2177
+ return doc_scope.anchors(project['root'],symbol,arguments.get('view_id'))
2145
2178
  return doc_check.coverage(project['root'],include_tests,limit,arguments.get('view_id'))
2179
+ if action=='layers':
2180
+ import layers
2181
+ return layers.report(project['root'],arguments.get('layers'),arguments.get('confirm',False),arguments.get('view_id'))
2182
+ if action=='pr_impact':
2183
+ import pr_impact
2184
+ limit=_parse_bounded_int(arguments.get('limit'),default=30,min_v=1,max_v=200,field_name='limit')
2185
+ return pr_impact.report(project['root'],arguments.get('base','HEAD'),limit,arguments.get('view_id'))
2146
2186
  if action=='affected_tests':
2147
2187
  import affected_tests
2148
2188
  limit=_parse_bounded_int(arguments.get('limit'),default=30,min_v=1,max_v=200,field_name='limit')
@@ -4584,14 +4624,18 @@ class MCPHandler(BaseHTTPRequestHandler):
4584
4624
 
4585
4625
  def _write_registry(port):
4586
4626
  os.makedirs(RUN_DIR, exist_ok=True)
4587
- with open(REGISTRY_PATH, "w", encoding="utf-8") as f:
4588
- json.dump({"url": f"http://127.0.0.1:{port}", "pid": os.getpid(), "port": port}, f)
4627
+ atomic_io.write_text(REGISTRY_PATH, json.dumps({"url": f"http://127.0.0.1:{port}", "pid": os.getpid(), "port": port}))
4589
4628
 
4590
4629
 
4591
4630
  def _remove_registry():
4631
+ """Removes the announcement only when this process wrote it: an old daemon exiting after its successor announced
4632
+ itself must not erase the successor's entry."""
4592
4633
  try:
4634
+ with open(REGISTRY_PATH, encoding="utf-8") as f:
4635
+ if json.load(f).get("pid") != os.getpid():
4636
+ return
4593
4637
  os.remove(REGISTRY_PATH)
4594
- except OSError:
4638
+ except (OSError, ValueError, AttributeError):
4595
4639
  pass
4596
4640
 
4597
4641
 
@@ -4615,13 +4659,20 @@ def _bind_server():
4615
4659
  """The port clients already know, then the default port, then any free port (announced in daemon.json and synced
4616
4660
  to the clients by endpoint_sync). A connected session keeps the URL it started with, so a restart that moved
4617
4661
  back to the default would cut every session on the known port. A port held by another live Smart Tool stops this
4618
- start instead of duplicating it."""
4662
+ start instead of duplicating it. A busy port is retried for BIND_WAIT_S before the next candidate: the daemon it
4663
+ belonged to may still be shutting down in a restart, or too loaded to answer the health check, and moving on then
4664
+ strands every client that wrote the old port."""
4619
4665
  for port in dict.fromkeys(p for p in (endpoint_sync.known_port(), DEFAULT_PORT, 0) if p is not None):
4620
- try:
4621
- return _ExclusiveThreadingHTTPServer(("127.0.0.1", port), MCPHandler)
4622
- except OSError:
4623
- if port and _smart_tool_answers(port):
4624
- raise SystemExit(f"Smart Tool is already running on port {port}.")
4666
+ deadline = time.monotonic() + (BIND_WAIT_S if port else 0)
4667
+ while True:
4668
+ try:
4669
+ return _ExclusiveThreadingHTTPServer(("127.0.0.1", port), MCPHandler)
4670
+ except OSError:
4671
+ if port and _smart_tool_answers(port):
4672
+ raise SystemExit(f"Smart Tool is already running on port {port}.")
4673
+ if time.monotonic() >= deadline:
4674
+ break
4675
+ time.sleep(BIND_RETRY_S)
4625
4676
  raise OSError("No local port available for the daemon.")
4626
4677
 
4627
4678
 
package/usage_meter.py CHANGED
@@ -11,7 +11,7 @@ import project_store
11
11
 
12
12
  _CONTEXT=contextvars.ContextVar('smart_usage',default=None)
13
13
  _PHASES={'scope':'scope','embedding_query':'query_embedding','model_probe':'embedding_probe',
14
- 'indexing':'index_embedding','reranking':'rerank','scout':'scout'}
14
+ 'indexing':'index_embedding','reranking':'rerank','scout':'scout','docs':'docs'}
15
15
 
16
16
 
17
17
  @contextlib.contextmanager
@@ -23,6 +23,11 @@ def job(root,view,job_id):
23
23
  finally:_CONTEXT.reset(token)
24
24
 
25
25
 
26
+ def purpose():
27
+ """Purpose of the model calls made now ('scope', 'docs'...), None outside a metered job."""
28
+ return (_CONTEXT.get() or {}).get('purpose')
29
+
30
+
26
31
  def phase(name):
27
32
  current=_CONTEXT.get()
28
33
  if current and name in _PHASES:_CONTEXT.set({**current,'purpose':_PHASES[name]})
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.61"
4
+ VERSION = "0.9.66"
5
5
  _CONTACT_RE = re.compile(r"^(?:[^\s@()<>;]+@[^\s@()<>;]+\.[^\s@()<>;]+|https?://[^\s()<>;]+)$")
6
6
 
7
7
 
package/web_fetch.py CHANGED
@@ -71,7 +71,7 @@ def _ip_allowed(ip):
71
71
 
72
72
 
73
73
  def _public_address(host, port):
74
- """Resolves once; every address must be publicly routable (no private, loopback, link-local, CGNAT/Tailscale)."""
74
+ """Resolves once; every address must be publicly routable (no private, loopback, link-local, CGNAT)."""
75
75
  try:
76
76
  infos = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)
77
77
  except (socket.gaierror, UnicodeError):