@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/duplicates.py CHANGED
@@ -45,17 +45,20 @@ _KEYWORDS = {
45
45
  "extends final finally float for if implements import instanceof int interface long native new null "
46
46
  "package private protected public return short static super switch synchronized this throw throws "
47
47
  "transient try void volatile while true false var",
48
+ "go": "break case chan const continue default defer else fallthrough for func go goto if import interface map "
49
+ "package range return select struct switch type var true false nil iota",
48
50
  }
49
51
  _KEYWORDS["ts"] = _KEYWORDS["js"] + " as interface type enum implements private public protected readonly keyof never unknown any"
50
52
  _KEYWORDS = {lang: frozenset(words.split()) for lang, words in _KEYWORDS.items()}
51
53
  _LANG = {"py": "py", "js": "js", "jsx": "js", "mjs": "js", "cjs": "js", "ts": "ts", "tsx": "ts", "mts": "ts",
52
- "cts": "ts", "java": "java"}
54
+ "cts": "ts", "java": "java", "go": "go"}
53
55
  _CONTRACT = re.compile(r"^(__\w+__|equals|hashCode|toString|compareTo|clone|close|run|call|apply|get|set|render|"
54
56
  r"constructor|ng[A-Z]\w*|componentDid\w+|main)$")
55
57
  _DOCSTRING = re.compile(r"\A\s*[rRuUbB]{0,2}(\"\"\"|''')[\s\S]*?\1")
56
58
  _GENERATED = re.compile(r"@generated|DO NOT EDIT|Code generated by|auto-generated", re.I)
57
59
  _WRITE_POOLS = {}
58
- _CONTAINER_KINDS = {"module", "template", "class", "interface"}
60
+ _CONTAINER_KINDS = {"module", "template", "class", "interface", "type"}
61
+ _DECLARATION_KINDS = _CONTAINER_KINDS | {"const", "var"}
59
62
  _GENERIC_NAMES = {"callback", "anonymous", "constructor"}
60
63
  _WARMING = set()
61
64
  _WARM_ERRORS = {}
@@ -208,7 +211,7 @@ def _working_tree_functions(root, changes, profile, include_tests=False):
208
211
  include_tests), with the same identity as indexed ones, so a copy written earlier in the session is caught and
209
212
  a function removed since the last indexing is not reported. The functions of a file are remembered per
210
213
  (modification time, size), so only files written since the last call are read and parsed again."""
211
- found = []
214
+ found, pending = [], []
212
215
  kinds = ("code", "test") if include_tests else ("code",)
213
216
  for rel, status in changes.items():
214
217
  ext = rel.rsplit(".", 1)[-1].lower() if "." in rel else ""
@@ -227,14 +230,17 @@ def _working_tree_functions(root, changes, profile, include_tests=False):
227
230
  source = stream.read()
228
231
  except (OSError, UnicodeDecodeError):
229
232
  continue
230
- if _GENERATED.search(source[:4000]):
231
- continue
233
+ if not _GENERATED.search(source[:4000]):
234
+ pending.append((rel, ext, kind, key, source))
235
+ braced = [(rel, source) for rel, _ext, _kind, _key, source in pending if not rel.lower().endswith(doc_check.PYTHON)]
236
+ symbols = dict(zip((rel for rel, _source in braced), doc_check.analyze_files(braced)))
237
+ for rel, ext, kind, key, source in pending:
232
238
  before = len(found)
233
239
  lines = source.splitlines()
234
- functions = doc_check.functions(rel, source)
240
+ functions = doc_check.functions(rel, source, symbols.get(rel))
235
241
  occurrences = {}
236
242
  for function in functions:
237
- if function["end"] - function["start"] + 1 < MIN_LINES or any(
243
+ if function.get("kind") in _DECLARATION_KINDS or function["end"] - function["start"] + 1 < MIN_LINES or any(
238
244
  other is not function and other["start"] <= function["start"] and function["end"] <= other["end"]
239
245
  and (other["start"], other["end"]) != (function["start"], function["end"]) for other in functions):
240
246
  continue
@@ -486,6 +492,8 @@ def on_write(root, path, before, after, written):
486
492
  remaining = {f["name"].split("(")[0].split(".")[-1] for f in written["all"]}
487
493
  matches = []
488
494
  for function in written["touched"]:
495
+ if function.get("kind") in _DECLARATION_KINDS:
496
+ continue
489
497
  name = function["name"].split("(")[0].split(".")[-1]
490
498
  text = "\n".join(lines[function["start"] - 1:function["end"]])
491
499
  body = _strip_comments(_body(text, ext), ext)
package/endpoint_sync.py CHANGED
@@ -250,9 +250,11 @@ def run_cli(command):
250
250
 
251
251
 
252
252
  def known_port():
253
- """Port the Claude Code MCP entry already points to, so a fallback bind can reuse it without any rewrite."""
253
+ """Port the Claude Code MCP entry (else the Codex one) already points to, so a fallback bind can reuse it without
254
+ any rewrite."""
255
+ held = registrations()
254
256
  try:
255
- parsed = urllib.parse.urlsplit(registrations()["claude"] or "")
257
+ parsed = urllib.parse.urlsplit(held["claude"] or held["codex"] or "")
256
258
  return parsed.port if parsed.hostname == "127.0.0.1" else None
257
259
  except ValueError:
258
260
  return None
package/hook_decision.py CHANGED
@@ -15,9 +15,11 @@ import os
15
15
  import affected_tests
16
16
  import code_graph
17
17
  import code_impact
18
+ import comment_check
18
19
  import config
19
20
  import dependency_notice
20
21
  import doc_check
22
+ import doc_scope
21
23
  import duplicates
22
24
  import edit_preview
23
25
  import index_profile
@@ -210,7 +212,12 @@ def _run_command(root, tests):
210
212
  def _doc_lines(findings):
211
213
  lines = []
212
214
  for root, rel, item in findings[:MAX_DOC_FINDINGS]:
213
- if item["issue"] == "missing":
215
+ short = item["name"].split(".")[-1]
216
+ if item["issue"] == "missing" and item.get("malformed"):
217
+ text = f"{item['name']} ({rel}:{item['start']}) has a doc comment that does not start with '{short} ': fix it."
218
+ elif item["issue"] == "missing" and item.get("convention") == "go":
219
+ text = f"{item['name']} ({rel}:{item['start']}) has no doc comment: write one starting with '{short} '."
220
+ elif item["issue"] == "missing":
214
221
  text = f"{item['name']} ({rel}:{item['start']}) has no docstring: write one (purpose, parameters, return)."
215
222
  else:
216
223
  text = (f"{item['name']} ({rel}:{item['start']}) changed its signature: update its docstring if the "
@@ -221,6 +228,32 @@ def _doc_lines(findings):
221
228
  return "Smart Tool docs: " + " ".join(lines)
222
229
 
223
230
 
231
+ _COMMENT_FIX = {
232
+ "commented_code": "is commented-out code: delete it, version control keeps it",
233
+ "history_tag": "carries a ticket, version or history tag: drop it, that belongs in the commit message",
234
+ "loose_docs": "documents the function below as a loose comment: move it into the docstring in the language's "
235
+ "standard format",
236
+ "inline_long": "is a long comment inside a function: keep one short line that says why, or move the contract "
237
+ "into the docstring",
238
+ }
239
+
240
+
241
+ def _comment_lines(findings):
242
+ lines = [f"{rel}:{item['line']} {_COMMENT_FIX[item['issue']]}" for rel, item in findings[:MAX_DOC_FINDINGS]]
243
+ if len(findings) > MAX_DOC_FINDINGS:
244
+ lines.append(f"{len(findings) - MAX_DOC_FINDINGS} more comment(s) in the same situation.")
245
+ return "Smart Tool comments: " + "; ".join(lines) + "."
246
+
247
+
248
+ def _scope_lines(findings):
249
+ shown = [f"{item['id']} ({'signature changed' if item['issue'] == 'signature_changed' else 'removed'}, "
250
+ f"{item['file']})" for item in findings[:MAX_DOC_FINDINGS]]
251
+ more = f" and {len(findings) - MAX_DOC_FINDINGS} more" if len(findings) > MAX_DOC_FINDINGS else ""
252
+ return ("Smart Tool docs scope: this edit leaves documented entries out of date: " + "; ".join(shown) + more
253
+ + ". After the edit, regenerate with project_manage action=docs generate=true and review the prose of "
254
+ "those entries.")
255
+
256
+
224
257
  def _duplicate_lines(findings):
225
258
  lines = []
226
259
  for rel, item in findings[:MAX_DUPLICATE_FINDINGS]:
@@ -237,14 +270,15 @@ def _duplicate_lines(findings):
237
270
  + " If the copy is intentional (moving the function, a deliberate fork), go ahead.")
238
271
 
239
272
 
240
- def _edit_review(payload, doc_mode, duplicate_mode, dependency_mode):
273
+ def _edit_review(payload, doc_mode, duplicate_mode, dependency_mode, comment_mode="off"):
241
274
  """Checks of an edit before it runs. Docstrings follow doc_mode, in code files of registered projects only (tests,
242
275
  docs and files outside a project are left out, as in the docs coverage): missing ones deny the edit in require mode and become a reminder in remind mode; a
243
- documented function whose signature changed always gets a reminder. Copies of indexed functions follow
244
- duplicate_mode and only add context, never deny. An edit of a package.json, requirements*.txt or go.mod follows dependency_mode: advisories
276
+ documented function whose signature changed always gets a reminder. Comments the edit adds in the wrong place
277
+ (see comment_check) follow comment_mode in the same files: require denies, remind adds context. Copies of indexed
278
+ functions follow duplicate_mode and only add context, never deny. An edit of a package.json, requirements*.txt or go.mod follows dependency_mode: advisories
245
279
  of the added or changed dependencies are added as context, never a denial."""
246
280
  with code_graph.pending_scope():
247
- return _edit_review_scoped(payload, doc_mode, duplicate_mode, dependency_mode)
281
+ return _edit_review_scoped(payload, doc_mode, duplicate_mode, dependency_mode, comment_mode)
248
282
 
249
283
 
250
284
  def _dependency_part(before, after, ecosystem):
@@ -260,9 +294,10 @@ def _dependency_part(before, after, ecosystem):
260
294
  return f"{dependency_notice.PREFIX}dependency check skipped: {exc}"
261
295
 
262
296
 
263
- def _edit_review_scoped(payload, doc_mode, duplicate_mode, dependency_mode):
297
+ def _edit_review_scoped(payload, doc_mode, duplicate_mode, dependency_mode, comment_mode="off"):
264
298
  """`_edit_review` inside one `code_graph.pending_scope`, so the pending-changes scan runs once per review."""
265
- doc_findings, duplicate_findings, failures, dependency_parts = [], [], [], []
299
+ doc_findings, scope_findings, duplicate_findings, failures, dependency_parts = [], [], [], [], []
300
+ comment_findings = []
266
301
  for path, before, after in edit_preview.preview(payload.get("tool_name"), payload.get("tool_input"), payload.get("cwd")):
267
302
  ecosystem = dependency_notice.ecosystem_of(path)
268
303
  if dependency_mode != "off" and ecosystem:
@@ -271,23 +306,36 @@ def _edit_review_scoped(payload, doc_mode, duplicate_mode, dependency_mode):
271
306
  if not doc_check.supported(path):
272
307
  continue
273
308
  root = _project_of(path)
274
- rel = os.path.relpath(path, root).replace(os.sep, "/") if root else os.path.basename(path)
309
+ rel = os.path.relpath(os.path.realpath(path), os.path.realpath(root)).replace(os.sep, "/") if root else os.path.basename(path)
275
310
  edited = doc_check.written(path, before, after)
276
311
  profile = index_profile.current((index_scope.load_scope(root) or {}).get("profile")) if root else None
277
312
  if doc_mode != "off" and root and index_profile.kind(rel, profile) == "code":
278
313
  doc_findings += [(root, rel, item) for item in doc_check.review(path, before, after, edited)]
314
+ if comment_mode != "off" and root and index_profile.kind(rel, profile) == "code":
315
+ comment_findings += [(rel, item) for item in comment_check.review(path, before, after, edited)]
316
+ if doc_mode != "off" and root:
317
+ try:
318
+ scope_findings += doc_scope.on_edit(root, rel, before, edited["all"])
319
+ except (OSError, UnicodeDecodeError) as exc:
320
+ failures.append(f"Smart Tool docs scope check skipped: {exc}")
279
321
  if duplicate_mode != "off" and root and edited["touched"]:
280
322
  try:
281
323
  duplicate_findings += [(rel, item) for item in duplicates.on_write(root, path, before, after, edited)]
282
324
  except (ValueError, RuntimeError) as exc:
283
325
  failures.append(f"Smart Tool duplicates check skipped: {exc}")
284
326
  parts = ([_doc_lines(doc_findings)] if doc_findings else []) + \
327
+ ([_comment_lines(comment_findings)] if comment_findings else []) + \
328
+ ([_scope_lines(scope_findings)] if scope_findings else []) + \
285
329
  ([_duplicate_lines(duplicate_findings)] if duplicate_findings else []) + failures + dependency_parts
286
330
  if not parts:
287
331
  return {}
288
332
  message = " ".join(parts)
289
- if doc_mode == "require" and any(item["issue"] == "missing" for _root, _rel, item in doc_findings):
290
- return deny(message + " Redo the edit with the docstring.")
333
+ missing_docs = doc_mode == "require" and any(item["issue"] == "missing" for _root, _rel, item in doc_findings)
334
+ wrong_comments = comment_mode == "require" and bool(comment_findings)
335
+ if missing_docs or wrong_comments:
336
+ fixes = " and ".join(text for text, needed in (("the docstring", missing_docs),
337
+ ("the comments fixed", wrong_comments)) if needed)
338
+ return deny(message + f" Redo the edit with {fixes}.")
291
339
  return {"hookSpecificOutput": {"hookEventName": "PreToolUse", "additionalContext": message}}
292
340
 
293
341
 
@@ -299,11 +347,11 @@ def decide(payload, client, web_route, jobs):
299
347
  subagent whose tool list has no Smart Tool MCP tool: it has nothing to switch to."""
300
348
  cfg = config.load_config()
301
349
  if isinstance(payload, dict) and payload.get("tool_name") in EDIT_TOOLS:
302
- doc_mode, duplicate_mode, dependency_mode = (config.doc_mode(cfg), config.duplicate_mode(cfg),
303
- config.dependency_mode(cfg))
304
- if doc_mode == "off" and duplicate_mode == "off" and dependency_mode == "off":
350
+ doc_mode, duplicate_mode, dependency_mode, comment_mode = (
351
+ config.doc_mode(cfg), config.duplicate_mode(cfg), config.dependency_mode(cfg), config.comment_mode(cfg))
352
+ if "off" == doc_mode == duplicate_mode == dependency_mode == comment_mode:
305
353
  return {}
306
- return _edit_review(payload, doc_mode, duplicate_mode, dependency_mode)
354
+ return _edit_review(payload, doc_mode, duplicate_mode, dependency_mode, comment_mode)
307
355
  if isinstance(payload, dict) and str(payload.get("tool_name")).startswith(f"mcp__{SMART_TOOL_SERVER}__"):
308
356
  if payload["tool_name"] == SMART_SEARCH_TOOL:
309
357
  router.CLIENT.set(client)
package/install.py CHANGED
@@ -129,8 +129,8 @@ def _daemon_up():
129
129
  try:
130
130
  url = json.loads(REGISTRY.read_text(encoding="utf-8"))["url"]
131
131
  with _OPENER.open(url + "/health", timeout=1) as response:
132
- return response.status == 200
133
- except (OSError, ValueError, KeyError):
132
+ return response.status == 200 and json.loads(response.read()).get("status") == "ok"
133
+ except (OSError, ValueError, KeyError, AttributeError):
134
134
  return False
135
135
 
136
136
 
package/layers.py ADDED
@@ -0,0 +1,237 @@
1
+ """Declared layers of a project: an ordered list from the highest layer (entry points) to the lowest (data access), each
2
+ defined by path globs and annotations, saved in the project at .smart-tool/layers.json once the agent confirms it.
3
+
4
+ The model follows the layer rules of validated tools: import-linter's layers contract (an ordered list, higher layers
5
+ may depend on lower ones), ArchUnit's layeredArchitecture (a layer is defined by a package pattern) and
6
+ dependency-cruiser (paths relative to the project root, forward slashes). A file belongs to the first layer, in the
7
+ declared order, whose path glob matches it or whose annotation starts one of its lines. The suggestion reads folder
8
+ names and annotations only; nothing is decided without the agent confirming it."""
9
+ import fnmatch
10
+ import json
11
+ import os
12
+ import posixpath
13
+ import re
14
+ from collections import Counter
15
+
16
+ import atomic_io
17
+ import code_graph
18
+ import index_profile
19
+ import index_scope
20
+
21
+ RULE_PATH = os.path.join(".smart-tool", "layers.json")
22
+ MAX_LAYERS = 12
23
+ MAX_PATTERNS = 200
24
+ MAX_UNASSIGNED = 30
25
+ _NAME = re.compile(r"[A-Za-z][\w-]{0,39}")
26
+ CONVENTIONS = (
27
+ ("entry", {"api", "apis", "cmd", "cli", "commands", "controller", "controllers", "endpoint", "endpoints",
28
+ "graphql", "handler", "handlers", "http", "resolvers", "rest", "route", "router", "routers", "routes",
29
+ "views", "web"},
30
+ ("@RestController", "@Controller", "@RequestMapping", "@GetMapping", "@PostMapping", "@PutMapping",
31
+ "@DeleteMapping", "@PatchMapping", "@Path", "@app.route", "@bp.route", "@blueprint.route", "@app.get",
32
+ "@app.post", "@app.put", "@app.delete", "@app.patch", "@router.get", "@router.post", "@router.put",
33
+ "@router.delete", "@router.patch")),
34
+ ("service", {"application", "business", "interactors", "service", "services", "usecase", "usecases",
35
+ "use_cases"},
36
+ ("@Service", "@Injectable")),
37
+ ("domain", {"core", "domain", "entities", "entity", "model", "models"},
38
+ ("@Entity", "@Embeddable")),
39
+ ("data", {"dao", "daos", "database", "db", "migrations", "persistence", "repo", "repos", "repositories",
40
+ "repository", "sql", "storage", "store"},
41
+ ("@Repository", "@Mapper", "@Dao")),
42
+ )
43
+
44
+
45
+ class Rule:
46
+ """A validated layer rule: assign() gives the layer of a file from its path and text."""
47
+
48
+ def __init__(self, layers):
49
+ self.layers = layers
50
+ self._paths = [[re.compile(fnmatch.translate(p)) for p in layer["paths"]] for layer in layers]
51
+ self._annotations = [re.compile(r"^[ \t]*(?:" + "|".join(re.escape(a) for a in layer["annotations"])
52
+ + r")(?![\w.])", re.M) if layer["annotations"] else None
53
+ for layer in layers]
54
+
55
+ def assign(self, path, text=None):
56
+ """Name of the first layer whose glob matches path or whose annotation starts a line of text; None if none.
57
+
58
+ Parameters: path (str) project-relative with forward slashes; text (str or None) the file's source.
59
+ Returns: str or None.
60
+ """
61
+ for layer, globs, annotation in zip(self.layers, self._paths, self._annotations):
62
+ if any(g.match(path) for g in globs) or (text and annotation and annotation.search(text)):
63
+ return layer["name"]
64
+ return None
65
+
66
+
67
+ def validate(layers):
68
+ """The layer list as saved, or ValueError naming the first problem.
69
+
70
+ Parameters: layers (list of {'name', 'paths', 'annotations'}) ordered from the highest layer to the lowest.
71
+ Returns: list of {'name': str, 'paths': [str], 'annotations': [str]}.
72
+ """
73
+ if not isinstance(layers, list) or not 1 <= len(layers) <= MAX_LAYERS:
74
+ raise ValueError(f"layers must be a list of 1 to {MAX_LAYERS} layers, highest first.")
75
+ clean, names = [], set()
76
+ for index, layer in enumerate(layers):
77
+ if not isinstance(layer, dict) or set(layer) - {"name", "paths", "annotations"}:
78
+ raise ValueError(f"layers[{index}] must be an object with name, paths and annotations only.")
79
+ name = layer.get("name")
80
+ if not isinstance(name, str) or not _NAME.fullmatch(name) or name.casefold() in names:
81
+ raise ValueError(f"layers[{index}].name must be a unique word (letters, digits, - or _, up to 40).")
82
+ names.add(name.casefold())
83
+ paths, annotations = layer.get("paths", []), layer.get("annotations", [])
84
+ if not isinstance(paths, list) or not all(isinstance(p, str) and p.strip() for p in paths) \
85
+ or len(paths) > MAX_PATTERNS:
86
+ raise ValueError(f"layers[{index}].paths must be a list of up to {MAX_PATTERNS} path globs.")
87
+ for pattern in paths:
88
+ parts = pattern.replace("\\", "/").split("/")
89
+ if pattern.startswith(("/", "\\")) or re.match(r"[A-Za-z]:", pattern) or ".." in parts:
90
+ raise ValueError(f"layers[{index}].paths: '{pattern}' must be relative to the project root.")
91
+ if not isinstance(annotations, list) or not all(isinstance(a, str) and re.fullmatch(r"@[\w.]+", a)
92
+ for a in annotations):
93
+ raise ValueError(f"layers[{index}].annotations must be a list like ['@RestController', '@app.route'].")
94
+ if not paths and not annotations:
95
+ raise ValueError(f"layers[{index}] ('{name}') needs at least one path glob or annotation.")
96
+ clean.append({"name": name, "paths": [p.replace("\\", "/") for p in paths], "annotations": annotations})
97
+ return clean
98
+
99
+
100
+ def load(root):
101
+ """The confirmed rule of the project, or None when it has none; a file that does not validate raises ValueError.
102
+
103
+ Parameters: root (str) project folder.
104
+ Returns: Rule or None.
105
+ """
106
+ path = os.path.join(root, RULE_PATH)
107
+ try:
108
+ with open(path, encoding="utf-8") as stream:
109
+ data = json.load(stream)
110
+ except FileNotFoundError:
111
+ return None
112
+ except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:
113
+ raise ValueError(f"{path} could not be read: {exc}") from None
114
+ if not isinstance(data, dict) or set(data) != {"layers"}:
115
+ raise ValueError(f"{path} must be an object with a single 'layers' list.")
116
+ try:
117
+ return Rule(validate(data["layers"]))
118
+ except ValueError as exc:
119
+ raise ValueError(f"{path}: {exc}") from None
120
+
121
+
122
+ def save(root, layers):
123
+ """Validate and write the rule to .smart-tool/layers.json in the project.
124
+
125
+ Parameters: root (str) project folder; layers (list) as validate() takes it.
126
+ Returns: Rule.
127
+ """
128
+ clean = validate(layers)
129
+ path = os.path.join(root, RULE_PATH)
130
+ os.makedirs(os.path.dirname(path), exist_ok=True)
131
+ atomic_io.write_text(path, json.dumps({"layers": clean}, indent=2, ensure_ascii=False) + "\n")
132
+ return Rule(clean)
133
+
134
+
135
+ def suggest(paths, read):
136
+ """Layer rule proposed from folder names and annotations, in the CONVENTIONS order.
137
+
138
+ The deepest folder named after a convention decides a file's layer (internal/service/model/x.go is domain); an
139
+ annotation of a higher layer wins over the folder. Folders become globs (`internal/handler/**`); annotations that
140
+ matched a file are kept on their layer.
141
+
142
+ Parameters: paths (iterable of str) code files, project-relative; read (callable path -> str or None) their text.
143
+ Returns: list of layers as validate() takes them (only layers that matched something).
144
+ """
145
+ globs, annotations = {name: set() for name, _f, _a in CONVENTIONS}, {name: set() for name, _f, _a in CONVENTIONS}
146
+ for path in paths:
147
+ text = read(path) or ""
148
+ hit = next(((name, a) for name, _folders, names in CONVENTIONS for a in names
149
+ if re.search(r"^[ \t]*" + re.escape(a) + r"(?![\w.])", text, re.M)), None)
150
+ if hit:
151
+ annotations[hit[0]].add(hit[1])
152
+ continue
153
+ parts = path.split("/")[:-1]
154
+ for depth in range(len(parts), 0, -1):
155
+ layer = next((name for name, folders, _a in CONVENTIONS if parts[depth - 1].lower() in folders), None)
156
+ if layer:
157
+ globs[layer].add("/".join(parts[:depth]) + "/**")
158
+ break
159
+ return [{"name": name, "paths": sorted(globs[name]), "annotations": sorted(annotations[name])}
160
+ for name, _f, _a in CONVENTIONS if globs[name] or annotations[name]]
161
+
162
+
163
+ def summary(rule, graph, read):
164
+ """How a rule splits the code graph: files and symbols per layer, calls between layers (direction 'down' follows
165
+ the declared order, 'up' goes against it) and the folders no layer covers.
166
+
167
+ Parameters: rule (Rule); graph (dict) code graph with 'symbols' and 'calls'; read (callable path -> str or None).
168
+ Returns: dict with 'layers', 'calls_between', 'unassigned' and 'truncated'.
169
+ """
170
+ order = {layer["name"]: index for index, layer in enumerate(rule.layers)}
171
+ paths = sorted({s["path"] for s in graph.get("symbols") or []})
172
+ layer_of = {path: rule.assign(path, read(path) if any(l["annotations"] for l in rule.layers) else None)
173
+ for path in paths}
174
+ symbol_layer = {s["id"]: layer_of[s["path"]] for s in graph.get("symbols") or []}
175
+ files, symbols = Counter(layer_of.values()), Counter(symbol_layer.values())
176
+ between = Counter()
177
+ for call in graph.get("calls") or []:
178
+ source, target = symbol_layer.get(call["source"]), symbol_layer.get(call["target"])
179
+ if source and target and source != target:
180
+ between[(source, target)] += call.get("count", 1)
181
+ unassigned = Counter(posixpath.dirname(p) or "." for p, layer in layer_of.items() if layer is None)
182
+ return {"layers": [{**layer, "files": files[layer["name"]], "symbols": symbols[layer["name"]]}
183
+ for layer in rule.layers],
184
+ "calls_between": [{"from": a, "to": b, "calls": n, "direction": "down" if order[a] < order[b] else "up"}
185
+ for (a, b), n in sorted(between.items(), key=lambda item: (order[item[0][0]],
186
+ order[item[0][1]]))],
187
+ "unassigned": [{"folder": folder, "files": n} for folder, n in unassigned.most_common(MAX_UNASSIGNED)],
188
+ "unassigned_files": files[None], "truncated": bool(graph.get("truncated"))}
189
+
190
+
191
+ def report(root, layers=None, confirm=False, view_id=None):
192
+ """The layers action: the saved rule, a suggestion, a preview of a proposed rule, or the confirmed save, each with
193
+ the summary of how it splits the project's code (tests left out).
194
+
195
+ Parameters: root (str) project folder; layers (list or None) proposed rule; confirm (bool) save the proposed rule;
196
+ view_id (str or None) index view to read.
197
+ Returns: dict with 'saved', 'rule_path', 'layers' (the rule with per-layer counts), 'calls_between', 'unassigned'
198
+ and 'guidance'.
199
+ """
200
+ if type(confirm) is not bool:
201
+ raise ValueError("confirm must be true or false.")
202
+ if confirm and layers is None:
203
+ raise ValueError("confirm=true saves the rule passed in layers; pass layers.")
204
+ graph = code_graph.build_current(root, view_id, shared=True)
205
+ profile = index_profile.current((index_scope.load_scope(root) or {}).get("profile"))
206
+ symbols = [s for s in graph.get("symbols") or [] if index_profile.kind(s["path"], profile) == "code"]
207
+ code = {**graph, "symbols": symbols}
208
+ texts = {}
209
+
210
+ def read(path):
211
+ if path not in texts:
212
+ try:
213
+ with open(os.path.join(root, path), encoding="utf-8") as stream:
214
+ texts[path] = stream.read()
215
+ except (OSError, UnicodeDecodeError):
216
+ texts[path] = None
217
+ return texts[path]
218
+
219
+ path = os.path.join(root, RULE_PATH)
220
+ if layers is not None:
221
+ rule = save(root, layers) if confirm else Rule(validate(layers))
222
+ guidance = ("Saved; documentation and the graph use this rule from now on." if confirm else
223
+ "Preview only: call again with the same layers and confirm=true to save the rule in the project.")
224
+ return {"saved": confirm, "rule_path": path, **summary(rule, code, read), "guidance": guidance}
225
+ rule = load(root)
226
+ if rule:
227
+ return {"saved": True, "rule_path": path, **summary(rule, code, read),
228
+ "guidance": "To change it, pass the new layers (preview), then the same layers with confirm=true."}
229
+ proposed = suggest(sorted({s["path"] for s in symbols}), read)
230
+ if not proposed:
231
+ return {"saved": False, "rule_path": path, "layers": [], "calls_between": [], "unassigned": [],
232
+ "truncated": bool(graph.get("truncated")),
233
+ "guidance": "No folder or annotation follows a known layer convention; declare the layers yourself "
234
+ "(name, paths, annotations, highest first) and confirm them."}
235
+ return {"saved": False, "rule_path": path, **summary(Rule(proposed), code, read),
236
+ "guidance": "Suggested from folder names and annotations, not saved: review the layers (rename, merge, move "
237
+ "folders from 'unassigned'), then pass them with confirm=true."}
@@ -53,6 +53,8 @@
53
53
  "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.": "smart_scout: escreve uma resposta curta sobre as linhas que leu e guarda só as que respondem. Vazio devolve as linhas literais, sem modelo.",
54
54
  "Web research": "Pesquisa na web",
55
55
  "Used by web_search with depth=research. Empty uses the router model.": "Usado por web_search com depth=research. Vazio usa o modelo do roteador.",
56
+ "Docs model": "Modelo da documentação",
57
+ "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.": "Escreve a prosa da documentação gerada (project_manage action=docs write_prose=true); cada parágrafo é conferido contra o código antes de ser gravado.",
56
58
  "Advanced web research limits": "Limites avançados da pesquisa na web",
57
59
  "Maximum research rounds": "Máximo de rodadas de pesquisa",
58
60
  "How many search rounds a research may run before answering.": "Quantas rodadas de busca uma pesquisa pode fazer antes de responder.",
@@ -185,6 +187,8 @@
185
187
  "Rerank": "Rerank",
186
188
  "Model check": "Verificação de modelos",
187
189
  "Scope": "Escopo",
190
+ "Scout": "Scout",
191
+ "Documentation": "Documentação",
188
192
  "Showing the latest {0} of {1}.": "Mostrando os {0} mais recentes de {1}.",
189
193
  "Role": "Função",
190
194
  "Model": "Modelo",
@@ -226,6 +230,11 @@
226
230
  "The edit runs; the agent is told which touched functions lack a docstring.": "A edição é feita; o agente é avisado de quais funções alteradas estão sem docstring.",
227
231
  "Require": "Exigir",
228
232
  "No documentation checks.": "Nenhuma verificação de documentação.",
233
+ "Comments in the wrong place": "Comentários no lugar errado",
234
+ "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.": "Verifica os comentários que uma edição adiciona: código comentado, tags de ticket ou de histórico, um bloco solto acima de uma função em vez da docstring e um bloco longo dentro do corpo da função. Um comentário curto que diz o porquê continua permitido.",
235
+ "An edit that adds a comment in the wrong place is blocked until it is fixed.": "Uma edição que adiciona um comentário no lugar errado é bloqueada até ser corrigida.",
236
+ "The edit runs; the agent is told which comments are misplaced.": "A edição é feita; o agente é avisado de quais comentários estão fora do lugar.",
237
+ "No comment checks.": "Nenhuma verificação de comentários.",
229
238
  "Duplicate functions on edit": "Funções duplicadas ao editar",
230
239
  "Compares the functions an edit writes with the indexed code: identical bodies, and near-identical ones with only local names changed. It never blocks.": "Compara as funções que uma edição escreve com o código indexado: corpos idênticos e quase idênticos, só com nomes locais alterados. Nunca bloqueia.",
231
240
  "Warn": "Avisar",
@@ -564,7 +573,7 @@
564
573
  "Reading the snapshot and analyzing imports and calls…": "Lendo o instantâneo e analisando importações e chamadas…",
565
574
  "Could not load the maps.": "Não foi possível carregar os mapas.",
566
575
  "Use Load maps to try again.": "Use Carregar mapas para tentar de novo.",
567
- "Local analysis of Java, Angular, Python, JavaScript/TypeScript, HTML/CSS and Markdown links. TXT and DOCX show up in coverage and in text search. {0} of {1} files were analyzed. Other languages and incomplete snapshots remain available in coverage.": "Análise local de Java, Angular, Python, JavaScript/TypeScript, HTML/CSS e links de Markdown. TXT e DOCX aparecem na cobertura e na busca de texto. {0} de {1} arquivos foram analisados. Outras linguagens e instantâneos incompletos continuam disponíveis na cobertura.",
576
+ "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. {0} of {1} files were analyzed. Other languages and incomplete snapshots remain available in coverage.": "Análise local de Java, Angular, Python, JavaScript/TypeScript, Go, HTML/CSS e links de Markdown. TXT e DOCX aparecem na cobertura e na busca de texto. {0} de {1} arquivos foram analisados. Outras linguagens e instantâneos incompletos continuam disponíveis na cobertura.",
568
577
  "{0} resolved internal references; {1} external references; {2} call relations. Unresolved targets are a limited sample ({3} records in the analysis).": "{0} referências internas resolvidas; {1} referências externas; {2} relações de chamada. Os destinos não resolvidos são uma amostra limitada ({3} registros na análise).",
569
578
  "The analysis limits were reached. Filter by folder to explore the available part.": "Os limites da análise foram atingidos. Filtre por pasta para explorar a parte disponível.",
570
579
  "{0} of {1} files · area by lines": "{0} de {1} arquivos · área por linhas",
package/model_client.py CHANGED
@@ -131,22 +131,27 @@ def _route(model):
131
131
  return str(model or "").replace("/", ".").replace(":", ".").split(".")[0].lower()
132
132
 
133
133
 
134
+ def _claude(model):
135
+ """Whether the model id names a Claude model, the only family that reads Anthropic's `output_config`."""
136
+ return "claude" in str(model or "").lower()
137
+
138
+
134
139
  def structured(model, system, user, tool, timeout=30):
135
140
  """One chat call whose answer is a JSON object validated against the parameters schema of `tool` (the tool
136
141
  definition is only the carrier of name and schema; `system` may be empty). The request format comes from the `structured_output`
137
- configuration: `output_config` for the routes listed there, `response_format` otherwise; never `temperature`.
142
+ configuration: `output_config` for the Claude models on the routes listed there, `response_format` otherwise; never `temperature`.
138
143
  Raises RuntimeError on a stop other than a normal one, a refusal or an empty answer, and ValueError when the
139
144
  object breaks the schema."""
140
145
  settings = config.structured_output()
141
146
  schema = _strict_schema(tool["function"]["parameters"], set(settings["unsupported_keywords"]))
142
147
  route = _route(model)
143
148
  routes = {item.lower() for item in settings["output_config_routes"]}
144
- if settings["mode"] == "output_config" and route not in routes:
145
- raise ValueError(f"structured_output.mode is output_config but the route {route!r} of {model} is not in "
146
- f"output_config_routes {sorted(routes)}.")
149
+ if settings["mode"] == "output_config" and (route not in routes or not _claude(model)):
150
+ raise ValueError(f"structured_output.mode is output_config but {model} is not a Claude model on a route of "
151
+ f"output_config_routes {sorted(routes)}; use mode auto or response_format.")
147
152
  messages = [{"role": "system", "content": system}] if system else []
148
153
  body = {"model": model, "messages": messages + [{"role": "user", "content": user}]}
149
- if settings["mode"] == "output_config" or (settings["mode"] == "auto" and route in routes):
154
+ if settings["mode"] == "output_config" or (settings["mode"] == "auto" and route in routes and _claude(model)):
150
155
  body["output_config"] = {"format": {"type": "json_schema", "schema": schema}}
151
156
  else:
152
157
  body["response_format"] = {"type": "json_schema", "json_schema": {
package/model_defaults.py CHANGED
@@ -6,16 +6,19 @@ import config
6
6
  import model_catalog
7
7
 
8
8
 
9
- # Matched as the last path/dot segment of the catalog id, so "claude-haiku-5-5" also finds "vertex_ai.anthropic.claude-haiku-5-5"
10
- # (LiteLLM aliases) and "anthropic/claude-haiku-5-5" (OpenRouter). Chosen by measurement, 3 rounds per model, correctness
11
- # first and price second (docs/research/2026-10-24-modelos-do-scout-e-dos-outros-papeis.md): the router answers pages
12
- # and the scout reads code excerpts, where Claude Haiku 5.5 answered every request and led the no-index path; scope and
13
- # research pick the GPT-5.4 nano, as accurate there at about half the price and without the long reasoning of the mini.
9
+ # Matched as the last path/dot segment of the catalog id, so a short name also finds its LiteLLM alias
10
+ # ("vertex_ai.anthropic.<name>") and its OpenRouter id ("anthropic/<name>"). Chosen by measurement, 3 rounds per model,
11
+ # correctness first and price second (docs/research/2026-10-24-modelos-do-scout-e-dos-outros-papeis.md): the router
12
+ # answers pages and the scout reads code excerpts, where Claude Haiku answered every request and led the no-index path;
13
+ # scope and research pick the GPT nano, as accurate there at about half the price and without the long reasoning of the
14
+ # mini. The documentation prose takes Haiku as well: as many paragraphs judged correct as Sonnet within the noise, at a
15
+ # tenth of its price, while the nano invented details (docs/research/2026-11-05-modelo-e-instrucao-da-prosa.md).
14
16
  _CHOICES = {
15
17
  "router_model": ("chat", "claude-haiku-5-5"),
16
18
  "scope_model": ("chat", "gpt-5.4-nano"),
17
19
  "scout_model": ("chat", "claude-haiku-5-5"),
18
20
  "research_model": ("chat", "gpt-5.4-nano"),
21
+ "docs_model": ("chat", "claude-haiku-5-5"),
19
22
  "embedding_model": ("embedding", "text-embedding-3-small"),
20
23
  "rerank_model": ("rerank", "rerank-3-5"),
21
24
  }
@@ -23,7 +26,7 @@ RECOMMENDED_MODELS = {role: _CHOICES[role] for role in config.MODEL_ROLES}
23
26
 
24
27
 
25
28
  def _route_rank(model_id):
26
- """Vertex first (the owner's gateway is stable there), Bedrock only when nothing else serves the model."""
29
+ """Vertex first, Bedrock only when nothing else serves the model."""
27
30
  route = re.split(r"[/.:]", model_id)[0].lower()
28
31
  return 0 if route.startswith("vertex") else 2 if route.startswith("bedrock") else 1
29
32
 
package/model_health.py CHANGED
@@ -29,6 +29,8 @@ SAMPLE_CHARS = 160
29
29
  GROUP_ROWS = 20
30
30
  PURPOSES = ("index_embedding", "query_embedding", "rerank", "embedding_probe", "scope")
31
31
  _PATHS = ("/v1/chat/completions", "/v1/embeddings", "/v1/rerank")
32
+ _PURPOSE_ROLE = {"scope": "scope_model", "scout": "scout_model", "docs": "docs_model", "rerank": "rerank_model",
33
+ "index_embedding": "embedding_model", "query_embedding": "embedding_model"}
32
34
  _TOOL = contextvars.ContextVar("model_health_tool", default=None)
33
35
  _COLLECTED = contextvars.ContextVar("model_health_collected", default=None)
34
36
  _SCHEMA = set()
@@ -81,9 +83,13 @@ def classify(error):
81
83
  return "connection" if _CONNECTION.search(error or "") else "other"
82
84
 
83
85
 
84
- def role_of(model, cfg=None):
85
- """Name of the config field that selects `model` ('other' when none does)."""
86
+ def role_of(model, cfg=None, purpose=None):
87
+ """Name of the config field that selects `model` ('other' when none does). Several roles may hold the same model:
88
+ the role of the running `purpose` (usage_meter.purpose) wins over the first field in MODEL_ROLES order."""
86
89
  cfg = cfg if cfg is not None else config.load_config()
90
+ declared = _PURPOSE_ROLE.get(purpose)
91
+ if declared and cfg.get(declared) == model:
92
+ return declared
87
93
  return next((field for field in config.MODEL_ROLES if cfg.get(field) == model), "other")
88
94
 
89
95
 
@@ -107,7 +113,7 @@ def record(path, body, failure=None):
107
113
  return
108
114
  try:
109
115
  model = str((body or {}).get("model", "")) if isinstance(body, dict) else ""
110
- role = role_of(model)
116
+ role = role_of(model, purpose=usage_meter.purpose())
111
117
  now = time.time()
112
118
  text = error_text(failure) if failure is not None else None
113
119
  with project_store._LOCK, _db() as db:
package/model_upgrade.py CHANGED
@@ -15,7 +15,7 @@ import model_catalog
15
15
  import model_defaults
16
16
 
17
17
  DEFAULTS_VERSION = 2
18
- ROLES = ("router_model", "scope_model", "scout_model", "research_model")
18
+ ROLES = ("router_model", "scope_model", "scout_model", "research_model", "docs_model")
19
19
  REMIND_EVERY_S = 24 * 3600
20
20
 
21
21