@allansantos-dev/smart-tool 0.9.81 → 0.9.83

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.
Files changed (59) hide show
  1. package/CHANGELOG.md +115 -0
  2. package/NOTICE +1 -1
  3. package/README.md +73 -14
  4. package/affected_tests.py +9 -8
  5. package/agent_redirect.py +32 -0
  6. package/autostart.py +32 -25
  7. package/browser_bridge.py +320 -0
  8. package/browser_control.py +76 -39
  9. package/browser_service_client.py +1 -7
  10. package/client_hooks.py +41 -42
  11. package/code_graph.py +66 -21
  12. package/code_graph_java.mjs +21 -12
  13. package/code_health.py +14 -9
  14. package/codex_config.py +3 -0
  15. package/commit_check.py +184 -0
  16. package/daemon_launcher.py +37 -5
  17. package/doc_candidates.py +63 -0
  18. package/doc_check.py +9 -3
  19. package/doc_extras.py +2 -3
  20. package/doc_insights.py +26 -2
  21. package/doc_prose.py +59 -11
  22. package/doc_registry.py +241 -0
  23. package/doc_scope.py +205 -39
  24. package/doc_turn.py +205 -0
  25. package/doc_validate.py +52 -9
  26. package/document_converter.py +4 -4
  27. package/document_read.py +19 -11
  28. package/document_url.py +107 -0
  29. package/edit_shape.py +119 -0
  30. package/endpoint_sync.py +3 -21
  31. package/engine_home.py +95 -0
  32. package/hook_call.py +133 -0
  33. package/hook_decision.py +142 -7
  34. package/hooks/pre_commit.py +45 -0
  35. package/hooks/pretool_router.py +36 -30
  36. package/hooks/turn_end.py +40 -0
  37. package/index_views.py +5 -0
  38. package/install.py +24 -9
  39. package/lazy_mcp_proxy.py +10 -9
  40. package/local_embedder.py +8 -1
  41. package/locales/pt-BR.json +1 -2
  42. package/model_breaker.py +6 -5
  43. package/package.json +2 -2
  44. package/process_limits.py +17 -3
  45. package/project_identity.py +19 -1
  46. package/project_scan.py +98 -0
  47. package/release_notes.py +125 -0
  48. package/rename_preview.py +95 -0
  49. package/requester.py +1 -1
  50. package/scout_access.py +48 -0
  51. package/shell_reads.py +67 -0
  52. package/smart_tool_daemon.py +245 -50
  53. package/tray.py +31 -0
  54. package/venv_launch.py +67 -0
  55. package/version.py +1 -1
  56. package/web_adapters/node/engine-home.mjs +42 -0
  57. package/web_adapters/node/package-lock.json +13 -0
  58. package/web_adapters/node/package.json +1 -0
  59. package/web_fetch_many.py +61 -0
package/client_hooks.py CHANGED
@@ -10,13 +10,15 @@ import tomllib
10
10
 
11
11
  import atomic_io
12
12
  import codex_config
13
- import daemon_launcher
14
13
  import endpoint_sync
14
+ import hook_call
15
15
 
16
16
  HOOK_SCRIPT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "hooks", "pretool_router.py")
17
17
  MARKER = "pretool_router.py"
18
18
  AUDIT_SCRIPT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "hooks", "session_audit.py")
19
19
  AUDIT_MARKER = "session_audit.py"
20
+ TURN_SCRIPT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "hooks", "turn_end.py")
21
+ TURN_MARKER = "turn_end.py"
20
22
  # Hook origin convention shared by every project that installs hooks: a failed command hook names its owner.
21
23
  HOOK_ORIGIN = "--hook-origin=smart-tool"
22
24
  AUDIT_MATCHER = "startup|resume|clear|compact|fork"
@@ -27,17 +29,14 @@ AUDIT_WAITING = "waiting_approval"
27
29
  OWNER = "smart-tool"
28
30
  MANAGER_TIMEOUT_S = 5
29
31
  MANAGER_HELD = ("quarantined", "held")
30
- HTTP_PATH = "/hooks/pretool"
31
- POST_PATH = "/hooks/posttool"
32
- # A redirected shell search waits for its answer in the PreToolUse (smart_tool_daemon.HOOK_SHELL_BUDGET_S).
33
- HTTP_TIMEOUT_S = 15
34
- # The PostToolUse waits for the Smart Tool answer of a redirected call (web_fetch reads a whole page).
35
- POST_TIMEOUT_S = 60
32
+ LEGACY_URL_PATHS = ("/hooks/pretool", "/hooks/posttool", "/hooks/subagent-start")
33
+ # Each entry's timeout covers the restart wait of `hook_call` plus the longest answer the daemon takes on that route
34
+ # (a redirected shell search in the PreToolUse, a whole page in the PostToolUse of web_fetch).
36
35
  HOME = os.path.expanduser("~")
37
36
  PREVIEW_TTL_S = 600
38
37
  CLIENTS = {
39
38
  "claude": {"label": "Claude Code", "names": {"claude-code"}, "files": [os.path.join(endpoint_sync.claude_dir(), "settings.json")],
40
- "docs": "https://code.claude.com/docs/en/hooks", "event": "PreToolUse", "matcher": "Grep|Glob|Read|Bash|PowerShell|WebSearch|WebFetch|Edit|MultiEdit|Write|mcp__smart-tool__smart_search|mcp__smart-tool__web_search|mcp__smart-tool__web_fetch", "http": True,
39
+ "docs": "https://code.claude.com/docs/en/hooks", "event": "PreToolUse", "matcher": "Agent|Task|Grep|Glob|Read|Bash|PowerShell|WebSearch|WebFetch|Edit|MultiEdit|Write|mcp__smart-tool__smart_search|mcp__smart-tool__web_search|mcp__smart-tool__web_fetch|mcp__smart-tool__web_fetch_many",
41
40
  "post_matcher": "Grep|Bash|PowerShell|WebFetch|WebSearch"},
42
41
  "codex": {"label": "Codex", "prefix": "codex", "files": [os.path.join(endpoint_sync.codex_dir(), "hooks.json"), os.path.join(endpoint_sync.codex_dir(), "config.toml")],
43
42
  "docs": "https://learn.chatgpt.com/docs/hooks", "event": "PreToolUse", "matcher": "Bash|apply_patch", "post_matcher": "Bash",
@@ -58,17 +57,30 @@ def identify(client_info):
58
57
 
59
58
 
60
59
  def _our_hook(hook):
61
- return isinstance(hook, dict) and (MARKER in str(hook.get("command", "")) or
62
- any(path in str(hook.get("url", "")) for path in (HTTP_PATH, POST_PATH)))
60
+ return isinstance(hook, dict) and (MARKER in str(hook.get("command", "")) or TURN_MARKER in str(hook.get("command", "")) or
61
+ any(path in str(hook.get("url", "")) for path in LEGACY_URL_PATHS))
62
+
63
+
64
+ def _events(client):
65
+ """Events install writes an entry of ours under for the client, known without the daemon (removal needs no URL)."""
66
+ spec = CLIENTS[client]
67
+ return [spec["event"], *(["PostToolUse"] if spec.get("post_matcher") else []), *(["SubagentStart", "Stop"] if client == "claude" else [])]
63
68
 
64
69
 
65
70
  def _entries(client):
66
71
  """{event: (matcher, handler)} of our hook entries for the client: the PreToolUse, plus the PostToolUse that returns
67
- the Smart Tool answer of a redirected call and the review of the files a shell call wrote."""
72
+ the Smart Tool answer of a redirected call and the review of the files a shell call wrote, plus, in Claude Code, the
73
+ Stop command of the end-of-turn documentation step (matcher None: Stop takes none), plus the SubagentStart that tells
74
+ every subagent about smart_scout (no matcher: it reaches every agent type)."""
68
75
  spec = CLIENTS[client]
69
76
  entries = {spec["event"]: (spec["matcher"], _handler(client))}
70
77
  if spec.get("post_matcher"):
71
- entries["PostToolUse"] = (spec["post_matcher"], _handler(client, POST_PATH, POST_TIMEOUT_S))
78
+ entries["PostToolUse"] = (spec["post_matcher"], _handler(client, "posttool"))
79
+ if "SubagentStart" in _events(client):
80
+ entries["SubagentStart"] = (None, _handler(client, "subagent-start"))
81
+ if "Stop" in _events(client):
82
+ entries["Stop"] = (None, {"type": "command", "timeout": _timeout("stop"),
83
+ "command": f"{_shell_safe(sys.executable)} {_shell_safe(TURN_SCRIPT)} {HOOK_ORIGIN}"})
72
84
  return entries
73
85
 
74
86
 
@@ -141,7 +153,7 @@ def inspect(client, trust=True, manager=True):
141
153
  text = stream.read()
142
154
  except FileNotFoundError:
143
155
  continue
144
- if MARKER not in text and HTTP_PATH not in text:
156
+ if MARKER not in text and not any(path in text for path in LEGACY_URL_PATHS):
145
157
  continue
146
158
  if not path.endswith(".json"):
147
159
  return {"state": "current", "changes": []}
@@ -167,7 +179,7 @@ def _entry_changes(event, matcher, expected, groups):
167
179
  group = ours[0]
168
180
  changes = []
169
181
  covered = str(group.get("matcher") or "").split("|")
170
- left_out = [tool for tool in matcher.split("|") if tool not in covered]
182
+ left_out = [tool for tool in (matcher or "").split("|") if tool not in covered]
171
183
  if left_out:
172
184
  changes.append(f"Its {event} entry does not cover {', '.join(left_out)}.")
173
185
  found = next(hook for hook in group["hooks"] if _our_hook(hook))
@@ -237,32 +249,20 @@ def _shell_safe(path):
237
249
  return path.replace("\\", "/")
238
250
 
239
251
 
240
- def _command(client, route=HTTP_PATH):
241
- """The command of a client without HTTP hooks for the PreToolUse route (default) or the PostToolUse one, signed with
242
- HOOK_ORIGIN at the end."""
243
- after = " --post" if route == POST_PATH else ""
244
- return f"{_shell_safe(sys.executable)} {_shell_safe(HOOK_SCRIPT)} --client {client}{after} {HOOK_ORIGIN}"
252
+ def _timeout(route):
253
+ """The entry timeout of a route: the restart wait plus the longest answer, with a second to spare."""
254
+ return hook_call.ROUTE_TIMEOUT_S[route] + 1 + hook_call.RESTART_WINDOW_S
245
255
 
246
256
 
247
- def _port_file():
248
- """The daemon's announcement file as `~/<path>`, the form the hook audit reads to know the URL port is managed."""
249
- relative = os.path.relpath(daemon_launcher.REGISTRY_PATH, os.path.expanduser("~")).replace("\\", "/")
250
- if relative.startswith(".."):
251
- raise ValueError(f"The daemon announcement ({daemon_launcher.REGISTRY_PATH}) is outside the home folder; "
252
- "the hook cannot name it as its port file.")
253
- return f"~/{relative}"
257
+ def _command(client, route):
258
+ """The command of a client for a route (`pretool`, `posttool`, `subagent-start`), signed with HOOK_ORIGIN at the
259
+ end; it finds the daemon through its run file on every call."""
260
+ return f"{_shell_safe(sys.executable)} {_shell_safe(HOOK_SCRIPT)} --client {client} --route {route} {HOOK_ORIGIN}"
254
261
 
255
262
 
256
- def _handler(client, route=HTTP_PATH, timeout=HTTP_TIMEOUT_S):
257
- """Claude Code posts the payload straight to the warm daemon (`type: "http"`, no process per tool call); other
258
- clients run the thin command that forwards to the route."""
259
- if CLIENTS[client].get("http"):
260
- registry = daemon_launcher.read_registry()
261
- if not registry or not registry.get("url"):
262
- raise ValueError("Smart Tool daemon has no registered URL; start the daemon before installing the hook.")
263
- query = f"client={client}&hook-origin={OWNER}&port-file={_port_file()}"
264
- return {"type": "http", "url": f"{registry['url']}{route}?{query}", "timeout": timeout}
265
- return {"type": "command", "command": _command(client, route), "timeout": timeout}
263
+ def _handler(client, route="pretool"):
264
+ """The command handler of a client's entry for a route."""
265
+ return {"type": "command", "command": _command(client, route), "timeout": _timeout(route)}
266
266
 
267
267
 
268
268
  def _slot(groups, is_ours):
@@ -301,7 +301,8 @@ def _plan(client_info):
301
301
  raise ValueError(f"{path}: hooks.{event} is not a list; nothing was changed.")
302
302
  before, slot = list(groups), _slot(groups, _our_hook)
303
303
  groups[:] = _without_ours(groups)
304
- changes[event] = (groups, {"matcher": matcher, "hooks": [handler]}, slot, before)
304
+ changes[event] = (groups, {"hooks": [handler]} if matcher is None else {"matcher": matcher, "hooks": [handler]},
305
+ slot, before)
305
306
  return client, spec, path, data, changes
306
307
 
307
308
 
@@ -342,9 +343,8 @@ def install(client_info, token, confirm):
342
343
 
343
344
 
344
345
  def remove(client):
345
- """Takes every redirect hook entry of ours (PreToolUse and PostToolUse) out of the client's hooks
346
- file after a backup; other hooks stay, in Codex at the approval of their new index. Returns {client, changed, file,
347
- backup}."""
346
+ """Takes every hook entry install wrote (each event of `_entries`) out of the client's hooks file after a backup;
347
+ other hooks stay, in Codex at the approval of their new index. Returns {client, changed, file, backup}."""
348
348
  path = os.path.realpath(CLIENTS[client]["files"][0])
349
349
  try:
350
350
  with open(path, encoding="utf-8") as stream:
@@ -355,8 +355,7 @@ def remove(client):
355
355
  if not isinstance(hooks, dict):
356
356
  raise ValueError(f"{path} does not have the expected format (object with 'hooks'); nothing was changed.")
357
357
  moved = {}
358
- spec = CLIENTS[client]
359
- for event in (spec["event"], *(["PostToolUse"] if spec.get("post_matcher") else [])):
358
+ for event in _events(client):
360
359
  groups = hooks.get(event)
361
360
  if not isinstance(groups, list) or not any(_ours(group) for group in groups):
362
361
  continue
package/code_graph.py CHANGED
@@ -17,6 +17,7 @@ from pathlib import Path
17
17
  import indexer
18
18
  import index_inventory
19
19
  import index_scope
20
+ import project_scan
20
21
  import project_identity
21
22
  import web_search_adapters
22
23
  import web_document_graph
@@ -97,6 +98,28 @@ def _snapshot(path):
97
98
  conn.close()
98
99
 
99
100
 
101
+ def python_import_targets(path,node,known):
102
+ """The files of `known` that an import statement of the Python file `path` names.
103
+
104
+ Parameters: path (str) project-relative path of the importing file; node (ast.Import or ast.ImportFrom); known
105
+ (container of str) the project's files.
106
+ Returns: list of (alias, target, base): `target` is the file the alias resolves to or None; `base` is the module file of
107
+ a `from` import (None for a plain import and when the module is not a project file).
108
+ """
109
+ def resolve_file(spec):
110
+ spec=posixpath.normpath(spec)
111
+ return next((p for p in (spec+'.py',spec+'/__init__.py','src/'+spec+'.py','src/'+spec+'/__init__.py') if p in known), None)
112
+ if isinstance(node,ast.Import):
113
+ return [(item,resolve_file(item.name.replace('.','/')),None) for item in node.names]
114
+ prefix=posixpath.dirname(path)
115
+ if node.level:
116
+ for _ in range(node.level-1):prefix=posixpath.dirname(prefix)
117
+ spec=posixpath.join(prefix,(node.module or '').replace('.','/'))
118
+ else:spec=(node.module or '').replace('.','/')
119
+ base=resolve_file(spec)
120
+ return [(item,(resolve_file(spec+'/'+item.name) if item.name!='*' else None) or base,base) for item in node.names]
121
+
122
+
100
123
  def _python_graph(sources):
101
124
  trees, symbols, dependencies, calls, unresolved, diagnostics = {}, [], [], [], [], []
102
125
  decls, aliases, scopes, classes, owners, shadow_scopes, node_symbols = {}, {}, {}, {}, {}, {}, {}
@@ -104,9 +127,6 @@ def _python_graph(sources):
104
127
  def bind_import(path,scope,name,binding):
105
128
  table=aliases[path].setdefault(scope,{})
106
129
  table[name]=binding if name not in table or table[name]==binding else None
107
- def resolve_file(spec):
108
- spec=posixpath.normpath(spec)
109
- return next((p for p in (spec+'.py',spec+'/__init__.py','src/'+spec+'.py','src/'+spec+'/__init__.py') if p in sources), None)
110
130
  for path, text in sources.items():
111
131
  if not path.endswith('.py'):
112
132
  continue
@@ -132,20 +152,11 @@ def _python_graph(sources):
132
152
  collect(tree)
133
153
  for node in ast.walk(tree):
134
154
  if isinstance(node,ast.Import):
135
- for item in node.names:
136
- spec=item.name.replace('.','/');target=resolve_file(spec)
155
+ for item,target,_base in python_import_targets(path,node,sources):
137
156
  bind_import(path,owners[id(node)],item.asname or item.name,(target,None))
138
157
  dependencies.append({'source':path,'target':target,'specifier':item.name,'line':node.lineno,'kind':'import','resolution':'resolved' if target else 'external'})
139
158
  elif isinstance(node,ast.ImportFrom):
140
- prefix=posixpath.dirname(path)
141
- if node.level:
142
- for _ in range(node.level-1):prefix=posixpath.dirname(prefix)
143
- spec=posixpath.join(prefix,(node.module or '').replace('.','/'))
144
- else:spec=(node.module or '').replace('.','/')
145
- base=resolve_file(spec)
146
- for item in node.names:
147
- target=resolve_file(spec+'/'+item.name) if item.name!='*' else None
148
- target=target or base
159
+ for item,target,base in python_import_targets(path,node,sources):
149
160
  bind_import(path,owners[id(node)],item.asname or item.name,(target,None if target and target!=base else item.name))
150
161
  dependencies.append({'source':path,'target':target,'specifier':('.'*node.level)+(node.module or '')+'.'+item.name,'line':node.lineno,'kind':'import','resolution':'resolved' if target else 'unresolved' if node.level else 'external'})
151
162
  def chain(expr):
@@ -418,7 +429,9 @@ def _disk_save(key,data):
418
429
  return None
419
430
 
420
431
 
421
- def cached_symbols(root):
432
+ def _cached_analysis(root):
433
+ """(key, analysis) of the project's current index when memory or disk holds it; (key, None) when it does not and (None,
434
+ None) when the project has no index. Starts nothing."""
422
435
  path=indexer.existing_db_path(root)
423
436
  if not path:
424
437
  return None,None
@@ -433,6 +446,35 @@ def cached_symbols(root):
433
446
  with _LOCK:
434
447
  _CACHE[key]=data
435
448
  while len(_CACHE)>3:_CACHE.popitem(last=False)
449
+ return key,data
450
+
451
+
452
+ def cached_graph(root):
453
+ """The analysis of the project's current index when memory or disk already holds it, else None: it never analyzes and
454
+ never starts the background warm-up. The caller must only read it."""
455
+ return _cached_analysis(root)[1]
456
+
457
+
458
+ def import_edges(data):
459
+ """Resolved import edges of an analysis: dict file -> set of project files it imports, every file of an edge a key."""
460
+ edges={}
461
+ for dependency in data.get('dependencies') or []:
462
+ if dependency.get('kind')=='import' and dependency.get('resolution')=='resolved' and dependency.get('target'):
463
+ edges.setdefault(dependency['source'],set()).add(dependency['target'])
464
+ edges.setdefault(dependency['target'],set())
465
+ return edges
466
+
467
+
468
+ def cached_symbols(root):
469
+ """Symbols by file of the project's current index when its analysis is cached, starting the background analysis when it
470
+ is not (the caller never waits for it).
471
+
472
+ Parameters: root (str) project folder.
473
+ Returns: tuple (dict {"symbols", "parsed", "note"} or None while no analysis is ready; str note or None).
474
+ """
475
+ key,data=_cached_analysis(root)
476
+ if key is None:
477
+ return None,None
436
478
  with _LOCK:
437
479
  state=_WARM_STATE.get(root)
438
480
  if data is None and state and state['key']==key and (state['result'] or time.time()-state['at']<WARM_RETRY_S):
@@ -593,12 +635,15 @@ def _pending_changes(root,view_path):
593
635
  changes[rel]='deleted';continue
594
636
  if (stat.st_size,stat.st_mtime_ns)!=(size,stamp):changes[rel]='changed'
595
637
  scope=index_scope.load_scope(root)
596
- listed=subprocess.run(['git','ls-files','-z'],cwd=root,capture_output=True,timeout=30,
597
- creationflags=getattr(subprocess,'CREATE_NO_WINDOW',0))
598
- if scope and listed.returncode==0:
599
- for rel in listed.stdout.decode('utf-8','replace').split('\0'):
600
- if rel and rel not in indexed and rel not in changes and rel.lower().endswith(SOURCE_EXTENSIONS) \
601
- and index_scope.in_scope(scope,rel) and os.path.isfile(os.path.join(root,rel)):
638
+ try:
639
+ tracked=project_scan.tracked_files(root)
640
+ except ValueError as exc:
641
+ if exc.__cause__:raise
642
+ tracked=[]
643
+ if scope:
644
+ for rel in tracked:
645
+ if rel not in indexed and rel not in changes and rel.lower().endswith(SOURCE_EXTENSIONS) \
646
+ and index_scope.in_scope(scope,rel):
602
647
  changes[rel]='changed'
603
648
  return changes
604
649
 
@@ -9,7 +9,7 @@ if(nodeModule.registerHooks){const bundle=new URL('chevrotain/lib/chevrotain.mjs
9
9
  load(url,context,next){return url.startsWith('lodash-function:')?{format:'module',source:`import _ from ${JSON.stringify(lodash)};export default _.${url.slice(16)};`,shortCircuit:true}:next(url,context)}})}
10
10
  const {parse}=await import(new URL('java-parser/src/index.js',modules).href);
11
11
  const input=JSON.parse(fs.readFileSync(0,'utf8'));
12
- const symbols=[],dependencies=[],calls=[],unresolved=[],diagnostics=[],units=[],classes=new Map(),methodNodes=new Map(),kids=new WeakMap();
12
+ const symbols=[],dependencies=[],calls=[],unresolved=[],diagnostics=[],units=[],classes=new Map(),kids=new WeakMap(),declaredOnly=new Set();
13
13
  const {symbols:MAX_SYMBOLS,edges:MAX_EDGES}=input.limits;const leftOut={symbols:0,edges:0};
14
14
  function room(list,max,kind){if(list.length<max)return true;leftOut[kind]++;return false}
15
15
  const NO_CHILDREN=Object.freeze([]);
@@ -20,23 +20,32 @@ function identifiers(n){const out=[];function visit(node){if(node?.children)for(
20
20
  function text(u,n){return n?.location?u.text.slice(n.location.startOffset,n.location.endOffset+1):''}
21
21
  function addSymbol(u,n,name,kind){if(!room(symbols,MAX_SYMBOLS,'symbols'))return null;const s={id:u.path+'::'+name+'@'+n.location.startLine+':'+n.location.startOffset,path:u.path,name,kind,language:'java',start_line:n.location.startLine,end_line:n.location.endLine};symbols.push(s);return s}
22
22
  const classKinds=new Set(['normalClassDeclaration','normalInterfaceDeclaration','enumDeclaration','recordDeclaration']);
23
- for(const file of input.files){try{const tree=parse(file.text),pkg=first(tree,'packageDeclaration'),unit={...file,tree,package:pkg?identifiers(pkg).map(t=>t.image).join('.'): '',imports:[],classes:[]};
23
+ const METHOD_KINDS=new Set(['methodDeclaration','interfaceMethodDeclaration','constructorDeclaration','compactConstructorDeclaration']);
24
+ // Each file is parsed twice, once to index its types and once to walk its calls, so only one syntax tree is alive at a time.
25
+ for(const file of input.files){try{const tree=parse(file.text),pkg=first(tree,'packageDeclaration'),unit={...file,methodsAt:new Map(),package:pkg?identifiers(pkg).map(t=>t.image).join('.'): '',imports:[],classes:[]};
24
26
  for(const n of all(tree,'importDeclaration')){const raw=text(unit,n).replace(/^import\s+/,'').replace(/;\s*$/,'').trim(),stat=raw.startsWith('static '),spec=(stat?raw.slice(7):raw).replace(/\s+/g,'');unit.imports.push({spec,static:stat,line:n.location.startLine})}
25
- function scan(n,parent=null){let current=parent;if(classKinds.has(n.name)){const id=first(n,'typeIdentifier')||first(n,'typeName'),short=identifiers(id||n)[0]?.image;if(!short)return;const local=(parent?parent.local+'.':'')+short,fqn=(unit.package?unit.package+'.':'')+local;const symbol=addSymbol(unit,n,local,n.name==='normalInterfaceDeclaration'?'interface':'class');if(!symbol)return;current={unit,fqn,local,short,symbol,node:n,body:n.children.classBody?.[0]||n.children.interfaceBody?.[0]||n.children.recordBody?.[0]||n.children.enumBody?.[0],methods:[],fields:new Map(),extends:text(unit,n.children.classExtends?.[0]).replace(/^extends\s+/, '').trim()};classes.set(fqn,classes.has(fqn)?null:current);unit.classes.push(current)}
27
+ function scan(n,parent=null){let current=parent;if(classKinds.has(n.name)){const id=first(n,'typeIdentifier')||first(n,'typeName'),short=identifiers(id||n)[0]?.image;if(!short)return;const local=(parent?parent.local+'.':'')+short,fqn=(unit.package?unit.package+'.':'')+local;const symbol=addSymbol(unit,n,local,n.name==='normalInterfaceDeclaration'?'interface':'class');if(!symbol)return;current={unit,fqn,local,short,symbol,node:n,offset:n.location.startOffset,body:n.children.classBody?.[0]||n.children.interfaceBody?.[0]||n.children.recordBody?.[0]||n.children.enumBody?.[0],methods:[],fields:new Map(),extends:text(unit,n.children.classExtends?.[0]).replace(/^extends\s+/, '').trim()};classes.set(fqn,classes.has(fqn)?null:current);unit.classes.push(current)}
26
28
  if(current&&n.name==='classBody'&&n!==current.body)return;
27
- if(current&&['methodDeclaration','interfaceMethodDeclaration','constructorDeclaration','compactConstructorDeclaration'].includes(n.name)){const declarator=first(n,'methodDeclarator')||first(n,'constructorDeclarator'),ctor=n.name.includes('Constructor')||n.name==='constructorDeclaration',name=ctor?current.short:(declarator?.children.Identifier?.[0]?.image);if(name){const params=all(declarator||n,'formalParameter'),types=params.map(p=>text(unit,first(p,'unannType'))||'?');const signature=name+'('+types.join(',')+')';const sym=addSymbol(unit,n,current.local+'.'+signature,ctor?'constructor':'method');if(sym){sym.signature=signature;const method={symbol:sym,name,arity:params.length,types,node:n,cls:current,params,concrete:!!first(n,'block')||ctor};current.methods.push(method);methodNodes.set(n,method)}}}
28
- for(const child of children(n))scan(child,current)}scan(tree);units.push(unit)
29
+ if(current&&METHOD_KINDS.has(n.name)){const declarator=first(n,'methodDeclarator')||first(n,'constructorDeclarator'),ctor=n.name.includes('Constructor')||n.name==='constructorDeclaration',name=ctor?current.short:(declarator?.children.Identifier?.[0]?.image);if(name){const params=all(declarator||n,'formalParameter'),types=params.map(p=>text(unit,first(p,'unannType'))||'?');const signature=name+'('+types.join(',')+')';const sym=addSymbol(unit,n,current.local+'.'+signature,ctor?'constructor':'method');if(sym){sym.signature=signature;const method={symbol:sym,name,arity:params.length,types,cls:current,concrete:!!first(n,'block')||ctor};current.methods.push(method);unit.methodsAt.set(n.location.startOffset,method)}}}
30
+ for(const child of children(n))scan(child,current)}scan(tree);indexFields(unit);units.push(unit)
29
31
  }catch{diagnostics.push({path:file.path,reason:'Invalid or fragmented Java, or syntax not supported by the parser.'})}}
32
+ function indexFields(unit){for(const cl of unit.classes){for(const node of scoped(cl.body,'fieldDeclaration')){const type=text(unit,first(node,'unannType'));for(const id of all(node,'variableDeclaratorId'))putBinding(cl.fields,identifiers(id)[0]?.image,type)}cl.bodyStart=cl.body?.location.startOffset;cl.node=cl.body=null}}
30
33
  function resolveType(unit,raw,context){let name=raw.replace(/@[\w.]+(?:\([^)]*\))?/g,'').replace(/<.*>/g,'').replace(/\[\]|\.\.\./g,'').trim();if(!name||['void','boolean','byte','short','int','long','float','double','char','var'].includes(name))return null;if(classes.has(name))return classes.get(name);const candidates=new Set();const local=[context?context.fqn+'.'+name:'',unit.package?unit.package+'.'+name:name];for(const fq of local)if(classes.has(fq))candidates.add(fq);for(const item of unit.imports.filter(i=>!i.static)){if(item.spec.endsWith('.'+name)&&classes.has(item.spec))candidates.add(item.spec);if(item.spec.endsWith('.*')){const fq=item.spec.slice(0,-1)+name;if(classes.has(fq))candidates.add(fq)}}return candidates.size===1?classes.get([...candidates][0]):null}
31
- function lookupMethod(cls,name,arity,visited=new Set()){if(!cls||visited.has(cls.fqn))return null;visited.add(cls.fqn);const methods=cls.methods.filter(m=>m.name===name&&m.arity===arity&&m.concrete);if(methods.length===1)return methods[0].symbol;if(methods.length>1)return null;return cls.extends?lookupMethod(resolveType(cls.unit,cls.extends,cls),name,arity,visited):null}
34
+ function lookupMethod(cls,name,arity,visited=new Set()){if(!cls||visited.has(cls.fqn))return null;visited.add(cls.fqn);const methods=cls.methods.filter(m=>m.name===name&&m.arity===arity&&m.concrete);if(methods.length===1)return methods[0].symbol;if(methods.length>1)return null;if(cls.symbol.kind==='interface')return declaredMethod(cls,name,arity);return cls.extends?lookupMethod(resolveType(cls.unit,cls.extends,cls),name,arity,visited):null}
35
+ /**
36
+ * The method an interface of the project declares with this name and arity, reached by a call through a field or
37
+ * variable of that type; a method the interface inherits from a library has no project symbol and stays unresolved.
38
+ * @param {object} cls interface entry; @param {string} name method name; @param {number} arity argument count
39
+ * @returns {object|null} the method symbol, or null when none or more than one matches
40
+ */
41
+ function declaredMethod(cls,name,arity){const methods=cls.methods.filter(m=>m.name===name&&m.arity===arity);if(methods.length!==1)return null;declaredOnly.add(methods[0].symbol.id);return methods[0].symbol}
32
42
  function putBinding(map,name,type){if(name)map.set(name,map.has(name)&&map.get(name)!==type?null:type)}
33
43
  function scoped(node,name){const out=[];function scan(n){if(n!==node&&(classKinds.has(n.name)||n.name==='lambdaExpression'||n.name==='classBody'))return;if(n.name===name)out.push(n);for(const c of children(n))scan(c)}scan(node);return out}
34
44
  function collectVariables(unit,node,map){for(const parentName of ['fieldDeclaration','localVariableDeclaration','variableParaRegularParameter','variableArityParameter'])for(const declaration of scoped(node,parentName)){const type=text(unit,first(declaration,'unannType'));for(const id of all(declaration,'variableDeclaratorId'))putBinding(map,identifiers(id)[0]?.image,type)}}
35
- for(const unit of units){for(const cl of unit.classes){const fieldNodes=scoped(cl.body,'fieldDeclaration');for(const node of fieldNodes){const type=text(unit,first(node,'unannType'));for(const id of all(node,'variableDeclaratorId'))putBinding(cl.fields,identifiers(id)[0]?.image,type)}}}
36
- for(const unit of units){
45
+ for(const unit of units){const tree=parse(unit.text);
37
46
  for(const item of unit.imports){const spec=item.spec;let target=classes.get(item.static?spec.split('.').slice(0,-1).join('.'):spec);dependencies.push({source:unit.path,target:target?.unit.path||null,specifier:spec,line:item.line,kind:item.static?'java_static_import':'import',resolution:target?'resolved':'external'})}
38
- function walk(n,cls=null,method=null,vars=new Map(),owner=null){if(classKinds.has(n.name))cls=unit.classes.find(c=>c.node===n)||cls;if(cls&&n.name==='classBody'&&n!==cls.body)return;
39
- if(methodNodes.has(n)){method=methodNodes.get(n);vars=new Map(cls.fields);collectVariables(unit,n,vars);owner=method.symbol}
47
+ function walk(n,cls=null,method=null,vars=new Map(),owner=null){if(classKinds.has(n.name))cls=unit.classes.find(c=>c.offset===n.location.startOffset)||cls;if(cls&&n.name==='classBody'&&n.location.startOffset!==cls.bodyStart)return;
48
+ if(METHOD_KINDS.has(n.name)&&unit.methodsAt.has(n.location.startOffset)){method=unit.methodsAt.get(n.location.startOffset);vars=new Map(cls.fields);collectVariables(unit,n,vars);owner=method.symbol}
40
49
  if(n.name==='lambdaExpression'){vars=new Map(vars);for(const param of identifiers(n.children.lambdaParameters?.[0]))vars.set(param.image,null);owner=addSymbol(unit,n,(cls?.local||'')+'.lambda@'+n.location.startLine,'function')||owner}
41
50
  if(cls&&['unannType','classType','interfaceType'].includes(n.name)){const type=resolveType(unit,text(unit,n),cls);if(type&&type.unit.path!==unit.path&&room(dependencies,MAX_EDGES,'edges'))dependencies.push({source:unit.path,target:type.unit.path,specifier:type.fqn,line:n.location.startLine,kind:'java_type',resolution:'resolved'})}
42
51
  if(cls&&n.name==='primary'){
@@ -49,13 +58,13 @@ for(const unit of units){
49
58
  for(const suffix of suffixes){const invoke=suffix.children.methodInvocationSuffix?.[0];if(!invoke){chain+=text(unit,suffix);continue}const args=invoke.children.argumentList?.[0],arity=args?(args.children.expression||[]).length:0;const match=/^(?:([\w.$]+)\.)?([\w$]+)$/.exec(chain);let target=null;
50
59
  if(match&&!fluent){const receiver=match[1],name=match[2];let type=null;if(!receiver||receiver==='this')type=cls;else if(receiver==='super')type=resolveType(unit,cls.extends,cls);else if(receiver.startsWith('this.'))type=resolveType(unit,cls.fields.get(receiver.slice(5))||'',cls);else if(vars.has(receiver))type=resolveType(unit,vars.get(receiver)||'',cls);else{type=resolveType(unit,receiver,cls);link(type,invoke.location.startLine)}target=lookupMethod(type,name,arity);if(!target&&!receiver){const candidates=unit.imports.filter(i=>i.static&&(i.spec.endsWith('.'+name)||i.spec.endsWith('.*'))).map(i=>lookupMethod(classes.get(i.spec.split('.').slice(0,-1).join('.')),name,arity)).filter(Boolean);if(candidates.length===1)target=candidates[0]}}
51
60
  if(constructed&&!fluent){const methodName=/\.([\w$]+)$/.exec(chain)?.[1];if(methodName)target=lookupMethod(constructed,methodName,arity)}
52
- if(target&&room(calls,MAX_EDGES,'edges'))calls.push({source:(owner||cls.symbol).id,target:target.id,line:invoke.location.startLine,kind:'call',resolution:'static'});
61
+ if(target&&room(calls,MAX_EDGES,'edges'))calls.push({source:(owner||cls.symbol).id,target:target.id,line:invoke.location.startLine,kind:'call',resolution:declaredOnly.has(target.id)?'declared':'static'});
53
62
  else if(unresolved.length<1000)unresolved.push({path:unit.path,line:invoke.location.startLine,expression:chain.slice(0,140),reason:'External/dynamic type, interface without implementation, or ambiguous overload in the Java snapshot.'});
54
63
  fluent=true;chain+='<result>';
55
64
  }
56
65
  }
57
66
  for(const child of children(n))walk(child,cls,method,vars,owner)
58
- }walk(unit.tree)
67
+ }walk(tree)
59
68
  }
60
69
  const ids=new Set(symbols.map(s=>s.id)),linked=calls.filter(c=>ids.has(c.source)&&ids.has(c.target));
61
70
  leftOut.edges+=calls.length-linked.length;
package/code_health.py CHANGED
@@ -73,15 +73,25 @@ def coupled_with(root, paths, view_id=None, limit=DEFAULT_LIMIT):
73
73
  commits, note = doc_insights.history(root)
74
74
  if note:
75
75
  return {"files": [], "note": note}
76
- changed, rows, seen = set(paths), [], set()
77
- for first, second, shared, degree, linked in doc_insights.coupling(model, commits):
76
+ return {"files": partners(doc_insights.coupling(model, commits), set(paths))[:limit], "note": ""}
77
+
78
+
79
+ def partners(pairs, changed):
80
+ """The files that change with the changed ones, from the pairs `doc_insights.coupling` returns.
81
+
82
+ Parameters: pairs (list) rows (a, b, shared, degree, linked), strongest first; changed (set of str) the changed files.
83
+ Returns: list of {"path", "with", "shared", "degree"}, strongest first, one row per partner outside `changed`; a pair
84
+ where one file imports the other is skipped.
85
+ """
86
+ rows, seen = [], set()
87
+ for first, second, shared, degree, linked in pairs:
78
88
  if linked or (first in changed) == (second in changed):
79
89
  continue
80
90
  partner, anchor = (second, first) if first in changed else (first, second)
81
91
  if partner not in seen:
82
92
  seen.add(partner)
83
93
  rows.append({"path": partner, "with": anchor, "shared": shared, "degree": int(degree * 100)})
84
- return {"files": rows[:limit], "note": ""}
94
+ return rows
85
95
 
86
96
 
87
97
  def _pop_component(stack, on_stack, node):
@@ -146,12 +156,7 @@ def import_cycles(root, view_id=None, limit=DEFAULT_LIMIT):
146
156
  data = code_graph.build_current(root, view_id, shared=True)
147
157
  if not data.get("symbols") and not data.get("dependencies"):
148
158
  raise ValueError(f"The code graph of {root} is empty: index the project first (project_manage action=index).")
149
- edges = {}
150
- for dependency in data.get("dependencies") or []:
151
- if dependency.get("kind") == "import" and dependency.get("resolution") == "resolved" and dependency.get("target"):
152
- edges.setdefault(dependency["source"], set()).add(dependency["target"])
153
- edges.setdefault(dependency["target"], set())
154
- cycles = sorted(_components(edges), key=lambda files: (-len(files), files))
159
+ cycles = sorted(_components(code_graph.import_edges(data)), key=lambda files: (-len(files), files))
155
160
  note = code_graph.left_out_sentence(data) if data.get("truncated") else ""
156
161
  return {"cycles": [{"files": files, "size": len(files)} for files in cycles[:limit]], "total": len(cycles),
157
162
  "files_in_cycles": sum(len(files) for files in cycles), "note": note}
package/codex_config.py CHANGED
@@ -57,6 +57,9 @@ def _value(value):
57
57
  .replace("\t", "\\t") + '"'
58
58
  if isinstance(value, (list, tuple)):
59
59
  return "[" + ", ".join(_value(item) for item in value) + "]"
60
+ if isinstance(value, dict):
61
+ return "{ " + ", ".join(f"{key if _BARE_KEY.match(key) else _value(key)} = {_value(item)}"
62
+ for key, item in value.items()) + " }"
60
63
  raise TypeError(f"Unsupported value for config.toml: {value!r}")
61
64
 
62
65
 
@@ -0,0 +1,184 @@
1
+ """Commit-time review of the staged change, and the opt-in git hook that prints it.
2
+
3
+ The review is the one the edit hook gives a finished diff (`hook_decision.review_diff`), over what `git diff --cached`
4
+ holds, so edits the agent hook never saw (an IDE, hand edits, another agent) are reviewed before they reach the commit.
5
+ The `pre-commit` script this module writes only forwards to the daemon (`hooks/pre_commit.py`) and never blocks a commit.
6
+ """
7
+ import glob
8
+ import json
9
+ import os
10
+ import shlex
11
+ import subprocess
12
+ import sys
13
+
14
+ import affected_tests
15
+ import atomic_io
16
+ import client_hooks
17
+ import config
18
+ import hook_decision
19
+
20
+ MARKER = "# smart-tool-commit-check"
21
+ HOOK_NAME = "pre-commit"
22
+ HOOK_SCRIPT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "hooks", "pre_commit.py")
23
+ HOOK_ORIGIN = client_hooks.HOOK_ORIGIN
24
+ MAX_FILES = 50
25
+ NO_WINDOW = getattr(subprocess, "CREATE_NO_WINDOW", 0)
26
+
27
+
28
+ def _git_raw(root, *args):
29
+ """The finished `git` process (bytes output) run in `root`; the caller reads the exit code."""
30
+ return subprocess.run(["git", *args], cwd=root, capture_output=True, timeout=60, creationflags=NO_WINDOW)
31
+
32
+
33
+ def _staged_text(root, rel):
34
+ """The text of `rel` as staged, or None when it is binary, not UTF-8 or over the review size."""
35
+ done = _git_raw(root, "show", f":./{rel}")
36
+ if done.returncode or len(done.stdout) > hook_decision.MAX_REVIEW_BYTES:
37
+ return None
38
+ try:
39
+ text = done.stdout.decode("utf-8")
40
+ except UnicodeDecodeError:
41
+ return None
42
+ return None if "\0" in text else text
43
+
44
+
45
+ def _staged_paths(root):
46
+ """Paths relative to `root` of the files the commit adds or changes (a deletion has nothing to review), sorted."""
47
+ fields = affected_tests._git(root, "diff", "--cached", "--name-status", "-z", "--no-renames", "--relative",
48
+ "--", ".").split("\0")
49
+ return sorted(path for status, path in zip(fields[0::2], fields[1::2]) if status != "D")
50
+
51
+
52
+ def review(root):
53
+ """Reviews the staged change of the repository at `root` with the notes the edit hook gives a finished diff.
54
+
55
+ Parameters: root (str) project folder, inside a git repository.
56
+ Returns: dict with `files` (the staged files that were reviewed) and `notes` (str; empty when every check is quiet,
57
+ and it says how many staged files past MAX_FILES were not reviewed).
58
+ Raises: ValueError when git cannot read the index, RuntimeError or OSError when a check cannot run.
59
+ """
60
+ paths = _staged_paths(root)
61
+ changes = []
62
+ for rel in paths[:MAX_FILES]:
63
+ after = _staged_text(root, rel)
64
+ if after is None:
65
+ continue
66
+ try:
67
+ before = affected_tests._git(root, "show", f"HEAD:./{rel}")
68
+ except ValueError:
69
+ before = None
70
+ changes.append((rel, os.path.join(root, *rel.split("/")), before, after))
71
+ notes = hook_decision.review_diff([(full, before, after) for _rel, full, before, after in changes],
72
+ config.load_config()) if changes else ""
73
+ left = len(paths) - MAX_FILES
74
+ if left > 0:
75
+ skipped = f"{left} staged file{'s were' if left != 1 else ' was'} not reviewed: the review reads the first {MAX_FILES}."
76
+ notes = f"{notes} {skipped}".strip()
77
+ return {"files": [rel for rel, *_ in changes], "notes": notes}
78
+
79
+
80
+ def hook_python():
81
+ """The interpreter the hook runs, with forward slashes and no spaces: this process's own, or its console twin when
82
+ that is the windowless `pythonw`, which would drop the notes the hook prints to stderr."""
83
+ path = sys.executable
84
+ if os.path.basename(path).lower() == "pythonw.exe":
85
+ path = os.path.join(os.path.dirname(path), "python.exe")
86
+ return client_hooks._shell_safe(path)
87
+
88
+
89
+ def _hook_text():
90
+ """The `pre-commit` script: the review client of the product, and a visible line, never a failing exit, when it
91
+ cannot start (a git hook that exits non-zero blocks the commit)."""
92
+ command = f"{shlex.quote(hook_python())} {shlex.quote(client_hooks._shell_safe(HOOK_SCRIPT))} {HOOK_ORIGIN}"
93
+ return (f"#!/bin/sh\n{MARKER}: written by Smart Tool (project_manage action=commit_hook_install); "
94
+ f"commit_hook_uninstall removes it\n"
95
+ f'{command} || echo "Smart Tool commit check could not run (exit $?), commit not reviewed" >&2\n'
96
+ "exit 0\n")
97
+
98
+
99
+ def _hooks_dir(root):
100
+ """The absolute folder git runs hooks from for the repository at `root` (a worktree or submodule shares the one
101
+ its `.git` file points to)."""
102
+ return os.path.abspath(os.path.join(root, affected_tests._git(root, "rev-parse", "--git-path", "hooks").strip()))
103
+
104
+
105
+ def _read(path):
106
+ with open(path, encoding="utf-8", errors="replace") as stream:
107
+ return stream.read()
108
+
109
+
110
+ def _husky(root):
111
+ """Sentences naming where husky manages the git hooks of the repository: a `.husky` folder, or `husky` in the
112
+ dependencies or scripts of a package.json, in `root` and in the top of the repository."""
113
+ top = affected_tests._git(root, "rev-parse", "--show-toplevel").strip()
114
+ found = []
115
+ for folder in {os.path.realpath(path): path for path in (root, top)}.values():
116
+ if os.path.isdir(os.path.join(folder, ".husky")):
117
+ found.append(f"husky manages the git hooks here (a .husky folder in {folder})")
118
+ try:
119
+ package = json.loads(_read(os.path.join(folder, "package.json")))
120
+ except (OSError, ValueError):
121
+ continue
122
+ used = isinstance(package, dict) and (
123
+ any("husky" in (package.get(kind) or {}) for kind in ("dependencies", "devDependencies")) or
124
+ any("husky" in str(command) for command in (package.get("scripts") or {}).values()))
125
+ if used:
126
+ found.append(f"husky manages the git hooks here (package.json in {folder} names it)")
127
+ return found
128
+
129
+
130
+ def _blockers(root, hook):
131
+ """Sentences naming what makes the install refuse: `core.hooksPath` set, husky, or a `pre-commit` that is not ours."""
132
+ found = []
133
+ configured = _git_raw(root, "config", "--show-scope", "--get", "core.hooksPath")
134
+ if configured.returncode == 0:
135
+ scope, _, value = configured.stdout.decode("utf-8", "replace").strip().partition("\t")
136
+ found.append(f"core.hooksPath is set ({scope}) to {value}, so git does not run .git/hooks")
137
+ elif configured.returncode != 1:
138
+ raise ValueError(f"git config core.hooksPath failed: {configured.stderr.decode('utf-8', 'replace').strip()[:300]}")
139
+ found += _husky(root)
140
+ if os.path.isfile(hook) and MARKER not in _read(hook):
141
+ found.append(f"{hook} already exists and is not Smart Tool's (it has no {MARKER} line)")
142
+ return found
143
+
144
+
145
+ def install_hook(root):
146
+ """Writes the opt-in `pre-commit` hook of the repository at `root`, after a backup of an older hook of ours.
147
+
148
+ Parameters: root (str) project folder, inside a git repository.
149
+ Returns: dict with `installed`, `changed`, `file` and `backup` (path of the copy of our older hook, None when new).
150
+ Raises: ValueError, naming everything found and changing nothing, when core.hooksPath is set, husky is used or a
151
+ `pre-commit` that is not ours exists.
152
+ """
153
+ hook = os.path.join(_hooks_dir(root), HOOK_NAME)
154
+ found = _blockers(root, hook)
155
+ if found:
156
+ raise ValueError("The commit hook was not installed and nothing was changed: " + "; ".join(found) + ".")
157
+ os.makedirs(os.path.dirname(hook), exist_ok=True)
158
+ backup = atomic_io.backup_file(hook)
159
+ atomic_io.write_text(hook, _hook_text())
160
+ os.chmod(hook, 0o755)
161
+ return {"installed": True, "changed": True, "file": hook, "backup": backup,
162
+ "note": "Commits in this repository print the review of the staged change to stderr and never wait on it "
163
+ "to succeed."}
164
+
165
+
166
+ def uninstall_hook(root):
167
+ """Removes our `pre-commit` hook of the repository at `root` and puts back a backed-up hook that is not ours.
168
+
169
+ Parameters: root (str) project folder, inside a git repository.
170
+ Returns: dict with `removed`, `restored` (path of the backup put back, None when there is none) and `file`; a
171
+ repository without a hook answers `removed` false with a `note`.
172
+ Raises: ValueError when the `pre-commit` file is not ours; it stays as it is.
173
+ """
174
+ hook = os.path.join(_hooks_dir(root), HOOK_NAME)
175
+ if not os.path.isfile(hook):
176
+ return {"removed": False, "restored": None, "file": hook, "note": f"No pre-commit hook at {hook}."}
177
+ if MARKER not in _read(hook):
178
+ raise ValueError(f"{hook} is not Smart Tool's (it has no {MARKER} line) and was left as it is.")
179
+ os.remove(hook)
180
+ copies = sorted(glob.glob(glob.escape(hook + atomic_io.BACKUP_INFIX) + "*"), reverse=True)
181
+ saved = next((copy for copy in copies if MARKER not in _read(copy)), None)
182
+ if saved:
183
+ os.replace(saved, hook)
184
+ return {"removed": True, "restored": saved, "file": hook}