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.
Files changed (64) hide show
  1. agent_efficiency/__init__.py +15 -0
  2. agent_efficiency/_bundle/mcp/server.py +519 -0
  3. agent_efficiency/_bundle/rules/AGENT_RULES.md +9 -0
  4. agent_efficiency/_bundle/scripts/ae_cli.py +327 -0
  5. agent_efficiency/_bundle/scripts/ae_init.py +267 -0
  6. agent_efficiency/_bundle/scripts/ae_manage.py +578 -0
  7. agent_efficiency/_bundle/scripts/install.py +308 -0
  8. agent_efficiency/_bundle/scripts/pretool_hook.py +350 -0
  9. agent_efficiency/_bundle/scripts/render_demo_svg.py +180 -0
  10. agent_efficiency/_bundle/scripts/setup_hooks.py +330 -0
  11. agent_efficiency/_bundle/scripts/sync_shared.py +85 -0
  12. agent_efficiency/_bundle/scripts/validate_skills.py +150 -0
  13. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/SKILL.md +80 -0
  14. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/config/models.json +237 -0
  15. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/examples/workflow.md +77 -0
  16. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/references/routing-and-escalation.md +63 -0
  17. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/references/state-and-handoff.md +84 -0
  18. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/__init__.py +90 -0
  19. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/io_lock.py +199 -0
  20. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/savings.py +249 -0
  21. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/security.py +235 -0
  22. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/usage.py +195 -0
  23. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/agent_state.py +266 -0
  24. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/context_doctor.py +780 -0
  25. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/llm_adapter.py +306 -0
  26. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/route_task.py +496 -0
  27. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/state_ops.py +580 -0
  28. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/state_render.py +428 -0
  29. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/state_store.py +440 -0
  30. agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/transcript_audit.py +854 -0
  31. agent_efficiency/_bundle/skills/local-context-index/SKILL.md +71 -0
  32. agent_efficiency/_bundle/skills/local-context-index/references/cli-reference.md +112 -0
  33. agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/__init__.py +90 -0
  34. agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/io_lock.py +199 -0
  35. agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/savings.py +249 -0
  36. agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/security.py +235 -0
  37. agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/usage.py +195 -0
  38. agent_efficiency/_bundle/skills/local-context-index/scripts/compact_run.py +395 -0
  39. agent_efficiency/_bundle/skills/local-context-index/scripts/context_index.py +341 -0
  40. agent_efficiency/_bundle/skills/local-context-index/scripts/idx_db.py +393 -0
  41. agent_efficiency/_bundle/skills/local-context-index/scripts/idx_ignore.py +184 -0
  42. agent_efficiency/_bundle/skills/local-context-index/scripts/idx_indexer.py +330 -0
  43. agent_efficiency/_bundle/skills/local-context-index/scripts/idx_lsp.py +213 -0
  44. agent_efficiency/_bundle/skills/local-context-index/scripts/idx_parsers.py +769 -0
  45. agent_efficiency/_bundle/skills/local-context-index/scripts/idx_search.py +498 -0
  46. agent_efficiency/_bundle/skills/local-context-index/scripts/idx_slice.py +610 -0
  47. agent_efficiency/_bundle/skills/local-context-index/scripts/idx_trace.py +553 -0
  48. agent_efficiency/_bundle/skills/local-context-index/scripts/idx_workspace.py +219 -0
  49. agent_efficiency/_bundle/skills/prompt-cache-manager/SKILL.md +52 -0
  50. agent_efficiency/_bundle/skills/prompt-cache-manager/references/provider-caching.md +52 -0
  51. agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/__init__.py +90 -0
  52. agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/io_lock.py +199 -0
  53. agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/savings.py +249 -0
  54. agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/security.py +235 -0
  55. agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/usage.py +195 -0
  56. agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/cache_payload.py +278 -0
  57. agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/prompt_cache.py +488 -0
  58. agent_efficiency/cli.py +23 -0
  59. agent_efficiency/mcp_entry.py +25 -0
  60. agent_efficiency-1.4.2.dist-info/METADATA +267 -0
  61. agent_efficiency-1.4.2.dist-info/RECORD +64 -0
  62. agent_efficiency-1.4.2.dist-info/WHEEL +4 -0
  63. agent_efficiency-1.4.2.dist-info/entry_points.txt +4 -0
  64. agent_efficiency-1.4.2.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,498 @@
1
+ """FTS5 BM25 hybrid search (Unicode-aware), symbol lookup, references, dependency blast radius & git delta."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import re
6
+ import sqlite3
7
+ from collections import defaultdict
8
+ from pathlib import Path
9
+ from typing import Any, Dict, List, Optional, Sequence, Set, Tuple
10
+
11
+ from _ae_core import estimate_tokens, git_cmd, normalize_rel_path, redact_secrets, sanitize_inline
12
+ from idx_db import db_open, split_identifier_tokens
13
+
14
+ _GIT_REF_RE = re.compile(r"^[A-Za-z0-9._/@^~:{}-]+$")
15
+ _INTERNAL_ARTIFACT_PREFIXES = (".agent-index/", ".agent-state/", ".agent-index", ".agent-state")
16
+
17
+
18
+ def _escape_like(value: str) -> str:
19
+ return value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
20
+
21
+
22
+ def tokenize_query(query: str, max_terms: int = 24) -> List[str]:
23
+ """Unicode-aware query tokenizer preserving underscores/dots/hyphens and expanding CamelCase/snake_case parts."""
24
+ raw = re.findall(r"[\w.-]+", query, flags=re.UNICODE)
25
+ expanded: List[str] = []
26
+ for tok in raw:
27
+ clean = tok.strip(".-")
28
+ if not clean:
29
+ continue
30
+ expanded.append(clean.lower())
31
+ split_parts = split_identifier_tokens(clean, max_tokens=8).split()
32
+ for sp in split_parts:
33
+ if sp != clean.lower():
34
+ expanded.append(sp)
35
+ filtered = [t for t in expanded if len(t) > 1] or expanded
36
+ out, seen = [], set()
37
+ for t in filtered:
38
+ if t not in seen:
39
+ seen.add(t)
40
+ out.append(t)
41
+ if len(out) >= max_terms:
42
+ break
43
+ return out
44
+
45
+
46
+ def _build_fts_query(terms: Sequence[str]) -> str:
47
+ clauses = []
48
+ for t in terms:
49
+ parts = [p for p in re.split(r"[^\w]+", t, flags=re.UNICODE) if p]
50
+ if len(parts) == 1:
51
+ clauses.append(f'"{parts[0]}"*')
52
+ elif len(parts) > 1:
53
+ clauses.append("(" + " ".join(f'"{p}"' for p in parts[:-1]) + f' "{parts[-1]}"*)')
54
+ return " OR ".join(clauses)
55
+
56
+
57
+ def _extract_snippets(content: str, terms: Sequence[str], max_snippets: int = 2, ctx: int = 2, max_chars: int = 360) -> List[Dict[str, Any]]:
58
+ lines, snippets, covered = content.splitlines(), [], set()
59
+ low_t = [t.lower() for t in terms]
60
+ for i, line in enumerate(lines):
61
+ if any(t in line.lower() for t in low_t) and i not in covered:
62
+ lo, hi = max(0, i - ctx), min(len(lines), i + ctx + 1)
63
+ covered.update(range(lo, hi))
64
+ txt = redact_secrets("\n".join(f"{ln + 1}: {lines[ln]}" for ln in range(lo, hi)))
65
+ if len(txt) > max_chars:
66
+ txt = txt[:max_chars] + "\n... [truncated]"
67
+ snippets.append({"start_line": lo + 1, "end_line": hi, "text": txt})
68
+ if len(snippets) >= max_snippets:
69
+ break
70
+ return snippets
71
+
72
+
73
+ def _filter_sql(lang: Optional[str], path_prefix: Optional[str], alias: str = "f") -> Tuple[str, List[Any]]:
74
+ clauses, params = [], []
75
+ if lang:
76
+ clauses.append(f"{alias}.language = ?")
77
+ params.append(lang.lower().lstrip("."))
78
+ if path_prefix:
79
+ np = normalize_rel_path(path_prefix).rstrip("/")
80
+ if np:
81
+ clauses.append(f"({alias}.path = ? OR {alias}.path LIKE ? ESCAPE '\\')")
82
+ params.extend([np, f"{_escape_like(np)}/%"])
83
+ return " AND ".join(clauses), params
84
+
85
+
86
+ def search(repo: Path, query: str, limit: int = 8, lang: Optional[str] = None, path_prefix: Optional[str] = None, max_tokens: Optional[int] = None) -> List[Dict[str, Any]]:
87
+ terms = tokenize_query(query)
88
+ if not terms:
89
+ return []
90
+ db, has_fts = db_open(repo.resolve(), read_only=True)
91
+ scores: Dict[str, float] = defaultdict(float)
92
+ fsql, fparams = _filter_sql(lang, path_prefix, "f")
93
+ and_f = f" AND {fsql}" if fsql else ""
94
+ fts_q = _build_fts_query(terms)
95
+
96
+ if has_fts and fts_q:
97
+ try:
98
+ f_cols = {r[1] for r in db.execute("PRAGMA table_info(files_fts)")}
99
+ s_cols = {r[1] for r in db.execute("PRAGMA table_info(symbols_fts)")}
100
+ except sqlite3.OperationalError:
101
+ f_cols, s_cols = set(), set()
102
+ f_bm25 = "bm25(files_fts, 8.0, 4.0, 5.0, 1.0, 4.5)" if "ident_tokens" in f_cols else "bm25(files_fts, 8.0, 4.0, 5.0, 1.0)"
103
+ s_bm25 = "bm25(symbols_fts, 1.0, 8.0, 6.0, 1.0, 3.0, 2.0, 6.0)" if "ident_tokens" in s_cols else "bm25(symbols_fts, 1.0, 8.0, 6.0, 1.0, 3.0, 2.0)"
104
+ try:
105
+ for p, rk in db.execute(f"SELECT f.path, {f_bm25} AS r FROM files_fts JOIN files f ON f.path = files_fts.path WHERE files_fts MATCH ?{and_f} ORDER BY r LIMIT ?", [fts_q, *fparams, max(limit * 4, 30)]):
106
+ scores[p] += max(0.5, -float(rk))
107
+ except sqlite3.OperationalError:
108
+ pass
109
+ try:
110
+ for p, rk in db.execute(f"SELECT s.path, MIN({s_bm25}) AS r FROM symbols_fts s JOIN files f ON f.path = s.path WHERE symbols_fts MATCH ?{and_f} GROUP BY s.path ORDER BY r LIMIT ?", [fts_q, *fparams, max(limit * 4, 30)]):
111
+ scores[p] += max(1.0, -float(rk) * 1.5)
112
+ except sqlite3.OperationalError:
113
+ pass
114
+
115
+ if not scores:
116
+ where = f" WHERE {fsql}" if fsql else ""
117
+ for p, sm, ct in db.execute(f"SELECT f.path, f.summary, f.content FROM files f{where}", fparams):
118
+ hay = f"{p}\n{sm}\n{ct}".lower()
119
+ s = sum(hay.count(t) * (4.0 if t in p.lower() else 1.0) for t in terms)
120
+ if s > 0:
121
+ scores[p] += s
122
+ else:
123
+ for p in list(scores.keys()):
124
+ lp = p.lower()
125
+ scores[p] += sum(4.0 for t in terms if t in lp)
126
+
127
+ top_c = [p for p, _ in sorted(scores.items(), key=lambda kv: (-kv[1], kv[0]))[: max(limit * 4, 50)]]
128
+ if top_c:
129
+ ph = ",".join("?" for _ in top_c)
130
+ for dst, deg in db.execute(f"SELECT dst_path, COUNT(DISTINCT src_path) FROM edges WHERE dst_path IN ({ph}) GROUP BY dst_path", top_c):
131
+ scores[dst] += min(2.0, 0.25 * deg)
132
+ # Boost files whose symbol names cover multiple distinct query terms (e.g., "token refresh" -> refreshAccessToken)
133
+ if len(terms) >= 2:
134
+ for p, sname in db.execute(f"SELECT path, LOWER(name || ' ' || qualified_name) FROM symbols WHERE path IN ({ph})", top_c):
135
+ hits_in_sym = sum(1 for t in terms if t in sname)
136
+ if hits_in_sym >= 2:
137
+ scores[p] += 3.0 * hits_in_sym
138
+
139
+ results, used_tok = [], 0
140
+ for p, sc in sorted(scores.items(), key=lambda kv: (-kv[1], kv[0]))[:limit]:
141
+ row = db.execute("SELECT language, lines, tokens_est, summary, content FROM files WHERE path=?", (p,)).fetchone()
142
+ if not row:
143
+ continue
144
+ all_s = db.execute("SELECT name, kind, line, end_line, signature FROM symbols WHERE path=? ORDER BY line", (p,)).fetchall()
145
+ matched = [s for s in all_s if any(t in s[0].lower() or t in s[4].lower() for t in terms)]
146
+ chosen = (matched + [s for s in all_s if s not in matched])[:8]
147
+ entry = {
148
+ "score": round(sc, 2), "path": p, "language": row[0], "lines": row[1],
149
+ "file_tokens_est": row[2], "summary": row[3],
150
+ "symbols": [{"name": s[0], "kind": s[1], "line": s[2], "end_line": s[3], "signature": s[4]} for s in chosen],
151
+ "snippets": _extract_snippets(row[4], terms),
152
+ }
153
+ etok = estimate_tokens(json.dumps(entry, ensure_ascii=False))
154
+ if max_tokens is not None and results and (used_tok + etok) > max_tokens:
155
+ break
156
+ results.append(entry)
157
+ used_tok += etok
158
+ db.close()
159
+ return results
160
+
161
+
162
+ def list_symbols(repo: Path, pattern: str = "", path_filter: Optional[str] = None, kind_filter: Optional[str] = None, limit: int = 30) -> List[Dict[str, Any]]:
163
+ db, _ = db_open(repo.resolve(), read_only=True)
164
+ clauses, params = [], []
165
+ if pattern:
166
+ esc = f"%{_escape_like(pattern.lower())}%"
167
+ clauses.append(r"(LOWER(name) LIKE ? ESCAPE '\' OR LOWER(qualified_name) LIKE ? ESCAPE '\' OR LOWER(signature) LIKE ? ESCAPE '\')")
168
+ params.extend([esc, esc, esc])
169
+ if path_filter:
170
+ np = normalize_rel_path(path_filter).rstrip("/")
171
+ if np:
172
+ clauses.append(r"(path = ? OR path LIKE ? ESCAPE '\')")
173
+ params.extend([np, f"{_escape_like(np)}/%"])
174
+ if kind_filter:
175
+ clauses.append("kind = ?")
176
+ params.append(kind_filter)
177
+ where = f" WHERE {' AND '.join(clauses)}" if clauses else ""
178
+ rows = db.execute(f"SELECT path, name, qualified_name, kind, line, end_line, signature, doc FROM symbols{where} ORDER BY path, line LIMIT ?", params + [limit]).fetchall()
179
+ db.close()
180
+ return [{"path": r[0], "name": r[1], "qualified_name": r[2], "kind": r[3], "line": r[4], "end_line": r[5], "signature": r[6], "doc": r[7]} for r in rows]
181
+
182
+
183
+ def find_refs(repo: Path, target: str, limit: int = 25) -> Dict[str, Any]:
184
+ db, has_fts = db_open(repo.resolve(), read_only=True)
185
+ importers = [{"src_path": r[0], "dst_raw": r[1], "kind": r[2]} for r in db.execute(r"SELECT src_path, dst_raw, kind FROM edges WHERE dst_path=? OR dst_raw LIKE ? ESCAPE '\' ORDER BY src_path LIMIT ?", (target, f"%{_escape_like(target)}%", limit))]
186
+ parts = [p for p in re.split(r"[^\w]+", target, flags=re.UNICODE) if p]
187
+ candidates: List[str] = []
188
+ if has_fts and parts:
189
+ fts_p = f'"{parts[0]}"' if len(parts) == 1 else f'"{" ".join(parts)}"'
190
+ try:
191
+ candidates = [r[0] for r in db.execute("SELECT path FROM files_fts WHERE files_fts MATCH ? LIMIT ?", (fts_p, max(limit * 3, 60)))]
192
+ except sqlite3.OperationalError:
193
+ candidates = []
194
+ if not candidates:
195
+ candidates = [r[0] for r in db.execute("SELECT path FROM files ORDER BY path")]
196
+
197
+ pb, sb = (r"\b" if (target and re.match(r"^\w", target)) else ""), (r"\b" if (target and re.search(r"\w$", target)) else "")
198
+ rx = re.compile(f"{pb}{re.escape(target)}{sb}")
199
+ occs: List[Dict[str, Any]] = []
200
+ for p in candidates:
201
+ row = db.execute("SELECT content FROM files WHERE path=?", (p,)).fetchone()
202
+ if not row:
203
+ continue
204
+ for idx, line in enumerate(row[0].splitlines(), start=1):
205
+ if rx.search(line):
206
+ occs.append({"path": p, "line": idx, "text": redact_secrets(sanitize_inline(line))[:180]})
207
+ if len(occs) >= limit:
208
+ break
209
+ if len(occs) >= limit:
210
+ break
211
+ db.close()
212
+ return {"target": target, "importers": importers, "occurrences": occs, "reference_files_count": len({o["path"] for o in occs} | {i["src_path"] for i in importers})}
213
+
214
+
215
+ def file_deps(repo: Path, rel_path: str, depth: int = 1) -> Dict[str, Any]:
216
+ rel = normalize_rel_path(rel_path)
217
+ db, _ = db_open(repo.resolve(), read_only=True)
218
+
219
+ def bfs(direction: str, max_d: int) -> List[Dict[str, Any]]:
220
+ vis, front, found = {rel}, [(rel, 0)], []
221
+ while front:
222
+ curr, d = front.pop(0)
223
+ if d >= max_d:
224
+ continue
225
+ if direction == "out":
226
+ for dst, raw in db.execute("SELECT dst_path, dst_raw FROM edges WHERE src_path=?", (curr,)):
227
+ tgt = dst or f"external:{raw}"
228
+ if tgt not in vis:
229
+ vis.add(tgt)
230
+ found.append({"path": tgt, "resolved": dst is not None, "depth": d + 1, "via": curr})
231
+ if dst is not None:
232
+ front.append((dst, d + 1))
233
+ else:
234
+ for (src,) in db.execute("SELECT src_path FROM edges WHERE dst_path=?", (curr,)):
235
+ if src not in vis:
236
+ vis.add(src)
237
+ found.append({"path": src, "resolved": True, "depth": d + 1, "via": curr})
238
+ front.append((src, d + 1))
239
+ return found
240
+
241
+ out, inc = bfs("out", max(1, depth)), bfs("in", max(1, depth))
242
+ db.close()
243
+ return {"path": rel, "depth": max(1, depth), "imports": out, "imported_by": inc, "blast_radius_dependents": len(inc)}
244
+
245
+
246
+ def format_compact_deps(deps: Dict[str, Any]) -> str:
247
+ out = [f"{deps['path']} (depth={deps['depth']}, blast_radius_dependents={deps['blast_radius_dependents']})"]
248
+ internal_out = [i["path"] for i in deps["imports"] if i["resolved"]]
249
+ external_out = [i["path"].removeprefix("external:") if hasattr(str, "removeprefix") else i["path"].replace("external:", "", 1) for i in deps["imports"] if not i["resolved"]]
250
+ if internal_out:
251
+ out.append(f" imports (internal): {', '.join(internal_out[:15])}")
252
+ if external_out:
253
+ out.append(f" imports (external): {', '.join(external_out[:15])}")
254
+ if deps["imported_by"]:
255
+ out.append(f" imported_by: {', '.join(i['path'] for i in deps['imported_by'][:20])}")
256
+ return "\n".join(out)
257
+
258
+
259
+ def _unquote_git_path(raw: str) -> str:
260
+ s = raw.strip()
261
+ if len(s) >= 2 and s[0] == '"' and s[-1] == '"':
262
+ s = s[1:-1].replace('\\"', '"').replace("\\\\", "\\")
263
+ return s
264
+
265
+
266
+ def _is_internal_artifact(p: str) -> bool:
267
+ norm = p.replace("\\", "/")
268
+ while norm.startswith("./"):
269
+ norm = norm[2:]
270
+ norm = norm.rstrip("/")
271
+ return norm in (".agent-index", ".agent-state") or norm.startswith((".agent-index/", ".agent-state/"))
272
+
273
+
274
+ def git_changed(repo: Path, base: str = "HEAD") -> Dict[str, Any]:
275
+ repo = repo.resolve()
276
+ if not base or base.startswith("-") or "\x00" in base or not _GIT_REF_RE.fullmatch(base):
277
+ raise SystemExit(f"Invalid git ref for --base: {base!r}")
278
+ changed_files, status_lines = [], []
279
+ try:
280
+ r = git_cmd(repo, ["status", "--porcelain"], timeout=5)
281
+ if r.returncode != 0:
282
+ return {"is_git": False, "error": r.stderr.strip() or "Not a git repository", "changed_files": []}
283
+ for line in r.stdout.splitlines():
284
+ if len(line) >= 4:
285
+ raw_path = line[3:].strip().split(" -> ", 1)[-1]
286
+ clean_p = _unquote_git_path(raw_path)
287
+ if _is_internal_artifact(clean_p):
288
+ continue
289
+ status_lines.append(line)
290
+ changed_files.append(clean_p)
291
+ if base != "HEAD":
292
+ if git_cmd(repo, ["rev-parse", "--verify", "--quiet", f"{base}^{{commit}}"], timeout=4).returncode != 0:
293
+ return {"is_git": True, "base": base, "error": f"Unknown git ref: {base}", "changed_files": []}
294
+ r2 = git_cmd(repo, ["diff", "--no-ext-diff", "--no-textconv", "--name-only", base, "--"], timeout=5)
295
+ if r2.returncode == 0:
296
+ for p in r2.stdout.splitlines():
297
+ cp = _unquote_git_path(p)
298
+ if cp and not _is_internal_artifact(cp):
299
+ changed_files.append(cp)
300
+ except Exception as e:
301
+ return {"is_git": False, "error": str(e), "changed_files": []}
302
+
303
+ db, _ = db_open(repo, read_only=True)
304
+ details = [
305
+ {"path": p, "symbols": [{"name": s[0], "kind": s[1], "line": s[2], "end_line": s[3]} for s in db.execute("SELECT name, kind, line, end_line FROM symbols WHERE path=? ORDER BY line LIMIT 15", (p,))]}
306
+ for p in sorted(set(changed_files))
307
+ ]
308
+ db.close()
309
+ return {"is_git": True, "base": base, "count": len(details), "status": status_lines[:40], "changed_files": details}
310
+
311
+
312
+ def format_compact_search(hits: List[Dict[str, Any]]) -> str:
313
+ if not hits:
314
+ return "No matches found."
315
+ out: List[str] = []
316
+ for h in hits:
317
+ syms = ", ".join(f"{s['name']}:L{s['line']}" for s in h["symbols"][:5])
318
+ out.append(f"[{h['score']}] {h['path']} ({h['lines']}L, ~{h['file_tokens_est']} tok) — {h['summary']}")
319
+ if syms:
320
+ out.append(f" syms: {syms}")
321
+ for sn in h["snippets"]:
322
+ out.append(f" --- L{sn['start_line']}-{sn['end_line']} ---")
323
+ out.extend(f" {ln}" for ln in sn["text"].splitlines())
324
+ return "\n".join(out)
325
+
326
+
327
+ def call_graph(
328
+ repo: Path,
329
+ symbol: str,
330
+ direction: str = "both",
331
+ depth: int = 2,
332
+ limit: int = 40,
333
+ *,
334
+ use_lsp: bool = False,
335
+ lsp_server_cmd: Optional[Sequence[str]] = None,
336
+ ) -> Dict[str, Any]:
337
+ """Query symbol-level callers and callees from the static call graph (with optional `--lsp` type-checked refs)."""
338
+ repo_r = repo.resolve()
339
+ norm = symbol.replace("::", ".").strip()
340
+ db, _ = db_open(repo_r, read_only=True)
341
+ tables = {r[0] for r in db.execute("SELECT name FROM sqlite_master WHERE type='table'")}
342
+ if "calls" not in tables:
343
+ db.close()
344
+ return {"symbol": symbol, "direction": direction, "callers": [], "callees": [], "note": "Re-index repo to build schema v4 call graph."}
345
+
346
+ # Resolve target definitions
347
+ defs = db.execute(
348
+ "SELECT path, name, qualified_name, line, end_line, signature FROM symbols WHERE LOWER(qualified_name)=LOWER(?) OR LOWER(name)=LOWER(?) ORDER BY CASE WHEN LOWER(qualified_name)=LOWER(?) THEN 0 ELSE 1 END, path, line LIMIT 10",
349
+ (norm, norm, norm),
350
+ ).fetchall()
351
+
352
+ def bfs_callers(max_d: int) -> List[Dict[str, Any]]:
353
+ seeds = [(r[0], r[2]) for r in defs] or [("", norm)]
354
+ vis = set(seeds)
355
+ front = [(p, q, 0) for p, q in seeds]
356
+ found: List[Dict[str, Any]] = []
357
+ while front and len(found) < limit:
358
+ cp, cq, d = front.pop(0)
359
+ if d >= max_d:
360
+ continue
361
+ leaf = cq.rsplit(".", 1)[-1]
362
+ if cp:
363
+ q_rows = db.execute(
364
+ "SELECT DISTINCT src_path, src_symbol, line FROM calls WHERE (dst_path=? AND LOWER(dst_symbol)=LOWER(?)) OR (dst_path IS NULL AND LOWER(callee_name)=LOWER(?)) LIMIT ?",
365
+ (cp, cq, leaf, limit),
366
+ ).fetchall()
367
+ else:
368
+ q_rows = db.execute(
369
+ "SELECT DISTINCT src_path, src_symbol, line FROM calls WHERE LOWER(dst_symbol)=LOWER(?) OR LOWER(callee_name)=LOWER(?) LIMIT ?",
370
+ (cq, leaf, limit),
371
+ ).fetchall()
372
+ for sp, ss, ln in q_rows:
373
+ if (sp, ss) not in vis:
374
+ vis.add((sp, ss))
375
+ found.append({"caller_path": sp, "caller_symbol": ss, "line": ln, "calls": cq, "depth": d + 1})
376
+ front.append((sp, ss, d + 1))
377
+ if len(found) >= limit:
378
+ break
379
+ return found
380
+
381
+ def bfs_callees(max_d: int) -> List[Dict[str, Any]]:
382
+ seeds = [(r[0], r[2]) for r in defs]
383
+ if not seeds:
384
+ return []
385
+ vis = set(seeds)
386
+ front = [(p, q, 0) for p, q in seeds]
387
+ found: List[Dict[str, Any]] = []
388
+ while front and len(found) < limit:
389
+ cp, cq, d = front.pop(0)
390
+ if d >= max_d:
391
+ continue
392
+ q_rows = db.execute(
393
+ "SELECT DISTINCT callee_name, dst_path, dst_symbol, line FROM calls WHERE src_path=? AND LOWER(src_symbol)=LOWER(?) ORDER BY line LIMIT ?",
394
+ (cp, cq, limit),
395
+ ).fetchall()
396
+ for cname, dp, ds, ln in q_rows:
397
+ key = (dp or "", ds or cname)
398
+ if key not in vis:
399
+ vis.add(key)
400
+ found.append({"from_symbol": cq, "callee_name": cname, "callee_path": dp, "callee_symbol": ds, "resolved": dp is not None, "line": ln, "depth": d + 1})
401
+ if dp and ds:
402
+ front.append((dp, ds, d + 1))
403
+ if len(found) >= limit:
404
+ break
405
+ return found
406
+
407
+ callers = bfs_callers(max(1, depth)) if direction in ("both", "callers") else []
408
+ callees = bfs_callees(max(1, depth)) if direction in ("both", "callees") else []
409
+
410
+ from idx_parsers import treesitter_available
411
+ def_paths = [r[0] for r in defs]
412
+ if treesitter_available() or (def_paths and all(p.endswith((".py", ".pyi")) for p in def_paths)):
413
+ confidence = "ast"
414
+ resolution_mode = "ast-syntax-name-matched"
415
+ else:
416
+ confidence = "heuristic"
417
+ resolution_mode = "heuristic-regex-name-matched"
418
+
419
+ lsp_info: Optional[Dict[str, Any]] = None
420
+ if use_lsp and defs and direction in ("both", "callers"):
421
+ from idx_lsp import query_lsp_references
422
+ d0_path, d0_name, d0_qname, d0_line, _d0_end, _d0_sig = defs[0]
423
+ target_fp = repo_r / d0_path
424
+ char_col = 0
425
+ if target_fp.is_file():
426
+ f_lines = target_fp.read_text(encoding="utf-8", errors="replace").splitlines()
427
+ if 1 <= d0_line <= len(f_lines):
428
+ idx_col = f_lines[d0_line - 1].find(d0_name)
429
+ if idx_col >= 0:
430
+ char_col = idx_col
431
+ lsp_res = query_lsp_references(repo_r, d0_path, d0_line, char_col, server_cmd=lsp_server_cmd)
432
+ if lsp_res.get("available"):
433
+ lsp_callers: List[Dict[str, Any]] = []
434
+ for loc in lsp_res.get("locations", [])[:limit]:
435
+ lp, lno = loc["path"], loc["line"]
436
+ enc = db.execute(
437
+ "SELECT qualified_name FROM symbols WHERE path=? AND line <= ? AND end_line >= ? ORDER BY (end_line - line) ASC LIMIT 1",
438
+ (lp, lno, lno),
439
+ ).fetchone()
440
+ lsp_callers.append({
441
+ "caller_path": lp,
442
+ "caller_symbol": enc[0] if enc else f"{Path(lp).stem}:L{lno}",
443
+ "line": lno,
444
+ "calls": d0_qname,
445
+ "depth": 1,
446
+ "source": "lsp",
447
+ })
448
+ callers = lsp_callers
449
+ confidence = "lsp"
450
+ resolution_mode = "type-checked-lsp"
451
+ lsp_info = {"used": True, "server": lsp_res.get("server"), "references_count": len(lsp_callers)}
452
+ else:
453
+ lsp_info = {"used": False, "fallback_reason": lsp_res.get("reason", "LSP unavailable")}
454
+
455
+ db.close()
456
+ res: Dict[str, Any] = {
457
+ "symbol": symbol,
458
+ "analysis_confidence": confidence,
459
+ "resolution_mode": resolution_mode,
460
+ "definitions": [{"path": r[0], "qualified_name": r[2], "lines": f"{r[3]}-{r[4]}"} for r in defs],
461
+ "direction": direction,
462
+ "depth": max(1, depth),
463
+ "callers_count": len(callers),
464
+ "callees_count": len(callees),
465
+ "callers": callers,
466
+ "callees": callees,
467
+ }
468
+ if lsp_info is not None:
469
+ res["lsp"] = lsp_info
470
+ return res
471
+
472
+
473
+ def format_compact_callgraph(cg: Dict[str, Any]) -> str:
474
+ conf = cg.get("analysis_confidence", "heuristic")
475
+ rmode = cg.get("resolution_mode") or ("ast-syntax-name-matched" if conf == "ast" else ("type-checked-lsp" if conf == "lsp" else "heuristic-regex-name-matched"))
476
+ if conf == "lsp":
477
+ srv = (cg.get("lsp") or {}).get("server", "lsp")
478
+ note = f" [lsp:{srv} · type-checked semantic references]"
479
+ elif conf == "ast":
480
+ note = " [ast-syntax · name-matched, not type-checked; pass --lsp for semantic resolution]"
481
+ else:
482
+ note = " [heuristic · name-matched, not type-checked; pass --lsp or install tree-sitter-language-pack]"
483
+ out = [f"CallGraph: {cg['symbol']} (callers={cg['callers_count']}, callees={cg['callees_count']}){note}"]
484
+ lsp_fb = (cg.get("lsp") or {}).get("fallback_reason")
485
+ if lsp_fb:
486
+ out.append(f" [LSP fallback -> {rmode}] {lsp_fb}")
487
+ for d in cg.get("definitions", [])[:4]:
488
+ out.append(f" [def] {d['path']}:L{d['lines']} {d['qualified_name']}")
489
+ if cg.get("callers"):
490
+ out.append(" Callers:")
491
+ for c in cg["callers"][:20]:
492
+ out.append(f" <- {c['caller_path']}:{c['line']} {c['caller_symbol']} (d={c['depth']})")
493
+ if cg.get("callees"):
494
+ out.append(" Callees:")
495
+ for c in cg["callees"][:20]:
496
+ tgt = f"{c['callee_path']}::{c['callee_symbol']}" if c["resolved"] else f"external:{c['callee_name']}"
497
+ out.append(f" -> L{c['line']} {tgt} (d={c['depth']})")
498
+ return "\n".join(out)