tokensafe 4.3.3 → 4.4.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.
@@ -8,10 +8,15 @@ from 10,000+ lines of integrity hashes and URLs down to a compact dependency bil
8
8
  - Reversible hash anchor pointing to the full raw file in TokenSafe stash.
9
9
  """
10
10
 
11
+ import os
11
12
  import json
12
13
  import re
14
+ import sqlite3
15
+ import time
16
+ import hashlib
13
17
  from typing import Tuple, Dict, Any, List, Optional
14
18
  from src.stash import stash_block
19
+ from src.paths import resolve_data_dir
15
20
 
16
21
 
17
22
  class LockfileReducer:
@@ -22,6 +27,8 @@ class LockfileReducer:
22
27
  name = filename_or_path.lower().split("/")[-1].split("\\")[-1]
23
28
  return name in (
24
29
  "package-lock.json",
30
+ "bun.lock",
31
+ "bun.lockb",
25
32
  "pnpm-lock.yaml",
26
33
  "yarn.lock",
27
34
  "cargo.lock",
@@ -31,6 +38,24 @@ class LockfileReducer:
31
38
  "go.sum",
32
39
  )
33
40
 
41
+ @classmethod
42
+ def _load_jsonc(cls, text: str) -> Optional[Dict[str, Any]]:
43
+ """Safely parses JSON or JSONC (JSON with comments and trailing commas)."""
44
+ if not text:
45
+ return None
46
+ try:
47
+ return json.loads(text)
48
+ except Exception:
49
+ pass
50
+ try:
51
+ # Strip whole-line comments // ... without corrupting base64 hashes inside strings
52
+ no_comments = re.sub(r'^\s*//.*$', '', text, flags=re.MULTILINE)
53
+ # Strip trailing commas before } or ]
54
+ cleaned = re.sub(r',(\s*[}\]])', r'\1', no_comments)
55
+ return json.loads(cleaned)
56
+ except Exception:
57
+ return None
58
+
34
59
  @classmethod
35
60
  def reduce(cls, content: str, filename: str = "package-lock.json") -> Tuple[str, bool]:
36
61
  """Reduces lockfile content to a clean summary. Returns (compacted_text, was_compacted)."""
@@ -42,6 +67,8 @@ class LockfileReducer:
42
67
 
43
68
  if fname == "package-lock.json":
44
69
  return cls._reduce_npm_lock(content)
70
+ elif fname in ("bun.lock", "bun.lockb"):
71
+ return cls._reduce_bun_lock(content, fname)
45
72
  elif fname == "cargo.lock":
46
73
  return cls._reduce_cargo_lock(content)
47
74
  elif fname == "poetry.lock":
@@ -49,6 +76,44 @@ class LockfileReducer:
49
76
 
50
77
  return cls._generic_reduce(content, fname)
51
78
 
79
+ @classmethod
80
+ def _reduce_bun_lock(cls, content: str, fname: str = "bun.lock") -> Tuple[str, bool]:
81
+ data = cls._load_jsonc(content)
82
+ if not data or not isinstance(data, dict):
83
+ return cls._generic_reduce(content, fname)
84
+
85
+ packages = data.get("packages", {})
86
+ workspaces = data.get("workspaces", {})
87
+ root_ws = workspaces.get("") if isinstance(workspaces, dict) else {}
88
+ root_deps = {}
89
+ if isinstance(root_ws, dict):
90
+ root_deps = {**root_ws.get("dependencies", {}), **root_ws.get("devDependencies", {})}
91
+
92
+ direct_deps = {}
93
+ total_count = len(packages) if isinstance(packages, dict) else 0
94
+
95
+ for dep_name, range_ver in sorted(root_deps.items()):
96
+ resolved_ver = range_ver
97
+ if isinstance(packages, dict) and dep_name in packages:
98
+ val = packages[dep_name]
99
+ if isinstance(val, list) and len(val) > 0 and isinstance(val[0], str):
100
+ resolved_ver = val[0].rsplit("@", 1)[1] if "@" in val[0] else val[0]
101
+ direct_deps[dep_name] = resolved_ver
102
+
103
+ lines = [
104
+ f"# [TokenSafe Lockfile Summary: {fname}]",
105
+ f"Total installed packages: {total_count}",
106
+ "",
107
+ "## Direct Dependencies:"
108
+ ]
109
+ for dname, dver in sorted(direct_deps.items()):
110
+ lines.append(f" - {dname}: {dver}")
111
+
112
+ hash8, marker = stash_block(content, source="lockfile:bun")
113
+ lines.append("")
114
+ lines.append(marker)
115
+ return "\n".join(lines), True
116
+
52
117
  @classmethod
53
118
  def _reduce_npm_lock(cls, content: str) -> Tuple[str, bool]:
54
119
  try:
@@ -155,3 +220,390 @@ class LockfileReducer:
155
220
  ["", marker]
156
221
  )
157
222
  return "\n".join(out), True
223
+
224
+ @classmethod
225
+ def find_lockfile(cls, directory: Optional[str] = None, start_dir: Optional[str] = None) -> Optional[str]:
226
+ """Locates the nearest lockfile in directory or parent directories up to git root, or downward in monorepos."""
227
+ target = directory or start_dir or os.getcwd()
228
+ start = os.path.abspath(target)
229
+ curr = start
230
+ candidates = (
231
+ "package-lock.json", "bun.lock", "bun.lockb",
232
+ "pnpm-lock.yaml", "yarn.lock", "Cargo.lock", "poetry.lock"
233
+ )
234
+ # 1. Upward search
235
+ for _ in range(6):
236
+ for c in candidates:
237
+ cand_path = os.path.join(curr, c)
238
+ if os.path.isfile(cand_path):
239
+ return cand_path
240
+ parent = os.path.dirname(curr)
241
+ if parent == curr:
242
+ break
243
+ curr = parent
244
+
245
+ # 2. Downward search (bounded: depth <= 2, skip heavy/vendor dirs, cap 60 directories)
246
+ dirs_checked = 0
247
+ skip_dirs = {"node_modules", ".git", "dist", "build", ".next", ".cache", "data", "target", ".venv", "venv", "__pycache__"}
248
+ for root, dirs, files in os.walk(start):
249
+ dirs[:] = [d for d in dirs if d not in skip_dirs and not d.startswith(".")]
250
+ dirs_checked += 1
251
+ if dirs_checked > 60:
252
+ break
253
+ rel_path = os.path.relpath(root, start)
254
+ rel_depth = 0 if rel_path == "." else rel_path.count(os.sep) + 1
255
+ if rel_depth > 2:
256
+ dirs[:] = []
257
+ continue
258
+ for c in candidates:
259
+ if c in files:
260
+ cand_path = os.path.join(root, c)
261
+ if os.path.isfile(cand_path):
262
+ return cand_path
263
+
264
+ return None
265
+
266
+ @classmethod
267
+ def _get_db_path(cls) -> str:
268
+ data_dir = resolve_data_dir()
269
+ os.makedirs(data_dir, exist_ok=True)
270
+ return os.path.join(data_dir, "lockfile_cache.db")
271
+
272
+ @classmethod
273
+ def _maybe_evict(cls, conn: sqlite3.Connection, max_rows: int = 5000) -> None:
274
+ """Evicts oldest entries when lockfile cache exceeds max_rows."""
275
+ try:
276
+ row = conn.execute("SELECT COUNT(*) FROM lockfile_cache;").fetchone()
277
+ count = row[0] if row else 0
278
+ if count > max_rows:
279
+ excess = count - max_rows
280
+ conn.execute(
281
+ "DELETE FROM lockfile_cache WHERE entry_key IN ("
282
+ "SELECT entry_key FROM lockfile_cache ORDER BY cached_at ASC LIMIT ?"
283
+ ");", (excess,)
284
+ )
285
+ except Exception:
286
+ pass
287
+
288
+ @classmethod
289
+ def _init_db(cls):
290
+ db_path = cls._get_db_path()
291
+ conn = None
292
+ try:
293
+ conn = sqlite3.connect(db_path, timeout=5.0)
294
+ conn.execute("PRAGMA journal_mode=WAL;")
295
+ conn.execute("PRAGMA busy_timeout=5000;")
296
+ conn.execute("""
297
+ CREATE TABLE IF NOT EXISTS lockfile_cache (
298
+ entry_key TEXT PRIMARY KEY,
299
+ lockfile_hash TEXT NOT NULL,
300
+ package_name TEXT NOT NULL,
301
+ json_result TEXT NOT NULL,
302
+ cached_at INTEGER NOT NULL
303
+ );
304
+ """)
305
+ conn.execute("CREATE INDEX IF NOT EXISTS idx_lockfile_hash ON lockfile_cache(lockfile_hash);")
306
+ conn.commit()
307
+ except Exception:
308
+ pass
309
+ finally:
310
+ if conn:
311
+ try:
312
+ conn.close()
313
+ except Exception:
314
+ pass
315
+
316
+ @classmethod
317
+ def query_dependency(cls, lockfile_path: Optional[str], package_name: str) -> Dict[str, Any]:
318
+ """Fast targeted resolution of a package in lockfile with Local First + Team Sync caching."""
319
+ target_path = lockfile_path or cls.find_lockfile()
320
+ if not target_path or not os.path.isfile(target_path):
321
+ return {
322
+ "found": False,
323
+ "package": package_name,
324
+ "error": f"No lockfile found in {os.getcwd()} or parent directories."
325
+ }
326
+
327
+ fname = os.path.basename(target_path).lower()
328
+ try:
329
+ with open(target_path, "r", encoding="utf-8", errors="replace") as f:
330
+ content = f.read()
331
+ _lockfile_bytes = os.path.getsize(target_path)
332
+ except Exception as e:
333
+ return {"found": False, "package": package_name, "error": f"Failed to read {fname}: {e}"}
334
+
335
+ lockfile_hash = hashlib.sha256(content.encode("utf-8")).hexdigest()[:16]
336
+ entry_key = f"{lockfile_hash}::{package_name.strip().lower()}"
337
+
338
+ # 1. Check L2 SQLite
339
+ cls._init_db()
340
+ db_path = cls._get_db_path()
341
+ conn = None
342
+ try:
343
+ conn = sqlite3.connect(db_path, timeout=5.0)
344
+ conn.execute("PRAGMA busy_timeout=5000;")
345
+ row = conn.execute("SELECT json_result FROM lockfile_cache WHERE entry_key = ?", (entry_key,)).fetchone()
346
+ if row:
347
+ res = json.loads(row[0])
348
+ if res.get("found"):
349
+ res["source"] = "L2_cache"
350
+ res["_lockfile_bytes"] = _lockfile_bytes
351
+ return res
352
+ except Exception:
353
+ pass
354
+ finally:
355
+ if conn:
356
+ try:
357
+ conn.close()
358
+ except Exception:
359
+ pass
360
+
361
+ # 2. Check L3 Team Sync
362
+ try:
363
+ from src.team_cache import TeamCache
364
+ team_val = TeamCache.get("LOCKFILE_INDEX", entry_key, timeout=0.5)
365
+ if team_val:
366
+ res = json.loads(team_val)
367
+ if res.get("found"):
368
+ res["source"] = "L3_team_cache"
369
+ res["_lockfile_bytes"] = _lockfile_bytes
370
+ # Store back to L2
371
+ back_conn = None
372
+ try:
373
+ back_conn = sqlite3.connect(db_path, timeout=5.0)
374
+ back_conn.execute("""
375
+ INSERT OR REPLACE INTO lockfile_cache (entry_key, lockfile_hash, package_name, json_result, cached_at)
376
+ VALUES (?, ?, ?, ?, ?)
377
+ """, (entry_key, lockfile_hash, package_name.strip().lower(), team_val, int(time.time())))
378
+ cls._maybe_evict(back_conn)
379
+ back_conn.commit()
380
+ except Exception:
381
+ pass
382
+ finally:
383
+ if back_conn:
384
+ try:
385
+ back_conn.close()
386
+ except Exception:
387
+ pass
388
+ return res
389
+ except Exception:
390
+ pass
391
+
392
+ # 3. Parse lockfile
393
+ res = cls._parse_dependency(fname, content, package_name)
394
+ res["lockfile"] = fname
395
+ res["lockfile_path"] = target_path
396
+ res["_lockfile_bytes"] = _lockfile_bytes
397
+
398
+ # 4. Save to L2 SQLite and sync to L3 Team Cache (only positive found lookups)
399
+ if res.get("found"):
400
+ save_conn = None
401
+ try:
402
+ raw_json = json.dumps(res, ensure_ascii=False)
403
+ save_conn = sqlite3.connect(db_path, timeout=5.0)
404
+ save_conn.execute("""
405
+ INSERT OR REPLACE INTO lockfile_cache (entry_key, lockfile_hash, package_name, json_result, cached_at)
406
+ VALUES (?, ?, ?, ?, ?)
407
+ """, (entry_key, lockfile_hash, package_name.strip().lower(), raw_json, int(time.time())))
408
+ cls._maybe_evict(save_conn)
409
+ save_conn.commit()
410
+ except Exception:
411
+ pass
412
+ finally:
413
+ if save_conn:
414
+ try:
415
+ save_conn.close()
416
+ except Exception:
417
+ pass
418
+
419
+ # Broadcast to L3 without leaking local filesystem paths or private byte counts
420
+ try:
421
+ from src.team_cache import TeamCache
422
+ team_payload = dict(res)
423
+ team_payload.pop("lockfile_path", None)
424
+ team_payload.pop("_lockfile_bytes", None)
425
+ TeamCache.put("LOCKFILE_INDEX", entry_key, json.dumps(team_payload, ensure_ascii=False), tokens_saved=250)
426
+ except Exception:
427
+ pass
428
+
429
+ res["source"] = "parsed_live"
430
+ return res
431
+
432
+ @classmethod
433
+ def _parse_dependency(cls, fname: str, content: str, pkg_name: str) -> Dict[str, Any]:
434
+ """Parses dependency entry from npm, cargo, poetry, pnpm, or bun."""
435
+ norm_pkg = pkg_name.strip()
436
+ if "bun.lock" in fname:
437
+ try:
438
+ data = cls._load_jsonc(content)
439
+ if isinstance(data, dict):
440
+ packages = data.get("packages")
441
+ if isinstance(packages, dict):
442
+ # 1. Direct package key (e.g. "marked", "@tanstack/react-query")
443
+ val = packages.get(norm_pkg)
444
+ # 2. Nested or prefixed node_modules/<pkg>
445
+ if not val:
446
+ exact_nm = f"node_modules/{norm_pkg}"
447
+ val = packages.get(exact_nm)
448
+ if not val:
449
+ suffix = f"/node_modules/{norm_pkg}"
450
+ for k, v in packages.items():
451
+ if k.endswith(suffix):
452
+ val = v
453
+ break
454
+ if val and isinstance(val, list) and len(val) > 0:
455
+ spec = val[0] if isinstance(val[0], str) else ""
456
+ ver = spec.rsplit("@", 1)[1] if "@" in spec else spec
457
+ meta = val[2] if len(val) > 2 and isinstance(val[2], dict) else {}
458
+ integrity = val[3] if len(val) > 3 and isinstance(val[3], str) else None
459
+ return {
460
+ "found": True,
461
+ "package": norm_pkg,
462
+ "version": ver,
463
+ "resolved": integrity,
464
+ "dependencies": meta.get("dependencies", {}),
465
+ "peerDependencies": meta.get("peerDependencies", {}),
466
+ "dev": False,
467
+ }
468
+ # 3. Fallback to workspaces[""] direct dependencies
469
+ workspaces = data.get("workspaces", {})
470
+ root_ws = workspaces.get("") if isinstance(workspaces, dict) else {}
471
+ if isinstance(root_ws, dict):
472
+ dev_deps = root_ws.get("devDependencies", {}) or {}
473
+ prod_deps = root_ws.get("dependencies", {}) or {}
474
+ all_root = {**prod_deps, **dev_deps}
475
+ if norm_pkg in all_root:
476
+ return {
477
+ "found": True,
478
+ "package": norm_pkg,
479
+ "version": all_root[norm_pkg],
480
+ "resolved": None,
481
+ "dependencies": {},
482
+ "peerDependencies": {},
483
+ "dev": norm_pkg in dev_deps,
484
+ }
485
+ except Exception:
486
+ pass
487
+
488
+ elif "package-lock" in fname:
489
+ try:
490
+ data = json.loads(content)
491
+ packages = data.get("packages")
492
+ if isinstance(packages, dict):
493
+ exact_key = f"node_modules/{norm_pkg}"
494
+ if exact_key in packages:
495
+ p = packages[exact_key]
496
+ return {
497
+ "found": True,
498
+ "package": norm_pkg,
499
+ "version": p.get("version", "*"),
500
+ "resolved": p.get("resolved"),
501
+ "dependencies": p.get("dependencies", {}),
502
+ "peerDependencies": p.get("peerDependencies", {}),
503
+ "dev": p.get("dev", False),
504
+ }
505
+ # Fallback scan for nested occurrences
506
+ suffix = f"/{exact_key}"
507
+ for k, p in packages.items():
508
+ if k.endswith(suffix):
509
+ return {
510
+ "found": True,
511
+ "package": norm_pkg,
512
+ "version": p.get("version", "*"),
513
+ "resolved": p.get("resolved"),
514
+ "dependencies": p.get("dependencies", {}),
515
+ "peerDependencies": p.get("peerDependencies", {}),
516
+ "dev": p.get("dev", False),
517
+ }
518
+ # Check v1 dependencies
519
+ deps = data.get("dependencies")
520
+ if isinstance(deps, dict) and norm_pkg in deps:
521
+ d = deps[norm_pkg]
522
+ return {
523
+ "found": True,
524
+ "package": norm_pkg,
525
+ "version": d.get("version", "*") if isinstance(d, dict) else str(d),
526
+ "dependencies": d.get("requires", {}) if isinstance(d, dict) else {},
527
+ "dev": d.get("dev", False) if isinstance(d, dict) else False,
528
+ }
529
+ except Exception:
530
+ pass
531
+
532
+ elif "cargo.lock" in fname or "poetry.lock" in fname:
533
+ pattern = re.compile(
534
+ rf'\[\[package\]\]\s+name\s*=\s*"{re.escape(norm_pkg)}"\s+version\s*=\s*"([^"]+)"'
535
+ r'(?:\s+source\s*=\s*"([^"]*)")?'
536
+ r'(?:\s+dependencies\s*=\s*(\[[^\]]*\]))?',
537
+ re.MULTILINE
538
+ )
539
+ m = pattern.search(content)
540
+ if m:
541
+ ver = m.group(1)
542
+ source_val = m.group(2)
543
+ deps_raw = m.group(3) or "[]"
544
+ try:
545
+ deps = json.loads(deps_raw) if deps_raw.startswith("[") else []
546
+ except Exception:
547
+ deps = []
548
+ res_dict = {
549
+ "found": True,
550
+ "package": norm_pkg,
551
+ "version": ver,
552
+ "dependencies": deps,
553
+ }
554
+ if source_val:
555
+ res_dict["resolved"] = source_val
556
+ return res_dict
557
+
558
+ elif "pnpm-lock" in fname:
559
+ # Pnpm regex lookup: /pkg@ver or 'pkg': ver
560
+ pnpm_re = re.compile(rf'["\']?/?{re.escape(norm_pkg)}[@/]([0-9a-zA-Z._-]+)["\']?:')
561
+ m = pnpm_re.search(content)
562
+ if m:
563
+ return {
564
+ "found": True,
565
+ "package": norm_pkg,
566
+ "version": m.group(1),
567
+ }
568
+
569
+ return {
570
+ "found": False,
571
+ "package": norm_pkg,
572
+ "message": f"Package '{norm_pkg}' not found in {fname}."
573
+ }
574
+
575
+ @classmethod
576
+ def generate_lockfile_summary(cls, lockfile_path: str) -> str:
577
+ """
578
+ Creates a virtual compact summary file with direct dependencies and MCP query instructions.
579
+ Returns the path to the temporary summary file.
580
+ """
581
+ fname = os.path.basename(lockfile_path)
582
+ try:
583
+ with open(lockfile_path, "r", encoding="utf-8", errors="replace") as f:
584
+ content = f.read()
585
+ except Exception as e:
586
+ return f"Error reading {fname}: {e}"
587
+
588
+ reduced_text, _ = cls.reduce(content, filename=fname)
589
+ h = hashlib.sha256(content.encode("utf-8")).hexdigest()[:12]
590
+
591
+ banner = (
592
+ f"// [TokenSafe Lockfile Guard: {fname}]\n"
593
+ f"// Notice: Full lockfile is {len(content.splitlines())} lines (~{len(content)//4} tokens).\n"
594
+ f"// To query exact version or transitive dependencies of a specific package, call:\n"
595
+ f"// tokensafe:query_dependency(package_name=\"<name>\")\n"
596
+ f"// --------------------------------------------------------------------------\n\n"
597
+ )
598
+ full_summary = banner + reduced_text
599
+
600
+ summaries_dir = os.path.join(resolve_data_dir(), "summaries")
601
+ os.makedirs(summaries_dir, exist_ok=True)
602
+ summary_path = os.path.join(summaries_dir, f"{h}.{fname}.summary.txt")
603
+
604
+ try:
605
+ with open(summary_path, "w", encoding="utf-8") as f:
606
+ f.write(full_summary)
607
+ return summary_path
608
+ except Exception:
609
+ return lockfile_path
package/src/installer.py CHANGED
@@ -63,6 +63,7 @@ UNIFIED_TOKENSAFE_RULE = (
63
63
  "12. **Proof-of-Savings Turn Footer (strictly English)**:\n"
64
64
  "At the end of your response for any turn where tools were executed, files were inspected, commands were sanitized, or prompts were compacted, append a compact 1-line footer. The ENTIRE footer is product-facing copy — 100% English, including the savings breakdown in parentheses, regardless of the chat language:\n"
65
65
  "`⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown in English>) | Cumulative Total: <total> tokens (≈$<usd> approx)`\n"
66
+ "13. **External Types & Lockfile Point Queries**: Use `tokensafe:slice_external_type(package_name, type_name)` to extract 3rd-party TypeScript interfaces from `node_modules` without crawling directories (-95% tokens, L1/L2/L3 cached). Use `tokensafe:query_dependency(lockfile_path, package_name)` for instant lockfile point lookups in <50 tokens; raw `read_file` on lockfiles without bounds is redirected to an index summary.\n"
66
67
  )
67
68
 
68
69
  # Short pointer written into PROJECT-level rule files when the full protocol is
@@ -70,10 +71,11 @@ UNIFIED_TOKENSAFE_RULE = (
70
71
  # Keeps every session's meta-context lean: ~110 tokens instead of ~850.
71
72
  POINTER_RULE = (
72
73
  "## TOKENSAFE GRAPH-FIRST OPTIMIZATION PROTOCOL\n"
73
- "The full 12-point protocol is installed globally in the agent-level instructions "
74
+ "The full 13-point protocol is installed globally in the agent-level instructions "
74
75
  "(~/.zcode/AGENTS.md, ~/.claude/CLAUDE.md, ~/.codex/AGENTS.md, ~/.kimi-code/AGENTS.md) and applies to this project. "
75
76
  "Core rules: never raw grep/find or `ls -la` — use `tokensafe:get_architecture_graph(project_path)` first for God Nodes, "
76
- "`tokensafe:scoped_search`, `tokensafe:smart_read_file(path, symbol)`, `tokensafe:smart_bundle` and `tokensafe:list_dir`; "
77
+ "`tokensafe:scoped_search`, `tokensafe:smart_read_file(path, symbol)`, `tokensafe:slice_external_type`, `tokensafe:query_dependency`, "
78
+ "`tokensafe:smart_bundle` and `tokensafe:list_dir`; "
77
79
  "sanitize high-output commands via `tokensafe:sanitize_command`; check `tokensafe:context_budget` (Grade S-F) "
78
80
  "before large tasks and compact via `tokensafe:compact_conversation` (orientation digest active); never hardcode secret "
79
81
  "fallbacks; append the `⚡ TokenSafe Turn Savings` footer on tool-using turns.\n"