@alexgreensh/token-optimizer 5.13.69 → 5.13.71
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/PRIVACY.md +4 -0
- package/hooks/hooks.json +11 -1
- package/hooks/module_runner.py +4 -1
- package/hooks/posttooluse_runner.py +44 -48
- package/hooks/sessionstart_runner.py +24 -5
- package/hooks/stop_runner.py +6 -6
- package/package.json +1 -1
- package/skills/token-optimizer/assets/dashboard.html +729 -767
- package/skills/token-optimizer/assets/savings_story.js +765 -0
- package/skills/token-optimizer/pricing/prices.json +1 -0
- package/skills/token-optimizer/references/cli-reference.md +1 -1
- package/skills/token-optimizer/references/implementation-playbook.md +3 -0
- package/skills/token-optimizer/scripts/_measure/__init__.py +3 -1
- package/skills/token-optimizer/scripts/_measure/archive_health.py +14 -0
- package/skills/token-optimizer/scripts/_measure/archive_void_codex.py +163 -0
- package/skills/token-optimizer/scripts/_measure/archive_void_evidence.py +165 -0
- package/skills/token-optimizer/scripts/_measure/audit.py +27 -135
- package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +339 -0
- package/skills/token-optimizer/scripts/_measure/cache_policy.py +261 -581
- package/skills/token-optimizer/scripts/_measure/checkpoint_direction.py +97 -0
- package/skills/token-optimizer/scripts/_measure/checkpoint_retention.py +20 -0
- package/skills/token-optimizer/scripts/_measure/cli.py +12 -8
- package/skills/token-optimizer/scripts/_measure/codex_quality.py +246 -0
- package/skills/token-optimizer/scripts/_measure/compaction_survival.py +158 -0
- package/skills/token-optimizer/scripts/_measure/compression_fixture_void.py +147 -0
- package/skills/token-optimizer/scripts/_measure/compression_scan_checkpoint.py +72 -0
- package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +66 -0
- package/skills/token-optimizer/scripts/_measure/continuity.py +64 -118
- package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +40 -0
- package/skills/token-optimizer/scripts/_measure/counted_cap.py +30 -0
- package/skills/token-optimizer/scripts/_measure/counted_orphans.py +190 -0
- package/skills/token-optimizer/scripts/_measure/counted_position.py +20 -0
- package/skills/token-optimizer/scripts/_measure/counted_pricing_v5.py +267 -0
- package/skills/token-optimizer/scripts/_measure/counted_subagents.py +371 -0
- package/skills/token-optimizer/scripts/_measure/coverage_report.py +295 -0
- package/skills/token-optimizer/scripts/_measure/daemon.py +53 -74
- package/skills/token-optimizer/scripts/_measure/dashboard.py +90 -151
- package/skills/token-optimizer/scripts/_measure/dashboard_heal_claim.py +36 -0
- package/skills/token-optimizer/scripts/_measure/evidence_parallel.py +95 -0
- package/skills/token-optimizer/scripts/_measure/feature_health.py +256 -0
- package/skills/token-optimizer/scripts/_measure/file_refetch.py +250 -0
- package/skills/token-optimizer/scripts/_measure/first_call_context.py +216 -0
- package/skills/token-optimizer/scripts/_measure/first_read_outcomes.py +261 -0
- package/skills/token-optimizer/scripts/_measure/first_read_revive.py +137 -0
- package/skills/token-optimizer/scripts/_measure/fixture_context.py +65 -0
- package/skills/token-optimizer/scripts/_measure/headline.py +100 -0
- package/skills/token-optimizer/scripts/_measure/holdout_fallback.py +96 -0
- package/skills/token-optimizer/scripts/_measure/holdout_report.py +129 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +201 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_linux.py +121 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +260 -0
- package/skills/token-optimizer/scripts/_measure/lean_resume_receivers.py +260 -0
- package/skills/token-optimizer/scripts/_measure/lean_resume_threshold.py +76 -0
- package/skills/token-optimizer/scripts/_measure/lease_candidate_cleanup.py +82 -0
- package/skills/token-optimizer/scripts/_measure/lifecycle.py +54 -162
- package/skills/token-optimizer/scripts/_measure/mcp_archive_tripwire.py +120 -0
- package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +178 -0
- package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +276 -0
- package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +105 -0
- package/skills/token-optimizer/scripts/_measure/output_reread.py +629 -0
- package/skills/token-optimizer/scripts/_measure/own_price_card.py +268 -0
- package/skills/token-optimizer/scripts/_measure/periphery_exposure.py +85 -0
- package/skills/token-optimizer/scripts/_measure/pricing.py +152 -87
- package/skills/token-optimizer/scripts/_measure/quality_archive.py +159 -215
- package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +174 -0
- package/skills/token-optimizer/scripts/_measure/quality_continuity.py +43 -0
- package/skills/token-optimizer/scripts/_measure/rework_metrics.py +194 -0
- package/skills/token-optimizer/scripts/_measure/routing_period.py +48 -0
- package/skills/token-optimizer/scripts/_measure/savings.py +439 -864
- package/skills/token-optimizer/scripts/_measure/savings_headline.py +130 -0
- package/skills/token-optimizer/scripts/_measure/savings_story.py +187 -0
- package/skills/token-optimizer/scripts/_measure/session_best.py +24 -0
- package/skills/token-optimizer/scripts/_measure/session_effect.py +557 -0
- package/skills/token-optimizer/scripts/_measure/session_flush_lock.py +75 -0
- package/skills/token-optimizer/scripts/_measure/session_store_spool.py +220 -0
- package/skills/token-optimizer/scripts/_measure/sessions.py +103 -196
- package/skills/token-optimizer/scripts/_measure/setup_attachment_counter.py +196 -0
- package/skills/token-optimizer/scripts/_measure/setup_budget_monitor.py +180 -0
- package/skills/token-optimizer/scripts/_measure/setup_connector_ledger.py +126 -0
- package/skills/token-optimizer/scripts/_measure/setup_step.py +220 -0
- package/skills/token-optimizer/scripts/_measure/status_bar_lock.py +117 -0
- package/skills/token-optimizer/scripts/_measure/structural_archives.py +79 -0
- package/skills/token-optimizer/scripts/_measure/structural_dedupe.py +91 -0
- package/skills/token-optimizer/scripts/_measure/structural_ledger.py +418 -0
- package/skills/token-optimizer/scripts/_measure/structural_listing.py +163 -0
- package/skills/token-optimizer/scripts/_measure/structural_report.py +339 -0
- package/skills/token-optimizer/scripts/_measure/structural_seed.py +164 -0
- package/skills/token-optimizer/scripts/_measure/structural_value.py +248 -0
- package/skills/token-optimizer/scripts/_measure/structure_funnel.py +97 -0
- package/skills/token-optimizer/scripts/_measure/timestamp_cache.py +11 -0
- package/skills/token-optimizer/scripts/_measure/token_type_split.py +29 -0
- package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +419 -0
- package/skills/token-optimizer/scripts/_measure/transcript_product.py +228 -0
- package/skills/token-optimizer/scripts/_measure/transcript_stream.py +279 -0
- package/skills/token-optimizer/scripts/_measure/trends.py +44 -185
- package/skills/token-optimizer/scripts/_measure/ttl_period.py +6 -0
- package/skills/token-optimizer/scripts/_measure/upgrade_drain_control.py +287 -0
- package/skills/token-optimizer/scripts/activity_tracker.py +4 -33
- package/skills/token-optimizer/scripts/antigravity_install.py +2 -0
- package/skills/token-optimizer/scripts/archive_result.py +15 -19
- package/skills/token-optimizer/scripts/archive_verify.py +165 -0
- package/skills/token-optimizer/scripts/bash_compress.py +14 -43
- package/skills/token-optimizer/scripts/bash_compress_hook.py +132 -2
- package/skills/token-optimizer/scripts/checkpoint_state.py +2 -2
- package/skills/token-optimizer/scripts/cloud_kit.py +3 -6
- package/skills/token-optimizer/scripts/codemap.py +274 -0
- package/skills/token-optimizer/scripts/codemap_hint.py +153 -0
- package/skills/token-optimizer/scripts/codemap_index.py +656 -0
- package/skills/token-optimizer/scripts/codemap_ledger.py +309 -0
- package/skills/token-optimizer/scripts/codemap_reread.py +161 -0
- package/skills/token-optimizer/scripts/codex_doctor.py +9 -1
- package/skills/token-optimizer/scripts/codex_log_index.py +34 -15
- package/skills/token-optimizer/scripts/codex_session.py +16 -216
- package/skills/token-optimizer/scripts/compression_backfill.py +4 -35
- package/skills/token-optimizer/scripts/context_intel.py +5 -3
- package/skills/token-optimizer/scripts/copilot_install.py +2 -0
- package/skills/token-optimizer/scripts/coverage_funnel.py +261 -0
- package/skills/token-optimizer/scripts/cursor_install.py +12 -0
- package/skills/token-optimizer/scripts/cursor_quality.py +16 -64
- package/skills/token-optimizer/scripts/dashboard_assets.py +21 -0
- package/skills/token-optimizer/scripts/deterministic_candidates.py +2 -10
- package/skills/token-optimizer/scripts/devin_source.py +8 -3
- package/skills/token-optimizer/scripts/devin_verify.py +7 -1
- package/skills/token-optimizer/scripts/grok_install.py +2 -0
- package/skills/token-optimizer/scripts/heal_report.py +7 -6
- package/skills/token-optimizer/scripts/hermes_doctor.py +9 -1
- package/skills/token-optimizer/scripts/hermes_install.py +7 -1
- package/skills/token-optimizer/scripts/hermes_session.py +14 -136
- package/skills/token-optimizer/scripts/hint_paths.py +21 -0
- package/skills/token-optimizer/scripts/holdout.py +136 -0
- package/skills/token-optimizer/scripts/hook_runtime.py +1 -0
- package/skills/token-optimizer/scripts/hook_skip_log.py +89 -0
- package/skills/token-optimizer/scripts/large_transcripts.py +31 -0
- package/skills/token-optimizer/scripts/lean_resume_carry.py +518 -0
- package/skills/token-optimizer/scripts/measure.py +34 -76
- package/skills/token-optimizer/scripts/post_run_classify.py +349 -0
- package/skills/token-optimizer/scripts/preserved_reinject.py +54 -0
- package/skills/token-optimizer/scripts/read_cache.py +99 -100
- package/skills/token-optimizer/scripts/reset_epoch.py +3 -3
- package/skills/token-optimizer/scripts/session_store.py +49 -99
- package/skills/token-optimizer/scripts/session_store_guard.py +75 -0
- package/skills/token-optimizer/scripts/settings_backup.py +379 -0
- package/skills/token-optimizer/scripts/shipped_hook_templates.py +1 -0
- package/skills/token-optimizer/scripts/statusline.js +144 -30
- package/skills/token-optimizer/scripts/structural.py +25 -0
- package/skills/token-optimizer/scripts/structure_map.py +4 -26
|
@@ -0,0 +1,656 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Serverless per-project code map index (stdlib only).
|
|
3
|
+
|
|
4
|
+
The index answers structural questions ("where is X defined", "what calls Y",
|
|
5
|
+
"what does this file import") from a small SQLite file in the plugin data dir,
|
|
6
|
+
so an agent can ask instead of grepping and reading whole files. There is no
|
|
7
|
+
resident server or file watcher: every query first runs a bounded mtime+size
|
|
8
|
+
sweep and re-parses only the files that changed, so answers are never staler
|
|
9
|
+
than the files on disk.
|
|
10
|
+
|
|
11
|
+
Parsing reuses structure_map (Python ``ast`` signatures, the JS/TS line
|
|
12
|
+
scanner and its comment/string stripper, the import resolvers). Everything
|
|
13
|
+
here is bounded: file count, per-file bytes, total build time and DB size.
|
|
14
|
+
Any failure raises ``CodemapError`` so callers can fail open to normal reads.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import ast
|
|
20
|
+
import hashlib
|
|
21
|
+
import os
|
|
22
|
+
import re
|
|
23
|
+
import sqlite3
|
|
24
|
+
import time
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
from typing import Dict, Iterable, Iterator, List, Optional, Sequence, Tuple
|
|
27
|
+
|
|
28
|
+
import structure_map as sm
|
|
29
|
+
|
|
30
|
+
SCHEMA_VERSION = "2"
|
|
31
|
+
MAX_FILES = 6000
|
|
32
|
+
MAX_PY_BYTES = sm.MAX_AST_BYTES
|
|
33
|
+
MAX_JS_BYTES = sm.MAX_JS_TS_BYTES
|
|
34
|
+
MAX_DB_BYTES = 96 * 1024 * 1024
|
|
35
|
+
BUILD_BUDGET_S = 8.0
|
|
36
|
+
SWEEP_BUDGET_S = 2.0
|
|
37
|
+
MAX_REFS_PER_FILE = 4000
|
|
38
|
+
MAX_DEFS_PER_FILE = 2000
|
|
39
|
+
SUPPORTED_SUFFIXES = frozenset({sm.PYTHON_SUFFIX}) | frozenset(sm.JS_TS_SUFFIXES)
|
|
40
|
+
SKIP_DIRS = frozenset({
|
|
41
|
+
".git", ".hg", ".svn", "node_modules", "__pycache__", ".venv", "venv", "env",
|
|
42
|
+
".tox", ".nox", ".mypy_cache", ".pytest_cache", ".ruff_cache", "dist", "build",
|
|
43
|
+
"out", "target", ".next", ".nuxt", "coverage", "site-packages", "vendor",
|
|
44
|
+
"bower_components", ".cache", ".idea", ".vscode", ".gradle", "Pods",
|
|
45
|
+
})
|
|
46
|
+
ROOT_MARKERS = (".git", "pyproject.toml", "package.json", "setup.py", "setup.cfg", "go.mod", "Cargo.toml")
|
|
47
|
+
_JS_CALL_RE = re.compile(r"(?<![\w$.])(?:new\s+)?([A-Za-z_$][\w$]*)\s*\(|\.([A-Za-z_$][\w$]*)\s*\(")
|
|
48
|
+
_JS_KEYWORDS = frozenset({
|
|
49
|
+
"if", "for", "while", "switch", "catch", "function", "return", "typeof", "await",
|
|
50
|
+
"super", "import", "require", "with", "do", "else", "new", "delete", "void", "in",
|
|
51
|
+
"of", "yield", "case", "throw", "constructor", "async",
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
_SCHEMA = """
|
|
55
|
+
CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v TEXT);
|
|
56
|
+
CREATE TABLE IF NOT EXISTS files (
|
|
57
|
+
fid INTEGER PRIMARY KEY, path TEXT UNIQUE, mtime_ns INTEGER, size INTEGER,
|
|
58
|
+
lang TEXT, tokens INTEGER, lines INTEGER, parse_ok INTEGER
|
|
59
|
+
);
|
|
60
|
+
CREATE TABLE IF NOT EXISTS defs (
|
|
61
|
+
name TEXT, qual TEXT, kind TEXT, fid INTEGER, line INTEGER, end_line INTEGER, sig TEXT
|
|
62
|
+
);
|
|
63
|
+
CREATE TABLE IF NOT EXISTS imports (fid INTEGER, module TEXT, target TEXT);
|
|
64
|
+
CREATE TABLE IF NOT EXISTS refs (fid INTEGER, line INTEGER, caller TEXT, callee TEXT, n INTEGER);
|
|
65
|
+
CREATE INDEX IF NOT EXISTS defs_name ON defs(name);
|
|
66
|
+
CREATE INDEX IF NOT EXISTS defs_fid ON defs(fid);
|
|
67
|
+
CREATE INDEX IF NOT EXISTS refs_callee ON refs(callee);
|
|
68
|
+
CREATE INDEX IF NOT EXISTS refs_fid ON refs(fid);
|
|
69
|
+
CREATE INDEX IF NOT EXISTS imports_fid ON imports(fid);
|
|
70
|
+
CREATE INDEX IF NOT EXISTS imports_target ON imports(target);
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _tokens_from_bytes(n: int) -> int:
|
|
75
|
+
try:
|
|
76
|
+
from token_estimate import estimate_tokens_from_bytes
|
|
77
|
+
return int(estimate_tokens_from_bytes(n))
|
|
78
|
+
except Exception:
|
|
79
|
+
return max(1, (int(n) + 3) // 4)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _discard_index_file(db: Path) -> None:
|
|
83
|
+
"""Remove a corrupt index (our own cache file and its WAL sidecars only)."""
|
|
84
|
+
if db.suffix != ".db" or db.parent.name != "codemap":
|
|
85
|
+
return
|
|
86
|
+
for suffix in ("", "-wal", "-shm"):
|
|
87
|
+
try:
|
|
88
|
+
Path(str(db) + suffix).unlink()
|
|
89
|
+
except OSError:
|
|
90
|
+
pass
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class CodemapError(Exception):
|
|
94
|
+
"""Any index failure. Callers fail open (serve normal reads)."""
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
# --------------------------------------------------------------------------- #
|
|
98
|
+
# Flags. ON by default; TOKEN_OPTIMIZER_CODEMAP=0 (or config v5_codemap=false)
|
|
99
|
+
# turns off lookups, hints and re-read outlines together.
|
|
100
|
+
# --------------------------------------------------------------------------- #
|
|
101
|
+
|
|
102
|
+
def codemap_enabled() -> bool:
|
|
103
|
+
try:
|
|
104
|
+
from plugin_env import is_v5_flag_enabled
|
|
105
|
+
return is_v5_flag_enabled("v5_codemap", "TOKEN_OPTIMIZER_CODEMAP", default=True)
|
|
106
|
+
except Exception:
|
|
107
|
+
return False
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def reread_outline_enabled() -> bool:
|
|
111
|
+
if not codemap_enabled():
|
|
112
|
+
return False
|
|
113
|
+
try:
|
|
114
|
+
from plugin_env import is_v5_flag_enabled
|
|
115
|
+
return is_v5_flag_enabled("v5_codemap_reread", "TOKEN_OPTIMIZER_CODEMAP_REREAD", default=True)
|
|
116
|
+
except Exception:
|
|
117
|
+
return False
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
# --------------------------------------------------------------------------- #
|
|
121
|
+
# Locations
|
|
122
|
+
# --------------------------------------------------------------------------- #
|
|
123
|
+
|
|
124
|
+
def find_project_root(start: str | os.PathLike[str]) -> Path:
|
|
125
|
+
"""Nearest ancestor with a project marker; the start dir when none is found.
|
|
126
|
+
|
|
127
|
+
The home directory and filesystem root are never treated as a project, so a
|
|
128
|
+
stray ``~/.git`` cannot make the index crawl a whole home folder.
|
|
129
|
+
"""
|
|
130
|
+
p = Path(str(start)).expanduser().resolve()
|
|
131
|
+
if p.is_file():
|
|
132
|
+
p = p.parent
|
|
133
|
+
home = Path.home().resolve()
|
|
134
|
+
cur = p
|
|
135
|
+
for _ in range(40):
|
|
136
|
+
if cur == home or cur.parent == cur:
|
|
137
|
+
break
|
|
138
|
+
if any((cur / m).exists() for m in ROOT_MARKERS):
|
|
139
|
+
return cur
|
|
140
|
+
cur = cur.parent
|
|
141
|
+
return p
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def index_dir() -> Path:
|
|
145
|
+
from plugin_env import resolve_snapshot_dir
|
|
146
|
+
return resolve_snapshot_dir() / "codemap"
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def index_path(root: Path) -> Path:
|
|
150
|
+
digest = hashlib.sha256(str(root).encode("utf-8", "replace")).hexdigest()[:16]
|
|
151
|
+
return index_dir() / f"{digest}.db"
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
# --------------------------------------------------------------------------- #
|
|
155
|
+
# Parsing (reuses structure_map)
|
|
156
|
+
# --------------------------------------------------------------------------- #
|
|
157
|
+
|
|
158
|
+
class FileFacts:
|
|
159
|
+
__slots__ = ("defs", "imports", "refs", "lines", "parse_ok")
|
|
160
|
+
|
|
161
|
+
def __init__(self) -> None:
|
|
162
|
+
self.defs: List[Tuple[str, str, str, int, int, str]] = []
|
|
163
|
+
self.imports: List[Tuple[str, Optional[str]]] = []
|
|
164
|
+
self.refs: List[Tuple[int, str, str]] = []
|
|
165
|
+
self.lines = 0
|
|
166
|
+
self.parse_ok = True
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _rel(root: Path, p: Path) -> Optional[str]:
|
|
170
|
+
try:
|
|
171
|
+
return p.resolve().relative_to(root).as_posix()
|
|
172
|
+
except (ValueError, OSError):
|
|
173
|
+
return None
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _first_existing(cands: Iterable[Path], root: Path) -> Optional[str]:
|
|
177
|
+
for c in cands:
|
|
178
|
+
try:
|
|
179
|
+
if c.is_file():
|
|
180
|
+
rel = _rel(root, c)
|
|
181
|
+
if rel is not None:
|
|
182
|
+
return rel
|
|
183
|
+
except OSError:
|
|
184
|
+
continue
|
|
185
|
+
return None
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _py_import_targets(node: ast.AST, path: Path, root: Path) -> List[Tuple[str, Optional[str]]]:
|
|
189
|
+
out: List[Tuple[str, Optional[str]]] = []
|
|
190
|
+
roots = [path.parent, root] + [a for a in path.parents if a.name == "src"]
|
|
191
|
+
if isinstance(node, ast.Import):
|
|
192
|
+
for alias in node.names:
|
|
193
|
+
cands = [c for r in roots for c in sm._module_to_file_candidates(alias.name, r)]
|
|
194
|
+
out.append((alias.name, _first_existing(cands, root)))
|
|
195
|
+
elif isinstance(node, ast.ImportFrom):
|
|
196
|
+
mod = node.module or ""
|
|
197
|
+
label = "." * (node.level or 0) + mod
|
|
198
|
+
if node.level:
|
|
199
|
+
base = path.parent
|
|
200
|
+
for _ in range(max(0, node.level - 1)):
|
|
201
|
+
base = base.parent
|
|
202
|
+
bases = [base]
|
|
203
|
+
else:
|
|
204
|
+
bases = roots
|
|
205
|
+
cands: List[Path] = []
|
|
206
|
+
for b in bases:
|
|
207
|
+
if mod:
|
|
208
|
+
cands.extend(sm._module_to_file_candidates(mod, b))
|
|
209
|
+
for alias in node.names:
|
|
210
|
+
sub = f"{mod}.{alias.name}" if mod else alias.name
|
|
211
|
+
cands.extend(sm._module_to_file_candidates(sub, b))
|
|
212
|
+
out.append((label or ".", _first_existing(cands, root)))
|
|
213
|
+
return out
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _parse_python(source: str, path: Path, root: Path, facts: FileFacts) -> None:
|
|
217
|
+
try:
|
|
218
|
+
tree = ast.parse(source, filename=str(path))
|
|
219
|
+
except (SyntaxError, ValueError, RecursionError, MemoryError):
|
|
220
|
+
facts.parse_ok = False
|
|
221
|
+
return
|
|
222
|
+
|
|
223
|
+
def visit(node: ast.AST, scope: List[str]) -> None:
|
|
224
|
+
for child in ast.iter_child_nodes(node):
|
|
225
|
+
if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
226
|
+
owner = scope[-1] if scope and scope[-1][:1].isupper() else None
|
|
227
|
+
try:
|
|
228
|
+
sig = sm._summarize_function(child, owner=owner).signature
|
|
229
|
+
except Exception:
|
|
230
|
+
sig = f"def {child.name}(...)"
|
|
231
|
+
kind = "method" if owner else "function"
|
|
232
|
+
qual = ".".join(scope + [child.name])
|
|
233
|
+
if len(facts.defs) < MAX_DEFS_PER_FILE:
|
|
234
|
+
facts.defs.append((child.name, qual, kind, child.lineno,
|
|
235
|
+
getattr(child, "end_lineno", child.lineno) or child.lineno, sig))
|
|
236
|
+
_calls(child, qual)
|
|
237
|
+
visit(child, scope + [child.name])
|
|
238
|
+
elif isinstance(child, ast.ClassDef):
|
|
239
|
+
try:
|
|
240
|
+
sig = sm._summarize_class(child).signature
|
|
241
|
+
except Exception:
|
|
242
|
+
sig = f"class {child.name}"
|
|
243
|
+
qual = ".".join(scope + [child.name])
|
|
244
|
+
if len(facts.defs) < MAX_DEFS_PER_FILE:
|
|
245
|
+
facts.defs.append((child.name, qual, "class", child.lineno,
|
|
246
|
+
getattr(child, "end_lineno", child.lineno) or child.lineno, sig))
|
|
247
|
+
visit(child, scope + [child.name])
|
|
248
|
+
elif isinstance(child, (ast.Import, ast.ImportFrom)) and not scope:
|
|
249
|
+
facts.imports.extend(_py_import_targets(child, path, root))
|
|
250
|
+
elif isinstance(child, (ast.Assign, ast.AnnAssign)) and not scope:
|
|
251
|
+
targets = child.targets if isinstance(child, ast.Assign) else [child.target]
|
|
252
|
+
for t in targets:
|
|
253
|
+
for name in sm._flatten_targets(t):
|
|
254
|
+
if name and len(facts.defs) < MAX_DEFS_PER_FILE:
|
|
255
|
+
facts.defs.append((name, name, "variable", child.lineno,
|
|
256
|
+
getattr(child, "end_lineno", child.lineno) or child.lineno,
|
|
257
|
+
name))
|
|
258
|
+
|
|
259
|
+
def _calls(fn: ast.AST, caller: str) -> None:
|
|
260
|
+
stack = list(ast.iter_child_nodes(fn))
|
|
261
|
+
while stack:
|
|
262
|
+
n = stack.pop()
|
|
263
|
+
if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda)):
|
|
264
|
+
continue
|
|
265
|
+
if isinstance(n, ast.Call) and len(facts.refs) < MAX_REFS_PER_FILE:
|
|
266
|
+
name = sm._call_target_name(n.func)
|
|
267
|
+
if name:
|
|
268
|
+
facts.refs.append((getattr(n, "lineno", 0), caller, name))
|
|
269
|
+
stack.extend(ast.iter_child_nodes(n))
|
|
270
|
+
|
|
271
|
+
try:
|
|
272
|
+
visit(tree, [])
|
|
273
|
+
# Module-level calls (scripts, decorators, registrations).
|
|
274
|
+
for top in tree.body:
|
|
275
|
+
if not isinstance(top, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
|
|
276
|
+
for n in ast.walk(top):
|
|
277
|
+
if isinstance(n, ast.Call) and len(facts.refs) < MAX_REFS_PER_FILE:
|
|
278
|
+
name = sm._call_target_name(n.func)
|
|
279
|
+
if name:
|
|
280
|
+
facts.refs.append((getattr(n, "lineno", 0), "<module>", name))
|
|
281
|
+
except RecursionError:
|
|
282
|
+
facts.parse_ok = False
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def _parse_js_ts(source: str, path: Path, root: Path, facts: FileFacts) -> None:
|
|
286
|
+
try:
|
|
287
|
+
imports, classes, functions, symbols = sm._collect_js_ts_structure(source)
|
|
288
|
+
clean = sm._strip_js_ts_comments_and_strings(source).splitlines()
|
|
289
|
+
except Exception:
|
|
290
|
+
facts.parse_ok = False
|
|
291
|
+
return
|
|
292
|
+
starts: List[Tuple[int, str]] = []
|
|
293
|
+
for c in classes:
|
|
294
|
+
facts.defs.append((c.name, c.name, "class", c.lineno, c.lineno, c.signature))
|
|
295
|
+
starts.append((c.lineno, c.name))
|
|
296
|
+
for m in c.methods:
|
|
297
|
+
q = f"{c.name}.{m.name}"
|
|
298
|
+
facts.defs.append((m.name, q, "method", m.lineno, m.lineno, m.signature))
|
|
299
|
+
starts.append((m.lineno, q))
|
|
300
|
+
for f in functions:
|
|
301
|
+
facts.defs.append((f.name, f.name, "function", f.lineno, f.lineno, f.signature))
|
|
302
|
+
starts.append((f.lineno, f.name))
|
|
303
|
+
for s in symbols:
|
|
304
|
+
facts.defs.append((s.name, s.name, s.kind, s.lineno, s.lineno, s.signature))
|
|
305
|
+
if s.kind in ("const", "let", "var"):
|
|
306
|
+
starts.append((s.lineno, s.name))
|
|
307
|
+
del facts.defs[MAX_DEFS_PER_FILE:]
|
|
308
|
+
starts.sort()
|
|
309
|
+
# End lines: the line before the next top-level start (approximate span).
|
|
310
|
+
ends: Dict[str, int] = {}
|
|
311
|
+
for i, (ln, q) in enumerate(starts):
|
|
312
|
+
ends[q] = (starts[i + 1][0] - 1) if i + 1 < len(starts) else len(clean)
|
|
313
|
+
facts.defs = [
|
|
314
|
+
(n, q, k, ln, max(ln, ends.get(q, ln)) if k in ("class", "function", "method") else e, sig)
|
|
315
|
+
for (n, q, k, ln, e, sig) in facts.defs
|
|
316
|
+
]
|
|
317
|
+
seen_specs = set()
|
|
318
|
+
raw_lines = source.splitlines()
|
|
319
|
+
for raw, cl in zip(raw_lines, clean):
|
|
320
|
+
if not sm.JS_TS_IMPORT_RE.match(cl.strip()):
|
|
321
|
+
continue
|
|
322
|
+
for rx in (sm._JS_TS_FROM_SPEC_RE, sm._JS_TS_SIDE_EFFECT_IMPORT_RE):
|
|
323
|
+
for m in rx.finditer(raw):
|
|
324
|
+
spec = m.group(1)
|
|
325
|
+
if spec in seen_specs:
|
|
326
|
+
continue
|
|
327
|
+
seen_specs.add(spec)
|
|
328
|
+
target = None
|
|
329
|
+
if spec.startswith("."):
|
|
330
|
+
target = _first_existing(sm._resolve_js_ts_spec(spec, path.parent), root)
|
|
331
|
+
facts.imports.append((spec, target))
|
|
332
|
+
import bisect
|
|
333
|
+
keys = [s[0] for s in starts]
|
|
334
|
+
for lineno, line in enumerate(clean, 1):
|
|
335
|
+
if "(" not in line:
|
|
336
|
+
continue
|
|
337
|
+
for m in _JS_CALL_RE.finditer(line):
|
|
338
|
+
name = m.group(1) or m.group(2)
|
|
339
|
+
if not name or name in _JS_KEYWORDS:
|
|
340
|
+
continue
|
|
341
|
+
idx = bisect.bisect_right(keys, lineno) - 1
|
|
342
|
+
caller = starts[idx][1] if idx >= 0 else "<module>"
|
|
343
|
+
if idx >= 0 and starts[idx][0] == lineno and caller.split(".")[-1] == name:
|
|
344
|
+
continue # the definition line itself
|
|
345
|
+
facts.refs.append((lineno, caller, name))
|
|
346
|
+
if len(facts.refs) >= MAX_REFS_PER_FILE:
|
|
347
|
+
return
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def parse_file(path: Path, root: Path, source: Optional[str] = None) -> FileFacts:
|
|
351
|
+
facts = FileFacts()
|
|
352
|
+
if source is None:
|
|
353
|
+
source = path.read_text(encoding="utf-8", errors="replace")
|
|
354
|
+
facts.lines = source.count("\n") + (1 if source and not source.endswith("\n") else 0)
|
|
355
|
+
if sm.is_python_file(path):
|
|
356
|
+
_parse_python(source, path, root, facts)
|
|
357
|
+
elif sm.is_js_ts_file(path):
|
|
358
|
+
_parse_js_ts(source, path, root, facts)
|
|
359
|
+
else:
|
|
360
|
+
facts.parse_ok = False
|
|
361
|
+
return facts
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
# --------------------------------------------------------------------------- #
|
|
365
|
+
# Store
|
|
366
|
+
# --------------------------------------------------------------------------- #
|
|
367
|
+
|
|
368
|
+
def _iter_source_files(root: Path, deadline: float) -> Iterator[Path]:
|
|
369
|
+
count = 0
|
|
370
|
+
for dirpath, dirnames, filenames in os.walk(root, followlinks=False):
|
|
371
|
+
dirnames[:] = sorted(d for d in dirnames if d not in SKIP_DIRS and not d.startswith("."))
|
|
372
|
+
for fn in sorted(filenames):
|
|
373
|
+
if Path(fn).suffix.lower() not in SUPPORTED_SUFFIXES:
|
|
374
|
+
continue
|
|
375
|
+
if fn.endswith((".min.js", ".bundle.js", ".d.ts")):
|
|
376
|
+
continue
|
|
377
|
+
count += 1
|
|
378
|
+
if count > MAX_FILES or time.monotonic() > deadline:
|
|
379
|
+
return
|
|
380
|
+
yield Path(dirpath) / fn
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
class CodeIndex:
|
|
384
|
+
"""One project's index. Use ``CodeIndex.open(root)`` then ``sync()``."""
|
|
385
|
+
|
|
386
|
+
def __init__(self, root: Path, conn: sqlite3.Connection, db_path: Path):
|
|
387
|
+
self.root = root
|
|
388
|
+
self.conn = conn
|
|
389
|
+
self.db_path = db_path
|
|
390
|
+
self.complete = False
|
|
391
|
+
|
|
392
|
+
@classmethod
|
|
393
|
+
def open(cls, root: str | os.PathLike[str], db_path: Optional[Path] = None) -> "CodeIndex":
|
|
394
|
+
root_p = Path(str(root)).resolve()
|
|
395
|
+
db = db_path or index_path(root_p)
|
|
396
|
+
try:
|
|
397
|
+
db.parent.mkdir(parents=True, exist_ok=True)
|
|
398
|
+
except OSError as exc:
|
|
399
|
+
raise CodemapError(f"index dir unavailable: {exc}") from exc
|
|
400
|
+
for attempt in (1, 2):
|
|
401
|
+
conn = None
|
|
402
|
+
try:
|
|
403
|
+
conn = sqlite3.connect(str(db), timeout=3.0)
|
|
404
|
+
conn.execute("PRAGMA busy_timeout=3000")
|
|
405
|
+
conn.execute("PRAGMA journal_mode=WAL")
|
|
406
|
+
conn.execute("CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v TEXT)")
|
|
407
|
+
ver = conn.execute("SELECT v FROM meta WHERE k='schema'").fetchone()
|
|
408
|
+
if ver is None or ver[0] != SCHEMA_VERSION:
|
|
409
|
+
for t in ("files", "defs", "imports", "refs"):
|
|
410
|
+
conn.execute(f"DROP TABLE IF EXISTS {t}")
|
|
411
|
+
conn.executescript(_SCHEMA)
|
|
412
|
+
conn.execute("INSERT OR REPLACE INTO meta VALUES('schema', ?)", (SCHEMA_VERSION,))
|
|
413
|
+
conn.execute("INSERT OR REPLACE INTO meta VALUES('root', ?)", (str(root_p),))
|
|
414
|
+
conn.commit()
|
|
415
|
+
return cls(root_p, conn, db)
|
|
416
|
+
except sqlite3.DatabaseError as exc:
|
|
417
|
+
if conn is not None:
|
|
418
|
+
try:
|
|
419
|
+
conn.close()
|
|
420
|
+
except Exception:
|
|
421
|
+
pass
|
|
422
|
+
# A corrupt index is only a cache: discard our own file once and rebuild.
|
|
423
|
+
if attempt == 1 and isinstance(exc, sqlite3.DatabaseError) and not isinstance(
|
|
424
|
+
exc, sqlite3.OperationalError):
|
|
425
|
+
_discard_index_file(db)
|
|
426
|
+
continue
|
|
427
|
+
raise CodemapError(f"index open failed: {exc}") from exc
|
|
428
|
+
raise CodemapError("index open failed")
|
|
429
|
+
|
|
430
|
+
def close(self) -> None:
|
|
431
|
+
try:
|
|
432
|
+
self.conn.close()
|
|
433
|
+
except Exception:
|
|
434
|
+
pass
|
|
435
|
+
|
|
436
|
+
# -- writes ------------------------------------------------------------ #
|
|
437
|
+
def _drop(self, rel: str) -> None:
|
|
438
|
+
row = self.conn.execute("SELECT fid FROM files WHERE path=?", (rel,)).fetchone()
|
|
439
|
+
if row is None:
|
|
440
|
+
return
|
|
441
|
+
for t in ("defs", "imports", "refs"):
|
|
442
|
+
self.conn.execute(f"DELETE FROM {t} WHERE fid=?", (row[0],))
|
|
443
|
+
self.conn.execute("DELETE FROM files WHERE fid=?", (row[0],))
|
|
444
|
+
|
|
445
|
+
def _store(self, rel: str, st: os.stat_result, facts: FileFacts) -> None:
|
|
446
|
+
self._drop(rel)
|
|
447
|
+
lang = sm.detect_structure_language(rel)
|
|
448
|
+
cur = self.conn.execute(
|
|
449
|
+
"INSERT INTO files (path, mtime_ns, size, lang, tokens, lines, parse_ok) "
|
|
450
|
+
"VALUES (?,?,?,?,?,?,?)",
|
|
451
|
+
(rel, st.st_mtime_ns, st.st_size, lang, _tokens_from_bytes(st.st_size),
|
|
452
|
+
facts.lines, 1 if facts.parse_ok else 0),
|
|
453
|
+
)
|
|
454
|
+
fid = cur.lastrowid
|
|
455
|
+
self.conn.executemany(
|
|
456
|
+
"INSERT INTO defs VALUES (?,?,?,?,?,?,?)",
|
|
457
|
+
[(n, q, k, fid, ln, e, sig[:240]) for (n, q, k, ln, e, sig) in facts.defs],
|
|
458
|
+
)
|
|
459
|
+
self.conn.executemany("INSERT INTO imports VALUES (?,?,?)",
|
|
460
|
+
[(fid, m[:200], t) for (m, t) in facts.imports])
|
|
461
|
+
# One row per (caller, callee): first call line plus a count. Callers
|
|
462
|
+
# are answered per call site group, which keeps the DB small.
|
|
463
|
+
grouped: Dict[Tuple[str, str], List[int]] = {}
|
|
464
|
+
for ln, c, n in facts.refs:
|
|
465
|
+
if len(n) < 2:
|
|
466
|
+
continue
|
|
467
|
+
g = grouped.get((c, n))
|
|
468
|
+
if g is None:
|
|
469
|
+
grouped[(c, n)] = [ln, 1]
|
|
470
|
+
else:
|
|
471
|
+
g[1] += 1
|
|
472
|
+
self.conn.executemany("INSERT INTO refs VALUES (?,?,?,?,?)",
|
|
473
|
+
[(fid, v[0], c, n, v[1]) for (c, n), v in grouped.items()])
|
|
474
|
+
|
|
475
|
+
def index_file(self, path: Path, st: Optional[os.stat_result] = None) -> bool:
|
|
476
|
+
rel = _rel(self.root, path)
|
|
477
|
+
if rel is None:
|
|
478
|
+
return False
|
|
479
|
+
try:
|
|
480
|
+
st = st or path.stat()
|
|
481
|
+
cap = MAX_PY_BYTES if sm.is_python_file(path) else MAX_JS_BYTES
|
|
482
|
+
if st.st_size > cap:
|
|
483
|
+
facts = FileFacts()
|
|
484
|
+
facts.parse_ok = False
|
|
485
|
+
else:
|
|
486
|
+
facts = parse_file(path, self.root)
|
|
487
|
+
except (OSError, ValueError):
|
|
488
|
+
self._drop(rel)
|
|
489
|
+
return False
|
|
490
|
+
self._store(rel, st, facts)
|
|
491
|
+
return True
|
|
492
|
+
|
|
493
|
+
def refresh_file(self, path: str | os.PathLike[str]) -> bool:
|
|
494
|
+
"""Re-index one file if its mtime/size changed. Returns True if fresh."""
|
|
495
|
+
p = Path(str(path)).resolve()
|
|
496
|
+
rel = _rel(self.root, p)
|
|
497
|
+
if rel is None or p.suffix.lower() not in SUPPORTED_SUFFIXES:
|
|
498
|
+
return False
|
|
499
|
+
try:
|
|
500
|
+
st = p.stat()
|
|
501
|
+
except OSError:
|
|
502
|
+
self._drop(rel)
|
|
503
|
+
self.conn.commit()
|
|
504
|
+
return False
|
|
505
|
+
row = self.conn.execute("SELECT mtime_ns, size FROM files WHERE path=?", (rel,)).fetchone()
|
|
506
|
+
if row is None or row[0] != st.st_mtime_ns or row[1] != st.st_size:
|
|
507
|
+
self.index_file(p, st)
|
|
508
|
+
self.conn.commit()
|
|
509
|
+
return True
|
|
510
|
+
|
|
511
|
+
def sync(self, budget_s: Optional[float] = None) -> Dict[str, int]:
|
|
512
|
+
"""Bring the index up to date: new/changed files re-parsed, deleted dropped.
|
|
513
|
+
|
|
514
|
+
Bounded by ``budget_s``; a sweep that runs out of time marks the index
|
|
515
|
+
incomplete and the next query continues where it stopped.
|
|
516
|
+
"""
|
|
517
|
+
start = time.monotonic()
|
|
518
|
+
done = self.conn.execute("SELECT v FROM meta WHERE k='complete'").fetchone()
|
|
519
|
+
first = done is None or done[0] != "1"
|
|
520
|
+
budget = budget_s if budget_s is not None else (BUILD_BUDGET_S if first else SWEEP_BUDGET_S)
|
|
521
|
+
deadline = start + budget
|
|
522
|
+
known = {r[0]: (r[1], r[2]) for r in self.conn.execute("SELECT path, mtime_ns, size FROM files")}
|
|
523
|
+
seen = set()
|
|
524
|
+
stats = {"parsed": 0, "unchanged": 0, "removed": 0}
|
|
525
|
+
timed_out = False
|
|
526
|
+
try:
|
|
527
|
+
for p in _iter_source_files(self.root, deadline):
|
|
528
|
+
rel = _rel(self.root, p)
|
|
529
|
+
if rel is None:
|
|
530
|
+
continue
|
|
531
|
+
seen.add(rel)
|
|
532
|
+
try:
|
|
533
|
+
st = p.stat()
|
|
534
|
+
except OSError:
|
|
535
|
+
continue
|
|
536
|
+
if known.get(rel) == (st.st_mtime_ns, st.st_size):
|
|
537
|
+
stats["unchanged"] += 1
|
|
538
|
+
continue
|
|
539
|
+
if time.monotonic() > deadline:
|
|
540
|
+
timed_out = True
|
|
541
|
+
break
|
|
542
|
+
self.index_file(p, st)
|
|
543
|
+
stats["parsed"] += 1
|
|
544
|
+
if stats["parsed"] % 200 == 0:
|
|
545
|
+
self.conn.commit()
|
|
546
|
+
if self.db_path.exists() and self.db_path.stat().st_size > MAX_DB_BYTES:
|
|
547
|
+
timed_out = True
|
|
548
|
+
break
|
|
549
|
+
else:
|
|
550
|
+
timed_out = time.monotonic() > deadline
|
|
551
|
+
if not timed_out:
|
|
552
|
+
for rel in set(known) - seen:
|
|
553
|
+
self._drop(rel)
|
|
554
|
+
stats["removed"] += 1
|
|
555
|
+
self.complete = not timed_out
|
|
556
|
+
self.conn.execute("INSERT OR REPLACE INTO meta VALUES('complete', ?)",
|
|
557
|
+
("1" if self.complete else "0",))
|
|
558
|
+
self.conn.commit()
|
|
559
|
+
except sqlite3.Error as exc:
|
|
560
|
+
raise CodemapError(f"index sync failed: {exc}") from exc
|
|
561
|
+
stats["ms"] = int((time.monotonic() - start) * 1000)
|
|
562
|
+
return stats
|
|
563
|
+
|
|
564
|
+
# -- reads ------------------------------------------------------------- #
|
|
565
|
+
_DEF_COLS = "d.name, d.qual, d.kind, f.path, d.line, d.end_line, d.sig"
|
|
566
|
+
_DEF_FROM = "FROM defs d JOIN files f ON f.fid=d.fid"
|
|
567
|
+
|
|
568
|
+
def file_row(self, rel: str) -> Optional[Tuple]:
|
|
569
|
+
return self.conn.execute(
|
|
570
|
+
"SELECT path, mtime_ns, size, lang, tokens, lines, parse_ok FROM files WHERE path=?",
|
|
571
|
+
(rel,)).fetchone()
|
|
572
|
+
|
|
573
|
+
def find_defs(self, symbol: str, limit: int = 40) -> List[Tuple]:
|
|
574
|
+
c, f = self._DEF_COLS, self._DEF_FROM
|
|
575
|
+
if "." in symbol:
|
|
576
|
+
rows = self.conn.execute(
|
|
577
|
+
f"SELECT {c} {f} WHERE d.qual=? OR d.qual LIKE ? ORDER BY f.path, d.line LIMIT ?",
|
|
578
|
+
(symbol, "%." + symbol, limit)).fetchall()
|
|
579
|
+
if rows:
|
|
580
|
+
return rows
|
|
581
|
+
symbol = symbol.rsplit(".", 1)[-1]
|
|
582
|
+
rows = self.conn.execute(
|
|
583
|
+
f"SELECT {c} {f} WHERE d.name=? ORDER BY d.kind='variable', f.path, d.line LIMIT ?",
|
|
584
|
+
(symbol, limit)).fetchall()
|
|
585
|
+
if rows:
|
|
586
|
+
return rows
|
|
587
|
+
pat = "%" + symbol.replace("\\", "").replace("%", "\\%").replace("_", "\\_") + "%"
|
|
588
|
+
return self.conn.execute(
|
|
589
|
+
f"SELECT {c} {f} WHERE d.name LIKE ? ESCAPE '\\' AND d.kind!='variable' "
|
|
590
|
+
"ORDER BY length(d.name), f.path, d.line LIMIT ?",
|
|
591
|
+
(pat, min(limit, 15))).fetchall()
|
|
592
|
+
|
|
593
|
+
def callers(self, symbol: str, limit: int = 300) -> List[Tuple]:
|
|
594
|
+
"""(path, first_line, caller, count) for every caller of ``symbol``'s name."""
|
|
595
|
+
name = symbol.rsplit(".", 1)[-1]
|
|
596
|
+
return self.conn.execute(
|
|
597
|
+
"SELECT f.path, r.line, r.caller, r.n FROM refs r JOIN files f ON f.fid=r.fid "
|
|
598
|
+
"WHERE r.callee=? ORDER BY f.path, r.line LIMIT ?",
|
|
599
|
+
(name, limit)).fetchall()
|
|
600
|
+
|
|
601
|
+
def outline(self, rel: str) -> List[Tuple]:
|
|
602
|
+
return self.conn.execute(
|
|
603
|
+
"SELECT d.name, d.qual, d.kind, d.line, d.end_line, d.sig FROM defs d "
|
|
604
|
+
"JOIN files f ON f.fid=d.fid WHERE f.path=? ORDER BY d.line", (rel,)).fetchall()
|
|
605
|
+
|
|
606
|
+
def imports_of(self, rel: str) -> List[Tuple]:
|
|
607
|
+
return self.conn.execute(
|
|
608
|
+
"SELECT i.module, i.target FROM imports i JOIN files f ON f.fid=i.fid WHERE f.path=?",
|
|
609
|
+
(rel,)).fetchall()
|
|
610
|
+
|
|
611
|
+
def importers_of(self, rel: str, limit: int = 60) -> List[str]:
|
|
612
|
+
"""Files importing ``rel``: resolved targets, plus unresolved imports whose
|
|
613
|
+
module name ends with the file's stem (sys.path-style imports)."""
|
|
614
|
+
stem = Path(rel).stem
|
|
615
|
+
if stem in ("__init__", "index"):
|
|
616
|
+
stem = Path(rel).parent.name or stem
|
|
617
|
+
return [r[0] for r in self.conn.execute(
|
|
618
|
+
"SELECT DISTINCT f.path FROM imports i JOIN files f ON f.fid=i.fid "
|
|
619
|
+
"WHERE f.path!=? AND (i.target=? OR (i.target IS NULL AND (i.module=? OR i.module LIKE ? OR i.module LIKE ?))) "
|
|
620
|
+
"ORDER BY f.path LIMIT ?", (rel, rel, stem, "%." + stem, "%/" + stem, limit))]
|
|
621
|
+
|
|
622
|
+
def file_tokens(self, rel: str) -> int:
|
|
623
|
+
row = self.conn.execute("SELECT tokens FROM files WHERE path=?", (rel,)).fetchone()
|
|
624
|
+
return int(row[0]) if row else 0
|
|
625
|
+
|
|
626
|
+
def counts(self) -> Dict[str, int]:
|
|
627
|
+
out = {}
|
|
628
|
+
for t in ("files", "defs", "imports", "refs"):
|
|
629
|
+
out[t] = int(self.conn.execute(f"SELECT COUNT(*) FROM {t}").fetchone()[0])
|
|
630
|
+
return out
|
|
631
|
+
|
|
632
|
+
def rel(self, path: str | os.PathLike[str]) -> Optional[str]:
|
|
633
|
+
p = Path(str(path))
|
|
634
|
+
if not p.is_absolute():
|
|
635
|
+
p = Path.cwd() / p
|
|
636
|
+
return _rel(self.root, p)
|
|
637
|
+
|
|
638
|
+
|
|
639
|
+
def open_synced(start: str | os.PathLike[str], budget_s: Optional[float] = None) -> CodeIndex:
|
|
640
|
+
"""Open (building lazily) and sync the index for the project containing ``start``."""
|
|
641
|
+
root = find_project_root(start)
|
|
642
|
+
idx = CodeIndex.open(root)
|
|
643
|
+
try:
|
|
644
|
+
idx.sync(budget_s)
|
|
645
|
+
except CodemapError:
|
|
646
|
+
idx.close()
|
|
647
|
+
raise
|
|
648
|
+
except Exception as exc: # parsing bugs must never escape to the agent
|
|
649
|
+
idx.close()
|
|
650
|
+
raise CodemapError(f"index sync failed: {exc}") from exc
|
|
651
|
+
return idx
|
|
652
|
+
|
|
653
|
+
|
|
654
|
+
def symbols_in(text: str) -> Sequence[str]:
|
|
655
|
+
"""Identifiers in ``text`` (used by the replay helper)."""
|
|
656
|
+
return re.findall(r"[A-Za-z_][A-Za-z0-9_]{2,}", text or "")
|