agent-efficiency 1.4.2__py3-none-any.whl
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.
- agent_efficiency/__init__.py +15 -0
- agent_efficiency/_bundle/mcp/server.py +519 -0
- agent_efficiency/_bundle/rules/AGENT_RULES.md +9 -0
- agent_efficiency/_bundle/scripts/ae_cli.py +327 -0
- agent_efficiency/_bundle/scripts/ae_init.py +267 -0
- agent_efficiency/_bundle/scripts/ae_manage.py +578 -0
- agent_efficiency/_bundle/scripts/install.py +308 -0
- agent_efficiency/_bundle/scripts/pretool_hook.py +350 -0
- agent_efficiency/_bundle/scripts/render_demo_svg.py +180 -0
- agent_efficiency/_bundle/scripts/setup_hooks.py +330 -0
- agent_efficiency/_bundle/scripts/sync_shared.py +85 -0
- agent_efficiency/_bundle/scripts/validate_skills.py +150 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/SKILL.md +80 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/config/models.json +237 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/examples/workflow.md +77 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/references/routing-and-escalation.md +63 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/references/state-and-handoff.md +84 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/__init__.py +90 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/io_lock.py +199 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/savings.py +249 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/security.py +235 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/usage.py +195 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/agent_state.py +266 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/context_doctor.py +780 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/llm_adapter.py +306 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/route_task.py +496 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/state_ops.py +580 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/state_render.py +428 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/state_store.py +440 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/transcript_audit.py +854 -0
- agent_efficiency/_bundle/skills/local-context-index/SKILL.md +71 -0
- agent_efficiency/_bundle/skills/local-context-index/references/cli-reference.md +112 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/__init__.py +90 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/io_lock.py +199 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/savings.py +249 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/security.py +235 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/usage.py +195 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/compact_run.py +395 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/context_index.py +341 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_db.py +393 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_ignore.py +184 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_indexer.py +330 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_lsp.py +213 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_parsers.py +769 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_search.py +498 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_slice.py +610 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_trace.py +553 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_workspace.py +219 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/SKILL.md +52 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/references/provider-caching.md +52 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/__init__.py +90 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/io_lock.py +199 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/savings.py +249 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/security.py +235 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/usage.py +195 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/cache_payload.py +278 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/prompt_cache.py +488 -0
- agent_efficiency/cli.py +23 -0
- agent_efficiency/mcp_entry.py +25 -0
- agent_efficiency-1.4.2.dist-info/METADATA +267 -0
- agent_efficiency-1.4.2.dist-info/RECORD +64 -0
- agent_efficiency-1.4.2.dist-info/WHEEL +4 -0
- agent_efficiency-1.4.2.dist-info/entry_points.txt +4 -0
- agent_efficiency-1.4.2.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
"""Incremental SHA-256 repository indexer (locked, workspace-aware, call-graph, auto git-exclude) & watcher."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import hashlib
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import stat
|
|
8
|
+
import sys
|
|
9
|
+
import threading
|
|
10
|
+
import time
|
|
11
|
+
from collections import defaultdict
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any, Dict, List, Optional, Set, Tuple
|
|
14
|
+
|
|
15
|
+
from _ae_core import atomic_write_text, ensure_git_info_exclude, estimate_tokens, file_lock, git_cmd, redact_secrets, sanitize_inline
|
|
16
|
+
from idx_db import assert_not_symlink_artifact, build_project_map, db_open, ensure_safe_artifact_dir, split_identifier_tokens
|
|
17
|
+
from idx_ignore import (
|
|
18
|
+
DEFAULT_MAP_BUDGET_TOKENS,
|
|
19
|
+
EXCLUDED_DIRS,
|
|
20
|
+
MAX_BYTES_DEFAULT,
|
|
21
|
+
SUPPORTED_BASENAMES,
|
|
22
|
+
SUPPORTED_EXTS,
|
|
23
|
+
GitIgnoreRule,
|
|
24
|
+
is_binary_bytes,
|
|
25
|
+
is_ignored,
|
|
26
|
+
load_dir_gitignore,
|
|
27
|
+
load_gitignore_rules,
|
|
28
|
+
load_repo_config,
|
|
29
|
+
)
|
|
30
|
+
from idx_parsers import CODE_EXTS, extract_calls, extract_file_metadata, resolve_import_edge
|
|
31
|
+
from idx_workspace import load_workspace_aliases
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _resolve_call_targets(
|
|
35
|
+
db: Any,
|
|
36
|
+
changed_paths: Set[str],
|
|
37
|
+
rebuild_all: bool,
|
|
38
|
+
) -> None:
|
|
39
|
+
"""Resolve `calls.dst_path` and `calls.dst_symbol` using same-file -> imported-files -> unique-global priority."""
|
|
40
|
+
sym_by_name: Dict[str, List[Tuple[str, str]]] = defaultdict(list)
|
|
41
|
+
sym_by_file_name: Dict[Tuple[str, str], str] = {}
|
|
42
|
+
for p, name, qname in db.execute("SELECT path, name, qualified_name FROM symbols WHERE kind IN ('function','async_function','method','class')"):
|
|
43
|
+
sym_by_name[name].append((p, qname))
|
|
44
|
+
sym_by_file_name[(p, name)] = qname
|
|
45
|
+
|
|
46
|
+
imports_by_src: Dict[str, Set[str]] = defaultdict(set)
|
|
47
|
+
for src, dst in db.execute("SELECT src_path, dst_path FROM edges WHERE dst_path IS NOT NULL"):
|
|
48
|
+
imports_by_src[src].add(dst)
|
|
49
|
+
|
|
50
|
+
if rebuild_all:
|
|
51
|
+
rows = db.execute("SELECT rowid, src_path, callee_name FROM calls").fetchall()
|
|
52
|
+
elif changed_paths:
|
|
53
|
+
ph = ",".join("?" for _ in changed_paths)
|
|
54
|
+
rows = db.execute(f"SELECT rowid, src_path, callee_name FROM calls WHERE src_path IN ({ph})", list(changed_paths)).fetchall()
|
|
55
|
+
else:
|
|
56
|
+
return
|
|
57
|
+
|
|
58
|
+
updates: List[Tuple[Optional[str], Optional[str], int]] = []
|
|
59
|
+
for rid, src_p, callee in rows:
|
|
60
|
+
dst_p: Optional[str] = None
|
|
61
|
+
dst_s: Optional[str] = None
|
|
62
|
+
if (src_p, callee) in sym_by_file_name:
|
|
63
|
+
dst_p, dst_s = src_p, sym_by_file_name[(src_p, callee)]
|
|
64
|
+
else:
|
|
65
|
+
cands = sym_by_name.get(callee, [])
|
|
66
|
+
if cands:
|
|
67
|
+
imp_set = imports_by_src.get(src_p, set())
|
|
68
|
+
in_imp = [(cp, cq) for cp, cq in cands if cp in imp_set]
|
|
69
|
+
if len(in_imp) == 1:
|
|
70
|
+
dst_p, dst_s = in_imp[0]
|
|
71
|
+
elif len(in_imp) > 1:
|
|
72
|
+
dst_p, dst_s = in_imp[0]
|
|
73
|
+
elif len(cands) == 1:
|
|
74
|
+
dst_p, dst_s = cands[0]
|
|
75
|
+
updates.append((dst_p, dst_s, rid))
|
|
76
|
+
if updates:
|
|
77
|
+
db.executemany("UPDATE calls SET dst_path=?, dst_symbol=? WHERE rowid=?", updates)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def index(
|
|
81
|
+
repo: Path,
|
|
82
|
+
force: bool = False,
|
|
83
|
+
map_budget_tokens: Optional[int] = None,
|
|
84
|
+
use_gitignore: Optional[bool] = None,
|
|
85
|
+
auto_git_exclude: Optional[bool] = None,
|
|
86
|
+
) -> Dict[str, Any]:
|
|
87
|
+
repo = repo.resolve()
|
|
88
|
+
idx_dir = ensure_safe_artifact_dir(repo)
|
|
89
|
+
cfg_path = idx_dir / "config.json"
|
|
90
|
+
cfg = load_repo_config(repo)
|
|
91
|
+
|
|
92
|
+
extra_excludes = list(cfg.get("exclude", []))
|
|
93
|
+
extra_includes = list(cfg.get("include", []))
|
|
94
|
+
max_bytes = int(cfg.get("max_file_bytes", MAX_BYTES_DEFAULT))
|
|
95
|
+
eff_budget = int(map_budget_tokens if map_budget_tokens is not None else cfg.get("map_budget_tokens", DEFAULT_MAP_BUDGET_TOKENS))
|
|
96
|
+
eff_gi = use_gitignore if use_gitignore is not None else bool(cfg.get("use_gitignore", True))
|
|
97
|
+
eff_git_excl = auto_git_exclude if auto_git_exclude is not None else bool(cfg.get("auto_git_exclude", True))
|
|
98
|
+
gi_rules: List[GitIgnoreRule] = load_gitignore_rules(repo) if eff_gi else []
|
|
99
|
+
git_excluded = ensure_git_info_exclude(repo, (".agent-index/",)) if eff_git_excl else False
|
|
100
|
+
|
|
101
|
+
with file_lock(idx_dir / ".index.lock"):
|
|
102
|
+
db, has_fts = db_open(repo, read_only=False)
|
|
103
|
+
try:
|
|
104
|
+
if force and has_fts:
|
|
105
|
+
db.execute("DELETE FROM files_fts")
|
|
106
|
+
db.execute("DELETE FROM symbols_fts")
|
|
107
|
+
if force:
|
|
108
|
+
db.execute("DELETE FROM calls")
|
|
109
|
+
|
|
110
|
+
seen: Set[str] = set()
|
|
111
|
+
changed_paths: Set[str] = set()
|
|
112
|
+
changed = unchanged = skipped = 0
|
|
113
|
+
|
|
114
|
+
for dirpath, dirnames, filenames in os.walk(repo, topdown=True, followlinks=False):
|
|
115
|
+
dp = Path(dirpath)
|
|
116
|
+
rel_dir = "" if dp == repo else dp.relative_to(repo).as_posix()
|
|
117
|
+
if eff_gi and rel_dir:
|
|
118
|
+
gi_rules.extend(load_dir_gitignore(dp, rel_dir))
|
|
119
|
+
dirnames[:] = [
|
|
120
|
+
d for d in sorted(dirnames)
|
|
121
|
+
if d not in EXCLUDED_DIRS and not is_ignored(f"{rel_dir}/{d}" if rel_dir else d, extra_excludes, gi_rules, extra_includes)
|
|
122
|
+
]
|
|
123
|
+
|
|
124
|
+
for fname in sorted(filenames):
|
|
125
|
+
rel = f"{rel_dir}/{fname}" if rel_dir else fname
|
|
126
|
+
full = dp / fname
|
|
127
|
+
if is_ignored(rel, extra_excludes, gi_rules, extra_includes):
|
|
128
|
+
skipped += 1
|
|
129
|
+
continue
|
|
130
|
+
if full.is_symlink():
|
|
131
|
+
try:
|
|
132
|
+
resolved_rel = full.resolve().relative_to(repo).as_posix()
|
|
133
|
+
except Exception:
|
|
134
|
+
skipped += 1
|
|
135
|
+
continue
|
|
136
|
+
if is_ignored(resolved_rel, extra_excludes, gi_rules, extra_includes):
|
|
137
|
+
skipped += 1
|
|
138
|
+
continue
|
|
139
|
+
if full.suffix.lower() not in SUPPORTED_EXTS and fname.lower() not in SUPPORTED_BASENAMES:
|
|
140
|
+
skipped += 1
|
|
141
|
+
continue
|
|
142
|
+
try:
|
|
143
|
+
st = full.stat()
|
|
144
|
+
if not stat.S_ISREG(st.st_mode) or st.st_size > max_bytes:
|
|
145
|
+
skipped += 1
|
|
146
|
+
continue
|
|
147
|
+
raw = full.read_bytes()
|
|
148
|
+
except OSError:
|
|
149
|
+
skipped += 1
|
|
150
|
+
continue
|
|
151
|
+
if is_binary_bytes(raw):
|
|
152
|
+
skipped += 1
|
|
153
|
+
continue
|
|
154
|
+
|
|
155
|
+
digest = hashlib.sha256(raw).hexdigest()
|
|
156
|
+
seen.add(rel)
|
|
157
|
+
old = db.execute("SELECT sha FROM files WHERE path=?", (rel,)).fetchone()
|
|
158
|
+
if old and old[0] == digest and not force:
|
|
159
|
+
unchanged += 1
|
|
160
|
+
continue
|
|
161
|
+
|
|
162
|
+
content = redact_secrets(raw.decode("utf-8", errors="replace"))
|
|
163
|
+
lang = full.suffix.lower().lstrip(".") or full.name.lower()
|
|
164
|
+
line_count = content.count("\n") + (1 if content and not content.endswith("\n") else 0)
|
|
165
|
+
syms, raw_imports, summary = extract_file_metadata(content, lang)
|
|
166
|
+
raw_calls = extract_calls(content, lang, syms)
|
|
167
|
+
|
|
168
|
+
if old or force:
|
|
169
|
+
db.execute("DELETE FROM symbols WHERE path=?", (rel,))
|
|
170
|
+
if not force:
|
|
171
|
+
db.execute("DELETE FROM calls WHERE src_path=?", (rel,))
|
|
172
|
+
dedup_imps = list(dict.fromkeys(i for i, _ in raw_imports))
|
|
173
|
+
db.execute(
|
|
174
|
+
"INSERT OR REPLACE INTO files(path, sha, size, lines, tokens_est, mtime, language, summary, imports_json, content) VALUES(?,?,?,?,?,?,?,?,?,?)",
|
|
175
|
+
(rel, digest, len(raw), line_count, estimate_tokens(content), st.st_mtime, lang, summary, json.dumps(dedup_imps, ensure_ascii=False), content),
|
|
176
|
+
)
|
|
177
|
+
if syms:
|
|
178
|
+
db.executemany("INSERT INTO symbols(path, name, qualified_name, kind, line, end_line, signature, doc) VALUES(?,?,?,?,?,?,?,?)", [(rel, *s) for s in syms])
|
|
179
|
+
if raw_calls:
|
|
180
|
+
db.executemany("INSERT INTO calls(src_path, src_symbol, callee_name, dst_path, dst_symbol, line) VALUES(?,?,?,NULL,NULL,?)", [(rel, sq, cn, ln) for sq, cn, ln in raw_calls])
|
|
181
|
+
if has_fts:
|
|
182
|
+
if old and not force:
|
|
183
|
+
db.execute("DELETE FROM files_fts WHERE path=?", (rel,))
|
|
184
|
+
db.execute("DELETE FROM symbols_fts WHERE path=?", (rel,))
|
|
185
|
+
sym_text = " ".join(f"{s[0]} {s[1]} {s[5]}" for s in syms)
|
|
186
|
+
file_ident = split_identifier_tokens(f"{rel} {sym_text} {content}", max_tokens=600)
|
|
187
|
+
db.execute("INSERT INTO files_fts(path, summary, symbols_text, content, ident_tokens) VALUES(?,?,?,?,?)", (rel, summary, sym_text, content, file_ident))
|
|
188
|
+
if syms:
|
|
189
|
+
db.executemany(
|
|
190
|
+
"INSERT INTO symbols_fts(path, name, qualified_name, kind, signature, doc, ident_tokens) VALUES(?,?,?,?,?,?,?)",
|
|
191
|
+
[(rel, s[0], s[1], s[2], s[5], s[6], split_identifier_tokens(f"{s[0]} {s[1]} {s[5]}", max_tokens=60)) for s in syms],
|
|
192
|
+
)
|
|
193
|
+
changed += 1
|
|
194
|
+
changed_paths.add(rel)
|
|
195
|
+
|
|
196
|
+
removed = {r[0] for r in db.execute("SELECT path FROM files")} - seen
|
|
197
|
+
for rel in removed:
|
|
198
|
+
db.execute("DELETE FROM files WHERE path=?", (rel,))
|
|
199
|
+
db.execute("DELETE FROM symbols WHERE path=?", (rel,))
|
|
200
|
+
db.execute("DELETE FROM edges WHERE src_path=? OR dst_path=?", (rel, rel))
|
|
201
|
+
db.execute("DELETE FROM calls WHERE src_path=? OR dst_path=?", (rel, rel))
|
|
202
|
+
if has_fts:
|
|
203
|
+
db.execute("DELETE FROM files_fts WHERE path=?", (rel,))
|
|
204
|
+
db.execute("DELETE FROM symbols_fts WHERE path=?", (rel,))
|
|
205
|
+
|
|
206
|
+
if changed > 0 or removed or force:
|
|
207
|
+
ws_aliases = load_workspace_aliases(repo, seen)
|
|
208
|
+
stem_idx: Dict[str, List[str]] = defaultdict(list)
|
|
209
|
+
for p in seen:
|
|
210
|
+
if Path(p).suffix.lower() in CODE_EXTS:
|
|
211
|
+
stem_idx[Path(p).stem].append(p)
|
|
212
|
+
db.execute("DELETE FROM edges")
|
|
213
|
+
for p, imp_json in db.execute("SELECT path, imports_json FROM files").fetchall():
|
|
214
|
+
try:
|
|
215
|
+
imps = json.loads(imp_json)
|
|
216
|
+
except Exception:
|
|
217
|
+
imps = []
|
|
218
|
+
batch, seen_e = [], set()
|
|
219
|
+
resolved_map: List[Tuple[str, Optional[str]]] = [(raw_imp, resolve_import_edge(p, raw_imp, seen, stem_idx, workspace_aliases=ws_aliases)) for raw_imp in imps]
|
|
220
|
+
unresolved_roots = {raw_imp for raw_imp, dst in resolved_map if dst is None and "." not in raw_imp}
|
|
221
|
+
for raw_imp, dst in resolved_map:
|
|
222
|
+
if dst is None and "." in raw_imp and raw_imp.split(".", 1)[0] in unresolved_roots:
|
|
223
|
+
continue
|
|
224
|
+
key = (dst if dst is not None else raw_imp, dst)
|
|
225
|
+
if key not in seen_e:
|
|
226
|
+
seen_e.add(key)
|
|
227
|
+
batch.append((p, raw_imp, dst, "import"))
|
|
228
|
+
if batch:
|
|
229
|
+
db.executemany("INSERT INTO edges(src_path, dst_raw, dst_path, kind) VALUES(?,?,?,?)", batch)
|
|
230
|
+
_resolve_call_targets(db, changed_paths, rebuild_all=True)
|
|
231
|
+
|
|
232
|
+
total_files = db.execute("SELECT COUNT(*) FROM files").fetchone()[0]
|
|
233
|
+
total_symbols = db.execute("SELECT COUNT(*) FROM symbols").fetchone()[0]
|
|
234
|
+
total_edges = db.execute("SELECT COUNT(*) FROM edges WHERE dst_path IS NOT NULL").fetchone()[0]
|
|
235
|
+
total_calls = db.execute("SELECT COUNT(*) FROM calls WHERE dst_path IS NOT NULL").fetchone()[0]
|
|
236
|
+
total_tokens = db.execute("SELECT COALESCE(SUM(tokens_est), 0) FROM files").fetchone()[0]
|
|
237
|
+
db.execute("INSERT OR REPLACE INTO meta(key, value) VALUES ('repo_root', ?)", (str(repo),))
|
|
238
|
+
db.execute("INSERT OR REPLACE INTO meta(key, value) VALUES ('last_indexed_at', ?)", (time.strftime("%Y-%m-%dT%H:%M:%S%z"),))
|
|
239
|
+
db.execute("INSERT OR REPLACE INTO meta(key, value) VALUES ('total_tokens_est', ?)", (str(total_tokens),))
|
|
240
|
+
try:
|
|
241
|
+
r_hd = git_cmd(repo, ["rev-parse", "--short", "HEAD"])
|
|
242
|
+
if r_hd.returncode == 0 and r_hd.stdout.strip():
|
|
243
|
+
db.execute("INSERT OR REPLACE INTO meta(key, value) VALUES ('git_head', ?)", (sanitize_inline(r_hd.stdout),))
|
|
244
|
+
except Exception:
|
|
245
|
+
pass
|
|
246
|
+
db.commit()
|
|
247
|
+
|
|
248
|
+
map_path = idx_dir / "PROJECT_MAP.md"
|
|
249
|
+
assert_not_symlink_artifact(map_path, repo)
|
|
250
|
+
map_updated = False
|
|
251
|
+
if changed > 0 or removed or force or not map_path.exists() or map_budget_tokens is not None:
|
|
252
|
+
map_text = build_project_map(repo, db, budget_tokens=eff_budget)
|
|
253
|
+
if not map_path.exists() or map_path.read_text(encoding="utf-8") != map_text:
|
|
254
|
+
atomic_write_text(map_path, map_text)
|
|
255
|
+
map_updated = True
|
|
256
|
+
|
|
257
|
+
if not cfg_path.exists() and not cfg_path.is_symlink():
|
|
258
|
+
atomic_write_text(cfg_path, json.dumps(cfg, indent=2) + "\n")
|
|
259
|
+
finally:
|
|
260
|
+
db.close()
|
|
261
|
+
|
|
262
|
+
return {
|
|
263
|
+
"indexed": total_files, "symbols": total_symbols, "resolved_edges": total_edges,
|
|
264
|
+
"resolved_calls": total_calls, "total_tokens_est": total_tokens, "changed": changed,
|
|
265
|
+
"unchanged": unchanged, "removed": len(removed), "skipped": skipped,
|
|
266
|
+
"fts5_enabled": has_fts, "git_excluded": git_excluded,
|
|
267
|
+
"map_updated": map_updated, "map_path": str(map_path),
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def run_watch(repo: Path, debounce: float = 0.5) -> None:
|
|
272
|
+
try:
|
|
273
|
+
from watchdog.events import FileSystemEventHandler
|
|
274
|
+
from watchdog.observers import Observer
|
|
275
|
+
except ImportError:
|
|
276
|
+
raise SystemExit("Install optional watcher dependency: pip install watchdog")
|
|
277
|
+
|
|
278
|
+
cfg = load_repo_config(repo)
|
|
279
|
+
extra = list(cfg.get("exclude", []))
|
|
280
|
+
extra_inc = list(cfg.get("include", []))
|
|
281
|
+
gi = load_gitignore_rules(repo) if cfg.get("use_gitignore", True) else []
|
|
282
|
+
timer_lock, reindex_lock = threading.Lock(), threading.Lock()
|
|
283
|
+
timer_holder: List[Optional[threading.Timer]] = [None]
|
|
284
|
+
|
|
285
|
+
def trigger() -> None:
|
|
286
|
+
with timer_lock:
|
|
287
|
+
timer_holder[0] = None
|
|
288
|
+
with reindex_lock:
|
|
289
|
+
res = index(repo)
|
|
290
|
+
if res["changed"] or res["removed"]:
|
|
291
|
+
print(json.dumps({"event": "reindexed", "changed": res["changed"], "removed": res["removed"]}), flush=True)
|
|
292
|
+
|
|
293
|
+
def matches(raw_p: Optional[str]) -> bool:
|
|
294
|
+
if not raw_p:
|
|
295
|
+
return False
|
|
296
|
+
try:
|
|
297
|
+
rel = Path(raw_p).resolve().relative_to(repo).as_posix()
|
|
298
|
+
except Exception:
|
|
299
|
+
return False
|
|
300
|
+
return not is_ignored(rel, extra, gi, extra_inc)
|
|
301
|
+
|
|
302
|
+
class Handler(FileSystemEventHandler):
|
|
303
|
+
def on_any_event(self, event: Any) -> None:
|
|
304
|
+
if getattr(event, "is_directory", False):
|
|
305
|
+
return
|
|
306
|
+
if not (matches(getattr(event, "src_path", None)) or matches(getattr(event, "dest_path", None))):
|
|
307
|
+
return
|
|
308
|
+
with timer_lock:
|
|
309
|
+
if timer_holder[0] is not None:
|
|
310
|
+
timer_holder[0].cancel()
|
|
311
|
+
t = threading.Timer(debounce, trigger)
|
|
312
|
+
t.daemon = True
|
|
313
|
+
timer_holder[0] = t
|
|
314
|
+
t.start()
|
|
315
|
+
|
|
316
|
+
print(json.dumps(index(repo)), flush=True)
|
|
317
|
+
obs = Observer()
|
|
318
|
+
obs.schedule(Handler(), str(repo), recursive=True)
|
|
319
|
+
obs.start()
|
|
320
|
+
print(f"Watching {repo} (debounce={debounce}s); Ctrl+C to stop.", file=sys.stderr, flush=True)
|
|
321
|
+
try:
|
|
322
|
+
while True:
|
|
323
|
+
time.sleep(1)
|
|
324
|
+
except KeyboardInterrupt:
|
|
325
|
+
with timer_lock:
|
|
326
|
+
if timer_holder[0] is not None:
|
|
327
|
+
timer_holder[0].cancel()
|
|
328
|
+
timer_holder[0] = None
|
|
329
|
+
obs.stop()
|
|
330
|
+
obs.join()
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"""Optional zero-dependency stdio LSP (Language Server Protocol) bridge for semantic reference lookup.
|
|
2
|
+
|
|
3
|
+
Talks JSON-RPC 2.0 (`Content-Length` framed) over stdin/stdout to locally installed language servers
|
|
4
|
+
(`typescript-language-server`, `pyright-langserver`, `pylsp`, `rust-analyzer`, `gopls`).
|
|
5
|
+
Strictly optional: gracefully reports `available=False` and lets callers fall back to the local SQLite index.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import shutil
|
|
12
|
+
import subprocess
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any, Dict, List, Optional, Sequence, Tuple
|
|
15
|
+
from urllib.parse import unquote, urlparse
|
|
16
|
+
|
|
17
|
+
from _ae_core import is_within, normalize_rel_path
|
|
18
|
+
|
|
19
|
+
# Ordered preference per language extension group
|
|
20
|
+
LSP_SERVER_SPECS: Dict[str, Tuple[str, List[Tuple[str, List[str]]]]] = {
|
|
21
|
+
"ts": ("typescript", [("typescript-language-server", ["--stdio"]), ("vtsls", ["--stdio"])]),
|
|
22
|
+
"tsx": ("typescriptreact", [("typescript-language-server", ["--stdio"]), ("vtsls", ["--stdio"])]),
|
|
23
|
+
"js": ("javascript", [("typescript-language-server", ["--stdio"]), ("vtsls", ["--stdio"])]),
|
|
24
|
+
"jsx": ("javascriptreact", [("typescript-language-server", ["--stdio"]), ("vtsls", ["--stdio"])]),
|
|
25
|
+
"mjs": ("javascript", [("typescript-language-server", ["--stdio"])]),
|
|
26
|
+
"cjs": ("javascript", [("typescript-language-server", ["--stdio"])]),
|
|
27
|
+
"py": ("python", [("pyright-langserver", ["--stdio"]), ("basedpyright-langserver", ["--stdio"]), ("pylsp", [])]),
|
|
28
|
+
"pyi": ("python", [("pyright-langserver", ["--stdio"]), ("basedpyright-langserver", ["--stdio"]), ("pylsp", [])]),
|
|
29
|
+
"rs": ("rust", [("rust-analyzer", [])]),
|
|
30
|
+
"go": ("go", [("gopls", ["serve"])]),
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def resolve_lsp_command(lang_ext: str, override_cmd: Optional[Sequence[str]] = None) -> Tuple[Optional[str], List[str]]:
|
|
35
|
+
"""Resolve `(language_id, argv)` for an extension, or `(None, [])` if no local LSP server is installed."""
|
|
36
|
+
lang_id = LSP_SERVER_SPECS.get(lang_ext.lower(), ("plaintext", []))[0]
|
|
37
|
+
if override_cmd:
|
|
38
|
+
return lang_id, list(override_cmd)
|
|
39
|
+
spec = LSP_SERVER_SPECS.get(lang_ext.lower())
|
|
40
|
+
if not spec:
|
|
41
|
+
return None, []
|
|
42
|
+
for exe, extra in spec[1]:
|
|
43
|
+
found = shutil.which(exe)
|
|
44
|
+
if found:
|
|
45
|
+
return lang_id, [found, *extra]
|
|
46
|
+
return None, []
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _uri_to_relpath(repo: Path, uri: str) -> Optional[str]:
|
|
50
|
+
if not uri.startswith("file://"):
|
|
51
|
+
return None
|
|
52
|
+
parsed = urlparse(uri)
|
|
53
|
+
raw_path = unquote(parsed.path)
|
|
54
|
+
# Handle Windows `/C:/...` URI path
|
|
55
|
+
if os.name == "nt" and len(raw_path) >= 3 and raw_path[0] == "/" and raw_path[2] == ":":
|
|
56
|
+
raw_path = raw_path[1:]
|
|
57
|
+
try:
|
|
58
|
+
resolved = Path(raw_path).resolve()
|
|
59
|
+
if not is_within(resolved, repo):
|
|
60
|
+
return None
|
|
61
|
+
return normalize_rel_path(resolved.relative_to(repo).as_posix())
|
|
62
|
+
except Exception:
|
|
63
|
+
return None
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _write_lsp_msg(stream: Any, payload: Dict[str, Any]) -> None:
|
|
67
|
+
raw = json.dumps(payload, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
|
|
68
|
+
header = f"Content-Length: {len(raw)}\r\n\r\n".encode("ascii")
|
|
69
|
+
stream.write(header + raw)
|
|
70
|
+
stream.flush()
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _read_lsp_msg(stream: Any) -> Optional[Dict[str, Any]]:
|
|
74
|
+
headers: Dict[str, str] = {}
|
|
75
|
+
while True:
|
|
76
|
+
line = stream.readline()
|
|
77
|
+
if not line:
|
|
78
|
+
return None
|
|
79
|
+
s = line.decode("ascii", errors="replace").strip()
|
|
80
|
+
if not s:
|
|
81
|
+
if headers:
|
|
82
|
+
break
|
|
83
|
+
continue
|
|
84
|
+
if ":" in s:
|
|
85
|
+
k, v = s.split(":", 1)
|
|
86
|
+
headers[k.strip().lower()] = v.strip()
|
|
87
|
+
length = int(headers.get("content-length", "0"))
|
|
88
|
+
if length <= 0:
|
|
89
|
+
return None
|
|
90
|
+
body = stream.read(length)
|
|
91
|
+
if not body:
|
|
92
|
+
return None
|
|
93
|
+
return json.loads(body.decode("utf-8", errors="replace"))
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _wait_for_response(stdout: Any, req_id: int, max_messages: int = 80) -> Optional[Dict[str, Any]]:
|
|
97
|
+
"""Read LSP messages until response matching `req_id` arrives (skipping server notifications)."""
|
|
98
|
+
for _ in range(max_messages):
|
|
99
|
+
msg = _read_lsp_msg(stdout)
|
|
100
|
+
if msg is None:
|
|
101
|
+
return None
|
|
102
|
+
if msg.get("id") == req_id and ("result" in msg or "error" in msg):
|
|
103
|
+
return msg
|
|
104
|
+
return None
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def query_lsp_references(
|
|
108
|
+
repo: Path,
|
|
109
|
+
rel_path: str,
|
|
110
|
+
line_1based: int,
|
|
111
|
+
character_0based: int,
|
|
112
|
+
*,
|
|
113
|
+
timeout_s: float = 8.0,
|
|
114
|
+
server_cmd: Optional[Sequence[str]] = None,
|
|
115
|
+
) -> Dict[str, Any]:
|
|
116
|
+
"""Query `textDocument/references` from an installed LSP server and return normalized in-repo locations."""
|
|
117
|
+
repo_r = repo.resolve()
|
|
118
|
+
rel = normalize_rel_path(rel_path)
|
|
119
|
+
target_file = (repo_r / rel).resolve()
|
|
120
|
+
if not target_file.is_file() or not is_within(target_file, repo_r):
|
|
121
|
+
return {"available": False, "reason": f"Target file not readable inside repo: {rel}", "locations": []}
|
|
122
|
+
|
|
123
|
+
ext = target_file.suffix.lower().lstrip(".")
|
|
124
|
+
lang_id, argv = resolve_lsp_command(ext, override_cmd=server_cmd)
|
|
125
|
+
if not argv or not lang_id:
|
|
126
|
+
return {
|
|
127
|
+
"available": False,
|
|
128
|
+
"reason": f"No local LSP server installed for '.{ext}' (install e.g. typescript-language-server, pyright-langserver, rust-analyzer, or gopls).",
|
|
129
|
+
"locations": [],
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
text = target_file.read_text(encoding="utf-8", errors="replace")
|
|
133
|
+
root_uri = repo_r.as_uri()
|
|
134
|
+
doc_uri = target_file.as_uri()
|
|
135
|
+
|
|
136
|
+
try:
|
|
137
|
+
proc = subprocess.Popen(
|
|
138
|
+
argv,
|
|
139
|
+
cwd=str(repo_r),
|
|
140
|
+
stdin=subprocess.PIPE,
|
|
141
|
+
stdout=subprocess.PIPE,
|
|
142
|
+
stderr=subprocess.PIPE,
|
|
143
|
+
)
|
|
144
|
+
except OSError as exc:
|
|
145
|
+
return {"available": False, "reason": f"Failed to start LSP server ({argv[0]}): {exc}", "locations": []}
|
|
146
|
+
|
|
147
|
+
assert proc.stdin and proc.stdout
|
|
148
|
+
locations: List[Dict[str, Any]] = []
|
|
149
|
+
try:
|
|
150
|
+
_write_lsp_msg(proc.stdin, {
|
|
151
|
+
"jsonrpc": "2.0",
|
|
152
|
+
"id": 1,
|
|
153
|
+
"method": "initialize",
|
|
154
|
+
"params": {
|
|
155
|
+
"processId": os.getpid(),
|
|
156
|
+
"rootUri": root_uri,
|
|
157
|
+
"capabilities": {"textDocument": {"references": {"dynamicRegistration": False}}},
|
|
158
|
+
},
|
|
159
|
+
})
|
|
160
|
+
init_resp = _wait_for_response(proc.stdout, 1)
|
|
161
|
+
if not init_resp or "error" in init_resp:
|
|
162
|
+
return {"available": False, "server": Path(argv[0]).name, "reason": "LSP initialize failed", "locations": []}
|
|
163
|
+
|
|
164
|
+
_write_lsp_msg(proc.stdin, {"jsonrpc": "2.0", "method": "initialized", "params": {}})
|
|
165
|
+
_write_lsp_msg(proc.stdin, {
|
|
166
|
+
"jsonrpc": "2.0",
|
|
167
|
+
"method": "textDocument/didOpen",
|
|
168
|
+
"params": {
|
|
169
|
+
"textDocument": {"uri": doc_uri, "languageId": lang_id, "version": 1, "text": text},
|
|
170
|
+
},
|
|
171
|
+
})
|
|
172
|
+
_write_lsp_msg(proc.stdin, {
|
|
173
|
+
"jsonrpc": "2.0",
|
|
174
|
+
"id": 2,
|
|
175
|
+
"method": "textDocument/references",
|
|
176
|
+
"params": {
|
|
177
|
+
"textDocument": {"uri": doc_uri},
|
|
178
|
+
"position": {"line": max(0, line_1based - 1), "character": max(0, character_0based)},
|
|
179
|
+
"context": {"includeDeclaration": False},
|
|
180
|
+
},
|
|
181
|
+
})
|
|
182
|
+
ref_resp = _wait_for_response(proc.stdout, 2)
|
|
183
|
+
raw_locs = (ref_resp or {}).get("result") or []
|
|
184
|
+
seen: set[Tuple[str, int]] = set()
|
|
185
|
+
for loc in raw_locs if isinstance(raw_locs, list) else []:
|
|
186
|
+
if not isinstance(loc, dict):
|
|
187
|
+
continue
|
|
188
|
+
uri = str(loc.get("uri") or loc.get("targetUri") or "")
|
|
189
|
+
rng = loc.get("range") or loc.get("targetSelectionRange") or {}
|
|
190
|
+
start = rng.get("start") if isinstance(rng, dict) else {}
|
|
191
|
+
ln_1 = int(start.get("line", 0)) + 1 if isinstance(start, dict) else 1
|
|
192
|
+
rel_hit = _uri_to_relpath(repo_r, uri)
|
|
193
|
+
if rel_hit and (rel_hit, ln_1) not in seen:
|
|
194
|
+
seen.add((rel_hit, ln_1))
|
|
195
|
+
locations.append({"path": rel_hit, "line": ln_1})
|
|
196
|
+
|
|
197
|
+
_write_lsp_msg(proc.stdin, {"jsonrpc": "2.0", "id": 3, "method": "shutdown", "params": None})
|
|
198
|
+
_write_lsp_msg(proc.stdin, {"jsonrpc": "2.0", "method": "exit", "params": None})
|
|
199
|
+
return {"available": True, "server": Path(argv[0]).name, "locations": locations}
|
|
200
|
+
except Exception as exc:
|
|
201
|
+
return {"available": False, "server": Path(argv[0]).name, "reason": f"LSP query error: {exc}", "locations": []}
|
|
202
|
+
finally:
|
|
203
|
+
for stream in (proc.stdin, proc.stdout, proc.stderr):
|
|
204
|
+
if stream:
|
|
205
|
+
try:
|
|
206
|
+
stream.close()
|
|
207
|
+
except Exception:
|
|
208
|
+
pass
|
|
209
|
+
try:
|
|
210
|
+
proc.wait(timeout=min(2.0, timeout_s))
|
|
211
|
+
except subprocess.TimeoutExpired:
|
|
212
|
+
proc.kill()
|
|
213
|
+
proc.wait(timeout=1.0)
|