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,553 @@
1
+ """Stacktrace-to-code-slice (`trace-pack`) and affected-test discovery (`tests-for`)."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ import json
6
+ import re
7
+ import stat
8
+ from collections import defaultdict
9
+ from pathlib import Path
10
+ from typing import Any, Dict, List, Optional, Sequence, Set, Tuple
11
+
12
+ from _ae_core import estimate_tokens, is_within, normalize_rel_path, redact_secrets, sanitize_inline
13
+ from idx_db import db_open
14
+ from idx_ignore import MAX_BYTES_DEFAULT, is_binary_bytes, is_ignored, load_ancestor_gitignore_rules, load_repo_config
15
+ from idx_indexer import index
16
+ from idx_parsers import CODE_EXTS, extract_symbols_and_imports
17
+ from idx_search import _GIT_REF_RE, git_changed
18
+
19
+ _PY_TRACE_RE = re.compile(r'File\s+"([^"]+)",\s+line\s+(\d+)(?:,\s+in\s+([^\r\n]+))?')
20
+ _JS_AT_PAREN_RE = re.compile(r"\bat\s+(?:async\s+)?(?:([^\s(]+)\s+)?\((?:file://)?([^\s():]+?\.(?:[cm]?[jt]sx?|vue|svelte)):(\d+)(?::\d+)?\)")
21
+ _JS_AT_BARE_RE = re.compile(r"\bat\s+(?:async\s+)?(?:file://)?([^\s():]+?\.(?:[cm]?[jt]sx?|vue|svelte)):(\d+)(?::\d+)?")
22
+ _TSC_ERR_RE = re.compile(r"([^\s():]+?\.[cm]?tsx?)\((\d+),\d+\):\s*error\s+TS\d+")
23
+ _RUST_LOC_RE = re.compile(r"(?:-->|\bat)\s+([^\s:]+\.rs):(\d+)(?::\d+)?")
24
+ _GO_LOC_RE = re.compile(r"([^\s:]+\.go):(\d+)(?:\s+\+0x[0-9a-f]+|:)")
25
+ _JAVA_AT_RE = re.compile(r"\bat\s+([\w.$<>]+)\(([\w$-]+\.(?:java|kt|scala)):(\d+)\)")
26
+ _GENERIC_LOC_RE = re.compile(
27
+ r"(?<![A-Za-z0-9_/])([A-Za-z0-9_./-]+\.(?:py|ts|tsx|js|jsx|mjs|cjs|go|rs|java|kt|scala|rb|c|cpp|h|hpp|cs|php|swift|dart|vue|svelte)):(\d+)(?::\d+)?"
28
+ )
29
+
30
+ _EXTERNAL_SEGMENTS = (
31
+ "/site-packages/", "/dist-packages/", "/node_modules/", "/.venv/", "/venv/",
32
+ "/Library/Frameworks/", "/usr/lib/", "/usr/local/lib/", "/.cargo/registry/",
33
+ )
34
+
35
+ _TEST_FILE_RE = re.compile(
36
+ r"(?i)(?:^test_[^/]+\.py$|_test\.(?:py|go|rs)$|\.(?:test|spec)\.(?:[cm]?[jt]sx?)$|_spec\.rb$|(?:Test|Spec)\.(?:java|kt|cs|scala|swift|php)$)"
37
+ )
38
+ _TEST_DIR_RE = re.compile(r"(?i)(?:^|/)(?:tests?|__tests__|specs?)/")
39
+ _NON_TEST_HELPERS = {"conftest.py", "__init__.py", "setup.py", "test_utils.py", "test_helpers.py", "helpers.ts", "helpers.js", "fixtures.py", "fixtures.ts", "fixtures.js"}
40
+
41
+
42
+ def _resolve_frame_relpath(
43
+ repo: Path,
44
+ raw_path: str,
45
+ indexed_by_name: Dict[str, List[str]],
46
+ func_hint: str = "",
47
+ ) -> Optional[str]:
48
+ cleaned = raw_path.strip().strip("'\"")
49
+ if cleaned.startswith("file://"):
50
+ cleaned = cleaned[7:]
51
+ if not cleaned or cleaned.startswith("<") or any(seg in cleaned for seg in _EXTERNAL_SEGMENTS):
52
+ return None
53
+ p = Path(cleaned)
54
+ rel: Optional[str] = None
55
+ if p.is_absolute():
56
+ try:
57
+ rel = p.resolve().relative_to(repo).as_posix()
58
+ except Exception:
59
+ # Handle macOS /var vs /private/var or container path suffix matching
60
+ parts = cleaned.replace("\\", "/").split("/")
61
+ for i in range(1, len(parts)):
62
+ cand = "/".join(parts[i:])
63
+ if (repo / cand).is_file():
64
+ rel = normalize_rel_path(cand)
65
+ break
66
+ else:
67
+ cand = normalize_rel_path(cleaned)
68
+ if cand and not cand.startswith(".."):
69
+ if (repo / cand).is_file():
70
+ rel = cand
71
+ elif cand in indexed_by_name:
72
+ matches = indexed_by_name[cand]
73
+ if len(matches) == 1:
74
+ rel = matches[0]
75
+ elif matches and func_hint:
76
+ pkg_hint = func_hint.replace(".", "/").lower()
77
+ best = next((m for m in matches if any(seg in m.lower() for seg in pkg_hint.split("/")[:3] if len(seg) > 2)), matches[0])
78
+ rel = best
79
+
80
+ if not rel or rel.startswith(".."):
81
+ return None
82
+ try:
83
+ resolved = (repo / rel).resolve()
84
+ if not is_within(resolved, repo) or not resolved.is_file():
85
+ return None
86
+ return resolved.relative_to(repo).as_posix()
87
+ except Exception:
88
+ return None
89
+
90
+
91
+ def parse_stacktrace_frames(repo: Path, text: str) -> List[Dict[str, Any]]:
92
+ """Extract ordered, deduplicated, in-repository stacktrace frames across Python/JS/TS/Go/Rust/Java/linters."""
93
+ repo_r = repo.resolve()
94
+ cfg = load_repo_config(repo_r)
95
+ extra_excl = list(cfg.get("exclude", []))
96
+ extra_inc = list(cfg.get("include", []))
97
+ use_gi = bool(cfg.get("use_gitignore", True))
98
+
99
+ indexed_by_name: Dict[str, List[str]] = defaultdict(list)
100
+ db, _ = db_open(repo_r, read_only=True)
101
+ for (p,) in db.execute("SELECT path FROM files"):
102
+ indexed_by_name[Path(p).name].append(p)
103
+ db.close()
104
+
105
+ py_frames: List[Tuple[str, int, str]] = []
106
+ other_frames: List[Tuple[str, int, str]] = []
107
+
108
+ for line in text.splitlines():
109
+ matched_line = False
110
+ m = _PY_TRACE_RE.search(line)
111
+ if m:
112
+ py_frames.append((m.group(1), int(m.group(2)), (m.group(3) or "").strip()))
113
+ matched_line = True
114
+ if not matched_line:
115
+ m = _JS_AT_PAREN_RE.search(line)
116
+ if m:
117
+ other_frames.append((m.group(2), int(m.group(3)), (m.group(1) or "").strip()))
118
+ matched_line = True
119
+ if not matched_line:
120
+ m = _JS_AT_BARE_RE.search(line)
121
+ if m:
122
+ other_frames.append((m.group(1), int(m.group(2)), ""))
123
+ matched_line = True
124
+ if not matched_line:
125
+ m = _TSC_ERR_RE.search(line)
126
+ if m:
127
+ other_frames.append((m.group(1), int(m.group(2)), ""))
128
+ matched_line = True
129
+ if not matched_line:
130
+ m = _RUST_LOC_RE.search(line)
131
+ if m:
132
+ other_frames.append((m.group(1), int(m.group(2)), ""))
133
+ matched_line = True
134
+ if not matched_line:
135
+ m = _GO_LOC_RE.search(line)
136
+ if m:
137
+ other_frames.append((m.group(1), int(m.group(2)), ""))
138
+ matched_line = True
139
+ if not matched_line:
140
+ m = _JAVA_AT_RE.search(line)
141
+ if m:
142
+ other_frames.append((m.group(2), int(m.group(3)), m.group(1).strip()))
143
+ matched_line = True
144
+ if not matched_line:
145
+ m = _GENERIC_LOC_RE.search(line)
146
+ if m:
147
+ other_frames.append((m.group(1), int(m.group(2)), ""))
148
+
149
+ # Python tracebacks print deepest/root-cause frame LAST — reverse so failure site is prioritized first!
150
+ ordered_raw = list(reversed(py_frames)) + other_frames
151
+ frames: List[Dict[str, Any]] = []
152
+ seen: Set[Tuple[str, int]] = set()
153
+ for raw_p, ln, fn in ordered_raw:
154
+ rel = _resolve_frame_relpath(repo_r, raw_p, indexed_by_name, func_hint=fn)
155
+ if not rel or ln <= 0:
156
+ continue
157
+ gi = load_ancestor_gitignore_rules(repo_r, rel) if use_gi else []
158
+ if is_ignored(rel, extra_excl, gi, extra_inc):
159
+ continue
160
+ if (rel, ln) in seen:
161
+ continue
162
+ seen.add((rel, ln))
163
+ frames.append({"path": rel, "line": ln, "function": sanitize_inline(fn)})
164
+ return frames
165
+
166
+
167
+ def _enclosing_symbol(
168
+ db: Any,
169
+ repo: Path,
170
+ rel: str,
171
+ line_no: int,
172
+ content: str,
173
+ disk_sha: str,
174
+ ) -> Optional[Dict[str, Any]]:
175
+ idx_row = db.execute("SELECT sha FROM files WHERE path=?", (rel,)).fetchone()
176
+ if idx_row and idx_row[0] == disk_sha:
177
+ row = db.execute(
178
+ "SELECT name, qualified_name, kind, line, end_line, signature FROM symbols "
179
+ "WHERE path=? AND line <= ? AND end_line >= ? "
180
+ "ORDER BY (end_line - line) ASC, line DESC LIMIT 1",
181
+ (rel, line_no, line_no),
182
+ ).fetchone()
183
+ if row:
184
+ return {"name": row[0], "qualified_name": row[1], "kind": row[2], "line": row[3], "end_line": row[4], "signature": row[5]}
185
+ # Live parse fallback if unindexed or stale
186
+ lang = Path(rel).suffix.lower().lstrip(".") or Path(rel).name.lower()
187
+ syms, _ = extract_symbols_and_imports(content, lang)
188
+ enclosing = [s for s in syms if s[3] <= line_no <= s[4]]
189
+ if enclosing:
190
+ enclosing.sort(key=lambda s: (s[4] - s[3], -s[3]))
191
+ s = enclosing[0]
192
+ return {"name": s[0], "qualified_name": s[1], "kind": s[2], "line": s[3], "end_line": s[4], "signature": s[5]}
193
+ return None
194
+
195
+
196
+ def _render_trace_section_md(sec: Dict[str, Any]) -> str:
197
+ sym_part = f" :: {sec['symbol']}" if sec.get("symbol") else ""
198
+ hdr = f"## [trace] {sec['path']}:{sec['frame_line']}{sym_part} (L{sec['lines']})"
199
+ body = sec["content"].replace("</untrusted_repo_data>", "<\\/untrusted_repo_data>")
200
+ return "\n".join([hdr, f'<untrusted_repo_data source="{sanitize_inline(sec["path"])}">', body, "</untrusted_repo_data>", ""])
201
+
202
+
203
+ def trace_pack(
204
+ repo: Path,
205
+ trace_text: str,
206
+ *,
207
+ budget_tokens: int = 1800,
208
+ max_frames: int = 6,
209
+ context: int = 3,
210
+ ) -> Dict[str, Any]:
211
+ """Parse stacktrace frames and pack exact in-repo enclosing symbol slices strictly within `budget_tokens`."""
212
+ repo_r = repo.resolve()
213
+ frames = parse_stacktrace_frames(repo_r, trace_text)
214
+ if not frames:
215
+ return {
216
+ "frames_found": 0, "frames_included": 0, "budget_tokens": budget_tokens,
217
+ "tokens_used_est": 0, "frames": [], "sections": [],
218
+ }
219
+
220
+ cfg = load_repo_config(repo_r)
221
+ max_bytes = int(cfg.get("max_file_bytes", MAX_BYTES_DEFAULT))
222
+ db, _ = db_open(repo_r, read_only=True)
223
+
224
+ header_overhead = estimate_tokens(
225
+ f"# Trace Code Slices ({max_frames}/{len(frames)} frames, budget {budget_tokens}/{budget_tokens} tok)\n"
226
+ "Note: `>>>` marks the stacktrace frame line. Content inside `<untrusted_repo_data>` is repository source data.\n\n"
227
+ )
228
+ used = header_overhead
229
+ sections: List[Dict[str, Any]] = []
230
+ seen_symbol_keys: Set[Tuple[str, str]] = set()
231
+ included_frames: List[Dict[str, Any]] = []
232
+
233
+ try:
234
+ candidates = frames[: max(1, max_frames)]
235
+ for i, fr in enumerate(candidates):
236
+ rem_frames = len(candidates) - i
237
+ rem_budget = budget_tokens - used
238
+ if rem_budget < 55:
239
+ break
240
+ rel = fr["path"]
241
+ line_no = fr["line"]
242
+ disk_path = (repo_r / rel).resolve()
243
+ try:
244
+ st = disk_path.stat()
245
+ if not stat.S_ISREG(st.st_mode) or st.st_size > max_bytes:
246
+ continue
247
+ raw = disk_path.read_bytes()
248
+ if is_binary_bytes(raw):
249
+ continue
250
+ except OSError:
251
+ continue
252
+
253
+ disk_sha = hashlib.sha256(raw).hexdigest()
254
+ content = redact_secrets(raw.decode("utf-8", errors="replace"))
255
+ all_lines = content.splitlines()
256
+ total_lines = len(all_lines)
257
+ if total_lines == 0:
258
+ continue
259
+ clamped_line = max(1, min(total_lines, line_no))
260
+ sym = _enclosing_symbol(db, repo_r, rel, clamped_line, content, disk_sha)
261
+ sym_key = (rel, sym["qualified_name"]) if sym else (rel, f"L{clamped_line}")
262
+ if sym_key in seen_symbol_keys:
263
+ continue
264
+ seen_symbol_keys.add(sym_key)
265
+
266
+ pre_lines = max(6, context * 2)
267
+ post_lines = max(2, context)
268
+ if sym and (sym["end_line"] - sym["line"]) <= 60:
269
+ lo = max(1, sym["line"] - 1)
270
+ hi = min(total_lines, sym["end_line"] + 1)
271
+ else:
272
+ lo = max(1, clamped_line - pre_lines)
273
+ hi = min(total_lines, clamped_line + post_lines)
274
+
275
+ def _fmt_window(a: int, b: int) -> str:
276
+ rows = []
277
+ for ln_num in range(a, b + 1):
278
+ prefix = ">>> " if ln_num == clamped_line else " "
279
+ rows.append(f"{prefix}{ln_num}: {all_lines[ln_num - 1]}")
280
+ return "\n".join(rows)
281
+
282
+ per_cap = max(60, rem_budget // rem_frames)
283
+ body = _fmt_window(lo, hi)
284
+ sec = {
285
+ "kind": "trace_slice",
286
+ "path": rel,
287
+ "frame_line": clamped_line,
288
+ "symbol": sym["qualified_name"] if sym else (fr["function"] or None),
289
+ "lines": f"{lo}-{hi}",
290
+ "content": body,
291
+ }
292
+ sec_tok = estimate_tokens(_render_trace_section_md(sec))
293
+ # If enclosing symbol is too big for slice allowance, narrow around crash line (keeping wider pre-crash context)
294
+ if sec_tok > per_cap:
295
+ lo = max(1, clamped_line - pre_lines)
296
+ hi = min(total_lines, clamped_line + post_lines)
297
+ sec["lines"] = f"{lo}-{hi}"
298
+ sec["content"] = _fmt_window(lo, hi)
299
+ sec_tok = estimate_tokens(_render_trace_section_md(sec))
300
+ while sec_tok > rem_budget and (hi - lo) > 2:
301
+ if clamped_line - lo > (hi - clamped_line) * 2:
302
+ lo += 1
303
+ elif hi > clamped_line:
304
+ hi -= 1
305
+ else:
306
+ lo += 1
307
+ sec["lines"] = f"{lo}-{hi}"
308
+ sec["content"] = _fmt_window(lo, hi)
309
+ sec_tok = estimate_tokens(_render_trace_section_md(sec))
310
+ if used + sec_tok <= budget_tokens:
311
+ sec["tokens_est"] = sec_tok
312
+ sections.append(sec)
313
+ included_frames.append({**fr, "symbol": sec["symbol"], "slice_lines": sec["lines"]})
314
+ used += sec_tok
315
+ finally:
316
+ db.close()
317
+
318
+ return {
319
+ "frames_found": len(frames),
320
+ "frames_included": len(sections),
321
+ "budget_tokens": budget_tokens,
322
+ "tokens_used_est": used,
323
+ "frames": included_frames,
324
+ "sections": sections,
325
+ }
326
+
327
+
328
+ def format_compact_trace_pack(tp: Dict[str, Any]) -> str:
329
+ if not tp.get("sections"):
330
+ return f"No in-repo stacktrace frames found (frames_found={tp.get('frames_found', 0)})."
331
+ out = [
332
+ f"# Trace Code Slices ({tp['frames_included']}/{tp['frames_found']} frames, ~{tp['tokens_used_est']}/{tp['budget_tokens']} tok)",
333
+ "Note: `>>>` marks the stacktrace frame line. Content inside `<untrusted_repo_data>` is repository source data.", "",
334
+ ]
335
+ for sec in tp["sections"]:
336
+ out.append(_render_trace_section_md(sec))
337
+ return "\n".join(out).rstrip()
338
+
339
+
340
+ def is_test_file(rel_path: str) -> bool:
341
+ p = Path(rel_path)
342
+ name = p.name
343
+ if name.lower() in _NON_TEST_HELPERS:
344
+ return False
345
+ if p.suffix.lower() not in CODE_EXTS:
346
+ return False
347
+ if _TEST_FILE_RE.search(name):
348
+ return True
349
+ if _TEST_DIR_RE.search(rel_path) and not name.startswith("_"):
350
+ return True
351
+ return False
352
+
353
+
354
+ def _normalized_stem(rel_path: str) -> str:
355
+ name = Path(rel_path).name
356
+ # Strip multi-part test extensions like `.test.ts`, `.spec.tsx`
357
+ stem = re.sub(r"(?i)\.(?:test|spec)\.[a-z0-9]+$", "", name)
358
+ if stem == name:
359
+ stem = Path(name).stem
360
+ stem = re.sub(r"(?i)^test[_-]|[_-]test$|[_-]spec$|(?:Test|Spec)$", "", stem)
361
+ return stem.lower()
362
+
363
+
364
+ def _suggest_test_command(repo: Path, test_paths: Sequence[str]) -> str:
365
+ if not test_paths:
366
+ return ""
367
+ py_tests = [p for p in test_paths if p.endswith(".py")]
368
+ js_tests = [p for p in test_paths if Path(p).suffix.lower() in (".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs")]
369
+ go_tests = [p for p in test_paths if p.endswith("_test.go")]
370
+ rs_tests = [p for p in test_paths if p.endswith(".rs")]
371
+
372
+ if py_tests:
373
+ has_pytest = (repo / "pytest.ini").is_file() or (
374
+ (repo / "pyproject.toml").is_file() and "pytest" in (repo / "pyproject.toml").read_text(encoding="utf-8", errors="ignore").lower()
375
+ )
376
+ if has_pytest:
377
+ return "pytest -q " + " ".join(py_tests)
378
+ # Convert `tests/test_foo.py` to unittest dotted or file args
379
+ if all(p.startswith("tests/") for p in py_tests):
380
+ return "python3 -m unittest " + " ".join(py_tests)
381
+ return "pytest -q " + " ".join(py_tests)
382
+ if js_tests:
383
+ pkg_json = repo / "package.json"
384
+ runner = "npx vitest run"
385
+ if pkg_json.is_file():
386
+ txt = pkg_json.read_text(encoding="utf-8", errors="ignore").lower()
387
+ if '"jest"' in txt and '"vitest"' not in txt:
388
+ runner = "npx jest"
389
+ return f"{runner} " + " ".join(js_tests)
390
+ if go_tests:
391
+ pkgs = sorted({("./" + str(Path(p).parent).lstrip("./")) if str(Path(p).parent) != "." else "." for p in go_tests})
392
+ return "go test " + " ".join(pkgs)
393
+ if rs_tests:
394
+ names = sorted({_normalized_stem(p) for p in rs_tests if _normalized_stem(p)})
395
+ return "cargo test " + " ".join(names)
396
+ return " ".join(test_paths)
397
+
398
+
399
+ def find_affected_tests(
400
+ repo: Path,
401
+ paths: Sequence[str] = (),
402
+ *,
403
+ base: str = "HEAD",
404
+ depth: int = 2,
405
+ max_tests: int = 15,
406
+ ) -> Dict[str, Any]:
407
+ """Identify minimal affected test files from changed paths using reverse imports, callgraph, naming, and FTS5."""
408
+ repo_r = repo.resolve()
409
+ if not base or base.startswith("-") or "\x00" in base or not _GIT_REF_RE.fullmatch(base):
410
+ raise SystemExit(f"Invalid git ref for --base: {base!r}")
411
+
412
+ db_path = repo_r / ".agent-index" / "index.sqlite3"
413
+ if not db_path.is_file():
414
+ index(repo_r)
415
+
416
+ if paths:
417
+ target_paths = sorted({normalize_rel_path(p) for p in paths if normalize_rel_path(p)})
418
+ else:
419
+ ch = git_changed(repo_r, base=base)
420
+ if not ch.get("is_git"):
421
+ return {"changed_files": [], "affected_tests": [], "total_test_files_in_repo": 0, "tests_skipped_count": 0, "suggested_command": "", "error": ch.get("error", "Not a git repository")}
422
+ target_paths = [x["path"] for x in ch.get("changed_files", [])]
423
+
424
+ db, has_fts = db_open(repo_r, read_only=True)
425
+ try:
426
+ all_files = [r[0] for r in db.execute("SELECT path FROM files ORDER BY path")]
427
+ all_tests = [p for p in all_files if is_test_file(p)]
428
+ test_set = set(all_tests)
429
+
430
+ if not target_paths:
431
+ return {
432
+ "changed_files": [],
433
+ "affected_tests": [],
434
+ "total_test_files_in_repo": len(all_tests),
435
+ "tests_skipped_count": len(all_tests),
436
+ "suggested_command": "",
437
+ }
438
+
439
+ scores: Dict[str, float] = defaultdict(float)
440
+ reasons: Dict[str, List[str]] = defaultdict(list)
441
+
442
+ def _add(tp: str, pts: float, why: str) -> None:
443
+ scores[tp] += pts
444
+ if why not in reasons[tp]:
445
+ reasons[tp].append(why)
446
+
447
+ # Signal A: Changed file is itself a test file
448
+ for p in target_paths:
449
+ if p in test_set or is_test_file(p):
450
+ _add(p, 100.0, "directly modified test")
451
+
452
+ # Signal B: Reverse import dependency BFS up to `depth`
453
+ vis_dep = set(target_paths)
454
+ front_dep = [(p, 0, p) for p in target_paths]
455
+ while front_dep:
456
+ curr, d, origin = front_dep.pop(0)
457
+ if d >= max(1, depth):
458
+ continue
459
+ for (src,) in db.execute("SELECT src_path FROM edges WHERE dst_path=?", (curr,)):
460
+ if src in test_set:
461
+ _add(src, round(50.0 / (d + 1), 1), f"imports {origin} (d={d + 1})")
462
+ if src not in vis_dep:
463
+ vis_dep.add(src)
464
+ front_dep.append((src, d + 1, origin))
465
+
466
+ # Signal C: Reverse symbol callgraph BFS up to `depth`
467
+ has_calls = "calls" in {r[0] for r in db.execute("SELECT name FROM sqlite_master WHERE type='table'")}
468
+ changed_syms: List[Tuple[str, str, str]] = []
469
+ ph = ",".join("?" for _ in target_paths)
470
+ changed_syms = db.execute(
471
+ f"SELECT path, name, qualified_name FROM symbols WHERE path IN ({ph}) AND kind IN ('function','async_function','method','class')",
472
+ target_paths,
473
+ ).fetchall()
474
+
475
+ if has_calls and changed_syms:
476
+ vis_cg = {(p, q) for p, _n, q in changed_syms}
477
+ front_cg = [(p, n, q, 0) for p, n, q in changed_syms]
478
+ while front_cg:
479
+ cp, cn, cq, d = front_cg.pop(0)
480
+ if d >= max(1, depth):
481
+ continue
482
+ q_rows = db.execute(
483
+ "SELECT DISTINCT src_path, src_symbol FROM calls WHERE (dst_path=? AND LOWER(dst_symbol)=LOWER(?)) OR (dst_path IS NULL AND LOWER(callee_name)=LOWER(?)) LIMIT 60",
484
+ (cp, cq, cn),
485
+ ).fetchall()
486
+ for sp, ss in q_rows:
487
+ if sp in test_set:
488
+ _add(sp, round(45.0 / (d + 1), 1), f"calls {cq} (d={d + 1})")
489
+ if (sp, ss) not in vis_cg:
490
+ vis_cg.add((sp, ss))
491
+ front_cg.append((sp, ss.rsplit(".", 1)[-1], ss, d + 1))
492
+
493
+ # Signal D: Filename stem + directory heuristic
494
+ target_stems = {p: _normalized_stem(p) for p in target_paths if p not in test_set}
495
+ for tp in all_tests:
496
+ t_stem = _normalized_stem(tp)
497
+ if not t_stem or len(t_stem) < 2:
498
+ continue
499
+ tp_parts = set(Path(tp).parts[:-1])
500
+ for src_p, s_stem in target_stems.items():
501
+ if s_stem and len(s_stem) >= 2 and (t_stem == s_stem or s_stem in t_stem.split("_")):
502
+ bonus = 5.0 if (tp_parts & set(Path(src_p).parts[:-1])) else 0.0
503
+ _add(tp, 35.0 + bonus, f"filename match for {src_p}")
504
+
505
+ # Signal E: FTS5 symbol-name fallback inside test files (catches dynamic imports / fixtures)
506
+ if has_fts and changed_syms:
507
+ unique_names = list(dict.fromkeys(n for _p, n, _q in changed_syms if len(n) >= 4))[:12]
508
+ for sname in unique_names:
509
+ try:
510
+ for (fp,) in db.execute("SELECT path FROM files_fts WHERE files_fts MATCH ? LIMIT 25", (f'"{sname}"',)):
511
+ if fp in test_set:
512
+ _add(fp, 20.0, f"references symbol {sname}")
513
+ except Exception:
514
+ continue
515
+ finally:
516
+ db.close()
517
+
518
+ ranked = sorted(scores.items(), key=lambda kv: (-kv[1], kv[0]))[: max(1, max_tests)]
519
+ affected = [{"path": tp, "score": round(sc, 1), "reasons": reasons[tp][:4]} for tp, sc in ranked]
520
+ selected_paths = [a["path"] for a in affected]
521
+ from idx_parsers import treesitter_available
522
+ conf = "ast" if (treesitter_available() or (target_paths and all(p.endswith((".py", ".pyi")) for p in target_paths))) else "heuristic"
523
+ rmode = "ast-syntax-name-matched" if conf == "ast" else "heuristic-regex-name-matched"
524
+ return {
525
+ "changed_files": target_paths,
526
+ "analysis_confidence": conf,
527
+ "resolution_mode": rmode,
528
+ "affected_tests_count": len(affected),
529
+ "total_test_files_in_repo": len(all_tests),
530
+ "tests_skipped_count": max(0, len(all_tests) - len(affected)),
531
+ "affected_tests": affected,
532
+ "suggested_command": _suggest_test_command(repo_r, selected_paths),
533
+ }
534
+
535
+
536
+ def format_compact_tests_for(res: Dict[str, Any]) -> str:
537
+ if res.get("error"):
538
+ return f"tests-for error: {res['error']}"
539
+ if not res.get("changed_files"):
540
+ return f"No changed files detected ({res.get('total_test_files_in_repo', 0)} test files in repo)."
541
+ if not res.get("affected_tests"):
542
+ return f"No affected tests mapped for: {', '.join(res['changed_files'])} (total tests in repo: {res['total_test_files_in_repo']})."
543
+ conf = res.get("analysis_confidence", "heuristic")
544
+ conf_note = " [ast-syntax · name-matched — verify final full suite]" if conf == "ast" else " [heuristic · name-matched — run full suite before final commit]"
545
+ out = [
546
+ f"# Affected Tests ({res['affected_tests_count']}/{res['total_test_files_in_repo']} test files, skipping {res['tests_skipped_count']}){conf_note}",
547
+ f"Changed: {', '.join(res['changed_files'][:10])}",
548
+ ]
549
+ for a in res["affected_tests"]:
550
+ out.append(f"- `{a['path']}` (score={a['score']}): {'; '.join(a['reasons'])}")
551
+ if res.get("suggested_command"):
552
+ out.append(f"\nRun: `{res['suggested_command']}`")
553
+ return "\n".join(out)