tokensafe 4.7.2 → 4.7.4

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.
@@ -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.2"
314
+ "User-Agent": "TokenSafe-Sync/4.7.4"
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.2"
20
+ CURRENT_VERSION = "4.7.4"
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