tokensafe 4.7.1 → 4.7.3

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.
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "4.7.1",
2
+ "version": "4.7.3",
3
3
  "name": "tokensafe",
4
4
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
5
5
  "author": {
package/README.md CHANGED
@@ -472,7 +472,7 @@ All hook adapters fail open: an internal error never stalls your agent. Failures
472
472
  |---|---|
473
473
  | `get_architecture_graph` | Architectural hotspots, dependency topology, and God Nodes detection before multi-file reading (persisted in SQLite cache) |
474
474
  | `get_api_surface` | Compact markdown map of all exported interfaces, classes, and types |
475
- | `smart_read_file` | AST-skeletonized file read preserving a target symbol and 1-hop dependencies; OpenAPI/Prisma/GraphQL/SQL auto-slice; lockfiles/CSV/TSV/SQL dump auto-reduction with reversible stash |
475
+ | `smart_read_file` | AST-skeletonized file read preserving a target symbol and 1-hop dependencies; `endpoint="POST /api/x"` resolves route → handler body + path + line range + whole-file version in one call; OpenAPI/Prisma/GraphQL/SQL auto-slice; lockfiles/CSV/TSV/SQL dump auto-reduction with reversible stash |
476
476
  | `smart_bundle` | 3–8 related symbols across files in one call: merged skeletons, deduplicated shared imports, unified 1-hop signatures |
477
477
  | `scoped_search` | Sub-millisecond keyword and symbol search powered by native SQLite FTS5 trigram index with BM25 relevance ranking (<1ms) |
478
478
  | `expand_ref` | Reversible stash expansion: recovers original un-truncated content by its 8-char hex hash anchor (`#a1b2c3d4`) without re-running tools |
package/kimi.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokensafe",
3
- "version": "4.7.1",
3
+ "version": "4.7.3",
4
4
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
5
5
  "homepage": "https://tokensafe.dev",
6
6
  "license": "Apache-2.0",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "4.7.1",
4
+ "version": "4.7.3",
5
5
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
6
6
  "main": "bin/tokensafe.js",
7
7
  "bin": {
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "displayName": "TokenSafe",
4
- "version": "4.7.1",
4
+ "version": "4.7.3",
5
5
  "license": "Apache-2.0",
6
6
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
7
7
  "logo": "assets/logo.png",
package/server.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "dev.tokensafe/tokensafe",
4
4
  "title": "TokenSafe",
5
5
  "description": "Your AI agent is smart enough to code all day. Local firewall & zero-loss runtime.",
6
- "version": "4.7.1",
6
+ "version": "4.7.3",
7
7
  "websiteUrl": "https://tokensafe.dev",
8
8
  "repository": {
9
9
  "url": "https://github.com/tokensafe-dev/tokensafe",
@@ -23,7 +23,7 @@
23
23
  "registryType": "npm",
24
24
  "registryBaseUrl": "https://registry.npmjs.org",
25
25
  "identifier": "tokensafe",
26
- "version": "4.7.1",
26
+ "version": "4.7.3",
27
27
  "runtimeHint": "npx",
28
28
  "transport": {
29
29
  "type": "stdio"
@@ -39,7 +39,7 @@
39
39
  "registryType": "pypi",
40
40
  "registryBaseUrl": "https://pypi.org",
41
41
  "identifier": "tokensafe",
42
- "version": "4.7.1",
42
+ "version": "4.7.3",
43
43
  "runtimeHint": "uvx",
44
44
  "transport": {
45
45
  "type": "stdio"
@@ -25,6 +25,9 @@ class AgentFirewall:
25
25
  _PRUNE_INTERVAL = 3600.0 # amortized hourly prune of the persistent layer
26
26
  _PRUNE_KEEP = 500
27
27
  _last_prune = 0.0
28
+ # Render revision for cached symbol slices (see _cache_symbol): bump when the
29
+ # shape of a slice changes, so unchanged bytes do not serve the old shape.
30
+ _SLICE_REVISION = "r3"
28
31
  # Content this process has actually delivered. The cache is keyed by session_id,
29
32
  # and host session ids like "mcp:<client>" outlive one process — so a DB hit alone
30
33
  # does not mean the caller already has the bytes in context, and saying "reused
@@ -61,6 +64,19 @@ class AgentFirewall:
61
64
  conn.execute("CREATE INDEX IF NOT EXISTS idx_subagent_hash ON subagent_file_cache(file_path, symbol, content_hash);")
62
65
  cls._INITIALIZED_DBS.add(tracker.db_path)
63
66
 
67
+ @staticmethod
68
+ def _cache_symbol(symbol: str) -> str:
69
+ """Namespace the cached slice by its render revision.
70
+
71
+ The cache is content-addressed by file bytes, which says nothing about
72
+ the *shape* of the answer: changing how a symbol slice is rendered (the
73
+ v1.3 headers, inlined cross-file declarations) must not serve the old
74
+ shape for unchanged bytes. Bump the revision instead of truncating the
75
+ table, so whole-file skeleton entries stay valid.
76
+ """
77
+ key = (symbol or "").strip()
78
+ return f"{key}#{AgentFirewall._SLICE_REVISION}" if key else ""
79
+
64
80
  @staticmethod
65
81
  def _file_content_hash(file_path: str) -> str:
66
82
  """sha256 of the file's RAW bytes — streamed in 64KB chunks."""
@@ -126,7 +142,7 @@ class AgentFirewall:
126
142
  return False, None, 0
127
143
 
128
144
  abs_path = os.path.abspath(file_path)
129
- symbol_key = (symbol or "").strip()
145
+ symbol_key = cls._cache_symbol(symbol)
130
146
  current_hash = ""
131
147
 
132
148
  hit_data = None
@@ -259,7 +275,7 @@ class AgentFirewall:
259
275
  mtime = time.time()
260
276
 
261
277
  abs_path = os.path.abspath(file_path)
262
- symbol_key = (symbol or "").strip()
278
+ symbol_key = cls._cache_symbol(symbol)
263
279
  tokens = count_tokens(content)
264
280
  now = int(time.time())
265
281
  content_hash = cls._file_content_hash(abs_path)
@@ -612,14 +612,18 @@ SYSTEM_BASELINE = (
612
612
  )
613
613
  SYSTEM_TOKENSAFE = (
614
614
  "You are a senior Go engineer working in a small Go module. The bug report has a repro; "
615
- "stop as soon as the oracle passes. Loop: (1) ts_scoped_search on the status code or error "
616
- "text from the repro → file:line hits; (2) ts_smart_read_file(path, symbol=<identifier or "
617
- "endpoint from the hit>) → the enclosing body or a window, with line numbers; "
615
+ "stop as soon as the oracle passes. Loop: (1) ts_smart_read_file(endpoint=<\"METHOD /path\" from the "
616
+ "repro>) → the handler body, its file, its line range and the whole-file version in ONE call; when the "
617
+ "route is registered in several apps the response lists each and shows all of them. "
618
+ "(2) if the defect is in a callee named on the response's `calls:` line, read it with "
619
+ "ts_smart_read_file(path=<that path>, symbol=<name>) — a symbol declared in another file is inlined in "
620
+ "the same response, so one call is enough. Every slice is exact file text: use it verbatim as the hunk "
621
+ "target, without re-reading to check. "
618
622
  "(3) ts_apply_edits with edits=[{path, hunks:[{target: exact snippet, replacement: fix, "
619
- 'start_line: the L from (2)}]}] plus verify="auto" → edit and verdict in one call; '
620
- "(4) if verify fails, fix the reported line and repeat (2)-(3). "
621
- "Skip ts_repo_map when the repro names the endpoint. Prefer these over list_files/read_file; "
622
- "never rewrite a whole file."
623
+ 'start_line: the L from the slice}]}] plus verify="auto" → edit and verdict in one call; '
624
+ "(4) if verify fails, fix the reported line and repeat (1)-(3). "
625
+ "Use ts_scoped_search only when the repro names no route. Skip ts_repo_map. Prefer these over "
626
+ "list_files/read_file; never rewrite a whole file."
623
627
  )
624
628
 
625
629
  SYSTEM_OUMV = (
@@ -510,12 +510,13 @@ SYSTEM_TOKENSAFE = (
510
510
  "You are a senior React engineer working in a small sandbox. The workspace has TokenSafe tools. "
511
511
  "Use this loop and stop as soon as the oracle reports 12: (1) ts_scoped_search for the behaviour named "
512
512
  "in the repro to get file:line hits; (2) ts_smart_read_file with that path and the identifier from the hit "
513
- "as `symbol` — it returns the enclosing component/handler body (or a window around the hit) with line numbers; "
514
- "(3) ts_apply_edits with one hunk {target: the exact snippet, replacement: the fix} plus "
515
- 'verify="auto" (the declared test command) — it edits and verifies in one call; (4) if verify fails, read the '
516
- "reported line and repeat (2)-(3). ts_repo_map is for an unfamiliar repository; skip it when the repro "
517
- "already names the component. Prefer these tools over list_files/read_file. Tests and adapter.ts are "
518
- "read-only. Do not rewrite whole files."
513
+ "as `symbol` — it returns the enclosing component/handler body (or a window around the hit) with line "
514
+ "numbers, and inlines the body when the identifier is declared in another file, so one call is enough; "
515
+ "(3) ts_apply_edits with one hunk {target: the exact snippet from that slice, replacement: the fix} plus "
516
+ 'verify="auto" (the declared test command) — it edits and verifies in one call. The slice is exact file '
517
+ "text: do not re-read_file to check it. (4) if verify fails, read the reported line and repeat (2)-(3). "
518
+ "ts_repo_map is for an unfamiliar repository; skip it when the repro already names the component. Prefer "
519
+ "these tools over list_files/read_file. Tests and adapter.ts are read-only. Do not rewrite whole files."
519
520
  )
520
521
 
521
522
  SYSTEM_OUMV = (
package/src/installer.py CHANGED
@@ -48,7 +48,7 @@ UNIFIED_TOKENSAFE_RULE = (
48
48
  "## TOKENSAFE GRAPH-FIRST OPTIMIZATION PROTOCOL\n"
49
49
  "Always use `tokensafe` MCP tools (`smart_read_file`, `scoped_search`, `apply_edits`, `repo_map`, `session_context`, `oumv`, `run_helper`) over default raw file reads or high-output terminal executions.\n\n"
50
50
  "1. **Zero Raw Grep/Find (Blocked & Replaced by `scoped_search`)**: Strictly NEVER execute terminal `grep`, `egrep`, `ripgrep`, or `find` on source code files or directories (`src/`, `views/`, `components/`, `.ts`, `.tsx`, `.py`, `.js`). Use `tokensafe:scoped_search(query, path='.', scope='code')` for single searches (`mode='auto'|'text'|'regex'|'glob'|'fuzzy'|'git'`) or `queries=[...]` for up to 20 concurrent queries in one call.\n"
51
- "2. **Mandatory Symbol, Bundle & External Type Inspection (`smart_read_file`)**: Always call `tokensafe:smart_read_file(path, symbol)` (default `dep_mode='signature'` folds inert code -95%+ tokens; pass `dep_mode='full'` only when needed, or `force_full=true` if a pointer hit references missing context). `symbol` accepts an identifier, a qualified member (`Type.Method`) or an endpoint target (`'POST /api/orders'`): when the target is not a declaration in that file you get the enclosing handler body (or a tight ±window around the hit) with line numbers — that is the slice you edit, never a folded skeleton you have to re-read. Pass `targets=[{path, symbol}]` to bundle 2-8 symbols across files in one call, or `package_name`+`symbol` for 3rd-party `.d.ts` interfaces. OpenAPI/Prisma/GraphQL/SQL schemas auto-slice via `symbol`.\n"
51
+ "2. **Mandatory Symbol, Endpoint, Bundle & External Type Inspection (`smart_read_file`)**: Always call `tokensafe:smart_read_file(path, symbol)` (default `dep_mode='signature'` folds inert code -95%+ tokens; pass `dep_mode='full'` only when needed, or `force_full=true` if a pointer hit references missing context). When the bug names a route, call `smart_read_file(endpoint='POST /api/orders')` FIRST: one call resolves the route registration across the repo → handler body + file path + line range + whole-file version (and names the handler's cross-file callees). `symbol` accepts an identifier, a qualified member (`Type.Method`) or an endpoint target (`'POST /api/orders'`): when the target is not a declaration in that file you get the enclosing handler body (or a tight ±window around the hit) with line numbers, plus the declaration itself when it lives in another file — that is the slice you edit, never a folded skeleton you have to re-read, and it is exact file text so it needs no confirming re-read. Pass `targets=[{path, symbol}]` to bundle 2-8 symbols across files in one call, or `package_name`+`symbol` for 3rd-party `.d.ts` interfaces. OpenAPI/Prisma/GraphQL/SQL schemas auto-slice via `symbol`.\n"
52
52
  "3. **Repeat Read Deduplication**: Never re-read unchanged files or symbols within the same session. Reuse the earlier skeleton or pointer hit (`// [TokenSafe: Pointer Hit ...]`).\n"
53
53
  "4. **Zero-Fluff Egress & Surgical Diffs**: Omit conversational filler. Reference line ranges (`file.ts#L10-L25`) and use `tokensafe:apply_edits` for multi-hunk/multi-file edits with optional inline `verify`. For a failing test, one hunk + `verify='auto'` (the project's own declared test command) per attempt: the edit and the verdict come back in one call, so read the reported line and apply the next hunk instead of rewriting whole files.\n"
54
54
  "5. **Architecture Graph, API Surface & Directory Tree (`repo_map`)**: For an unfamiliar repository or a broad refactor, FIRST call `tokensafe:repo_map(view='graph', project_path=...)` for God Nodes (<250 tokens). Use `view='api'` for exported types/interfaces and `view='tree'` instead of `ls -la`. Skip the map when the task already names the failing endpoint, symbol or file — go straight to `scoped_search` + `smart_read_file`.\n"
package/src/mcp_server.py CHANGED
@@ -37,13 +37,14 @@ from src.agent_firewall import AgentFirewall
37
37
  from src.diff_slicer import DiffSlicer
38
38
  from src.guard import TokenSafeGuard
39
39
  from src.scoped_search import ScopedSearch
40
+ from src import route_index
40
41
  from src.license_manager import LicenseManager
41
42
  from src.paths import get_active_workspace, is_plugin_or_system_dir
42
43
  from src.session_context import current_root, current_session_id
43
44
 
44
45
  SERVER_INFO = {
45
46
  "name": "tokensafe-mcp",
46
- "version": "4.7.1"
47
+ "version": "4.7.3"
47
48
  }
48
49
 
49
50
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -674,10 +675,12 @@ _LEAN_TOOL_NAMES = frozenset({"smart_read_file", "scoped_search", "apply_edits",
674
675
  # previous literal: this schema is re-sent in every request of every session.
675
676
  TOOLS = [{'name': 'smart_read_file',
676
677
  'annotations': {'readOnlyHint': True},
677
- 'description': 'AST-skeleton reader. path+symbol for one file, targets=[{path,symbol}] for 2-8 at once, '
678
- 'package_name+symbol for .d.ts.',
678
+ 'description': 'AST-skeleton reader. endpoint="POST /api/x" resolves route→handler body + path + lines + version in one call; '
679
+ 'path+symbol for one file; targets=[{path,symbol}] for 2-8 at once; package_name+symbol for .d.ts.',
679
680
  'inputSchema': {'type': 'object',
680
- 'properties': {'path': {'type': 'string', 'description': 'File path'},
681
+ 'properties': {'endpoint': {'type': 'string',
682
+ 'description': "'METHOD /path' repo route target"},
683
+ 'path': {'type': 'string', 'description': 'File path'},
681
684
  'symbol': {'type': 'string',
682
685
  'description': "Identifier, 'Type.Method', endpoint or schema "
683
686
  'model; a non-declaration returns the enclosing '
@@ -694,45 +697,24 @@ TOOLS = [{'name': 'smart_read_file',
694
697
  'symbol': {'type': 'string'}},
695
698
  'required': ['path']}},
696
699
  'package_name': {'type': 'string', 'description': '.d.ts npm package'}},
697
- 'required': ['path']}},
700
+ 'anyOf': [{'required': ['path']}, {'required': ['endpoint']}, {'required': ['package_name']}]}},
698
701
  {'name': 'scoped_search',
699
702
  'annotations': {'readOnlyHint': True},
700
- 'description': 'Bounded search replacing grep/find. Single query+scope, or '
701
- 'queries=[{pattern,type,path,glob}] for up to 20.',
703
+ 'description': 'Search replacing grep/find: query+scope, or queries=[{pattern,type,path,glob}] batch (max 20).',
702
704
  'inputSchema': {'type': 'object',
703
705
  'properties': {'query': {'type': 'string'},
704
706
  'mode': {'type': 'string',
705
- 'enum': ['auto', 'text', 'regex', 'glob', 'fuzzy', 'git']},
707
+ 'description': 'auto|text|regex|glob|fuzzy|git'},
706
708
  'scope': {'type': 'string',
707
- 'description': "'code','config','all', ext or subfolder"},
709
+ 'description': "code|config|all|ext|subfolder"},
708
710
  'path': {'type': 'string'},
709
- 'project_path': {'type': 'string', 'description': 'alias for path'},
710
- 'cwd': {'type': 'string',
711
- 'description': 'base dir for a relative path'},
712
- 'use_regex': {'type': 'boolean'},
713
- 'case_sensitive': {'type': 'boolean'},
714
- 'max_results': {'type': 'integer', 'description': 'default 25, max 100'},
715
- 'per_file': {'type': 'integer',
716
- 'description': 'hits per file (default auto)'},
711
+ 'cwd': {'type': 'string'},
712
+ 'max_results': {'type': 'integer', 'description': 'default 25'},
713
+ 'per_file': {'type': 'integer'},
717
714
  'queries': {'type': 'array',
718
715
  'maxItems': 20,
719
- 'items': {'type': 'object',
720
- 'properties': {'pattern': {'type': 'string'},
721
- 'type': {'type': 'string',
722
- 'enum': ['text',
723
- 'regex',
724
- 'glob',
725
- 'fuzzy',
726
- 'git']},
727
- 'path': {'type': 'string'},
728
- 'glob': {'type': 'string'},
729
- 'file_type': {'type': 'string'},
730
- 'output_mode': {'type': 'string',
731
- 'enum': ['content',
732
- 'files_with_matches',
733
- 'count']},
734
- 'max_results': {'type': 'integer'}},
735
- 'required': ['pattern']}}}}},
716
+ 'description': 'batch items: {pattern, type?, path?, glob?}',
717
+ 'items': {'type': 'object'}}}}},
736
718
  {'name': 'apply_edits',
737
719
  'annotations': {'readOnlyHint': False, 'destructiveHint': False},
738
720
  'description': 'Multi-hunk editor (up to 50 files) with optional inline verify: the edit and its verdict '
@@ -1298,6 +1280,36 @@ def _symbol_scope(graph: Any, rel_path: str, symbol: str, code: str) -> Dict[str
1298
1280
  return plan
1299
1281
 
1300
1282
 
1283
+ def _cross_file_declaration(plan: Dict[str, Any], from_path: str) -> Tuple[str, str]:
1284
+ """(header, body) for the one declaration that lives in another file.
1285
+
1286
+ A miss used to end with "call smart_read_file(path=..., symbol=...)" — which
1287
+ the measured runs did, or worse, replaced with a raw read of the whole file.
1288
+ When the declaration is small the answer fits in this response, so the
1289
+ follow-up call disappears.
1290
+ """
1291
+ elsewhere = plan.get("elsewhere")
1292
+ if not elsewhere:
1293
+ return "", ""
1294
+ rel, start, end, name = elsewhere
1295
+ if end < start or (end - start + 1) > _SYMBOL_MISS_FULL_DECL_LINES:
1296
+ return "", ""
1297
+ try:
1298
+ root = GraphEngine.find_project_root(from_path)
1299
+ full = os.path.join(root, rel)
1300
+ if os.path.getsize(full) > 2_000_000:
1301
+ return "", ""
1302
+ with open(full, "r", encoding="utf-8", errors="replace") as handle:
1303
+ lines = handle.read().splitlines()
1304
+ except (OSError, ValueError):
1305
+ return "", ""
1306
+ if start > len(lines):
1307
+ return "", ""
1308
+ version = route_index.file_version(full)
1309
+ header = f"// --- L{start}-L{end} ({rel}, {name}, ver={version})"
1310
+ return header, "\n".join(lines[start - 1:end])
1311
+
1312
+
1301
1313
  def _render_symbol_scope_miss(plan: Dict[str, Any], path: str, symbol: str, code: str) -> str:
1302
1314
  """Honest, actionable replacement for a skeleton that folded the requested symbol away."""
1303
1315
  base = os.path.basename(path)
@@ -1305,17 +1317,24 @@ def _render_symbol_scope_miss(plan: Dict[str, Any], path: str, symbol: str, code
1305
1317
  probe = plan.get("probe")
1306
1318
  probe_note = f" (matched '{probe}')" if probe and probe != symbol else ""
1307
1319
  elsewhere = plan["elsewhere"]
1320
+ decl_header, decl_body = _cross_file_declaration(plan, path)
1308
1321
  pointer = ""
1309
- if elsewhere:
1322
+ if elsewhere and not decl_body:
1310
1323
  r, es, ee, _n = elsewhere
1311
1324
  pointer = (
1312
1325
  f"\n// ['{symbol}' is declared in {r} L{es}-L{ee} — call smart_read_file(path=\"{r}\", symbol=\"{symbol}\")"
1313
1326
  f" if you need that declaration instead]"
1314
1327
  )
1328
+ tail = f"\n{decl_header}\n{decl_body}" if decl_body else ""
1315
1329
 
1316
1330
  if plan["status"] == "absent":
1317
1331
  decl_txt = ", ".join(f"{n} L{s}-L{e}" for n, s, e in plan["decls"][:12]) or "none indexed"
1318
- return f"// [TokenSafe: '{symbol}' does not occur in {base}. Declarations in this file: {decl_txt}]{pointer}"
1332
+ head = f"// [TS: '{symbol}' does not occur in {base}"
1333
+ if decl_body:
1334
+ head += f"; declared in {elsewhere[0]} L{elsewhere[1]}-L{elsewhere[2]}, shown below]"
1335
+ else:
1336
+ head += f". Declarations here: {decl_txt}]"
1337
+ return f"{head}{pointer}{tail}"
1319
1338
 
1320
1339
  lines = code.splitlines()
1321
1340
  enclosing = plan["enclosing"]
@@ -1325,8 +1344,8 @@ def _render_symbol_scope_miss(plan: Dict[str, Any], path: str, symbol: str, code
1325
1344
  name, start, end = enclosing
1326
1345
  windows = [(start, end)]
1327
1346
  head = (
1328
- f"// [TokenSafe Text-Anchor Slice: '{symbol}' is not a declaration in {base}; "
1329
- f"it occurs at {hits}{probe_note} inside {name} (L{start}-L{end}) — that declaration is shown in full]"
1347
+ f"// [TS: '{symbol}' at {base} {hits}{probe_note} inside {name} L{start}-L{end}"
1348
+ f" — full declaration below]"
1330
1349
  )
1331
1350
  else:
1332
1351
  pad = _SYMBOL_MISS_WINDOW_PAD
@@ -1340,21 +1359,14 @@ def _render_symbol_scope_miss(plan: Dict[str, Any], path: str, symbol: str, code
1340
1359
  else:
1341
1360
  merged.append((s, e))
1342
1361
  windows = merged
1343
- if enclosing:
1344
- name, ds, de = enclosing
1345
- head = (
1346
- f"// [TokenSafe Text-Anchor Slice: '{symbol}' is not a declaration in {base}; "
1347
- f"it occurs at {hits}{probe_note} inside {name} (L{ds}-L{de}) — showing ±{pad} lines around each hit]"
1348
- f"\n// {lines[ds - 1].strip()}"
1349
- )
1350
- else:
1351
- head = (
1352
- f"// [TokenSafe Text-Anchor Slice: '{symbol}' is not a declaration in {base}; "
1353
- f"it occurs at {hits}{probe_note} outside any indexed declaration — showing ±{pad} lines around each hit]"
1354
- )
1362
+ where = f"inside {enclosing[0]} L{enclosing[1]}-L{enclosing[2]}" if enclosing else "outside any declaration"
1363
+ head = (
1364
+ f"// [TS: '{symbol}' is not a declaration in {base}; hits {hits}{probe_note} {where}"
1365
+ f" — ±{pad} lines per hit]"
1366
+ )
1355
1367
 
1356
1368
  if not windows:
1357
- return f"{head}{pointer}"
1369
+ return f"{head}{pointer}{tail}"
1358
1370
 
1359
1371
  budget = _SYMBOL_MISS_MAX_LINES
1360
1372
  chunks: List[str] = []
@@ -1371,7 +1383,7 @@ def _render_symbol_scope_miss(plan: Dict[str, Any], path: str, symbol: str, code
1371
1383
  if e < windows[i][1]:
1372
1384
  chunks.append("// [window truncated]")
1373
1385
 
1374
- return f"{head}{pointer}\n" + "\n".join(chunks)
1386
+ return f"{head}{pointer}\n" + "\n".join(chunks) + tail
1375
1387
 
1376
1388
 
1377
1389
  def _resolve_dep_mode(args: dict) -> Tuple[bool, str]:
@@ -1385,6 +1397,151 @@ def _resolve_dep_mode(args: dict) -> Tuple[bool, str]:
1385
1397
  return True, "signature"
1386
1398
 
1387
1399
 
1400
+ def _endpoint_symbol_index(graph: Any) -> Dict[str, List[Tuple[str, str, int, int]]]:
1401
+ """name -> [(file, qualified, start, end)] for resolving named route handlers."""
1402
+ index: Dict[str, List[Tuple[str, str, int, int]]] = {}
1403
+ for key, sym in getattr(graph, "symbols", {}).items():
1404
+ qualified = key.split("::", 1)[-1]
1405
+ index.setdefault(sym.name, []).append(
1406
+ (sym.file_path, qualified, sym.line_start, sym.line_end)
1407
+ )
1408
+ return index
1409
+
1410
+
1411
+ def _endpoint_callee_line(
1412
+ names: List[str], hit: Any, index: Dict[str, List[Tuple[str, str, int, int]]], limit: int = 2
1413
+ ) -> str:
1414
+ """`name -> path Ls-Le` for the handler's cross-file callees, capped.
1415
+
1416
+ This is the second half of the one-call promise: the route call says where
1417
+ the work continues, so the follow-up read is a direct path+symbol hit
1418
+ instead of another search. Callees in the handler's own top-level directory
1419
+ come first — a framework helper three trees away is not where the fix lives.
1420
+ """
1421
+ top = lambda file: file.split("/", 1)[0].lower()
1422
+ ranked: List[Tuple[int, str]] = []
1423
+ for name in names:
1424
+ entries = index.get(name) or []
1425
+ if len(entries) != 1:
1426
+ continue
1427
+ file, _qualified, start, end = entries[0]
1428
+ if file == hit.file:
1429
+ continue
1430
+ ranked.append((0 if top(file) == top(hit.file) else 1, f"{name} → {file} L{start}-L{end}"))
1431
+ ranked.sort()
1432
+ return "; ".join(entry for _rank, entry in ranked[:limit])
1433
+
1434
+
1435
+ def _render_endpoint_slice(
1436
+ endpoint: Any,
1437
+ prefer_path: str,
1438
+ tracker: Any,
1439
+ max_lines: int = 160,
1440
+ fallback_on_miss: bool = False,
1441
+ ) -> Optional[str]:
1442
+ """Route → handler body in one response: path, line range, whole-file version."""
1443
+ verb, route = endpoint
1444
+ root = os.path.abspath(_workspace_root() or os.getcwd())
1445
+ if prefer_path:
1446
+ # The caller named the file: its own project root is the honest scan root,
1447
+ # even when the MCP workspace points somewhere else.
1448
+ try:
1449
+ root = GraphEngine.find_project_root(prefer_path)
1450
+ except Exception:
1451
+ pass
1452
+ graph = None
1453
+ files: Optional[List[str]] = None
1454
+ try:
1455
+ graph = GraphEngine.get_instance(root)
1456
+ files = list(graph.file_stats.keys())
1457
+ except Exception:
1458
+ files = None
1459
+ prefer_rel = ""
1460
+ if prefer_path and files is not None:
1461
+ try:
1462
+ root_real = os.path.realpath(root)
1463
+ real = os.path.realpath(prefer_path)
1464
+ if real == root_real or real.startswith(root_real + os.sep):
1465
+ prefer_rel = os.path.relpath(real, root_real).replace("\\", "/")
1466
+ files = [prefer_rel] + [f for f in files if f != prefer_rel]
1467
+ except ValueError:
1468
+ prefer_rel = ""
1469
+ hits, scanned = route_index.find_registrations(root, verb, route, files=files)
1470
+ label = f"{verb} {route}".strip()
1471
+ if prefer_rel and hits:
1472
+ # The caller named a file: expand it first even though the repo answer is
1473
+ # sorted independently of the caller's context.
1474
+ hits.sort(key=lambda h: (h.file != prefer_rel, not h.exact, h.file, h.line))
1475
+ if not hits:
1476
+ if fallback_on_miss:
1477
+ return None
1478
+ others, _ = route_index.find_registrations(root, "", route, files=files, max_hits=3)
1479
+ if others:
1480
+ verbs = ", ".join(sorted({f"{h.verb} {h.route} L{h.line} in {h.file}" for h in others}))
1481
+ return (
1482
+ f"// [TS endpoint: no registration for '{label}' — the path exists as {verbs};"
1483
+ f" retry with one of those verbs]"
1484
+ )
1485
+ return (
1486
+ f"// [TS endpoint: no registration for '{label}' among {scanned} code files."
1487
+ f" Find the literal with scoped_search(query=\"{route}\") or pass the file path.]"
1488
+ )
1489
+ index = _endpoint_symbol_index(graph) if graph is not None else {}
1490
+ entries: List[str] = []
1491
+ total = 0
1492
+ for pos, hit in enumerate(hits, 1):
1493
+ full = os.path.join(root, hit.file)
1494
+ version = route_index.file_version(full)
1495
+ prefix = f"[{pos}] " if len(hits) > 1 else ""
1496
+ head = (
1497
+ f"// [TS endpoint {prefix}{verb} {route} → {hit.file} L{hit.line}-L{hit.end_line} "
1498
+ f"ver={version} via {hit.via}]"
1499
+ )
1500
+ body_lines, first, last = hit.body, hit.line, hit.end_line
1501
+ if hit.handler_kind == "named" and hit.handler:
1502
+ short = hit.handler.split(".")[-1]
1503
+ decls = [d for d in index.get(short, []) if d[0] != hit.file] or index.get(short, [])
1504
+ if decls:
1505
+ file, _qualified, start, end = decls[0]
1506
+ try:
1507
+ with open(os.path.join(root, file), "r", encoding="utf-8", errors="replace") as handle:
1508
+ src = handle.read().splitlines()
1509
+ body_lines, first, last = src[start - 1:end], start, end
1510
+ head = (
1511
+ f"// [TS endpoint {prefix}{verb} {route} → handler {short} in {file} "
1512
+ f"L{start}-L{end} ver={route_index.file_version(os.path.join(root, file))}]"
1513
+ )
1514
+ except OSError:
1515
+ pass
1516
+ if total + (last - first + 1) > max_lines:
1517
+ entries.append(f"// [... {len(hits) - pos + 1} more registration(s) suppressed; pass path= to pick one]")
1518
+ break
1519
+ total += last - first + 1
1520
+ entries.append(head)
1521
+ names = hit.callees() if hit.handler_kind == "inline" else route_index.extract_callees("\n".join(body_lines))
1522
+ callees = _endpoint_callee_line(names, hit, index)
1523
+ if callees:
1524
+ entries.append(f"// calls: {callees}")
1525
+ entries.append(f"// --- L{first}-L{last}")
1526
+ entries.extend(body_lines)
1527
+ delivered = "\n".join(entries) + "\n"
1528
+ if tracker is not None:
1529
+ try:
1530
+ orig_chars = 0
1531
+ for file in {h.file for h in hits}:
1532
+ orig_chars += os.path.getsize(os.path.join(root, file))
1533
+ tracker.record_event(
1534
+ session_id=_mcp_session_id(),
1535
+ event_type="ENDPOINT_SLICE",
1536
+ original_tokens=max(1, orig_chars // 4),
1537
+ optimized_tokens=count_tokens(delivered),
1538
+ details={"endpoint": label, "hits": len(hits), "scanned": scanned},
1539
+ )
1540
+ except Exception:
1541
+ pass
1542
+ return delivered
1543
+
1544
+
1388
1545
  def _repo_fingerprint(graph) -> str:
1389
1546
  """Stable Shared-Team-Symbol-Index cache key for an indexed repo: repo name +
1390
1547
  per-file relative paths + sizes. Machine-independent on purpose (mtimes differ
@@ -1615,6 +1772,19 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1615
1772
  if start_line is not None:
1616
1773
  start_line = max(1, start_line)
1617
1774
 
1775
+ # A route target ("POST /api/products") is resolved across the repo in one
1776
+ # call: registration site → handler body → path + line range + version.
1777
+ # Without this the caller spent two calls to find the file and a third to
1778
+ # read the handler (measured: 6.3 discovery calls per edit in matrix v4).
1779
+ endpoint_target = str(args.get("endpoint") or "").strip()
1780
+ if not endpoint_target:
1781
+ endpoint_target = str(symbol or "").strip()
1782
+ endpoint = route_index.parse_endpoint(endpoint_target) if endpoint_target else None
1783
+ if endpoint:
1784
+ rendered = _render_endpoint_slice(endpoint, path, tracker, fallback_on_miss=bool(path))
1785
+ if rendered is not None:
1786
+ return {"content": [{"type": "text", "text": rendered}]}
1787
+
1618
1788
  active_ws = _workspace_root()
1619
1789
  if path and not os.path.isabs(path):
1620
1790
  if active_ws and os.path.exists(os.path.join(active_ws, path)):
@@ -2485,22 +2655,39 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
2485
2655
  return {"content": [{"type": "text", "text": surface_md}]}
2486
2656
 
2487
2657
  elif name == "list_dir":
2488
- path = args.get("path") or args.get("project_path") or args.get("directory") or args.get("root_dir") or ""
2489
- if not path:
2658
+ path = args.get("path") or args.get("directory") or ""
2659
+ explicit_root = args.get("project_path") or args.get("root_dir")
2660
+ if not path and not explicit_root:
2490
2661
  return _fallback_error("list_dir", "missing required 'path' argument")
2491
2662
 
2492
- # Resolve path relative to active workspace, cwd, or absolute
2663
+ # An explicit project_path is the base for a relative path. Before this,
2664
+ # `path` shadowed it and joined to the session workspace, so repo_map
2665
+ # view='tree' on a second repo reported "directory not found".
2493
2666
  active_ws = _workspace_root()
2494
- if not os.path.isabs(path):
2495
- if active_ws and os.path.isdir(os.path.join(active_ws, path)):
2496
- abs_path = os.path.abspath(os.path.join(active_ws, path))
2497
- else:
2498
- abs_path = os.path.abspath(path)
2499
- else:
2667
+
2668
+ def _abs_candidate(value: str) -> str:
2669
+ if os.path.isabs(value):
2670
+ return os.path.abspath(value)
2671
+ if active_ws and os.path.isdir(os.path.join(active_ws, value)):
2672
+ return os.path.abspath(os.path.join(active_ws, value))
2673
+ return os.path.abspath(value)
2674
+
2675
+ base_dir = _abs_candidate(str(explicit_root)) if explicit_root else None
2676
+ if base_dir and not os.path.isdir(base_dir):
2677
+ return _fallback_error("list_dir", f"project_path not found or not a directory: '{explicit_root}'")
2678
+
2679
+ if not path:
2680
+ abs_path = base_dir
2681
+ elif os.path.isabs(path):
2500
2682
  abs_path = os.path.abspath(path)
2683
+ elif base_dir:
2684
+ abs_path = os.path.abspath(os.path.join(base_dir, path))
2685
+ else:
2686
+ abs_path = _abs_candidate(path)
2501
2687
 
2502
2688
  if not os.path.isdir(abs_path):
2503
- return _fallback_error("list_dir", f"directory not found: {abs_path}")
2689
+ where = f" (resolved from '{path}' under '{base_dir}')" if base_dir and not os.path.isabs(path) else ""
2690
+ return _fallback_error("list_dir", f"directory not found: {abs_path}{where}")
2504
2691
  if is_plugin_or_system_dir(abs_path):
2505
2692
  return _fallback_error("list_dir", f"refusing to inspect system root or plugin dir '{path}'")
2506
2693
  system_roots = {"/", "/Users", "/home", "/root", os.path.expanduser("~")}
@@ -0,0 +1,444 @@
1
+ """Repo-wide route registration index for `smart_read_file(endpoint=...)`.
2
+
3
+ An agent that knows the failing route ("POST /api/products") should not have to
4
+ guess which file registers it, then read that file, then read the handler. One
5
+ call resolves route -> registration site -> handler body -> path + line range +
6
+ sha256 version, which is the unit `apply_edits` consumes.
7
+
8
+ The index is a bounded text scan, not a compiler front end: it recognises the
9
+ idiomatic registration shapes of the stacks TokenSafe targets (Go net/http,
10
+ gin, chi, tokensafe; Express/Fastify/Koa; FastAPI/Flask) and normalises path
11
+ templates (`{id}`, `:id`, `<int:id>`) so a concrete target still matches. Every
12
+ candidate file comes from the already-scanned code graph, so this adds no walk
13
+ of its own.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import hashlib
19
+ import os
20
+ import re
21
+ from dataclasses import dataclass, field
22
+ from typing import Dict, Iterable, List, Optional, Sequence, Tuple
23
+
24
+ # Callee names that are syntax, not project functions.
25
+ _NON_CALLEES = frozenset({
26
+ "if", "for", "switch", "select", "case", "return", "func", "function", "defer", "go",
27
+ "make", "new", "len", "cap", "append", "copy", "delete", "panic", "recover", "print",
28
+ "println", "range", "var", "const", "type", "struct", "map", "chan", "interface",
29
+ "catch", "while", "with", "require", "import", "await", "async", "new", "typeof",
30
+ "JSON", "Error", "String", "Number", "Promise", "Object", "Array", "console", "this",
31
+ "super", "self", "cls", "str", "int", "float", "bool", "list", "dict", "set", "tuple",
32
+ "isinstance", "hasattr", "getattr", "super", "print", "range", "enumerate", "zip",
33
+ })
34
+
35
+ _GO_VERB_CALL = re.compile(
36
+ r"\b(?P<recv>[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)\s*\.\s*"
37
+ r"(?P<method>Get|Post|Put|Patch|Delete|Head|Options|Handle|HandleFunc|Route|Group)\s*\(",
38
+ re.IGNORECASE,
39
+ )
40
+ _JS_VERB_CALL = re.compile(
41
+ r"\b(?P<recv>[A-Za-z_$][\w$.]*)\s*\.\s*"
42
+ r"(?P<method>get|post|put|patch|delete|del|all|route)\s*\(",
43
+ re.IGNORECASE,
44
+ )
45
+ _PY_DECORATOR = re.compile(r"^\s*@\s*(?P<recv>[A-Za-z_][\w.]*)\s*\.\s*"
46
+ r"(?P<method>get|post|put|patch|delete|route|api_route)\s*\(")
47
+ _STRING_LIT = re.compile(r"""[rbuRBU]{0,2}(?P<q>"|'|`)(?P<body>[^"'`\n]*)(?P=q)""")
48
+ _METHODS_KW = re.compile(r"methods\s*=\s*\[(?P<body>[^\]]*)\]", re.IGNORECASE)
49
+ _VERB_WORDS = {
50
+ "get": "GET", "post": "POST", "put": "PUT", "patch": "PATCH", "delete": "DELETE",
51
+ "del": "DELETE", "head": "HEAD", "options": "OPTIONS", "all": "ALL",
52
+ }
53
+ _TEMPLATE_SEG = re.compile(r"^(?:\{[^/}]*\}|:[A-Za-z_]\w*|<[^/>]*>|\$[A-Za-z_]\w*|\*)$")
54
+ _ID_SEG = re.compile(r"^(?:\d+|[0-9a-fA-F]{8,}(?:-[0-9a-fA-F]{4,})*)$")
55
+
56
+
57
+ def parse_endpoint(target: str) -> Optional[Tuple[str, str]]:
58
+ """`"POST /api/products"` / `"post:/api/products"` / `"/api/products"` -> (verb, path).
59
+
60
+ A bare path has no verb; callers that need one receive `""` and match any verb.
61
+ """
62
+ raw = (target or "").strip().strip("`\"'")
63
+ if not raw:
64
+ return None
65
+ match = re.match(r"^(?:(?P<verb>[A-Za-z]+)\s*[:\s]\s*)?(?P<path>/\S*)", raw)
66
+ if not match:
67
+ return None
68
+ verb = (match.group("verb") or "").strip().upper()
69
+ path = match.group("path").strip().rstrip(".,;")
70
+ if verb and verb not in {"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS", "ALL"}:
71
+ return None
72
+ if not path.startswith("/"):
73
+ return None
74
+ return verb, path
75
+
76
+
77
+ def normalize_route(path: str) -> str:
78
+ """Collapse every template placeholder to `*` so declared routes compare cheaply."""
79
+ clean = (path or "").split("?", 1)[0].split("#", 1)[0].strip()
80
+ if len(clean) > 1:
81
+ clean = clean.rstrip("/")
82
+ return "/" + "/".join(
83
+ "*" if _TEMPLATE_SEG.match(seg) else seg.lower() for seg in clean.split("/") if seg
84
+ )
85
+
86
+
87
+ def _segments(path: str) -> List[str]:
88
+ clean = (path or "").split("?", 1)[0].split("#", 1)[0].strip()
89
+ if len(clean) > 1:
90
+ clean = clean.rstrip("/")
91
+ return [seg for seg in clean.split("/") if seg]
92
+
93
+
94
+ def route_matches(declared: str, target: str) -> Tuple[bool, bool]:
95
+ """(matches, exact) for a declared template against a concrete target path.
96
+
97
+ Segment-wise on purpose: `POST /api/orders/123/cancel` must resolve the
98
+ registration `POST /api/orders/{id}/cancel`, which a flat string compare of
99
+ normalised paths cannot do.
100
+ """
101
+ left, right = _segments(declared), _segments(target)
102
+ if len(left) != len(right):
103
+ return False, False
104
+ exact = True
105
+ for a, b in zip(left, right):
106
+ if a == b:
107
+ continue
108
+ if _TEMPLATE_SEG.match(a) or _TEMPLATE_SEG.match(b) or _ID_SEG.match(a) or _ID_SEG.match(b):
109
+ exact = False
110
+ continue
111
+ return False, False
112
+ return True, exact
113
+
114
+
115
+ def _strip_code_noise(text: str) -> str:
116
+ """Blank out string literals and // comments so bracket counting is honest."""
117
+ out = []
118
+ i, n = 0, len(text)
119
+ while i < n:
120
+ ch = text[i]
121
+ if ch in "\"'`":
122
+ quote = ch
123
+ i += 1
124
+ while i < n and text[i] != quote:
125
+ i += 2 if text[i] == "\\" else 1
126
+ i += 1
127
+ out.append(" ")
128
+ continue
129
+ if ch == "/" and i + 1 < n and text[i + 1] == "/":
130
+ break
131
+ out.append(ch)
132
+ i += 1
133
+ return "".join(out)
134
+
135
+
136
+ def _statement_end(lines: Sequence[str], start: int, max_lines: int = 40) -> int:
137
+ """Exclusive end index of the call statement starting at `lines[start]`."""
138
+ depth = 0
139
+ opened = False
140
+ last = min(len(lines), start + max_lines)
141
+ for idx in range(start, last):
142
+ for ch in _strip_code_noise(lines[idx]):
143
+ if ch in "([{":
144
+ depth += 1
145
+ opened = True
146
+ elif ch in ")]}":
147
+ depth -= 1
148
+ if opened and depth <= 0:
149
+ return idx + 1
150
+ return last
151
+
152
+
153
+ def _first_route_string(text: str) -> Optional[Tuple[str, int, int]]:
154
+ """First path-like string literal in `text` -> (value, match_start, match_end).
155
+
156
+ `match_end` is past the closing quote, which is where the handler argument
157
+ begins; using the body end instead leaves a stray quote that defeats the
158
+ handler parse.
159
+ """
160
+ for match in _STRING_LIT.finditer(text):
161
+ body = match.group("body")
162
+ if body.startswith("/") and not body.startswith("//"):
163
+ return body, match.start(), match.end()
164
+ return None
165
+
166
+
167
+ def _verbs_for(method: str, statement: str) -> List[str]:
168
+ lowered = method.lower()
169
+ if lowered in _VERB_WORDS:
170
+ return [_VERB_WORDS[lowered]]
171
+ if lowered in {"handlefunc", "handle", "route", "api_route"}:
172
+ found: List[str] = []
173
+ methods = _METHODS_KW.search(statement)
174
+ if methods:
175
+ found = [word.upper() for word in re.findall(r"[A-Za-z]+", methods.group("body"))]
176
+ if not found:
177
+ inline = re.search(r"""["']([A-Z]{3,7})\s+(/\S*)""", statement)
178
+ if inline:
179
+ found = [inline.group(1)]
180
+ return found or ["ALL"]
181
+ return []
182
+
183
+
184
+ def _route_literal(route: str) -> str:
185
+ """Cheap prefilter needle: the first two concrete path segments, quoted."""
186
+ segments = [seg for seg in route.split("/") if seg]
187
+ if not segments:
188
+ return ""
189
+ return "/" + "/".join(segments[:2])
190
+
191
+
192
+ def _handler_after(statement: str, path_end: int) -> Tuple[str, str, int]:
193
+ """(kind, expression, body_offset) of the handler argument after the route literal."""
194
+ tail = statement[path_end:]
195
+ lead = len(tail) - len(tail.lstrip(" ,:)\t\r\n"))
196
+ body_start = path_end + lead
197
+ head = tail[lead:]
198
+ if not head:
199
+ return "", "", body_start
200
+ if head.startswith("func(") or head.startswith("func (") or head.startswith("function"):
201
+ brace = head.find("{")
202
+ return "inline", head[:brace if brace > 0 else 60].strip(), body_start
203
+ if head.startswith("(") or head.startswith("async") or "=>" in head.split("{", 1)[0]:
204
+ brace = head.find("{")
205
+ return "inline", head[:brace if brace > 0 else 60].strip()[:80], body_start
206
+ named = re.match(r"(?P<name>[A-Za-z_$][\w$.]*)", head)
207
+ if named:
208
+ # `cancelOrder(store)` is a handler factory: resolve the function name,
209
+ # not the call expression, so the declaration can be located.
210
+ return "named", named.group("name"), body_start
211
+ return "", "", body_start
212
+
213
+
214
+ def _line_starts_call(line: str) -> bool:
215
+ """Cheap anchor: the registration call must begin on this very line.
216
+
217
+ Scanning from an arbitrary line merged a `})` line with the registration
218
+ below it and then skipped the real registration — every parse is anchored to
219
+ the line that opens the call.
220
+ """
221
+ stripped = line.lstrip()
222
+ if not stripped or stripped.startswith(("//", "#", "*")):
223
+ return False
224
+ if _PY_DECORATOR.match(line):
225
+ return True
226
+ return bool(_GO_VERB_CALL.search(line) or _JS_VERB_CALL.search(line))
227
+
228
+
229
+ @dataclass
230
+ class RouteHit:
231
+ file: str # workspace-relative path
232
+ line: int # 1-based registration line
233
+ end_line: int # 1-based last line of the registration statement
234
+ verb: str # "POST" / "ALL"
235
+ route: str # declared template, e.g. "/api/products/{id}"
236
+ handler_kind: str # "inline" | "named" | ""
237
+ handler: str # "db.CreateProduct" / "func(c *gin.Context)"
238
+ via: str # "tokensafe.Post" / "app.get" / "@router.post"
239
+ body: List[str] = field(default_factory=list)
240
+ handler_offset: int = 0 # char offset of the handler inside the body text
241
+ exact: bool = True # route matched without a template placeholder
242
+
243
+ def header(self, version: str = "") -> str:
244
+ label = f"{self.verb} {self.route}" if self.verb not in ("", "ALL") else self.route
245
+ handler = f" {self.handler}" if self.handler and self.handler_kind == "named" else ""
246
+ ver = f" ver={version}" if version else ""
247
+ return f"{label} → {self.file} L{self.line}-L{self.end_line}{handler}{ver}"
248
+
249
+ def callees(self) -> List[str]:
250
+ """Names called inside the handler, in first-seen order.
251
+
252
+ Empty for a named handler: the registration statement names the handler
253
+ but does not contain its body — the caller resolves that file first.
254
+ """
255
+ if self.handler_kind != "inline":
256
+ return []
257
+ text = "\n".join(self.body)[self.handler_offset:]
258
+ return extract_callees(text)
259
+
260
+
261
+ def extract_callees(text: str) -> List[str]:
262
+ seen: Dict[str, bool] = {}
263
+ for match in re.finditer(r"\b(?:(?P<qual>[A-Za-z_]\w*)\.)?(?P<name>[A-Za-z_]\w*)\s*\(", text):
264
+ name = match.group("name")
265
+ if name in _NON_CALLEES or name in seen:
266
+ continue
267
+ seen[name] = True
268
+ return list(seen)
269
+
270
+
271
+ def _match_statement(line: str, statement: str) -> Optional[Tuple[str, str, str, str, str, int]]:
272
+ """(verb, route, handler_kind, handler, via, handler_offset) for one statement."""
273
+ candidates: List[Tuple[int, str, str]] = [] # (position, via, method)
274
+ py = _PY_DECORATOR.match(line)
275
+ if py:
276
+ candidates.append((0, f"@{py.group('recv')}.{py.group('method')}", py.group("method")))
277
+ go = _GO_VERB_CALL.search(statement)
278
+ if go:
279
+ candidates.append((go.start(), f"{go.group('recv')}.{go.group('method')}", go.group("method")))
280
+ js = _JS_VERB_CALL.search(statement)
281
+ if js:
282
+ candidates.append((js.start(), f"{js.group('recv')}.{js.group('method')}", js.group("method")))
283
+ if not candidates:
284
+ return None
285
+ candidates.sort()
286
+ _pos, via, method = candidates[0]
287
+ head_offset = statement.find("(")
288
+ found = _first_route_string(statement[head_offset:])
289
+ if not found:
290
+ return None
291
+ route, _start, match_end = found
292
+ verbs = _verbs_for(method, statement)
293
+ if not verbs:
294
+ return None
295
+ kind, handler, offset = _handler_after(statement, head_offset + match_end)
296
+ return verbs[0], route, kind, handler, via, offset
297
+
298
+
299
+ def _py_handler(lines: Sequence[str], start: int) -> Tuple[str, int, int]:
300
+ """A decorated Python handler: (name, first_line_index, last_line_index)."""
301
+ idx = start + 1
302
+ while idx < len(lines) and not lines[idx].strip():
303
+ idx += 1
304
+ if idx >= len(lines):
305
+ return "", start, start
306
+ match = re.match(r"\s*(?:async\s+)?def\s+(?P<name>[A-Za-z_]\w*)", lines[idx])
307
+ if not match:
308
+ return "", start, start
309
+ indent = len(lines[idx]) - len(lines[idx].lstrip())
310
+ last = idx
311
+ for probe in range(idx + 1, min(len(lines), idx + 200)):
312
+ text = lines[probe]
313
+ if not text.strip():
314
+ continue
315
+ if len(text) - len(text.lstrip()) <= indent and not text.lstrip().startswith((")", "]", "}")):
316
+ break
317
+ last = probe
318
+ return match.group("name"), idx, last
319
+
320
+
321
+ def find_registrations(
322
+ root: str,
323
+ verb: str,
324
+ route: str,
325
+ *,
326
+ files: Optional[Iterable[str]] = None,
327
+ max_files: int = 3000,
328
+ max_hits: int = 6,
329
+ max_file_bytes: int = 2_000_000,
330
+ ) -> Tuple[List[RouteHit], int]:
331
+ """All registrations matching (verb, route). Returns (hits, files_scanned).
332
+
333
+ `files` are workspace-relative paths (the code graph's `file_stats` keys);
334
+ without it a bounded walk is used, which keeps the function testable.
335
+ Ordering is deterministic — exact routes first, then route-named files, real
336
+ code before tests, then alphabetical — so two runs answer identically.
337
+ """
338
+ if files is None:
339
+ files = _walk_code_files(root)
340
+ needle = _route_literal(route)
341
+ hits: List[RouteHit] = []
342
+ scanned = 0
343
+ seen: set = set()
344
+ for rel in _prioritized(list(files)):
345
+ if scanned >= max_files or len(hits) >= max_hits:
346
+ break
347
+ full = os.path.join(root, rel)
348
+ real = os.path.realpath(full)
349
+ if real in seen: # the same file under two spellings must not be reported twice
350
+ continue
351
+ seen.add(real)
352
+ try:
353
+ if os.path.getsize(full) > max_file_bytes:
354
+ continue
355
+ with open(full, "r", encoding="utf-8", errors="replace") as handle:
356
+ text = handle.read()
357
+ except OSError:
358
+ continue
359
+ scanned += 1
360
+ if needle and needle not in text:
361
+ continue
362
+ lines = text.splitlines()
363
+ idx = 0
364
+ while idx < len(lines):
365
+ if not _line_starts_call(lines[idx]):
366
+ idx += 1
367
+ continue
368
+ end = _statement_end(lines, idx)
369
+ statement = "\n".join(lines[idx:end])
370
+ parsed = _match_statement(lines[idx], statement)
371
+ if not parsed:
372
+ idx += 1
373
+ continue
374
+ hit_verb, hit_route, kind, handler, via, offset = parsed
375
+ matched, exact = route_matches(hit_route, route)
376
+ if not matched or (verb and hit_verb != verb and hit_verb != "ALL"):
377
+ idx = max(end, idx + 1)
378
+ continue
379
+ body_end = end
380
+ if _PY_DECORATOR.match(lines[idx]):
381
+ name, _def_start, def_end = _py_handler(lines, idx)
382
+ if name:
383
+ kind, handler = "named", name
384
+ body_end = def_end + 1
385
+ hits.append(RouteHit(
386
+ file=rel, line=idx + 1, end_line=body_end, verb=hit_verb, route=hit_route,
387
+ handler_kind=kind, handler=handler, via=via,
388
+ body=lines[idx:body_end], handler_offset=offset if kind == "inline" else 0,
389
+ exact=exact,
390
+ ))
391
+ if len(hits) >= max_hits:
392
+ break
393
+ idx = max(body_end, idx + 1)
394
+ hits.sort(key=lambda h: (not h.exact, h.file, h.line))
395
+ return hits, scanned
396
+
397
+
398
+ def _prioritized(files: List[str]) -> List[str]:
399
+ hints = ("route", "router", "routes", "server", "app", "api", "url", "urls", "view", "handler", "main", "endpoint")
400
+ def key(rel: str) -> Tuple[int, int, str]:
401
+ lowered = rel.lower()
402
+ base = os.path.basename(lowered)
403
+ named = 0 if any(hint in base for hint in hints) else 1
404
+ # A test that registers a route is evidence, not the app: rank it last so a
405
+ # real registration is found inside the hit budget.
406
+ test = 1 if (base.endswith("_test.go") or base.startswith("test_")
407
+ or ".test." in base or ".spec." in base
408
+ or "/tests/" in f"/{lowered}" or "/__tests__/" in f"/{lowered}") else 0
409
+ return named + test, test, rel
410
+ return sorted(files, key=key)
411
+
412
+
413
+ _NOISE_DIRS = frozenset({
414
+ "node_modules", ".git", "vendor", "dist", "build", "target", ".venv", "venv",
415
+ "__pycache__", ".next", ".nuxt", "coverage", ".mypy_cache", ".pytest_cache",
416
+ })
417
+ _CODE_EXTS = frozenset({
418
+ ".go", ".py", ".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", ".vue", ".svelte",
419
+ ".rb", ".php", ".java", ".kt", ".rs", ".cs",
420
+ })
421
+
422
+
423
+ def _walk_code_files(root: str, limit: int = 3000) -> List[str]:
424
+ out: List[str] = []
425
+ for dirpath, dirnames, filenames in os.walk(root):
426
+ dirnames[:] = [d for d in dirnames if d not in _NOISE_DIRS and not d.startswith(".")]
427
+ for name in filenames:
428
+ if os.path.splitext(name)[1].lower() in _CODE_EXTS:
429
+ out.append(os.path.relpath(os.path.join(dirpath, name), root).replace("\\", "/"))
430
+ if len(out) >= limit:
431
+ return out
432
+ return out
433
+
434
+
435
+ def file_version(path: str) -> str:
436
+ """Whole-file sha256 as OCC token (12 hex is enough to detect drift)."""
437
+ digest = hashlib.sha256()
438
+ try:
439
+ with open(path, "rb") as handle:
440
+ for chunk in iter(lambda: handle.read(1 << 16), b""):
441
+ digest.update(chunk)
442
+ except OSError:
443
+ return ""
444
+ return digest.hexdigest()[:12]
package/src/scaffold.py CHANGED
@@ -577,7 +577,7 @@ 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.7\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.5.0\n)\n")
581
581
  write_fn(p("main.go"), """package main
582
582
 
583
583
  import (
@@ -91,14 +91,16 @@ class ScopedSearch:
91
91
  @classmethod
92
92
  def _resolve_per_file(cls, per_file: int, max_results: int) -> int:
93
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."""
94
+ a 20-hit query used to render 2 KB of near-identical lines from 2 files.
95
+ The cap is what the model actually pays for, so it is set to the number
96
+ of hits a caller can still act on (4-8), not to the result budget."""
95
97
  try:
96
98
  per_file = int(per_file or 0)
97
99
  except (TypeError, ValueError):
98
100
  per_file = 0
99
101
  if per_file > 0:
100
102
  return per_file
101
- return max(6, min(12, max_results // 2))
103
+ return max(4, min(8, max_results // 3))
102
104
 
103
105
  @classmethod
104
106
  def search(
@@ -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.1"
314
+ "User-Agent": "TokenSafe-Sync/4.7.3"
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.1"
20
+ CURRENT_VERSION = "4.7.3"
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