tokensafe 4.12.4 → 4.13.1
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/.codex-plugin/plugin.json +1 -1
- package/README.md +8 -6
- package/hooks/pre_invocation.py +8 -4
- package/kimi.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/rules/AGENTS.md +4 -3
- package/server.json +3 -3
- package/src/auto_inject.py +1026 -279
- package/src/backend_release.py +10 -0
- package/src/batch_editor.py +18 -8
- package/src/batch_search.py +39 -16
- package/src/bundle_probe.py +205 -0
- package/src/cli.py +76 -7
- package/src/fts_index.py +9 -0
- package/src/globmatch.py +124 -0
- package/src/governor.py +120 -44
- package/src/graph_engine.py +292 -14
- package/src/installer.py +3 -3
- package/src/mcp_server.py +153 -35
- package/src/metrics.py +7 -0
- package/src/oumv_brief.py +346 -0
- package/src/oumv_gateway.py +132 -43
- package/src/quality_score.py +46 -24
- package/src/retrofit.py +35 -11
- package/src/savings.py +1 -0
- package/src/scoped_search.py +238 -9
- package/src/session_brief.py +6 -1
- package/src/telemetry_sync.py +1 -1
- package/src/treesitter_backend.py +26 -1
- package/src/version_checker.py +1 -1
- package/src/web_reader.py +42 -0
- package/src/workspace_roots.py +246 -0
package/src/quality_score.py
CHANGED
|
@@ -46,12 +46,17 @@ class ContextQualityScore:
|
|
|
46
46
|
) -> Dict[str, Any]:
|
|
47
47
|
"""Calculates letter grade and detailed health metrics from budget and audit data."""
|
|
48
48
|
# 1. Dynamic Headroom (0 to 70 pts)
|
|
49
|
-
|
|
49
|
+
used_pct_raw = budget.get("used_pct")
|
|
50
|
+
used_pct = float(used_pct_raw) if used_pct_raw is not None else None
|
|
50
51
|
used_estimated = int(budget.get("used_estimated", 0) or 0)
|
|
51
52
|
window_tokens = int(budget.get("window_tokens", 200_000) or 200_000)
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
53
|
+
measurement = str(budget.get("measurement") or "measured")
|
|
54
|
+
if used_pct is None:
|
|
55
|
+
headroom_pct = None
|
|
56
|
+
headroom_score = 0.0
|
|
57
|
+
else:
|
|
58
|
+
headroom_pct = max(0.0, round(100.0 - used_pct, 1))
|
|
59
|
+
headroom_score = (headroom_pct / 100.0) * 70.0
|
|
55
60
|
|
|
56
61
|
# 2. Static Context Tax (0 to 20 pts)
|
|
57
62
|
audit = audit or {}
|
|
@@ -96,29 +101,44 @@ class ContextQualityScore:
|
|
|
96
101
|
total_score = max(0, min(100, int(round(headroom_score + static_score + hygiene_score))))
|
|
97
102
|
|
|
98
103
|
# Determine Letter Grade & Label
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
label = "Healthy"
|
|
106
|
-
desc = "Healthy context, ample headroom"
|
|
107
|
-
elif total_score >= 60:
|
|
108
|
-
grade = "B"
|
|
109
|
-
label = "Moderate"
|
|
110
|
-
desc = "Moderate load, surgical reads advised"
|
|
111
|
-
elif total_score >= 40:
|
|
112
|
-
grade = "C"
|
|
113
|
-
label = "Constrained"
|
|
114
|
-
desc = "Constrained context, compaction recommended"
|
|
104
|
+
estimate_limited = False
|
|
105
|
+
if used_pct is None:
|
|
106
|
+
total_score = None
|
|
107
|
+
grade = "?"
|
|
108
|
+
label = "Unknown"
|
|
109
|
+
desc = "Context size unknown: no measured prompt size or instrumented traffic"
|
|
115
110
|
else:
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
111
|
+
if measurement == "estimated" and total_score < 40:
|
|
112
|
+
# An estimate is a floor, not the prompt size: it must never
|
|
113
|
+
# produce a false "Critical" that triggers a compaction.
|
|
114
|
+
total_score = 40
|
|
115
|
+
estimate_limited = True
|
|
116
|
+
if total_score >= 88:
|
|
117
|
+
grade = "S"
|
|
118
|
+
label = "Optimal"
|
|
119
|
+
desc = "Pristine context, maximal headroom (>90%)"
|
|
120
|
+
elif total_score >= 75:
|
|
121
|
+
grade = "A"
|
|
122
|
+
label = "Healthy"
|
|
123
|
+
desc = "Healthy context, ample headroom"
|
|
124
|
+
elif total_score >= 60:
|
|
125
|
+
grade = "B"
|
|
126
|
+
label = "Moderate"
|
|
127
|
+
desc = "Moderate load, surgical reads advised"
|
|
128
|
+
elif total_score >= 40:
|
|
129
|
+
grade = "C"
|
|
130
|
+
label = "Constrained"
|
|
131
|
+
desc = "Constrained context, compaction recommended"
|
|
132
|
+
else:
|
|
133
|
+
grade = "F"
|
|
134
|
+
label = "Critical"
|
|
135
|
+
desc = "Critical exhaustion or severe bloat, immediate compaction required"
|
|
119
136
|
|
|
120
137
|
tax_str = f"~{static_tokens:,} tok/turn" if static_tokens else "0 tok/turn"
|
|
121
|
-
|
|
138
|
+
if headroom_pct is None:
|
|
139
|
+
summary = f"Grade: ? (unknown headroom · static tax: {tax_str})"
|
|
140
|
+
else:
|
|
141
|
+
summary = f"Grade: {grade} ({label}, {headroom_pct:.0f}% headroom · static tax: {tax_str})"
|
|
122
142
|
|
|
123
143
|
return {
|
|
124
144
|
"grade": grade,
|
|
@@ -133,6 +153,8 @@ class ContextQualityScore:
|
|
|
133
153
|
"has_mcp_bloat": bool(bloated_servers),
|
|
134
154
|
"has_ghost_tokens": bool(ghost.get("has_ghost_tokens")),
|
|
135
155
|
"deductions": deductions,
|
|
156
|
+
"grade_basis": measurement,
|
|
157
|
+
"estimate_limited": estimate_limited,
|
|
136
158
|
"summary": summary,
|
|
137
159
|
}
|
|
138
160
|
|
package/src/retrofit.py
CHANGED
|
@@ -282,15 +282,23 @@ def detect_project_stack(workspace_dir: str) -> Dict[str, Any]:
|
|
|
282
282
|
if "go" not in stack["package_managers"]:
|
|
283
283
|
stack["package_managers"].append("go")
|
|
284
284
|
framework = "net/http"
|
|
285
|
+
supported = True
|
|
286
|
+
status = "manual"
|
|
287
|
+
note = (
|
|
288
|
+
"net/http needs the stdhttp adapter's mux: replace http.NewServeMux() "
|
|
289
|
+
"with oumvstdhttp.NewServeMux(rt) and mount the RPC path; "
|
|
290
|
+
"`tokensafe inject --status` prints the recipe"
|
|
291
|
+
)
|
|
285
292
|
try:
|
|
286
293
|
with open(go_mod_path, "r", encoding="utf-8") as f:
|
|
287
294
|
content = f.read()
|
|
288
295
|
if "github.com/gin-gonic/gin" in content:
|
|
289
|
-
framework = "gin"
|
|
296
|
+
framework, status, note = "gin", "ready", None
|
|
290
297
|
elif "github.com/go-chi/chi" in content:
|
|
291
|
-
framework = "chi"
|
|
298
|
+
framework, status, note = "chi", "ready", None
|
|
292
299
|
elif "github.com/labstack/echo" in content:
|
|
293
|
-
framework = "echo"
|
|
300
|
+
framework, supported, status = "echo", False, "planned"
|
|
301
|
+
note = "no Echo adapter yet"
|
|
294
302
|
except Exception:
|
|
295
303
|
pass
|
|
296
304
|
go_entry = {
|
|
@@ -299,20 +307,25 @@ def detect_project_stack(workspace_dir: str) -> Dict[str, Any]:
|
|
|
299
307
|
"adapter": "tokensafe-backend/go",
|
|
300
308
|
"language": "go",
|
|
301
309
|
"root": os.path.dirname(rel_mod) or ".",
|
|
302
|
-
"oumv_supported":
|
|
303
|
-
"status":
|
|
310
|
+
"oumv_supported": supported,
|
|
311
|
+
"status": status,
|
|
304
312
|
}
|
|
313
|
+
if note:
|
|
314
|
+
go_entry["note"] = note
|
|
305
315
|
if not stack["backend"] or not stack["backend"].get("oumv_supported", False):
|
|
306
316
|
stack["backend"] = go_entry
|
|
307
|
-
|
|
317
|
+
package_entry = {
|
|
308
318
|
"role": "backend",
|
|
309
319
|
"path": go_entry["root"],
|
|
310
320
|
"framework": framework,
|
|
311
321
|
"provider": "go",
|
|
312
322
|
"adapter": "tokensafe-backend/go",
|
|
313
|
-
"oumvSupported":
|
|
314
|
-
"status":
|
|
315
|
-
}
|
|
323
|
+
"oumvSupported": supported,
|
|
324
|
+
"status": status,
|
|
325
|
+
}
|
|
326
|
+
if note:
|
|
327
|
+
package_entry["reason"] = note
|
|
328
|
+
_add_package(package_entry)
|
|
316
329
|
|
|
317
330
|
# Python Backend detection
|
|
318
331
|
py_files = [
|
|
@@ -536,7 +549,7 @@ def generate_config(
|
|
|
536
549
|
},
|
|
537
550
|
"oumv": {
|
|
538
551
|
"enabled": True,
|
|
539
|
-
"profiles": profiles
|
|
552
|
+
"profiles": profiles,
|
|
540
553
|
},
|
|
541
554
|
"adapters": adapters,
|
|
542
555
|
"permissions": {
|
|
@@ -554,6 +567,12 @@ def generate_config(
|
|
|
554
567
|
except Exception:
|
|
555
568
|
pass
|
|
556
569
|
|
|
570
|
+
# An unknown stack must not get a manifest claiming two profiles it does
|
|
571
|
+
# not have: `.tokensafe/oumv.json` is a fact about detected adapters.
|
|
572
|
+
if not profiles:
|
|
573
|
+
config["_skipped_reason"] = "no OUMV profile detected"
|
|
574
|
+
return config, "", False
|
|
575
|
+
|
|
557
576
|
if not dry_run:
|
|
558
577
|
os.makedirs(target_dir, exist_ok=True)
|
|
559
578
|
with open(target_file, "w", encoding="utf-8") as f:
|
|
@@ -1045,15 +1064,20 @@ def run_doctor(workspace_dir: str) -> Dict[str, Any]:
|
|
|
1045
1064
|
continue
|
|
1046
1065
|
provider = detected.get("provider", "")
|
|
1047
1066
|
framework = detected.get("framework", "")
|
|
1067
|
+
supported = bool(detected.get("oumv_supported", True))
|
|
1048
1068
|
presence = _adapter_presence(workspace_dir, profile, provider, framework)
|
|
1049
1069
|
live = has_runtime and runtime_data.get("type", profile) in (profile, None)
|
|
1050
1070
|
readiness[profile] = {
|
|
1051
1071
|
"provider": provider,
|
|
1052
1072
|
"framework": framework,
|
|
1073
|
+
"supported": supported,
|
|
1074
|
+
"status": detected.get("status", "ready"),
|
|
1053
1075
|
"installed": presence["installed"],
|
|
1054
1076
|
"evidence": presence["evidence"],
|
|
1055
1077
|
"live": bool(live),
|
|
1056
|
-
"ready":
|
|
1078
|
+
# A planned stack is never "ready": an installed npm package does not
|
|
1079
|
+
# create an adapter that does not exist yet.
|
|
1080
|
+
"ready": bool(supported and (presence["installed"] or live)),
|
|
1057
1081
|
}
|
|
1058
1082
|
|
|
1059
1083
|
permissions = config_data.get("permissions", {"observe": True, "mutate": True})
|
package/src/savings.py
CHANGED
|
@@ -69,6 +69,7 @@ def build_savings_report(tracker: Optional[MetricsTracker] = None) -> Dict[str,
|
|
|
69
69
|
"saved_tokens_live": live_saved,
|
|
70
70
|
"saved_tokens_measured": int(summary.get("total_saved_tokens_measured", 0)),
|
|
71
71
|
"saved_tokens_estimated": int(summary.get("total_saved_tokens_estimated", 0)),
|
|
72
|
+
"saved_tokens_basis": summary.get("total_saved_tokens_basis", "estimated"),
|
|
72
73
|
"pruned_synced_saved_tokens": pruned["saved_tokens"],
|
|
73
74
|
"cumulative_saved_tokens": cumulative,
|
|
74
75
|
"usd_saved_approx": summary.get("total_usd_saved", 0.0),
|
package/src/scoped_search.py
CHANGED
|
@@ -178,7 +178,8 @@ class ScopedSearch:
|
|
|
178
178
|
max_results: int = 25,
|
|
179
179
|
case_sensitive: bool = False,
|
|
180
180
|
use_regex: Optional[bool] = None,
|
|
181
|
-
per_file: int = 0
|
|
181
|
+
per_file: int = 0,
|
|
182
|
+
target_file: Optional[str] = None
|
|
182
183
|
) -> Dict[str, Any]:
|
|
183
184
|
"""
|
|
184
185
|
Executes a bounded code/config search and returns structured results and compact markdown.
|
|
@@ -247,6 +248,22 @@ class ScopedSearch:
|
|
|
247
248
|
"markdown": f"Regex compilation error: {str(e)}"
|
|
248
249
|
}
|
|
249
250
|
|
|
251
|
+
# `path` pointing at a file must search that file, never its parent
|
|
252
|
+
# directory: the old dirname fallback returned sibling hits as if they
|
|
253
|
+
# matched the requested file.
|
|
254
|
+
if target_file:
|
|
255
|
+
return cls._search_single_file(
|
|
256
|
+
query=query,
|
|
257
|
+
target_file=os.path.abspath(target_file),
|
|
258
|
+
root_dir=root_dir,
|
|
259
|
+
scope=scope,
|
|
260
|
+
pattern=pattern,
|
|
261
|
+
regex_mode=regex_mode,
|
|
262
|
+
auto_regex=auto_regex,
|
|
263
|
+
max_results=max_results,
|
|
264
|
+
per_file=per_file,
|
|
265
|
+
)
|
|
266
|
+
|
|
250
267
|
# Fast-path: SQLite FTS5 trigram BM25 search for plain case-insensitive queries
|
|
251
268
|
if not regex_mode and not case_sensitive and len(query) >= 3 and not any(c in query for c in "*?[]{}()^$+\\|"):
|
|
252
269
|
try:
|
|
@@ -277,23 +294,42 @@ class ScopedSearch:
|
|
|
277
294
|
})
|
|
278
295
|
fts_hit_files.add(f_rel)
|
|
279
296
|
if fts_matches:
|
|
297
|
+
try:
|
|
298
|
+
indexed_count = int(fts.indexed_file_count() or 0)
|
|
299
|
+
except Exception:
|
|
300
|
+
indexed_count = 0
|
|
301
|
+
coverage_files = indexed_count or len(fts_hit_files)
|
|
280
302
|
return {
|
|
281
303
|
"success": True,
|
|
282
304
|
"query": query,
|
|
283
305
|
"scope": scope,
|
|
284
306
|
"source": "fts_trigram",
|
|
307
|
+
"path_is_file": False,
|
|
285
308
|
"files_matched": len(fts_hit_files),
|
|
286
|
-
"scanned_files":
|
|
309
|
+
"scanned_files": coverage_files,
|
|
310
|
+
"total_files": coverage_files,
|
|
287
311
|
"total_matches": len(fts_matches),
|
|
288
312
|
"overflow_matches": sum(overflow.values()),
|
|
289
313
|
"per_file_cap": per_file_cap,
|
|
290
314
|
"timed_out": False,
|
|
291
315
|
"partial": False,
|
|
316
|
+
"truncated": len(fts_matches) >= max_results,
|
|
317
|
+
"coverage": {
|
|
318
|
+
"complete": False,
|
|
319
|
+
"stopped_reason": "index_only",
|
|
320
|
+
"source": "fts_trigram",
|
|
321
|
+
"index_only": True,
|
|
322
|
+
"indexed_files": indexed_count,
|
|
323
|
+
},
|
|
292
324
|
"matches": fts_matches,
|
|
293
325
|
"markdown": cls._render_markdown(
|
|
294
|
-
query, fts_matches,
|
|
326
|
+
query, fts_matches, coverage_files, False, max_results,
|
|
295
327
|
hit_files=fts_hit_files, scope=scope, root_dir=root_dir,
|
|
296
328
|
overflow=overflow, per_file_cap=per_file_cap,
|
|
329
|
+
total_files=coverage_files,
|
|
330
|
+
stopped_reason="index_only",
|
|
331
|
+
coverage_complete=False,
|
|
332
|
+
coverage_source="fts_trigram",
|
|
297
333
|
),
|
|
298
334
|
}
|
|
299
335
|
except Exception:
|
|
@@ -308,12 +344,16 @@ class ScopedSearch:
|
|
|
308
344
|
indexed = 0
|
|
309
345
|
try:
|
|
310
346
|
graph = cls._graph_symbol_index(root_dir)
|
|
311
|
-
indexed = len(graph.file_symbols) if graph else 0
|
|
347
|
+
indexed = len(set(graph.file_stats) | set(graph.file_symbols)) if graph else 0
|
|
312
348
|
except Exception:
|
|
313
349
|
indexed = 0
|
|
314
350
|
markdown = cls._render_markdown(
|
|
315
351
|
query, symbol_matches, indexed or len(hit_files), False, max_results,
|
|
316
352
|
hit_files=hit_files, scope=scope, root_dir=root_dir,
|
|
353
|
+
total_files=indexed or len(hit_files),
|
|
354
|
+
stopped_reason="index_only",
|
|
355
|
+
coverage_complete=False,
|
|
356
|
+
coverage_source="graph_symbol_index",
|
|
317
357
|
)
|
|
318
358
|
if indexed:
|
|
319
359
|
markdown += (
|
|
@@ -325,13 +365,23 @@ class ScopedSearch:
|
|
|
325
365
|
"query": query,
|
|
326
366
|
"scope": scope,
|
|
327
367
|
"source": "graph_symbol_index",
|
|
368
|
+
"path_is_file": False,
|
|
328
369
|
"files_matched": len(hit_files),
|
|
329
370
|
"scanned_files": indexed or len(hit_files),
|
|
371
|
+
"total_files": indexed or len(hit_files),
|
|
330
372
|
"total_matches": len(symbol_matches),
|
|
331
373
|
"overflow_matches": 0,
|
|
332
374
|
"per_file_cap": cls._resolve_per_file(per_file, max_results),
|
|
333
375
|
"timed_out": False,
|
|
334
376
|
"partial": False,
|
|
377
|
+
"truncated": len(symbol_matches) >= max_results,
|
|
378
|
+
"coverage": {
|
|
379
|
+
"complete": False,
|
|
380
|
+
"stopped_reason": "index_only",
|
|
381
|
+
"source": "graph_symbol_index",
|
|
382
|
+
"index_only": True,
|
|
383
|
+
"indexed_files": indexed,
|
|
384
|
+
},
|
|
335
385
|
"matches": symbol_matches,
|
|
336
386
|
"markdown": markdown,
|
|
337
387
|
}
|
|
@@ -347,12 +397,15 @@ class ScopedSearch:
|
|
|
347
397
|
timeout_seconds = 4.0
|
|
348
398
|
max_scanned_files = 2500
|
|
349
399
|
timed_out = False
|
|
400
|
+
stopped_reason = "complete"
|
|
350
401
|
|
|
351
402
|
for dirpath, dirnames, filenames in os.walk(root_dir):
|
|
352
403
|
if time.monotonic() - start_time > timeout_seconds:
|
|
353
404
|
timed_out = True
|
|
405
|
+
stopped_reason = "time_budget"
|
|
354
406
|
break
|
|
355
407
|
if total_scanned_files >= max_scanned_files:
|
|
408
|
+
stopped_reason = "file_budget"
|
|
356
409
|
break
|
|
357
410
|
|
|
358
411
|
# Prune ignored directories in-place (allow safe dot-config dirs like .github/.claude/.gemini)
|
|
@@ -365,8 +418,10 @@ class ScopedSearch:
|
|
|
365
418
|
for fname in sorted(filenames, key=lambda s: (0 if s.lower() in manifest_priority else 1, s.lower())):
|
|
366
419
|
if time.monotonic() - start_time > timeout_seconds:
|
|
367
420
|
timed_out = True
|
|
421
|
+
stopped_reason = "time_budget"
|
|
368
422
|
break
|
|
369
423
|
if total_scanned_files >= max_scanned_files:
|
|
424
|
+
stopped_reason = "file_budget"
|
|
370
425
|
break
|
|
371
426
|
full_path = os.path.join(dirpath, fname)
|
|
372
427
|
rel_path = os.path.relpath(full_path, root_dir).replace("\\", "/")
|
|
@@ -411,15 +466,30 @@ class ScopedSearch:
|
|
|
411
466
|
hit_files.add(rel_path)
|
|
412
467
|
|
|
413
468
|
if len(matches) >= max_results:
|
|
469
|
+
stopped_reason = "max_results"
|
|
414
470
|
break
|
|
415
471
|
except Exception:
|
|
416
472
|
continue
|
|
417
473
|
|
|
418
474
|
if len(matches) >= max_results:
|
|
475
|
+
stopped_reason = "max_results"
|
|
419
476
|
break
|
|
420
|
-
if
|
|
477
|
+
if stopped_reason != "complete":
|
|
421
478
|
break
|
|
422
479
|
|
|
480
|
+
# A result cap or a search budget stops the walk before the tree ends;
|
|
481
|
+
# count the remaining candidates with a name-only pass so coverage says
|
|
482
|
+
# "240/1,940" instead of presenting 240 as the whole repository.
|
|
483
|
+
if stopped_reason == "complete":
|
|
484
|
+
total_candidate_files: Optional[int] = total_scanned_files
|
|
485
|
+
coverage_complete = True
|
|
486
|
+
else:
|
|
487
|
+
total_candidate_files, counted = cls._count_candidate_files(root_dir, scope)
|
|
488
|
+
coverage_complete = counted
|
|
489
|
+
partial = stopped_reason in ("file_budget", "time_budget")
|
|
490
|
+
coverage_complete = (not partial) and coverage_complete
|
|
491
|
+
truncated = stopped_reason == "max_results"
|
|
492
|
+
|
|
423
493
|
markdown = cls._render_markdown(
|
|
424
494
|
query,
|
|
425
495
|
matches,
|
|
@@ -435,9 +505,11 @@ class ScopedSearch:
|
|
|
435
505
|
max_scanned_files=max_scanned_files,
|
|
436
506
|
overflow=overflow,
|
|
437
507
|
per_file_cap=per_file_cap,
|
|
508
|
+
total_files=total_candidate_files,
|
|
509
|
+
stopped_reason=stopped_reason,
|
|
510
|
+
coverage_complete=coverage_complete,
|
|
438
511
|
)
|
|
439
512
|
|
|
440
|
-
partial = bool(timed_out or total_scanned_files >= max_scanned_files)
|
|
441
513
|
if partial and not matches:
|
|
442
514
|
markdown += (
|
|
443
515
|
"\n_Scan stopped at its safety budget, so coverage was partial: the match may live "
|
|
@@ -454,22 +526,149 @@ class ScopedSearch:
|
|
|
454
526
|
"query": query,
|
|
455
527
|
"scope": scope,
|
|
456
528
|
"source": "disk_scan",
|
|
529
|
+
"path_is_file": False,
|
|
457
530
|
"total_matches": len(matches),
|
|
458
531
|
"overflow_matches": sum(overflow.values()),
|
|
459
532
|
"per_file_cap": per_file_cap,
|
|
460
533
|
"files_matched": len(hit_files),
|
|
461
534
|
"scanned_files": total_scanned_files,
|
|
535
|
+
"total_files": total_candidate_files,
|
|
462
536
|
"timed_out": timed_out,
|
|
463
537
|
"partial": partial,
|
|
538
|
+
"truncated": truncated,
|
|
464
539
|
"coverage": {
|
|
540
|
+
"complete": coverage_complete,
|
|
541
|
+
"stopped_reason": stopped_reason,
|
|
542
|
+
"source": "disk_scan",
|
|
465
543
|
"file_budget": max_scanned_files,
|
|
466
544
|
"time_budget_seconds": timeout_seconds,
|
|
467
|
-
"stopped_early": partial,
|
|
468
545
|
},
|
|
469
546
|
"matches": matches,
|
|
470
547
|
"markdown": markdown,
|
|
471
548
|
}
|
|
472
549
|
|
|
550
|
+
@classmethod
|
|
551
|
+
def _search_single_file(
|
|
552
|
+
cls,
|
|
553
|
+
query: str,
|
|
554
|
+
target_file: str,
|
|
555
|
+
root_dir: str,
|
|
556
|
+
scope: str,
|
|
557
|
+
pattern: Any,
|
|
558
|
+
regex_mode: bool,
|
|
559
|
+
auto_regex: bool,
|
|
560
|
+
max_results: int,
|
|
561
|
+
per_file: int,
|
|
562
|
+
) -> Dict[str, Any]:
|
|
563
|
+
"""Searches exactly the requested file, never its parent directory."""
|
|
564
|
+
if not os.path.isfile(target_file):
|
|
565
|
+
return {
|
|
566
|
+
"success": False,
|
|
567
|
+
"error": f"target file not found: {target_file}",
|
|
568
|
+
"matches": [],
|
|
569
|
+
"total_matches": 0,
|
|
570
|
+
"markdown": f"Target file not found: {target_file}",
|
|
571
|
+
}
|
|
572
|
+
rel = os.path.relpath(target_file, root_dir).replace("\\", "/")
|
|
573
|
+
per_file_cap = cls._resolve_per_file(per_file, max_results)
|
|
574
|
+
matches: List[Dict[str, Any]] = []
|
|
575
|
+
overflow = 0
|
|
576
|
+
try:
|
|
577
|
+
with open(target_file, "r", encoding="utf-8", errors="replace") as f:
|
|
578
|
+
for line_idx, line in enumerate(f, 1):
|
|
579
|
+
if len(line) > 8192:
|
|
580
|
+
continue
|
|
581
|
+
if not pattern.search(line):
|
|
582
|
+
continue
|
|
583
|
+
if len(matches) >= max_results:
|
|
584
|
+
overflow += 1
|
|
585
|
+
continue
|
|
586
|
+
clean_line = line.strip()
|
|
587
|
+
if len(clean_line) > 100:
|
|
588
|
+
clean_line = clean_line[:97] + "..."
|
|
589
|
+
matches.append({"file": rel, "line": line_idx, "text": clean_line})
|
|
590
|
+
except OSError as e:
|
|
591
|
+
return {
|
|
592
|
+
"success": False,
|
|
593
|
+
"error": f"cannot read target file: {e}",
|
|
594
|
+
"matches": [],
|
|
595
|
+
"total_matches": 0,
|
|
596
|
+
"markdown": f"Cannot read target file: {e}",
|
|
597
|
+
}
|
|
598
|
+
stopped_reason = "max_results" if overflow else "complete"
|
|
599
|
+
markdown = cls._render_markdown(
|
|
600
|
+
query, matches, 1, False, max_results,
|
|
601
|
+
hit_files={rel}, scope=scope, root_dir=root_dir,
|
|
602
|
+
auto_regex=auto_regex, regex_mode=regex_mode,
|
|
603
|
+
overflow={rel: overflow} if overflow else None,
|
|
604
|
+
per_file_cap=per_file_cap,
|
|
605
|
+
total_files=1,
|
|
606
|
+
stopped_reason=stopped_reason,
|
|
607
|
+
coverage_complete=True,
|
|
608
|
+
coverage_source="file_scan",
|
|
609
|
+
path_is_file=True,
|
|
610
|
+
query_path=rel,
|
|
611
|
+
)
|
|
612
|
+
return {
|
|
613
|
+
"success": True,
|
|
614
|
+
"query": query,
|
|
615
|
+
"scope": scope,
|
|
616
|
+
"source": "file_scan",
|
|
617
|
+
"path_is_file": True,
|
|
618
|
+
"path_file": rel,
|
|
619
|
+
"files_matched": 1 if matches else 0,
|
|
620
|
+
"scanned_files": 1,
|
|
621
|
+
"total_files": 1,
|
|
622
|
+
"total_matches": len(matches),
|
|
623
|
+
"overflow_matches": overflow,
|
|
624
|
+
"per_file_cap": per_file_cap,
|
|
625
|
+
"timed_out": False,
|
|
626
|
+
"partial": False,
|
|
627
|
+
"truncated": bool(overflow),
|
|
628
|
+
"coverage": {
|
|
629
|
+
"complete": True,
|
|
630
|
+
"stopped_reason": stopped_reason,
|
|
631
|
+
"source": "file_scan",
|
|
632
|
+
"file": rel,
|
|
633
|
+
},
|
|
634
|
+
"matches": matches,
|
|
635
|
+
"markdown": markdown,
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
@classmethod
|
|
639
|
+
def _count_candidate_files(cls, root_dir: str, scope: str, budget_s: float = 1.5) -> Tuple[Optional[int], bool]:
|
|
640
|
+
"""Name-only walk that counts the files the scan would consider.
|
|
641
|
+
|
|
642
|
+
Runs only when the search stopped early, so coverage can say
|
|
643
|
+
"scanned 240/1,940" instead of presenting 240 as the whole repo.
|
|
644
|
+
Returns (count, complete); count is None when the budget cut the walk.
|
|
645
|
+
"""
|
|
646
|
+
start = time.monotonic()
|
|
647
|
+
count = 0
|
|
648
|
+
allowed_dot = (".github", ".gitlab", ".claude", ".gemini", ".agents")
|
|
649
|
+
for dirpath, dirnames, filenames in os.walk(root_dir):
|
|
650
|
+
if time.monotonic() - start > budget_s:
|
|
651
|
+
return None, False
|
|
652
|
+
dirnames[:] = [
|
|
653
|
+
d for d in sorted(dirnames)
|
|
654
|
+
if d not in IGNORED_DIRS and (not d.startswith(".") or d in allowed_dot)
|
|
655
|
+
]
|
|
656
|
+
for fname in filenames:
|
|
657
|
+
if time.monotonic() - start > budget_s:
|
|
658
|
+
return None, False
|
|
659
|
+
full_path = os.path.join(dirpath, fname)
|
|
660
|
+
rel_path = os.path.relpath(full_path, root_dir).replace("\\", "/")
|
|
661
|
+
if not cls.is_match_file(fname, rel_path, scope):
|
|
662
|
+
continue
|
|
663
|
+
try:
|
|
664
|
+
st = os.stat(full_path)
|
|
665
|
+
except OSError:
|
|
666
|
+
continue
|
|
667
|
+
if not stat.S_ISREG(st.st_mode) or st.st_size > 1024 * 1024:
|
|
668
|
+
continue
|
|
669
|
+
count += 1
|
|
670
|
+
return count, True
|
|
671
|
+
|
|
473
672
|
@classmethod
|
|
474
673
|
def _render_markdown(
|
|
475
674
|
cls,
|
|
@@ -487,6 +686,12 @@ class ScopedSearch:
|
|
|
487
686
|
max_scanned_files: int = 2500,
|
|
488
687
|
overflow: Optional[Dict[str, int]] = None,
|
|
489
688
|
per_file_cap: int = 0,
|
|
689
|
+
total_files: Optional[int] = None,
|
|
690
|
+
stopped_reason: str = "complete",
|
|
691
|
+
coverage_complete: bool = True,
|
|
692
|
+
coverage_source: str = "disk_scan",
|
|
693
|
+
path_is_file: bool = False,
|
|
694
|
+
query_path: str = "",
|
|
490
695
|
) -> str:
|
|
491
696
|
"""Generates compact bounded Markdown output for both FTS5 and disk search paths.
|
|
492
697
|
|
|
@@ -502,11 +707,16 @@ class ScopedSearch:
|
|
|
502
707
|
count_label = f"{len(matches)} match{'es' if len(matches) != 1 else ''}"
|
|
503
708
|
if more_hidden:
|
|
504
709
|
count_label = f"{len(matches)} shown, {more_hidden} more"
|
|
710
|
+
if path_is_file:
|
|
711
|
+
target_label = f"file: `{query_path}`"
|
|
712
|
+
else:
|
|
713
|
+
target_label = f"dir: `{display_root}`"
|
|
505
714
|
lines = [
|
|
506
|
-
f"### TokenSafe Scoped Search: '{query}' ({count_label} in {len(hit_files)} file{'s' if len(hit_files) != 1 else ''},
|
|
715
|
+
f"### TokenSafe Scoped Search: '{query}' ({count_label} in {len(hit_files)} file{'s' if len(hit_files) != 1 else ''}, {target_label}, scope: {scope}{mode_suffix})"
|
|
507
716
|
]
|
|
508
717
|
if not matches:
|
|
509
|
-
|
|
718
|
+
where = f"file `{query_path}`" if path_is_file else f"{total_scanned_files} scanned files in `{root_dir}`"
|
|
719
|
+
lines.append(f"_No matches found in {where}._")
|
|
510
720
|
if auto_regex and regex_mode:
|
|
511
721
|
lines.append("_Auto-regex mode found nothing; pass use_regex=false to force a literal search._")
|
|
512
722
|
else:
|
|
@@ -536,4 +746,23 @@ class ScopedSearch:
|
|
|
536
746
|
elif total_scanned_files >= max_scanned_files:
|
|
537
747
|
lines.append(f"_Scan bounded at {max_scanned_files} files limit. Narrow 'project_path' if needed._")
|
|
538
748
|
|
|
749
|
+
source_suffix = "" if coverage_source == "disk_scan" else f" · source: {coverage_source}"
|
|
750
|
+
if path_is_file:
|
|
751
|
+
lines.append(f"_coverage: file `{query_path}`, complete{source_suffix}._")
|
|
752
|
+
elif total_files is None:
|
|
753
|
+
lines.append(
|
|
754
|
+
f"_coverage: scanned {total_scanned_files:,} files, total unknown "
|
|
755
|
+
f"({stopped_reason}){source_suffix}._"
|
|
756
|
+
)
|
|
757
|
+
elif coverage_complete:
|
|
758
|
+
cap_note = ", results capped" if stopped_reason == "max_results" else ""
|
|
759
|
+
lines.append(f"_coverage: scanned {total_scanned_files:,}/{total_files:,} files, complete{cap_note}{source_suffix}._")
|
|
760
|
+
else:
|
|
761
|
+
lines.append(
|
|
762
|
+
f"_coverage: scanned {total_scanned_files:,}/{total_files:,} files, "
|
|
763
|
+
f"partial: {stopped_reason}{source_suffix}._"
|
|
764
|
+
)
|
|
765
|
+
if coverage_source in ("fts_trigram", "graph_symbol_index"):
|
|
766
|
+
lines.append("_Index-only answer: pass `use_regex=true` to force a bounded disk scan._")
|
|
767
|
+
|
|
539
768
|
return "\n".join(lines)
|
package/src/session_brief.py
CHANGED
|
@@ -218,7 +218,12 @@ def _activation(workspace: str, stack: Dict[str, Any]) -> List[str]:
|
|
|
218
218
|
for profile, item in readiness.items():
|
|
219
219
|
if item.get("ready"):
|
|
220
220
|
continue
|
|
221
|
-
if
|
|
221
|
+
if not item.get("supported", True):
|
|
222
|
+
hints.append(
|
|
223
|
+
f"no OUMV adapter for {item.get('provider')}/{item.get('framework')} yet — "
|
|
224
|
+
"use tokensafe tools (repo_map, scoped_search, smart_read_file) instead"
|
|
225
|
+
)
|
|
226
|
+
elif profile == "frontend":
|
|
222
227
|
hints.append("activate frontend: run `tokensafe dev` (installs nothing into the repo)")
|
|
223
228
|
elif item.get("provider") == "fastapi":
|
|
224
229
|
hints.append('activate backend: `pip install "tokensafe-backend-python @ git+https://github.com/tokensafe-dev/tokensafe-backend.git#subdirectory=python"` then run the server via `tokensafe run-backend ...`')
|
package/src/telemetry_sync.py
CHANGED
|
@@ -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.
|
|
314
|
+
"User-Agent": "TokenSafe-Sync/4.13.1"
|
|
315
315
|
}
|
|
316
316
|
if active_key:
|
|
317
317
|
headers["Authorization"] = f"Bearer {active_key}"
|