tokensafe 4.7.0 → 4.7.2

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/src/retrofit.py CHANGED
@@ -424,8 +424,8 @@ def get_adapters_catalog() -> List[Dict[str, Any]]:
424
424
  "profiles": ["frontend"],
425
425
  "repo": "tokensafe-ui",
426
426
  "mode": "hybrid",
427
- "status": "ready",
428
- "description": "Vue component hierarchy and store snapshot observer",
427
+ "status": "planned",
428
+ "description": "Programmatic adapter exists (manual component registration); no Vite integration or OUMV certification yet — use static analysis for Vue today",
429
429
  "technology": {
430
430
  "language": "typescript",
431
431
  "framework": "vue",
@@ -491,8 +491,24 @@ def get_adapters_catalog() -> List[Dict[str, Any]]:
491
491
  "profiles": ["backend"],
492
492
  "repo": "tokensafe-backend/node",
493
493
  "mode": "hybrid",
494
- "status": "planned",
495
- "description": "Express/Fastify route handler & middleware reflection",
494
+ "status": "ready",
495
+ "description": "Express/Fastify runtime: route reflection, OCC source edits, loopback verify, SSE/WS (certified Level 3)",
496
+ "technology": {
497
+ "language": "typescript",
498
+ "framework": "express | fastify",
499
+ "package": {"manager": "npm", "name": "tokensafe-backend-node", "install": "npm install tokensafe-backend-node"},
500
+ },
501
+ "capabilities": [
502
+ {"name": "observe.pulse", "constraints": {"readOnly": True, "developmentOnly": True}},
503
+ {"name": "observe.surface", "constraints": {"readOnly": True, "developmentOnly": True}},
504
+ {"name": "observe.contract", "constraints": {"readOnly": True, "developmentOnly": True}},
505
+ {"name": "observe.source", "constraints": {"readOnly": True, "developmentOnly": True}},
506
+ {"name": "observe.traces", "constraints": {"readOnly": True, "developmentOnly": True}},
507
+ {"name": "understand.impact", "constraints": {"readOnly": True, "developmentOnly": True}},
508
+ {"name": "understand.causality", "constraints": {"readOnly": True, "developmentOnly": True}},
509
+ {"name": "mutate.source", "constraints": {"readOnly": False, "developmentOnly": True, "requiresPermission": "permissions.mutate != false"}},
510
+ {"name": "verify.behavior", "constraints": {"readOnly": True, "developmentOnly": True}},
511
+ ],
496
512
  },
497
513
  ]
498
514
 
@@ -817,7 +833,13 @@ def format_oumv_workspace_brief(workspace_dir: str, include_live: bool = False)
817
833
  except Exception:
818
834
  pass
819
835
 
820
- return "[TokenSafe OUMV Workspace Matrix | " + " | ".join(parts) + "]"
836
+ return (
837
+ "[TokenSafe OUMV Workspace Matrix @ "
838
+ + (os.path.basename(os.path.abspath(workspace_dir)) or workspace_dir)
839
+ + " | "
840
+ + " | ".join(parts)
841
+ + "]"
842
+ )
821
843
 
822
844
 
823
845
  _STACK_CACHE: Dict[str, Tuple[float, Dict[str, Any]]] = {}
package/src/scaffold.py CHANGED
@@ -577,10 +577,11 @@ createRoot(document.getElementById('root')!).render(<App />);
577
577
  def _scaffold_go_backend(cls, target_dir, project_name, subpath, write_fn):
578
578
  p = lambda rel: os.path.join(subpath, rel) if subpath else rel
579
579
  slug = project_name.lower().replace(" ", "-")
580
- write_fn(p("go.mod"), f"module example.com/{slug}\n\ngo 1.21\n\nrequire (\n\tgithub.com/gin-gonic/gin v1.10.0\n\tgithub.com/tokensafe-dev/tokensafe-backend/go v0.4.3\n)\n")
580
+ write_fn(p("go.mod"), f"module example.com/{slug}\n\ngo 1.21\n\nrequire (\n\tgithub.com/gin-gonic/gin v1.10.0\n\tgithub.com/tokensafe-dev/tokensafe-backend/go v0.4.7\n)\n")
581
581
  write_fn(p("main.go"), """package main
582
582
 
583
583
  import (
584
+ "log"
584
585
  "net/http"
585
586
 
586
587
  "github.com/gin-gonic/gin"
@@ -593,10 +594,11 @@ func main() {
593
594
  c.JSON(http.StatusOK, gin.H{"status": "ok"})
594
595
  })
595
596
 
596
- // OUMV: observe/understand/mutate/verify over POST /__oumv/rpc.
597
- oumvgin.AutoMount(r)
598
-
599
- _ = r.Run(":8080")
597
+ // OUMV: observe/understand/mutate/verify over POST /__oumv/rpc, plus the
598
+ // §9.2 discovery descriptor written with the real bound port.
599
+ if err := oumvgin.AutoMountAndServe(r, ":8080"); err != nil {
600
+ log.Fatal(err)
601
+ }
600
602
  }
601
603
  """)
602
604
 
@@ -619,7 +621,7 @@ npm run dev:api # backend through `tokensafe run-backend` / go r
619
621
  The adapters are already wired, so an agent works through the OUMV protocol:
620
622
 
621
623
  * frontend — `tokensafe dev` serves L0-L4 plus OCC source edits; nothing is added to git.
622
- * backend — FastAPI auto-mounts via `tokensafe run-backend`, Go via `oumvgin.AutoMount`.
624
+ * backend — FastAPI auto-mounts via `tokensafe run-backend`, Go via `oumvgin.AutoMountAndServe`.
623
625
  * `tokensafe inject --status` prints the live wiring plan; `tokensafe oumv doctor` shows readiness.
624
626
  """
625
627
 
@@ -88,6 +88,18 @@ class ScopedSearch:
88
88
  return True
89
89
  return False
90
90
 
91
+ @classmethod
92
+ def _resolve_per_file(cls, per_file: int, max_results: int) -> int:
93
+ """Hits kept per file. One hot file must not eat the whole result budget:
94
+ a 20-hit query used to render 2 KB of near-identical lines from 2 files."""
95
+ try:
96
+ per_file = int(per_file or 0)
97
+ except (TypeError, ValueError):
98
+ per_file = 0
99
+ if per_file > 0:
100
+ return per_file
101
+ return max(6, min(12, max_results // 2))
102
+
91
103
  @classmethod
92
104
  def search(
93
105
  cls,
@@ -96,7 +108,8 @@ class ScopedSearch:
96
108
  scope: str = "all",
97
109
  max_results: int = 25,
98
110
  case_sensitive: bool = False,
99
- use_regex: Optional[bool] = None
111
+ use_regex: Optional[bool] = None,
112
+ per_file: int = 0
100
113
  ) -> Dict[str, Any]:
101
114
  """
102
115
  Executes a bounded code/config search and returns structured results and compact markdown.
@@ -172,14 +185,22 @@ class ScopedSearch:
172
185
  fts = CodeFTSIndex(root_dir)
173
186
  fts_results = fts.search(query, limit=max_results)
174
187
  if fts_results:
188
+ per_file_cap = cls._resolve_per_file(per_file, max_results)
189
+ per_file_counts: Dict[str, int] = {}
190
+ overflow: Dict[str, int] = {}
175
191
  fts_matches = []
176
192
  fts_hit_files = set()
177
193
  for r in fts_results:
178
194
  f_rel = r["file"]
179
195
  if cls.is_match_file(os.path.basename(f_rel), f_rel, scope):
196
+ seen = per_file_counts.get(f_rel, 0)
197
+ if seen >= per_file_cap:
198
+ overflow[f_rel] = overflow.get(f_rel, 0) + 1
199
+ continue
180
200
  clean_line = str(r.get("content") or "").strip()
181
201
  if len(clean_line) > 100:
182
202
  clean_line = clean_line[:97] + "..."
203
+ per_file_counts[f_rel] = seen + 1
183
204
  fts_matches.append({
184
205
  "file": f_rel,
185
206
  "line": r["line"],
@@ -194,11 +215,14 @@ class ScopedSearch:
194
215
  "files_matched": len(fts_hit_files),
195
216
  "scanned_files": len(fts_hit_files),
196
217
  "total_matches": len(fts_matches),
218
+ "overflow_matches": sum(overflow.values()),
219
+ "per_file_cap": per_file_cap,
197
220
  "timed_out": False,
198
221
  "matches": fts_matches,
199
222
  "markdown": cls._render_markdown(
200
223
  query, fts_matches, len(fts_hit_files), False, max_results,
201
224
  hit_files=fts_hit_files, scope=scope, root_dir=root_dir,
225
+ overflow=overflow, per_file_cap=per_file_cap,
202
226
  ),
203
227
  }
204
228
  except Exception:
@@ -207,6 +231,9 @@ class ScopedSearch:
207
231
  matches: List[Dict[str, Any]] = []
208
232
  total_scanned_files = 0
209
233
  hit_files = set()
234
+ per_file_cap = cls._resolve_per_file(per_file, max_results)
235
+ per_file_counts: Dict[str, int] = {}
236
+ overflow: Dict[str, int] = {}
210
237
  start_time = time.monotonic()
211
238
  timeout_seconds = 4.0
212
239
  max_scanned_files = 2500
@@ -262,6 +289,11 @@ class ScopedSearch:
262
289
  if len(clean_line) > 100:
263
290
  clean_line = clean_line[:97] + "..."
264
291
 
292
+ seen_in_file = per_file_counts.get(rel_path, 0)
293
+ if seen_in_file >= per_file_cap:
294
+ overflow[rel_path] = overflow.get(rel_path, 0) + 1
295
+ continue
296
+ per_file_counts[rel_path] = seen_in_file + 1
265
297
  matches.append({
266
298
  "file": rel_path,
267
299
  "line": line_idx,
@@ -292,6 +324,8 @@ class ScopedSearch:
292
324
  regex_mode=regex_mode,
293
325
  timeout_seconds=timeout_seconds,
294
326
  max_scanned_files=max_scanned_files,
327
+ overflow=overflow,
328
+ per_file_cap=per_file_cap,
295
329
  )
296
330
 
297
331
  return {
@@ -299,6 +333,8 @@ class ScopedSearch:
299
333
  "query": query,
300
334
  "scope": scope,
301
335
  "total_matches": len(matches),
336
+ "overflow_matches": sum(overflow.values()),
337
+ "per_file_cap": per_file_cap,
302
338
  "files_matched": len(hit_files),
303
339
  "scanned_files": total_scanned_files,
304
340
  "timed_out": timed_out,
@@ -321,26 +357,52 @@ class ScopedSearch:
321
357
  regex_mode: bool = False,
322
358
  timeout_seconds: float = 4.0,
323
359
  max_scanned_files: int = 2500,
360
+ overflow: Optional[Dict[str, int]] = None,
361
+ per_file_cap: int = 0,
324
362
  ) -> str:
325
- """Generates compact bounded Markdown output for both FTS5 and disk search paths."""
363
+ """Generates compact bounded Markdown output for both FTS5 and disk search paths.
364
+
365
+ Hits are grouped per file: the path is printed once per file instead of on
366
+ every line, which keeps a 20-hit query near 1 KB instead of 2 KB.
367
+ """
326
368
  if hit_files is None:
327
369
  hit_files = {m["file"] for m in matches if "file" in m}
370
+ overflow = overflow or {}
328
371
  display_root = os.path.basename(root_dir) or root_dir or "."
329
372
  mode_suffix = ", auto-regex" if auto_regex and regex_mode else ""
373
+ more_hidden = sum(overflow.values())
374
+ count_label = f"{len(matches)} match{'es' if len(matches) != 1 else ''}"
375
+ if more_hidden:
376
+ count_label = f"{len(matches)} shown, {more_hidden} more"
330
377
  lines = [
331
- f"### TokenSafe Scoped Search: '{query}' ({len(matches)} match{'es' if len(matches) != 1 else ''} in {len(hit_files)} file{'s' if len(hit_files) != 1 else ''}, dir: `{display_root}`, scope: {scope}{mode_suffix})"
378
+ f"### TokenSafe Scoped Search: '{query}' ({count_label} in {len(hit_files)} file{'s' if len(hit_files) != 1 else ''}, dir: `{display_root}`, scope: {scope}{mode_suffix})"
332
379
  ]
333
380
  if not matches:
334
381
  lines.append(f"_No matches found across {total_scanned_files} scanned files in `{root_dir}`._")
335
382
  if auto_regex and regex_mode:
336
383
  lines.append("_Auto-regex mode found nothing; pass use_regex=false to force a literal search._")
337
384
  else:
385
+ by_file: Dict[str, List[Dict[str, Any]]] = {}
338
386
  for m in matches:
339
- txt = m.get("text") if "text" in m else m.get("content", "")
340
- lines.append(f"- `{m['file']}:{m['line']}`: `{txt}`")
387
+ by_file.setdefault(m.get("file", ""), []).append(m)
388
+ multi_file = len(by_file) > 1
389
+ for fpath, file_matches in by_file.items():
390
+ if multi_file:
391
+ lines.append(f"**{fpath}**")
392
+ for m in file_matches:
393
+ txt = m.get("text") if "text" in m else m.get("content", "")
394
+ if multi_file:
395
+ lines.append(f" - L{m['line']}: `{txt}`")
396
+ else:
397
+ lines.append(f"- `{fpath}:{m['line']}`: `{txt}`")
398
+ hidden = overflow.get(fpath, 0)
399
+ if hidden:
400
+ lines.append(f" … +{hidden} more in this file")
341
401
 
342
402
  if len(matches) >= max_results:
343
403
  lines.append(f"_Results capped at {max_results} matches._")
404
+ elif more_hidden:
405
+ lines.append(f"_Kept at most {per_file_cap} hits per file; raise `per_file` for every occurrence._")
344
406
  elif timed_out:
345
407
  lines.append(f"_Search bounded at {timeout_seconds}s safety limit ({total_scanned_files} files scanned). Narrow 'project_path' for exhaustive scan._")
346
408
  elif total_scanned_files >= max_scanned_files:
@@ -25,8 +25,9 @@ _FRONTEND_LINES = {
25
25
  "before reading files; run `tokensafe dev` if no runtime is live."
26
26
  ),
27
27
  "vue": (
28
- "frontend {provider}/{framework}: OUMV via `tokensafe dev` (L0-L2 from DOM). "
29
- "Use tokensafe:oumv observe before file crawls."
28
+ "frontend {provider}/{framework}: no OUMV adapter yet (the Vite plugin serves no "
29
+ "OUMV endpoints for Vue). Use tokensafe:repo_map, smart_read_file and scoped_search; "
30
+ "verify UI changes with the app's own tests."
30
31
  ),
31
32
  }
32
33
 
@@ -37,10 +38,15 @@ _BACKEND_LINES = {
37
38
  "Prefer tokensafe:oumv(action='observe'|'understand'|'mutate'|'verify') over grep/curl."
38
39
  ),
39
40
  "go": (
40
- "backend {provider}/{framework}: OUMV mounts with one AutoMount line "
41
- "(`tokensafe inject --status` shows it; `tokensafe inject --revert` removes it). "
41
+ "backend {provider}/{framework}: OUMV mounts with one AutoMountAndServe line "
42
+ "(discovery included; `tokensafe inject --status` shows it, `--revert` removes it). "
42
43
  "Use tokensafe:oumv for endpoints/source/impact, oumv_verify for in-process checks."
43
44
  ),
45
+ "node": (
46
+ "backend node/{framework}: install `tokensafe-backend-node` and mount it "
47
+ "(`mountTokensafe(app)` for Express, `registerTokensafe(app)` for Fastify); "
48
+ "then use tokensafe:oumv for endpoints/impact and oumv_verify for live checks."
49
+ ),
44
50
  }
45
51
 
46
52
 
@@ -53,6 +59,128 @@ def _read_permissions(workspace: str) -> Dict[str, Any]:
53
59
  return {}
54
60
 
55
61
 
62
+ _PAYLOAD_ROOT_KEYS = (
63
+ "workspacePaths", # ZCode / Antigravity: every open folder, not just the first
64
+ "workspace_roots",
65
+ "workspaceRoots",
66
+ "workspace_dirs",
67
+ "additionalDirectories",
68
+ "additional_directories",
69
+ "roots",
70
+ )
71
+
72
+
73
+ def workspace_roots_from_payload(payload: Any) -> List[str]:
74
+ """Every workspace root the host reported, primary first.
75
+
76
+ Hosts that support several open folders (ZCode sends ``workspacePaths``)
77
+ were previously reduced to ``workspacePaths[0]``; the remaining repos then
78
+ looked like they did not exist, and the brief's single-root verdict read as
79
+ a global "OUMV is unavailable here"."""
80
+ roots: List[str] = []
81
+ if not isinstance(payload, dict):
82
+ return roots
83
+ for key in _PAYLOAD_ROOT_KEYS:
84
+ value = payload.get(key)
85
+ if isinstance(value, str):
86
+ value = [value]
87
+ if not isinstance(value, (list, tuple)):
88
+ continue
89
+ for item in value:
90
+ if isinstance(item, str) and item.strip():
91
+ roots.append(item.strip())
92
+ return roots
93
+
94
+
95
+ def workspace_roots_from_env(env: Optional[Dict[str, str]] = None) -> List[str]:
96
+ """Explicit extra roots for hosts that expose no multi-root payload."""
97
+ raw = str((env or os.environ).get("TOKENSAFE_WORKSPACES") or "").strip()
98
+ if not raw:
99
+ return []
100
+ return [p.strip() for p in raw.replace("\n", os.pathsep).split(os.pathsep) if p.strip()]
101
+
102
+
103
+ def _profile_supported(kind: str, entry: Dict[str, Any]) -> bool:
104
+ """Adapter availability for one detected profile.
105
+
106
+ ``detect_project_stack`` ships the authoritative boolean (``oumv_supported``);
107
+ the template tables only cover a few providers and the Vue template is itself
108
+ a negative line, so template presence alone must not imply "ready"."""
109
+ flag = entry.get("oumv_supported")
110
+ if isinstance(flag, bool):
111
+ return flag
112
+ table = _FRONTEND_LINES if kind == "frontend" else _BACKEND_LINES
113
+ template = table.get(str(entry.get("provider") or ""))
114
+ return bool(template) and "no OUMV adapter" not in template
115
+
116
+
117
+ def _stack_labels(stack: Dict[str, Any]) -> List[tuple]:
118
+ """(kind, provider, framework, supported, adapter) per detected profile.
119
+
120
+ A routing template decides when one exists (it says how to mount, or says
121
+ there is no adapter); the detection flag only fills the gap for providers
122
+ the templates do not cover yet (e.g. Solid)."""
123
+ labels: List[tuple] = []
124
+ for kind, table in (("frontend", _FRONTEND_LINES), ("backend", _BACKEND_LINES)):
125
+ entry = stack.get(kind) or {}
126
+ provider = str(entry.get("provider") or "")
127
+ if not provider:
128
+ continue
129
+ framework = str(entry.get("framework") or provider)
130
+ template = table.get(provider)
131
+ if template is not None:
132
+ supported = "no OUMV adapter" not in template
133
+ else:
134
+ supported = _profile_supported(kind, entry)
135
+ labels.append((kind, provider, framework, supported, str(entry.get("adapter") or "")))
136
+ return labels
137
+
138
+
139
+ def _is_root(path: str) -> bool:
140
+ try:
141
+ from src.paths import is_project_root
142
+ return bool(is_project_root(path))
143
+ except Exception:
144
+ return False
145
+
146
+
147
+ def _extra_root_lines(roots: List[str], seen: set) -> List[str]:
148
+ """One compact line per non-primary root: ready → exact call, else fallback."""
149
+ try:
150
+ from src.retrofit import detect_project_stack
151
+ except Exception:
152
+ return []
153
+ lines: List[str] = []
154
+ for raw in roots:
155
+ if not raw:
156
+ continue
157
+ path = os.path.abspath(str(raw))
158
+ if not os.path.isdir(path):
159
+ continue
160
+ real = os.path.realpath(path)
161
+ if real in seen:
162
+ continue
163
+ seen.add(real)
164
+ if not _is_root(path):
165
+ continue
166
+ try:
167
+ stack = detect_project_stack(path)
168
+ except Exception:
169
+ continue
170
+ for kind, provider, framework, supported, adapter in _stack_labels(stack):
171
+ if supported:
172
+ lines.append(
173
+ f"- {path}: {kind} {provider}/{framework} — OUMV ready; "
174
+ f"tokensafe:oumv(workspace_dir='{path}') for status/observe/mutate."
175
+ )
176
+ else:
177
+ lines.append(
178
+ f"- {path}: {kind} {provider}/{framework} — no OUMV adapter; "
179
+ f"repo_map/scoped_search with project_path='{path}'."
180
+ )
181
+ return lines
182
+
183
+
56
184
  def _activation(workspace: str, stack: Dict[str, Any]) -> List[str]:
57
185
  """Exact next command(s) when an adapter is missing — no guessing."""
58
186
  hints: List[str] = []
@@ -84,16 +212,19 @@ def build_workspace_brief(
84
212
  workspace: Optional[str] = None,
85
213
  include_live: bool = False,
86
214
  max_chars: int = MAX_BRIEF_CHARS,
215
+ extra_workspaces: Optional[List[str]] = None,
87
216
  ) -> str:
88
- """Builds the compact routing brief. Returns "" for non-project directories."""
217
+ """Builds the compact routing brief. Returns "" for non-project directories.
218
+
219
+ ``extra_workspaces`` covers the other roots an agent can edit in the same
220
+ session (ZCode ``workspacePaths[1:]``, ``TOKENSAFE_WORKSPACES``). Every root
221
+ is classified on its own: the primary verdict must never be read as a
222
+ statement about another repository, so the brief always states its scope.
223
+ """
89
224
  if not workspace or not os.path.isdir(workspace):
90
225
  return ""
91
- try:
92
- from src.paths import is_project_root
93
- if not is_project_root(workspace):
94
- return ""
95
- except Exception:
96
- pass
226
+ if not _is_root(workspace):
227
+ return ""
97
228
 
98
229
  try:
99
230
  from src.retrofit import detect_project_stack
@@ -106,21 +237,50 @@ def build_workspace_brief(
106
237
  if not frontend and not backend:
107
238
  return ""
108
239
 
240
+ seen = {os.path.realpath(workspace)}
241
+ extra_lines = _extra_root_lines(extra_workspaces or [], seen)
242
+
109
243
  lines: List[str] = ["[TokenSafe OUMV routing brief]"]
110
- for entry in (frontend, backend):
244
+ if extra_lines:
245
+ lines.append(
246
+ "- scope: per-root verdicts below; for any unlisted repo call "
247
+ "tokensafe:oumv(action='status', workspace_dir='<repo>')."
248
+ )
249
+ else:
250
+ lines.append(
251
+ "- scope: this verdict covers this root only; before editing another repo call "
252
+ "tokensafe:oumv(action='status', workspace_dir='<repo>')."
253
+ )
254
+ for kind, entry in (("frontend", frontend), ("backend", backend)):
111
255
  if not entry:
112
256
  continue
113
257
  provider = str(entry.get("provider") or "")
114
- framework = str(entry.get("framework") or "")
115
- template = _FRONTEND_LINES.get(provider) if entry is frontend else _BACKEND_LINES.get(provider)
258
+ framework = str(entry.get("framework") or provider)
259
+ supported = _profile_supported(kind, entry)
260
+ table = _FRONTEND_LINES if kind == "frontend" else _BACKEND_LINES
261
+ template = table.get(provider)
116
262
  if template:
117
263
  lines.append("- " + template.format(provider=provider, framework=framework))
264
+ elif _profile_supported(kind, entry):
265
+ # Provider without a routing template (e.g. Solid) but with a
266
+ # runtime-reported adapter: route through OUMV instead of greps.
267
+ adapter = str(entry.get("adapter") or "")
268
+ via = f" via {adapter}" if adapter else ""
269
+ live = "; start live bridge via `tokensafe dev`" if entry.get("vite") else ""
270
+ lines.append(
271
+ f"- {kind} {provider}/{framework}: OUMV ready{via}{live}; call "
272
+ "tokensafe:oumv(action='status'|'observe'|'mutate') before reading files."
273
+ )
118
274
  else:
119
275
  lines.append(
120
276
  f"- {provider}/{framework}: OUMV has no adapter yet — use "
121
277
  "tokensafe:repo_map / scoped_search / smart_read_file instead of oumv."
122
278
  )
123
279
 
280
+ if extra_lines:
281
+ lines.append("- other workspace roots:")
282
+ lines.extend(extra_lines)
283
+
124
284
  permissions = _read_permissions(workspace)
125
285
  if permissions:
126
286
  mutate = permissions.get("mutate", True)
@@ -150,5 +310,10 @@ def build_workspace_brief(
150
310
 
151
311
  brief = "\n".join(lines)
152
312
  if len(brief) > max_chars:
153
- brief = brief[: max_chars - 1].rstrip() + "…"
313
+ # Cut on a line boundary: a half-written path in a truncated root line
314
+ # is worse than a dropped tail line (the scope sentence stays at the top).
315
+ cut = brief[: max_chars - 1]
316
+ if "\n" in cut:
317
+ cut = cut.rsplit("\n", 1)[0]
318
+ brief = cut.rstrip() + "…"
154
319
  return brief
@@ -119,6 +119,12 @@ class BraceLexer:
119
119
  class Skeletonizer:
120
120
  """Generates structural AST skeletons without LLMs with incremental mtime caching."""
121
121
 
122
+ # Below this size a skeleton costs MORE than it saves: the caller asked for the
123
+ # file, gets only signatures, and has to spend a second call to read the body it
124
+ # needed — measured in the OUMV agent matrix (a 155-line Go app: 727-char skeleton
125
+ # + 3,209-char re-read vs 3,200-char raw read in one call). Above it, folding wins.
126
+ MIN_SKELETON_LINES = 200
127
+
122
128
  # Design-token selectors matched on word boundaries so class names like
123
129
  # `.html-widget` or identifiers like `innerHTML` no longer masquerade as tokens.
124
130
  TOKEN_SELECTOR_REGEX = re.compile(r'(?<![\w.#-])(?::root|@theme|html|body)(?![\w-])')
@@ -782,7 +788,7 @@ class Skeletonizer:
782
788
  return None, 0, 0
783
789
 
784
790
  lines_count = len(code.splitlines())
785
- if lines_count < 150:
791
+ if lines_count < cls.MIN_SKELETON_LINES:
786
792
  return None, 0, 0
787
793
 
788
794
  ext = os.path.splitext(original_path)[1]
@@ -822,10 +828,10 @@ class Skeletonizer:
822
828
  else:
823
829
  header_comment = (
824
830
  f"// [TOCP AST Skeleton: {lines_count} lines folded into API signatures]\n"
825
- f"// [To inspect implementation of a specific method, call read_file with StartLine/EndLine]\n\n"
831
+ f"// [For one symbol's body call smart_read_file(symbol=...); for a range call smart_read_file(start_line=, end_line=)]\n\n"
826
832
  ) if ext != ".py" else (
827
833
  f"# [TOCP AST Skeleton: {lines_count} lines folded into API signatures]\n"
828
- f"# [To inspect implementation of a specific method, call read_file with StartLine/EndLine]\n\n"
834
+ f"# [For one symbol's body call smart_read_file(symbol=...); for a range call smart_read_file(start_line=, end_line=)]\n\n"
829
835
  )
830
836
 
831
837
  full_content = header_comment + (prefetch_block + "\n" if prefetch_block else "") + skeleton_content
@@ -311,7 +311,7 @@ class TelemetrySync:
311
311
  current_last_id = last_id
312
312
  headers = {
313
313
  "Content-Type": "application/json",
314
- "User-Agent": "TokenSafe-Sync/4.7.0"
314
+ "User-Agent": "TokenSafe-Sync/4.7.2"
315
315
  }
316
316
  if active_key:
317
317
  headers["Authorization"] = f"Bearer {active_key}"
@@ -17,7 +17,7 @@ import urllib.request
17
17
  import urllib.error
18
18
  from typing import Dict, Any, Optional, Tuple
19
19
 
20
- CURRENT_VERSION = "4.7.0"
20
+ CURRENT_VERSION = "4.7.2"
21
21
  CACHE_TTL = 86400 # 24 hours
22
22
  # When the cloud is unreachable we must NOT cache the synthesized "up to date"
23
23
  # answer for a full day — otherwise an update released right after an outage