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,393 @@
1
+ """SQLite FTS5 store, schema lifecycle, cache-optimal PROJECT_MAP.md builder & staleness status."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ import os
6
+ import re
7
+ import sqlite3
8
+ import stat
9
+ from collections import Counter, defaultdict
10
+ from pathlib import Path
11
+ from typing import Any, Dict, List, Optional, Set, Tuple
12
+
13
+ from _ae_core import estimate_tokens, is_within, normalize_rel_path, sanitize_inline
14
+ from idx_ignore import (
15
+ DEFAULT_MAP_BUDGET_TOKENS,
16
+ ENTRYPOINT_NAMES,
17
+ EXCLUDED_DIRS,
18
+ MAX_BYTES_DEFAULT,
19
+ SUPPORTED_BASENAMES,
20
+ SUPPORTED_EXTS,
21
+ is_binary_bytes,
22
+ is_ignored,
23
+ load_dir_gitignore,
24
+ load_gitignore_rules,
25
+ load_repo_config,
26
+ )
27
+
28
+ SCHEMA_VERSION = 5
29
+ _FTS5_AVAILABLE: Optional[bool] = None
30
+
31
+ _IDENT_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_-]{2,}")
32
+ _CAMEL_ACRONYM_RE = re.compile(r"([A-Z]+)([A-Z][a-z])")
33
+ _CAMEL_BOUNDARY_RE = re.compile(r"([a-z0-9])([A-Z])")
34
+
35
+
36
+ def split_identifier_tokens(text: str, max_tokens: int = 600) -> str:
37
+ """Split CamelCase, ACRONYMWord, snake_case, and kebab-case identifiers into space-separated lowercase subwords for FTS5."""
38
+ if not text:
39
+ return ""
40
+ out: List[str] = []
41
+ seen_out: Set[str] = set()
42
+ seen_ident: Set[str] = set()
43
+ for m in _IDENT_RE.finditer(text):
44
+ ident = m.group(0)
45
+ if ident in seen_ident:
46
+ continue
47
+ seen_ident.add(ident)
48
+ # Fast-path skip plain lowercase words without delimiters
49
+ if ident.islower() and "_" not in ident and "-" not in ident:
50
+ continue
51
+ raw_low = ident.lower()
52
+ parts: List[str] = []
53
+ for seg in re.split(r"[_-]+", ident):
54
+ if not seg:
55
+ continue
56
+ s1 = _CAMEL_ACRONYM_RE.sub(r"\1 \2", seg)
57
+ s2 = _CAMEL_BOUNDARY_RE.sub(r"\1 \2", s1)
58
+ for sub in s2.split():
59
+ sl = sub.lower()
60
+ if len(sl) >= 2:
61
+ parts.append(sl)
62
+ if len(parts) < 2 and (not parts or parts[0] == raw_low):
63
+ continue
64
+ for p in parts:
65
+ if p not in seen_out:
66
+ seen_out.add(p)
67
+ out.append(p)
68
+ if len(out) >= max_tokens:
69
+ return " ".join(out)
70
+ return " ".join(out)
71
+
72
+ SCHEMA_SQL = """
73
+ CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
74
+ CREATE TABLE IF NOT EXISTS files (
75
+ path TEXT PRIMARY KEY, sha TEXT NOT NULL, size INTEGER NOT NULL, lines INTEGER NOT NULL,
76
+ tokens_est INTEGER NOT NULL, mtime REAL NOT NULL, language TEXT NOT NULL,
77
+ summary TEXT NOT NULL, imports_json TEXT NOT NULL, content TEXT NOT NULL
78
+ );
79
+ CREATE TABLE IF NOT EXISTS symbols (
80
+ path TEXT NOT NULL, name TEXT NOT NULL, qualified_name TEXT NOT NULL, kind TEXT NOT NULL,
81
+ line INTEGER NOT NULL, end_line INTEGER NOT NULL, signature TEXT NOT NULL, doc TEXT NOT NULL
82
+ );
83
+ CREATE TABLE IF NOT EXISTS edges (src_path TEXT NOT NULL, dst_raw TEXT NOT NULL, dst_path TEXT, kind TEXT NOT NULL);
84
+ CREATE TABLE IF NOT EXISTS calls (
85
+ src_path TEXT NOT NULL, src_symbol TEXT NOT NULL, callee_name TEXT NOT NULL,
86
+ dst_path TEXT, dst_symbol TEXT, line INTEGER NOT NULL
87
+ );
88
+ CREATE INDEX IF NOT EXISTS idx_symbols_path ON symbols(path);
89
+ CREATE INDEX IF NOT EXISTS idx_symbols_name ON symbols(name);
90
+ CREATE INDEX IF NOT EXISTS idx_symbols_qname ON symbols(qualified_name);
91
+ CREATE INDEX IF NOT EXISTS idx_edges_src ON edges(src_path);
92
+ CREATE INDEX IF NOT EXISTS idx_edges_dst ON edges(dst_path);
93
+ CREATE INDEX IF NOT EXISTS idx_calls_src ON calls(src_path, src_symbol);
94
+ CREATE INDEX IF NOT EXISTS idx_calls_dst ON calls(dst_path, dst_symbol);
95
+ CREATE INDEX IF NOT EXISTS idx_calls_callee ON calls(callee_name);
96
+ """
97
+
98
+ FTS_SQL = """
99
+ CREATE VIRTUAL TABLE IF NOT EXISTS files_fts USING fts5(path, summary, symbols_text, content, ident_tokens, tokenize='unicode61 tokenchars _');
100
+ CREATE VIRTUAL TABLE IF NOT EXISTS symbols_fts USING fts5(path, name, qualified_name, kind, signature, doc, ident_tokens, tokenize='unicode61 tokenchars _');
101
+ """
102
+
103
+
104
+ def assert_not_symlink_artifact(path: Path, repo: Path) -> None:
105
+ if path.is_symlink():
106
+ raise SystemExit(f"Refusing to follow symlinked artifact: {path.name}")
107
+ if path.exists() and not is_within(path, repo):
108
+ raise SystemExit(f"Artifact escapes repository root: {path.name}")
109
+
110
+
111
+ def ensure_safe_artifact_dir(repo: Path) -> Path:
112
+ idx_dir = repo / ".agent-index"
113
+ if idx_dir.is_symlink() or (idx_dir.exists() and not is_within(idx_dir, repo)):
114
+ raise SystemExit("Refusing to use symlinked or out-of-repo .agent-index directory.")
115
+ idx_dir.mkdir(parents=True, exist_ok=True)
116
+ return idx_dir
117
+
118
+
119
+ def supports_fts5() -> bool:
120
+ global _FTS5_AVAILABLE
121
+ if _FTS5_AVAILABLE is None:
122
+ try:
123
+ mem = sqlite3.connect(":memory:")
124
+ mem.execute("CREATE VIRTUAL TABLE _probe USING fts5(x)")
125
+ mem.close()
126
+ _FTS5_AVAILABLE = True
127
+ except sqlite3.OperationalError:
128
+ _FTS5_AVAILABLE = False
129
+ return _FTS5_AVAILABLE
130
+
131
+
132
+ def _remove_corrupt_db(db_path: Path) -> None:
133
+ for suffix in ("", "-wal", "-shm"):
134
+ p = Path(str(db_path) + suffix)
135
+ try:
136
+ if p.exists() and not p.is_symlink():
137
+ p.unlink()
138
+ except OSError:
139
+ pass
140
+
141
+
142
+ def db_open(repo: Path, read_only: bool = False) -> Tuple[sqlite3.Connection, bool]:
143
+ repo = repo.resolve()
144
+ has_fts = supports_fts5()
145
+ idx_dir = repo / ".agent-index"
146
+ db_path = idx_dir / "index.sqlite3"
147
+
148
+ if read_only:
149
+ if idx_dir.is_symlink() or db_path.is_symlink():
150
+ raise SystemExit("Refusing to read symlinked .agent-index artifact.")
151
+ if not db_path.is_file():
152
+ mem = sqlite3.connect(":memory:")
153
+ mem.execute("PRAGMA trusted_schema=OFF")
154
+ mem.executescript(SCHEMA_SQL)
155
+ if has_fts:
156
+ mem.executescript(FTS_SQL)
157
+ return mem, has_fts
158
+ db: Optional[sqlite3.Connection] = None
159
+ try:
160
+ db = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True, timeout=15.0)
161
+ db.execute("PRAGMA trusted_schema=OFF")
162
+ db.execute("PRAGMA query_only=ON")
163
+ tables = {r[0] for r in db.execute("SELECT name FROM sqlite_master WHERE type='table'")}
164
+ return db, (has_fts and "files_fts" in tables and "symbols_fts" in tables)
165
+ except sqlite3.DatabaseError as exc:
166
+ if db is not None:
167
+ try:
168
+ db.close()
169
+ except Exception:
170
+ pass
171
+ raise SystemExit(f"Index database is corrupted ({exc}); rebuild with `context_index.py index {repo} --force`.")
172
+
173
+ idx_dir = ensure_safe_artifact_dir(repo)
174
+ assert_not_symlink_artifact(db_path, repo)
175
+
176
+ def _init_writable() -> Tuple[sqlite3.Connection, bool]:
177
+ conn = sqlite3.connect(db_path, timeout=15.0)
178
+ try:
179
+ conn.execute("PRAGMA trusted_schema=OFF")
180
+ conn.execute("PRAGMA journal_mode=WAL")
181
+ conn.execute("PRAGMA synchronous=NORMAL")
182
+
183
+ tables = {r[0] for r in conn.execute("SELECT name FROM sqlite_master WHERE type='table'")}
184
+ needs_reset = False
185
+ if "files" in tables:
186
+ cols = {r[1] for r in conn.execute("PRAGMA table_info(files)")}
187
+ if "tokens_est" not in cols or "meta" not in tables:
188
+ needs_reset = True
189
+ else:
190
+ row = conn.execute("SELECT value FROM meta WHERE key='schema_version'").fetchone()
191
+ try:
192
+ ver = int(row[0]) if row else -1
193
+ except (TypeError, ValueError):
194
+ ver = -1
195
+ if ver != SCHEMA_VERSION:
196
+ needs_reset = True
197
+
198
+ if needs_reset:
199
+ for tbl in ("files_fts", "symbols_fts", "calls", "edges", "symbols", "files", "meta"):
200
+ conn.execute(f"DROP TABLE IF EXISTS {tbl}")
201
+ conn.commit()
202
+
203
+ conn.executescript(SCHEMA_SQL)
204
+ if has_fts:
205
+ conn.executescript(FTS_SQL)
206
+ conn.execute("INSERT OR REPLACE INTO meta(key, value) VALUES ('schema_version', ?)", (str(SCHEMA_VERSION),))
207
+ conn.commit()
208
+ return conn, has_fts
209
+ except Exception:
210
+ try:
211
+ conn.close()
212
+ except Exception:
213
+ pass
214
+ raise
215
+
216
+ try:
217
+ return _init_writable()
218
+ except sqlite3.DatabaseError:
219
+ _remove_corrupt_db(db_path)
220
+ return _init_writable()
221
+
222
+
223
+ def build_project_map(repo: Path, db: sqlite3.Connection, budget_tokens: int = DEFAULT_MAP_BUDGET_TOKENS) -> str:
224
+ """Build deterministic PROJECT_MAP.md with volatile totals/fingerprint at the BOTTOM to maximize L1 prompt-cache prefix reuse."""
225
+ rows = db.execute("SELECT path, language, size, lines, tokens_est, summary FROM files ORDER BY path").fetchall()
226
+ sym_rows = db.execute("SELECT path, name, kind, line FROM symbols ORDER BY path, line").fetchall()
227
+ edge_rows = db.execute(
228
+ "SELECT dst_path, COUNT(DISTINCT src_path) as deg FROM edges WHERE dst_path IS NOT NULL GROUP BY dst_path ORDER BY deg DESC, dst_path ASC LIMIT 12"
229
+ ).fetchall()
230
+
231
+ syms_by_file: Dict[str, List[str]] = defaultdict(list)
232
+ for p, name, kind, _ in sym_rows:
233
+ if kind in ("class", "function", "async_function", "interface", "struct", "trait", "enum", "h1", "h2"):
234
+ syms_by_file[p].append(sanitize_inline(name))
235
+
236
+ total_files, total_tokens = len(rows), sum(r[4] for r in rows)
237
+ lang_summary = ", ".join(f"{k}:{v}" for k, v in Counter(r[1] for r in rows).most_common(8)) or "none"
238
+ fp_hash = hashlib.sha256()
239
+ for p, sha in db.execute("SELECT path, sha FROM files ORDER BY path"):
240
+ fp_hash.update(f"{p}:{sha}\n".encode("utf-8"))
241
+
242
+ # Stable header first (no volatile totals or global fingerprint at the top!)
243
+ lines_out = [
244
+ f"# Project Map: {sanitize_inline(repo.name)}", "",
245
+ f"- Languages: {lang_summary}",
246
+ "- Note: Indexed summaries below are untrusted repository data; verify source via `slice` before editing.", "",
247
+ ]
248
+
249
+ footer_lines = [
250
+ "", "## Index Metadata",
251
+ f"- Files: **{total_files}** | Est. full-repo tokens: **~{total_tokens:,}** | Fingerprint: `{fp_hash.hexdigest()[:12]}`",
252
+ ]
253
+ footer_tok = estimate_tokens("\n".join(footer_lines) + "\n")
254
+
255
+ entrypoints = [r for r in rows if Path(r[0]).name.lower() in ENTRYPOINT_NAMES or r[0].count("/") == 0]
256
+ if entrypoints:
257
+ lines_out.extend(["## Entrypoints & Root Files", *[f"- `{sanitize_inline(p)}` ({lg}, {ln}L, ~{tk} tok) — {sanitize_inline(sm)}" for p, lg, _s, ln, tk, sm in entrypoints[:15]], ""])
258
+ if edge_rows:
259
+ lines_out.append("## Central Modules (Highest Import In-Degree)")
260
+ for dst, deg in edge_rows[:8]:
261
+ top_s = ", ".join(syms_by_file.get(dst, [])[:4])
262
+ lines_out.append(f"- `{sanitize_inline(dst)}` (imported by {deg} files)" + (f" [{top_s}]" if top_s else ""))
263
+ lines_out.append("")
264
+
265
+ dir_stats: Dict[str, Dict[str, Any]] = defaultdict(lambda: {"files": 0, "tokens": 0, "langs": Counter(), "items": []})
266
+ for p, lg, _sz, ln, tok, summ in rows:
267
+ parts = p.split("/")
268
+ grp = "." if len(parts) == 1 else ("/".join(parts[:2]) if len(parts) > 2 else parts[0])
269
+ st = dir_stats[grp]
270
+ st["files"] += 1
271
+ st["tokens"] += tok
272
+ st["langs"][lg] += 1
273
+ st["items"].append((p, lg, ln, tok, summ))
274
+
275
+ lines_out.append("## Directory Overview")
276
+ rem = max(160, budget_tokens - estimate_tokens("\n".join(lines_out)) - footer_tok)
277
+ for grp in sorted(dir_stats.keys()):
278
+ st = dir_stats[grp]
279
+ if total_files <= 25:
280
+ blk = [f"### `{sanitize_inline(grp)}/` ({st['files']} files, ~{st['tokens']:,} tok)"]
281
+ for p, _lg, ln, tok, sm in st["items"]:
282
+ ts = ", ".join(syms_by_file.get(p, [])[:5])
283
+ blk.append(f"- `{sanitize_inline(p)}` ({ln}L, ~{tok} tok)" + (f" | syms: {ts}" if ts else "") + f" — {sanitize_inline(sm)}")
284
+ btok = estimate_tokens("\n".join(blk) + "\n")
285
+ if btok <= rem:
286
+ lines_out.extend(blk + [""])
287
+ rem -= btok
288
+ continue
289
+ langs = "/".join(k for k, _ in st["langs"].most_common(3))
290
+ top_f = ", ".join(sanitize_inline(Path(x[0]).name) for x in st["items"][:4]) + (f", +{st['files'] - 4} more" if st["files"] > 4 else "")
291
+ entry = f"- `{sanitize_inline(grp)}/` ({st['files']} files, {langs}, ~{st['tokens']:,} tok): {top_f}"
292
+ if estimate_tokens(entry) > rem:
293
+ lines_out.append(f"- ... ({len(dir_stats)} total groups; run `context_index.py search` for deeper paths)")
294
+ break
295
+ lines_out.append(entry)
296
+ rem -= estimate_tokens(entry)
297
+ lines_out.extend(footer_lines)
298
+ return "\n".join(lines_out).rstrip() + "\n"
299
+
300
+
301
+ def status(repo: Path, check_stale: bool = False) -> Dict[str, Any]:
302
+ repo = repo.resolve()
303
+ db, has_fts = db_open(repo, read_only=True)
304
+ file_count = db.execute("SELECT COUNT(*) FROM files").fetchone()[0]
305
+ sym_count = db.execute("SELECT COUNT(*) FROM symbols").fetchone()[0]
306
+ edge_count = db.execute("SELECT COUNT(*) FROM edges WHERE dst_path IS NOT NULL").fetchone()[0]
307
+ has_calls = "calls" in {r[0] for r in db.execute("SELECT name FROM sqlite_master WHERE type='table'")}
308
+ call_count = db.execute("SELECT COUNT(*) FROM calls WHERE dst_path IS NOT NULL").fetchone()[0] if has_calls else 0
309
+ total_tok = db.execute("SELECT COALESCE(SUM(tokens_est), 0) FROM files").fetchone()[0]
310
+ meta = dict(db.execute("SELECT key, value FROM meta").fetchall())
311
+ stale_files: List[str] = []
312
+ if check_stale:
313
+ cfg = load_repo_config(repo)
314
+ max_bytes = int(cfg.get("max_file_bytes", MAX_BYTES_DEFAULT))
315
+ extra_excludes = list(cfg.get("exclude", []))
316
+ extra_includes = list(cfg.get("include", []))
317
+ eff_gi = bool(cfg.get("use_gitignore", True))
318
+ gi_rules = load_gitignore_rules(repo) if eff_gi else []
319
+ indexed_map: Dict[str, str] = {}
320
+ for rel, sha in db.execute("SELECT path, sha FROM files").fetchall():
321
+ indexed_map[rel] = sha
322
+ norm = normalize_rel_path(rel)
323
+ if not norm or norm.startswith(".."):
324
+ stale_files.append(f"invalid:{rel}")
325
+ continue
326
+ fp = repo / norm
327
+ if fp.is_symlink() or not is_within(fp, repo):
328
+ stale_files.append(f"unsafe:{norm}")
329
+ elif not fp.exists():
330
+ stale_files.append(f"deleted:{norm}")
331
+ else:
332
+ try:
333
+ st = fp.stat()
334
+ if not stat.S_ISREG(st.st_mode) or st.st_size > max_bytes:
335
+ stale_files.append(f"skipped:{norm}")
336
+ elif hashlib.sha256(fp.read_bytes()).hexdigest() != sha:
337
+ stale_files.append(f"modified:{norm}")
338
+ except OSError:
339
+ stale_files.append(f"unreadable:{norm}")
340
+
341
+ # Detect newly added unindexed files on disk
342
+ for dirpath, dirnames, filenames in os.walk(repo, topdown=True, followlinks=False):
343
+ dp = Path(dirpath)
344
+ rel_dir = "" if dp == repo else dp.relative_to(repo).as_posix()
345
+ if eff_gi and rel_dir:
346
+ gi_rules.extend(load_dir_gitignore(dp, rel_dir))
347
+ dirnames[:] = [
348
+ d for d in sorted(dirnames)
349
+ 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)
350
+ ]
351
+ for fname in sorted(filenames):
352
+ rel = f"{rel_dir}/{fname}" if rel_dir else fname
353
+ if rel in indexed_map:
354
+ continue
355
+ full = dp / fname
356
+ if is_ignored(rel, extra_excludes, gi_rules, extra_includes):
357
+ continue
358
+ if full.is_symlink():
359
+ try:
360
+ rrel = full.resolve().relative_to(repo).as_posix()
361
+ except Exception:
362
+ continue
363
+ if is_ignored(rrel, extra_excludes, gi_rules, extra_includes):
364
+ continue
365
+ if full.suffix.lower() not in SUPPORTED_EXTS and fname.lower() not in SUPPORTED_BASENAMES:
366
+ continue
367
+ try:
368
+ st = full.stat()
369
+ if not stat.S_ISREG(st.st_mode) or st.st_size > max_bytes:
370
+ continue
371
+ if is_binary_bytes(full.read_bytes()[:8192]):
372
+ continue
373
+ except OSError:
374
+ continue
375
+ stale_files.append(f"added:{rel}")
376
+ db.close()
377
+ try:
378
+ sv = int(meta.get("schema_version", SCHEMA_VERSION))
379
+ except (TypeError, ValueError):
380
+ sv = SCHEMA_VERSION
381
+ from idx_parsers import treesitter_backend
382
+ ts_be = treesitter_backend()
383
+ res: Dict[str, Any] = {
384
+ "indexed_files": file_count, "symbols": sym_count, "resolved_edges": edge_count,
385
+ "resolved_calls": call_count, "parser_backend": "tree-sitter" if ts_be != "stdlib" else "stdlib",
386
+ "parser_backend_detail": ts_be,
387
+ "total_tokens_est": total_tok, "fts5_enabled": has_fts, "schema_version": sv,
388
+ "last_indexed_at": meta.get("last_indexed_at"), "indexed_git_head": meta.get("git_head"),
389
+ "map": str(repo / ".agent-index" / "PROJECT_MAP.md"),
390
+ }
391
+ if check_stale:
392
+ res["stale_count"], res["stale_files"] = len(stale_files), stale_files[:30]
393
+ return res
@@ -0,0 +1,184 @@
1
+ """Exclusion rules, .gitignore handling (with nested dirs & negation), repo config loading & binary detection."""
2
+ from __future__ import annotations
3
+
4
+ import fnmatch
5
+ import json
6
+ from pathlib import Path
7
+ from typing import Any, Dict, List, Sequence, Set, Tuple
8
+
9
+ from _ae_core import HARD_SECRET_PATH_RE, is_secret_path, is_within, normalize_rel_path
10
+
11
+ MAX_BYTES_DEFAULT = 1_500_000
12
+ DEFAULT_MAP_BUDGET_TOKENS = 1_500
13
+
14
+ # Directories excluded at any depth
15
+ EXCLUDED_DIRS: Set[str] = {
16
+ ".git", ".hg", ".svn", ".venv", "venv", ".tox", ".mypy_cache", ".ruff_cache",
17
+ ".pytest_cache", "__pycache__", "node_modules", ".next", ".nuxt", ".svelte-kit",
18
+ ".turbo", ".cache", "coverage", ".idea", ".vscode", ".agent-index", ".agent-state",
19
+ "Pods", ".gradle", ".aws", ".kube", ".docker",
20
+ }
21
+
22
+ # Build/output/env directories excluded by default only at repo root (not inside `src/env/`, `src/build/`, `src/out/`)
23
+ ROOT_EXCLUDED_DIRS: Set[str] = {"env", "dist", "build", "out", "target", "vendor"}
24
+
25
+ SUPPORTED_EXTS: Set[str] = {
26
+ ".py", ".pyi", ".js", ".jsx", ".mjs", ".cjs", ".ts", ".tsx", ".mts", ".cts",
27
+ ".java", ".kt", ".kts", ".go", ".rs", ".c", ".h", ".cpp", ".hpp", ".cc", ".hh",
28
+ ".cs", ".php", ".rb", ".swift", ".scala", ".sh", ".bash", ".zsh", ".ps1", ".sql",
29
+ ".html", ".htm", ".css", ".scss", ".sass", ".less", ".json", ".yaml", ".yml",
30
+ ".toml", ".ini", ".cfg", ".md", ".mdx", ".rst", ".txt", ".xml", ".graphql",
31
+ ".gql", ".proto", ".tf", ".hcl", ".dockerfile",
32
+ ".vue", ".svelte", ".astro", ".dart", ".zig", ".lua", ".ex", ".exs", ".sol",
33
+ ".prisma", ".nix", ".groovy",
34
+ }
35
+
36
+ SUPPORTED_BASENAMES: Set[str] = {
37
+ "makefile", "dockerfile", "justfile", "procfile", "gemfile", "rakefile",
38
+ "cmakelists.txt", "build", "workspace", "go.mod", "go.work",
39
+ ".env.example", ".env.sample", ".env.template",
40
+ }
41
+
42
+ ENTRYPOINT_NAMES: Set[str] = {
43
+ "readme.md", "skill.md", "agents.md", "claude.md", "pyproject.toml", "package.json",
44
+ "cargo.toml", "go.mod", "makefile", "dockerfile", "docker-compose.yml", "docker-compose.yaml",
45
+ "main.py", "app.py", "cli.py", "server.py", "index.ts", "index.js", "main.ts", "main.go", "main.rs", "lib.rs",
46
+ }
47
+
48
+ GitIgnoreRule = Tuple[str, str, bool] # (base_dir, pattern, is_negated)
49
+
50
+
51
+ def _parse_gitignore_file(path: Path, base_dir: str) -> List[GitIgnoreRule]:
52
+ if path.is_symlink() or not path.is_file():
53
+ return []
54
+ out: List[GitIgnoreRule] = []
55
+ try:
56
+ for raw_line in path.read_text(encoding="utf-8", errors="replace").splitlines():
57
+ line = raw_line.strip()
58
+ if not line or line.startswith("#"):
59
+ continue
60
+ negated = False
61
+ if line.startswith("!"):
62
+ negated = True
63
+ line = line[1:].strip()
64
+ if not line:
65
+ continue
66
+ out.append((base_dir, line.rstrip("/"), negated))
67
+ except OSError:
68
+ pass
69
+ return out
70
+
71
+
72
+ def load_gitignore_rules(repo: Path) -> List[GitIgnoreRule]:
73
+ rules: List[GitIgnoreRule] = []
74
+ for path in (repo / ".git" / "info" / "exclude", repo / ".gitignore"):
75
+ rules.extend(_parse_gitignore_file(path, ""))
76
+ return rules
77
+
78
+
79
+ def load_dir_gitignore(dirpath: Path, rel_dir: str) -> List[GitIgnoreRule]:
80
+ if not rel_dir:
81
+ return []
82
+ return _parse_gitignore_file(dirpath / ".gitignore", rel_dir)
83
+
84
+
85
+ def load_ancestor_gitignore_rules(repo: Path, rel_path: str) -> List[GitIgnoreRule]:
86
+ """Load root .gitignore plus every nested .gitignore along the ancestor directories of `rel_path`."""
87
+ repo_r = repo.resolve()
88
+ rules = load_gitignore_rules(repo_r)
89
+ norm = normalize_rel_path(rel_path)
90
+ if not norm or "/" not in norm:
91
+ return rules
92
+ parts = norm.split("/")[:-1]
93
+ cur = repo_r
94
+ rel_parts: List[str] = []
95
+ for seg in parts:
96
+ cur = cur / seg
97
+ rel_parts.append(seg)
98
+ if cur.is_symlink() or not cur.is_dir():
99
+ break
100
+ rules.extend(load_dir_gitignore(cur, "/".join(rel_parts)))
101
+ return rules
102
+
103
+
104
+ def _matches_gitignore(rel: str, base_dir: str, pattern: str) -> bool:
105
+ if base_dir:
106
+ if rel == base_dir or not rel.startswith(base_dir + "/"):
107
+ return False
108
+ sub_rel = rel[len(base_dir) + 1 :]
109
+ else:
110
+ sub_rel = rel
111
+ anchored = pattern.startswith("/")
112
+ pat = pattern.lstrip("/")
113
+ if pat.startswith("**/") and _matches_gitignore(sub_rel, "", pat[3:]):
114
+ return True
115
+ if anchored:
116
+ return fnmatch.fnmatch(sub_rel, pat) or fnmatch.fnmatch(sub_rel, f"{pat}/*")
117
+ if "/" not in pat:
118
+ return any(fnmatch.fnmatch(part, pat) for part in sub_rel.split("/"))
119
+ return (
120
+ fnmatch.fnmatch(sub_rel, pat)
121
+ or fnmatch.fnmatch(sub_rel, f"{pat}/*")
122
+ or fnmatch.fnmatch(sub_rel, f"*/{pat}")
123
+ or fnmatch.fnmatch(sub_rel, f"*/{pat}/*")
124
+ )
125
+
126
+
127
+ def load_repo_config(repo: Path) -> Dict[str, Any]:
128
+ cfg_path = repo / ".agent-index" / "config.json"
129
+ cfg: Dict[str, Any] = {
130
+ "exclude": [], "include": [], "max_file_bytes": MAX_BYTES_DEFAULT,
131
+ "map_budget_tokens": DEFAULT_MAP_BUDGET_TOKENS, "use_gitignore": True,
132
+ "auto_git_exclude": True,
133
+ }
134
+ if not cfg_path.is_symlink() and cfg_path.is_file() and is_within(cfg_path, repo):
135
+ try:
136
+ loaded = json.loads(cfg_path.read_text(encoding="utf-8"))
137
+ if isinstance(loaded, dict):
138
+ cfg.update(loaded)
139
+ except Exception:
140
+ pass
141
+ return cfg
142
+
143
+
144
+ def is_ignored(
145
+ rel: str,
146
+ extra_excludes: Sequence[str] = (),
147
+ gitignore_rules: Sequence[Any] = (),
148
+ extra_includes: Sequence[str] = (),
149
+ ) -> bool:
150
+ norm = normalize_rel_path(rel)
151
+ if not norm:
152
+ return True
153
+ parts = norm.split("/")
154
+ if any(p == ".." or p in EXCLUDED_DIRS for p in parts):
155
+ return True
156
+ # Hard secrets (.env, .pem, .key, .tfstate, service-account JSON) can NEVER be included
157
+ if HARD_SECRET_PATH_RE.search(norm):
158
+ return True
159
+ # Explicit config allowlist overrides soft secret names, root build dirs, and gitignore
160
+ explicitly_allowed = any(_matches_gitignore(norm, "", pat) for pat in extra_includes)
161
+ if explicitly_allowed:
162
+ return False
163
+ if parts[0] in ROOT_EXCLUDED_DIRS:
164
+ return True
165
+ if is_secret_path(norm):
166
+ return True
167
+ for pat in extra_excludes:
168
+ if _matches_gitignore(norm, "", pat):
169
+ return True
170
+ ignored = False
171
+ for rule in gitignore_rules:
172
+ if isinstance(rule, tuple) and len(rule) == 3:
173
+ base_dir, pat, negated = rule
174
+ elif isinstance(rule, tuple) and len(rule) == 2:
175
+ base_dir, pat, negated = rule[0], rule[1], False
176
+ else:
177
+ base_dir, pat, negated = "", str(rule), False
178
+ if _matches_gitignore(norm, base_dir, pat):
179
+ ignored = not negated
180
+ return ignored
181
+
182
+
183
+ def is_binary_bytes(raw: bytes) -> bool:
184
+ return b"\x00" in raw[:8192]