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,780 @@
1
+ #!/usr/bin/env python3
2
+ """AgentEfficiency — Context-Bloat, MCP-Schema & Cache-Buster Doctor (`ae doctor`).
3
+
4
+ Strictly read-only diagnostic that measures always-on per-turn token overhead across:
5
+ 1. Instruction/rules files (CLAUDE.md, AGENTS.md, GEMINI.md, .cursorrules, .cursor/rules/*.mdc, copilot-instructions.md)
6
+ including cache-buster detection (timestamps/UUIDs/turn counters) and hardcoded secret leak scans.
7
+ 2. Installed agent skills always-loaded frontmatter descriptions.
8
+ 3. Configured MCP server tool-schema token tax (flagging heavy `full` profiles).
9
+ 4. Repository readiness (local index, `.git/info/exclude`, `tree-sitter` AST backend, oversized context-trap files).
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import json
15
+ import os
16
+ import re
17
+ import shutil
18
+ import sys
19
+ import time
20
+ from pathlib import Path
21
+ from typing import Any, Dict, List, Optional, Sequence, Tuple
22
+
23
+ _SCRIPT_DIR = str(Path(__file__).resolve().parent)
24
+ if _SCRIPT_DIR not in sys.path:
25
+ sys.path.insert(0, _SCRIPT_DIR)
26
+
27
+ from _ae_core import configure_utf8_stdio, estimate_tokens, find_secret_leak_lines, sanitize_inline # noqa: E402
28
+
29
+ # Cache-buster patterns (same core detectors as prompt_cache.py, zero cross-skill import required)
30
+ _CACHE_BUSTER_PATTERNS: Tuple[Tuple[str, re.Pattern[str]], ...] = (
31
+ ("iso_timestamp", re.compile(r"\b20\d{2}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2})?(?:Z|[+-]\d{2}:?\d{2})?\b")),
32
+ ("uuid", re.compile(r"\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}\b")),
33
+ ("turn_counter", re.compile(r"(?i)\b(?:turn|step|attempt|iteration)\s*[:=#]\s*\d+\b")),
34
+ ("volatile_tmp_path", re.compile(r"(?:/tmp/|/var/folders/|C:\\Users\\[^\\]+\\AppData\\Local\\Temp\\)")),
35
+ )
36
+ # Detect dynamic/volatile state file imports inside always-loaded rules (e.g. `@.agent-state/CHECKPOINT.md`)
37
+ _DYNAMIC_INCLUDE_RE = re.compile(
38
+ r"(?:(?:^|[\s(])@(?:[^\s)]*\.agent-state/[^\s)]+|[^\s)]*(?:CHECKPOINT|HANDOFF|CURRENT_STATE|TASK_QUEUE|MEMORY)\.md\b)"
39
+ r"|(?im:^\s*(?:include|import|source)\s*[:=]\s*[^\n]*(?:\.agent-state/|(?:CHECKPOINT|HANDOFF|CURRENT_STATE|TASK_QUEUE)\.md\b)))"
40
+ )
41
+
42
+ _DEFAULT_MCP_SCHEMA_TOKENS = 650
43
+ _AE_MCP_PROFILE_TOKENS = {"core": 622, "ide": 1200, "full": 3274}
44
+ _RULES_MARKER = "<!-- agent-efficiency:start -->"
45
+ _AE_OWN_SKILLS = {"local-context-index", "adaptive-orchestration-handoff", "prompt-cache-manager"}
46
+ _AST_EXTS = {".ts", ".tsx", ".js", ".jsx", ".mjs", ".go", ".rs", ".java", ".kt", ".swift"}
47
+ _SKIP_DIRS = {".git", "node_modules", ".venv", "venv", "__pycache__", "dist", "build", ".next", "target", ".agent-index", ".agent-state"}
48
+
49
+
50
+ def _box_row(text: str, width: int = 62) -> str:
51
+ clipped = text if len(text) <= width else (text[: max(1, width - 1)] + "…")
52
+ return f"│{clipped:<{width}}│"
53
+
54
+
55
+ def _bar(fraction: float, width: int = 16) -> str:
56
+ f = max(0.0, min(1.0, fraction))
57
+ n = int(round(f * width))
58
+ return "█" * n + "░" * (width - n)
59
+
60
+
61
+ def _fmt_tok(n: int) -> str:
62
+ if n >= 1_000_000:
63
+ return f"{n / 1_000_000:.2f}M"
64
+ if n >= 1_000:
65
+ return f"{n / 1_000:.1f}k"
66
+ return str(n)
67
+
68
+
69
+ def _lint_prompt_file(path: Path) -> Dict[str, Any]:
70
+ text = path.read_text(encoding="utf-8", errors="replace")
71
+ tok = estimate_tokens(text)
72
+ lines = text.splitlines()
73
+ busters: List[str] = []
74
+ for label, pat in _CACHE_BUSTER_PATTERNS:
75
+ if pat.search(text):
76
+ busters.append(label)
77
+ dyn_includes = sorted({m.group(0).strip() for m in _DYNAMIC_INCLUDE_RE.finditer(text)})[:10]
78
+ if dyn_includes:
79
+ busters.append("dynamic_state_include")
80
+ secret_hits = find_secret_leak_lines(text)
81
+ return {
82
+ "path": str(path),
83
+ "lines": len(lines),
84
+ "tokens_est": tok,
85
+ "has_ae_rules": _RULES_MARKER in text,
86
+ "cache_busters": busters,
87
+ "dynamic_includes": dyn_includes,
88
+ "secret_leaks_count": len(secret_hits),
89
+ "secret_leak_lines": secret_hits[:10],
90
+ }
91
+
92
+
93
+ def _scan_rules_files(repo: Path, home: Path, include_global: bool) -> Tuple[List[Dict[str, Any]], bool]:
94
+ candidates: List[Tuple[str, Path]] = [
95
+ ("repo", repo / "CLAUDE.md"),
96
+ ("repo", repo / "AGENTS.md"),
97
+ ("repo", repo / "GEMINI.md"),
98
+ ("repo", repo / ".cursorrules"),
99
+ ("repo", repo / ".github" / "copilot-instructions.md"),
100
+ ("repo", repo / ".windsurfrules"),
101
+ ]
102
+ cursor_rules_dir = repo / ".cursor" / "rules"
103
+ if cursor_rules_dir.is_dir():
104
+ for p in sorted(cursor_rules_dir.glob("*.mdc"))[:20]:
105
+ candidates.append(("repo", p))
106
+ if include_global:
107
+ candidates.extend([
108
+ ("global", home / ".claude" / "CLAUDE.md"),
109
+ ("global", home / ".gemini" / "GEMINI.md"),
110
+ ("global", home / ".codex" / "AGENTS.md"),
111
+ ("global", home / ".agents" / "AGENTS.md"),
112
+ ("global", home / ".config" / "opencode" / "AGENTS.md"),
113
+ ("global", home / ".codeium" / "windsurf" / "memories" / "global_rules.md"),
114
+ ])
115
+ g_cursor = home / ".cursor" / "rules"
116
+ if g_cursor.is_dir():
117
+ for p in sorted(g_cursor.glob("*.mdc"))[:10]:
118
+ candidates.append(("global", p))
119
+
120
+ seen: set[Path] = set()
121
+ items: List[Dict[str, Any]] = []
122
+ has_ae_rules = False
123
+ for scope, p in candidates:
124
+ try:
125
+ if not p.is_file():
126
+ continue
127
+ rp = p.resolve()
128
+ if rp in seen:
129
+ continue
130
+ seen.add(rp)
131
+ info = _lint_prompt_file(p)
132
+ info["scope"] = scope
133
+ info["display"] = p.relative_to(repo).as_posix() if scope == "repo" else f"~/{p.relative_to(home).as_posix()}"
134
+ if info["has_ae_rules"]:
135
+ has_ae_rules = True
136
+ items.append(info)
137
+ except OSError:
138
+ continue
139
+ items.sort(key=lambda x: (-x["tokens_est"], x["display"]))
140
+ return items, has_ae_rules
141
+
142
+
143
+ def _extract_frontmatter_desc(skill_md: Path) -> Tuple[str, str]:
144
+ try:
145
+ raw = skill_md.read_text(encoding="utf-8", errors="replace").replace("\r\n", "\n")
146
+ except OSError:
147
+ return skill_md.parent.name, ""
148
+ if not raw.startswith("---\n"):
149
+ return skill_md.parent.name, ""
150
+ end = raw.find("\n---\n", 4)
151
+ if end == -1:
152
+ return skill_md.parent.name, ""
153
+ name = skill_md.parent.name
154
+ desc = ""
155
+ for line in raw[4:end].splitlines():
156
+ if ":" in line:
157
+ k, v = line.split(":", 1)
158
+ kl = k.strip().lower()
159
+ val = v.strip().strip('"').strip("'")
160
+ if kl == "name" and val:
161
+ name = val
162
+ elif kl == "description" and val:
163
+ desc = val
164
+ return name, desc
165
+
166
+
167
+ def _skill_roots(home: Path) -> List[Tuple[str, Path]]:
168
+ return [
169
+ ("claude", home / ".claude" / "skills"),
170
+ ("gemini", home / ".gemini" / "config" / "skills"),
171
+ ("codex", home / ".codex" / "skills"),
172
+ ("cursor", home / ".cursor" / "skills"),
173
+ ("agents", home / ".agents" / "skills"),
174
+ ("opencode", home / ".config" / "opencode" / "skills"),
175
+ ("windsurf", home / ".codeium" / "windsurf" / "skills"),
176
+ ("copilot", home / ".copilot" / "skills"),
177
+ ]
178
+
179
+
180
+ def _scan_skills_overhead(home: Path, include_global: bool) -> Dict[str, Any]:
181
+ if not include_global:
182
+ return {"directories": [], "total_skills": 0, "unique_skills": 0, "always_on_tokens_est": 0, "heaviest_skills": []}
183
+ skill_roots = _skill_roots(home)
184
+ dirs_summary: List[Dict[str, Any]] = []
185
+ unique_by_name: Dict[str, Dict[str, Any]] = {}
186
+ max_dir_tok = 0
187
+ for label, sdir in skill_roots:
188
+ if not sdir.is_dir():
189
+ continue
190
+ count = 0
191
+ dir_tok = 0
192
+ try:
193
+ for child in sorted(sdir.iterdir()):
194
+ if not child.is_dir() or child.name.startswith("."):
195
+ continue
196
+ smd = child / "SKILL.md"
197
+ if not smd.is_file():
198
+ continue
199
+ sname, desc = _extract_frontmatter_desc(smd)
200
+ dtok = estimate_tokens(f"{sname}: {desc}")
201
+ disp_dir = f"~/{child.relative_to(home).as_posix()}"
202
+ disp_md = f"~/{smd.relative_to(home).as_posix()}"
203
+ count += 1
204
+ dir_tok += dtok
205
+ prev = unique_by_name.get(sname)
206
+ if prev is None or dtok > prev["tokens_est"]:
207
+ locs = list(prev["locations"]) if prev else []
208
+ abs_locs = list(prev["abs_paths"]) if prev else []
209
+ if disp_dir not in locs:
210
+ locs.append(disp_dir)
211
+ if str(child) not in abs_locs:
212
+ abs_locs.append(str(child))
213
+ unique_by_name[sname] = {
214
+ "name": sname,
215
+ "dir_name": child.name,
216
+ "tokens_est": dtok,
217
+ "chars": len(desc),
218
+ "runtime": label,
219
+ "display_path": disp_md,
220
+ "display_dir": disp_dir,
221
+ "locations": locs,
222
+ "abs_paths": abs_locs,
223
+ }
224
+ else:
225
+ if disp_dir not in prev["locations"]:
226
+ prev["locations"].append(disp_dir)
227
+ if str(child) not in prev["abs_paths"]:
228
+ prev["abs_paths"].append(str(child))
229
+ except OSError:
230
+ continue
231
+ if count > 0:
232
+ max_dir_tok = max(max_dir_tok, dir_tok)
233
+ dirs_summary.append({"runtime": label, "dir": f"~/{sdir.relative_to(home).as_posix()}", "skills": count, "tokens_est": dir_tok})
234
+ heaviest_full = sorted(unique_by_name.values(), key=lambda item: (-item["tokens_est"], item["name"]))
235
+ heaviest = [
236
+ {
237
+ "name": item["name"],
238
+ "tokens_est": item["tokens_est"],
239
+ "chars": item["chars"],
240
+ "runtime": item["runtime"],
241
+ "display_path": item["display_path"],
242
+ "display_dir": item["display_dir"],
243
+ "locations": item["locations"],
244
+ }
245
+ for item in heaviest_full[:10]
246
+ ]
247
+ return {
248
+ "directories": dirs_summary,
249
+ "total_skills": sum(d["skills"] for d in dirs_summary),
250
+ "unique_skills": len(unique_by_name),
251
+ # A single IDE runtime loads its own skills dir; report peak single-runtime load as always-on cost
252
+ "always_on_tokens_est": max_dir_tok,
253
+ "heaviest_skills": heaviest,
254
+ "_all_skills": heaviest_full,
255
+ }
256
+
257
+
258
+ def prune_skills(
259
+ *,
260
+ home: Optional[Path] = None,
261
+ skill_names: Sequence[str] = (),
262
+ top_n: int = 0,
263
+ min_tokens: int = 0,
264
+ apply: bool = False,
265
+ restore: Sequence[str] = (),
266
+ ) -> Dict[str, Any]:
267
+ """Safely archive heavy/unused installed skills into `~/.agent-efficiency/archived-skills/` (dry-run by default)."""
268
+ home_r = (home or Path.home()).expanduser().resolve()
269
+ archive_root = home_r / ".agent-efficiency" / "archived-skills"
270
+ manifest_path = archive_root / "manifest.json"
271
+
272
+ def _load_manifest() -> Dict[str, Any]:
273
+ if manifest_path.is_file():
274
+ try:
275
+ data = json.loads(manifest_path.read_text(encoding="utf-8"))
276
+ if isinstance(data, dict):
277
+ return data
278
+ except Exception:
279
+ pass
280
+ return {"archived": []}
281
+
282
+ if restore:
283
+ wanted_r = {r.strip() for r in restore if r and r.strip()}
284
+ man = _load_manifest()
285
+ restored: List[Dict[str, str]] = []
286
+ remaining: List[Dict[str, Any]] = []
287
+ for entry in man.get("archived", []):
288
+ if entry.get("name") in wanted_r or entry.get("dir_name") in wanted_r:
289
+ arch_p = Path(entry["archive_path"])
290
+ orig_p = Path(entry["original_path"])
291
+ if arch_p.is_dir() and not orig_p.exists():
292
+ if apply:
293
+ orig_p.parent.mkdir(parents=True, exist_ok=True)
294
+ shutil.move(str(arch_p), str(orig_p))
295
+ restored.append({
296
+ "name": entry.get("name", ""),
297
+ "from": str(arch_p),
298
+ "to": str(orig_p),
299
+ "action": "restored" if apply else "would_restore",
300
+ })
301
+ if not apply:
302
+ remaining.append(entry)
303
+ continue
304
+ remaining.append(entry)
305
+ if apply and restored:
306
+ archive_root.mkdir(parents=True, exist_ok=True)
307
+ manifest_path.write_text(json.dumps({"archived": remaining}, indent=2) + "\n", encoding="utf-8")
308
+ return {"mode": "restore", "apply": apply, "count": len(restored), "actions": restored}
309
+
310
+ skills_info = _scan_skills_overhead(home_r, include_global=True)
311
+ all_sk = [s for s in skills_info.get("_all_skills", []) if s["name"] not in _AE_OWN_SKILLS and s["dir_name"] not in _AE_OWN_SKILLS]
312
+
313
+ wanted_names = {n.strip().lower() for n in skill_names if n and n.strip()}
314
+ selected: List[Dict[str, Any]] = []
315
+ if wanted_names:
316
+ selected = [s for s in all_sk if s["name"].lower() in wanted_names or s["dir_name"].lower() in wanted_names]
317
+ elif min_tokens > 0:
318
+ selected = [s for s in all_sk if int(s["tokens_est"]) >= min_tokens]
319
+ if top_n > 0:
320
+ selected = selected[:top_n]
321
+ else:
322
+ n_take = top_n if top_n > 0 else 5
323
+ selected = all_sk[:n_take]
324
+
325
+ actions: List[Dict[str, Any]] = []
326
+ man = _load_manifest()
327
+ ts_tag = time.strftime("%Y%m%d-%H%M%S")
328
+ tokens_reclaimed = 0
329
+
330
+ for item in selected:
331
+ tokens_reclaimed += int(item["tokens_est"])
332
+ for abs_str in item["abs_paths"]:
333
+ src = Path(abs_str)
334
+ if not src.is_dir():
335
+ continue
336
+ rt_name = item["runtime"]
337
+ for r_lbl, r_root in _skill_roots(home_r):
338
+ try:
339
+ src.relative_to(r_root)
340
+ rt_name = r_lbl
341
+ break
342
+ except ValueError:
343
+ continue
344
+ dst = archive_root / rt_name / src.name
345
+ if dst.exists():
346
+ dst = archive_root / rt_name / f"{src.name}-{ts_tag}"
347
+ if apply:
348
+ dst.parent.mkdir(parents=True, exist_ok=True)
349
+ shutil.move(str(src), str(dst))
350
+ man["archived"].append({
351
+ "name": item["name"],
352
+ "dir_name": src.name,
353
+ "runtime": rt_name,
354
+ "tokens_est": int(item["tokens_est"]),
355
+ "original_path": str(src),
356
+ "archive_path": str(dst),
357
+ "archived_at": ts_tag,
358
+ })
359
+ actions.append({
360
+ "name": item["name"],
361
+ "runtime": rt_name,
362
+ "tokens_est": int(item["tokens_est"]),
363
+ "from": str(src),
364
+ "to": str(dst),
365
+ "action": "archived" if apply else "would_archive",
366
+ })
367
+
368
+ if apply and actions:
369
+ archive_root.mkdir(parents=True, exist_ok=True)
370
+ manifest_path.write_text(json.dumps(man, indent=2) + "\n", encoding="utf-8")
371
+
372
+ return {
373
+ "mode": "prune",
374
+ "apply": apply,
375
+ "archive_dir": str(archive_root),
376
+ "selected_skills": len(selected),
377
+ "directories_affected": len(actions),
378
+ "tokens_reclaimed_est": tokens_reclaimed,
379
+ "actions": actions,
380
+ }
381
+
382
+
383
+ def _scan_mcp_overhead(repo: Path, home: Path, include_global: bool) -> Dict[str, Any]:
384
+ cfg_candidates: List[Tuple[str, Path]] = [
385
+ ("repo/.mcp.json", repo / ".mcp.json"),
386
+ ("repo/.cursor/mcp.json", repo / ".cursor" / "mcp.json"),
387
+ ("repo/.claude/settings.local.json", repo / ".claude" / "settings.local.json"),
388
+ ("repo/.gemini/settings.json", repo / ".gemini" / "settings.json"),
389
+ ]
390
+ if include_global:
391
+ cfg_candidates.extend([
392
+ ("~/.claude.json", home / ".claude.json"),
393
+ ("~/.claude/settings.json", home / ".claude" / "settings.json"),
394
+ ("~/.gemini/settings.json", home / ".gemini" / "settings.json"),
395
+ ("~/.cursor/mcp.json", home / ".cursor" / "mcp.json"),
396
+ ("~/.codex/mcp.json", home / ".codex" / "mcp.json"),
397
+ ])
398
+
399
+ servers: List[Dict[str, Any]] = []
400
+ seen_keys: set[Tuple[str, str]] = set()
401
+ ae_full_profile_found = False
402
+
403
+ for source_lbl, path in cfg_candidates:
404
+ if not path.is_file():
405
+ continue
406
+ try:
407
+ data = json.loads(path.read_text(encoding="utf-8", errors="replace"))
408
+ except Exception:
409
+ continue
410
+ if not isinstance(data, dict):
411
+ continue
412
+ mcp_map = data.get("mcpServers")
413
+ if not isinstance(mcp_map, dict):
414
+ continue
415
+ for srv_name, spec in sorted(mcp_map.items()):
416
+ key = (source_lbl, str(srv_name))
417
+ if key in seen_keys:
418
+ continue
419
+ seen_keys.add(key)
420
+ est_tok = _DEFAULT_MCP_SCHEMA_TOKENS
421
+ note = "estimated"
422
+ if str(srv_name).lower() in ("agent-efficiency", "agentefficiency", "ae"):
423
+ args_list = spec.get("args", []) if isinstance(spec, dict) else []
424
+ env_map = spec.get("env", {}) if isinstance(spec, dict) else {}
425
+ prof = "full"
426
+ if isinstance(args_list, list):
427
+ for i, a in enumerate(args_list):
428
+ if a == "--profile" and i + 1 < len(args_list):
429
+ prof = str(args_list[i + 1]).lower()
430
+ elif isinstance(a, str) and a.startswith("--profile="):
431
+ prof = a.split("=", 1)[1].lower()
432
+ if prof == "full" and isinstance(env_map, dict):
433
+ ep = str(env_map.get("AGENT_EFFICIENCY_MCP_PROFILE", "")).strip().lower()
434
+ if ep in _AE_MCP_PROFILE_TOKENS:
435
+ prof = ep
436
+ est_tok = _AE_MCP_PROFILE_TOKENS.get(prof, _AE_MCP_PROFILE_TOKENS["full"])
437
+ note = f"profile={prof}"
438
+ if prof == "full":
439
+ ae_full_profile_found = True
440
+ servers.append({"name": sanitize_inline(str(srv_name)), "source": source_lbl, "est_schema_tokens": est_tok, "note": note})
441
+
442
+ # Deduplicate by server name for realistic single-session estimate
443
+ dedup_tok: Dict[str, int] = {}
444
+ for s in servers:
445
+ dedup_tok[s["name"]] = max(dedup_tok.get(s["name"], 0), int(s["est_schema_tokens"]))
446
+ return {
447
+ "servers": servers,
448
+ "unique_server_count": len(dedup_tok),
449
+ "est_schema_tokens_per_turn": sum(dedup_tok.values()),
450
+ "ae_full_profile_detected": ae_full_profile_found,
451
+ }
452
+
453
+
454
+ def _scan_repo_hygiene(repo: Path) -> Dict[str, Any]:
455
+ index_db = repo / ".agent-index" / "index.sqlite3"
456
+ has_index = index_db.is_file()
457
+ git_excl = repo / ".git" / "info" / "exclude"
458
+ excl_txt = git_excl.read_text(encoding="utf-8", errors="replace") if git_excl.is_file() else ""
459
+ has_git_exclude = ".agent-index/" in excl_txt
460
+
461
+ has_ts_or_compiled = False
462
+ large_files: List[Dict[str, Any]] = []
463
+ file_count = 0
464
+ for dirpath, dirnames, filenames in os.walk(repo, followlinks=False):
465
+ dirnames[:] = [d for d in dirnames if d not in _SKIP_DIRS and not d.startswith(".git")]
466
+ dp = Path(dirpath)
467
+ for fn in filenames:
468
+ file_count += 1
469
+ if file_count > 4000:
470
+ break
471
+ p = dp / fn
472
+ ext = p.suffix.lower()
473
+ if ext in _AST_EXTS:
474
+ has_ts_or_compiled = True
475
+ try:
476
+ sz = p.stat().st_size
477
+ except OSError:
478
+ continue
479
+ if sz >= 50_000 and ext in (".json", ".lock", ".yaml", ".yml", ".csv", ".sql", ".md", ".txt", ".js", ".ts", ".py", ".xml"):
480
+ try:
481
+ rel = p.relative_to(repo).as_posix()
482
+ except ValueError:
483
+ rel = fn
484
+ large_files.append({"path": rel, "bytes": sz, "tokens_est": sz // 4})
485
+ if file_count > 4000:
486
+ break
487
+
488
+ large_files.sort(key=lambda x: -x["bytes"])
489
+ ts_installed = False
490
+ for mod in ("tree_sitter_language_pack", "tree_sitter_languages"):
491
+ try:
492
+ __import__(mod)
493
+ ts_installed = True
494
+ break
495
+ except Exception:
496
+ continue
497
+
498
+ return {
499
+ "file_count_scanned": file_count,
500
+ "has_index": has_index,
501
+ "has_git_exclude": has_git_exclude,
502
+ "has_non_python_code": has_ts_or_compiled,
503
+ "tree_sitter_installed": ts_installed,
504
+ "large_context_trap_files": large_files[:6],
505
+ }
506
+
507
+
508
+ def run_doctor(
509
+ repo: Path,
510
+ *,
511
+ home: Optional[Path] = None,
512
+ include_global: bool = True,
513
+ ) -> Dict[str, Any]:
514
+ """Run full read-only context bloat, cache-buster, MCP schema, and repo hygiene audit."""
515
+ repo_r = repo.expanduser().resolve()
516
+ home_r = (home or Path.home()).expanduser().resolve()
517
+
518
+ rules_files, has_ae_rules = _scan_rules_files(repo_r, home_r, include_global=include_global)
519
+ skills = _scan_skills_overhead(home_r, include_global=include_global)
520
+ skills.pop("_all_skills", None)
521
+ mcp = _scan_mcp_overhead(repo_r, home_r, include_global=include_global)
522
+ hygiene = _scan_repo_hygiene(repo_r)
523
+
524
+ rules_tok = sum(f["tokens_est"] for f in rules_files)
525
+ skills_tok = int(skills["always_on_tokens_est"])
526
+ mcp_tok = int(mcp["est_schema_tokens_per_turn"])
527
+ total_always_on = rules_tok + skills_tok + mcp_tok
528
+
529
+ # Estimate monthly uncached + cached cost of always-on tax (40 turns/day * 22 days = 880 turns/mo, 85% cached @ 10%)
530
+ monthly_turns = 880
531
+ eff_monthly_tok = total_always_on * monthly_turns * (0.15 + 0.85 * 0.10)
532
+ est_monthly_usd = round((eff_monthly_tok / 1_000_000.0) * 3.00, 2)
533
+
534
+ score = 100
535
+ findings: List[Dict[str, str]] = []
536
+
537
+ secret_files = [f for f in rules_files if f["secret_leaks_count"] > 0]
538
+ if secret_files:
539
+ score -= 25
540
+ findings.append({
541
+ "severity": "critical",
542
+ "area": "secrets",
543
+ "message": f"Hardcoded secret literal detected in {len(secret_files)} prompt/rules file(s): {', '.join(f['display'] for f in secret_files[:3])}",
544
+ "fix": "Remove raw secrets from rules/prompt files immediately and rotate affected keys.",
545
+ })
546
+
547
+ dyn_inc_files = [f for f in rules_files if f.get("dynamic_includes")]
548
+ if dyn_inc_files:
549
+ score -= 15
550
+ inc_examples = ", ".join(sorted({inc for f in dyn_inc_files for inc in f["dynamic_includes"]})[:3])
551
+ findings.append({
552
+ "severity": "high",
553
+ "area": "prompt-cache",
554
+ "message": f"Dynamic state/checkpoint include ({inc_examples}) found in always-on rules: {', '.join(f['display'] for f in dyn_inc_files[:3])}",
555
+ "fix": "Never @-import mutable .agent-state/* or CHECKPOINT.md/HANDOFF.md in CLAUDE.md/AGENTS.md (invalidates prompt cache prefix on every checkpoint). Load on demand via `ae brief` instead.",
556
+ })
557
+
558
+ buster_files = [f for f in rules_files if [b for b in f["cache_busters"] if b != "dynamic_state_include"]]
559
+ if buster_files:
560
+ score -= 15
561
+ findings.append({
562
+ "severity": "high",
563
+ "area": "prompt-cache",
564
+ "message": f"Cache-busters ({', '.join(sorted({b for f in buster_files for b in f['cache_busters'] if b != 'dynamic_state_include'}))}) found in {', '.join(f['display'] for f in buster_files[:3])}",
565
+ "fix": "Move volatile timestamps/UUIDs/turn counters out of static CLAUDE.md/AGENTS.md files so provider prefix caching stays warm.",
566
+ })
567
+
568
+ if mcp["ae_full_profile_detected"]:
569
+ score -= 12
570
+ findings.append({
571
+ "severity": "high",
572
+ "area": "mcp",
573
+ "message": "AgentEfficiency MCP is configured with `full` (39 tools, ~3.4k tok/turn) instead of lean `core` (7 tools, ~550 tok/turn).",
574
+ "fix": "Switch MCP args to `--profile core` (saves ~2.8k schema tokens EVERY turn).",
575
+ })
576
+
577
+ if mcp_tok > 3500:
578
+ score -= min(20, (mcp_tok - 3500) // 400 + 5)
579
+ findings.append({
580
+ "severity": "high" if mcp_tok > 6000 else "medium",
581
+ "area": "mcp",
582
+ "message": f"{mcp['unique_server_count']} MCP server(s) add ~{mcp_tok:,} schema tokens per turn.",
583
+ "fix": "Disable unused MCP servers or prefer zero-schema CLI skills (`ae`) over heavy MCP tool packs.",
584
+ })
585
+
586
+ if rules_tok > 2500:
587
+ score -= min(18, (rules_tok - 2500) // 500 + 5)
588
+ heavy_r = rules_files[0]["display"] if rules_files else "CLAUDE.md"
589
+ findings.append({
590
+ "severity": "medium",
591
+ "area": "rules",
592
+ "message": f"Always-loaded rules/instructions consume ~{rules_tok:,} tok/turn (heaviest: `{heavy_r}`).",
593
+ "fix": "Move reference docs out of CLAUDE.md/AGENTS.md into linked on-demand files.",
594
+ })
595
+
596
+ if skills_tok > 1800:
597
+ score -= min(15, (skills_tok - 1800) // 400 + 4)
598
+ top_names = ", ".join(f"{s['name']}(~{s['tokens_est']})" for s in skills.get("heaviest_skills", [])[:3])
599
+ top_hint = f" [heaviest: {top_names}]" if top_names else ""
600
+ findings.append({
601
+ "severity": "medium",
602
+ "area": "skills",
603
+ "message": f"Installed skill descriptions consume ~{skills_tok:,} always-on tokens ({skills['unique_skills']} skills){top_hint}.",
604
+ "fix": "Archive unused heavy skills safely via `ae doctor --prune --top 10` (dry-run; add `--apply` to archive) or trim `description:` (<200 chars).",
605
+ })
606
+
607
+ if hygiene["file_count_scanned"] >= 15 and not hygiene["has_index"]:
608
+ score -= 8
609
+ findings.append({
610
+ "severity": "medium",
611
+ "area": "index",
612
+ "message": f"Repo has {hygiene['file_count_scanned']} files but no `.agent-index/` yet.",
613
+ "fix": "Run `ae init` (or `ae index`) for incremental FTS5 search, multi-slice, and affected-test discovery.",
614
+ })
615
+
616
+ if not has_ae_rules:
617
+ score -= 6
618
+ findings.append({
619
+ "severity": "low",
620
+ "area": "workflow",
621
+ "message": "No AgentEfficiency workflow rules found in CLAUDE.md / AGENTS.md / GEMINI.md / Cursor rules.",
622
+ "fix": "Run `ae init` to merge the 6-line `ae` rules block (add `--hooks` for safe hints or `--auto-wrap` for opt-in test wrapping).",
623
+ })
624
+
625
+ if hygiene["has_non_python_code"] and not hygiene["tree_sitter_installed"]:
626
+ findings.append({
627
+ "severity": "info",
628
+ "area": "parser",
629
+ "message": "Repo contains JS/TS/Go/Rust/Java code running on heuristic stdlib parser.",
630
+ "fix": "Optional upgrade for full AST precision: `pip install tree-sitter-language-pack` (or `pip install 'agent-efficiency[ast]'`).",
631
+ })
632
+
633
+ if hygiene["large_context_trap_files"]:
634
+ top_big = hygiene["large_context_trap_files"][0]
635
+ findings.append({
636
+ "severity": "info",
637
+ "area": "hygiene",
638
+ "message": f"Large context-trap file detected: `{top_big['path']}` (~{_fmt_tok(top_big['tokens_est'])} tok if read whole).",
639
+ "fix": "Add generated/lock/data dumps to `.agent-index/config.json` exclude or `.gitignore` and use `ae slice`.",
640
+ })
641
+
642
+ score = max(0, min(100, score))
643
+ grade = "A" if score >= 90 else ("B" if score >= 75 else ("C" if score >= 55 else "D"))
644
+ return {
645
+ "repo": str(repo_r),
646
+ "health_score": score,
647
+ "grade": grade,
648
+ "always_on_tokens_per_turn": {
649
+ "total": total_always_on,
650
+ "rules": rules_tok,
651
+ "skills": skills_tok,
652
+ "mcp_schemas": mcp_tok,
653
+ "est_monthly_overhead_usd": est_monthly_usd,
654
+ },
655
+ "rules_files": rules_files,
656
+ "skills": skills,
657
+ "mcp": mcp,
658
+ "repo_hygiene": hygiene,
659
+ "findings": findings,
660
+ }
661
+
662
+
663
+ def format_doctor_card(rep: Dict[str, Any]) -> str:
664
+ ao = rep["always_on_tokens_per_turn"]
665
+ tot = max(1, int(ao["total"]))
666
+ score = int(rep["health_score"])
667
+ grade = rep["grade"]
668
+ repo_name = Path(rep["repo"]).name
669
+
670
+ hdr_right = f"Grade {grade} ({score:>3}/100)"
671
+ max_name = max(8, 62 - len(" AgentEfficiency Doctor · ") - len(hdr_right) - 1)
672
+ r_disp = repo_name if len(repo_name) <= max_name else (repo_name[: max_name - 1] + "…")
673
+ hdr_row = f" AgentEfficiency Doctor · {r_disp:<{max_name}} {hdr_right}"
674
+
675
+ lines = [
676
+ "┌──────────────────────────────────────────────────────────────┐",
677
+ _box_row(hdr_row),
678
+ "├──────────────────────────────────────────────────────────────┤",
679
+ _box_row(f" Always-On Tax : ~{_fmt_tok(ao['total']):>6} tok/turn (~${ao['est_monthly_overhead_usd']:.2f}/mo @ 880 turns)"),
680
+ "├──────────────────────────────────────────────────────────────┤",
681
+ ]
682
+ for label, val in (
683
+ ("Rules/Prompts", ao["rules"]),
684
+ ("Skill Descs ", ao["skills"]),
685
+ ("MCP Schemas ", ao["mcp_schemas"]),
686
+ ):
687
+ bar = _bar(val / tot if ao["total"] > 0 else 0.0, width=18)
688
+ pct = round((val / tot) * 100) if ao["total"] > 0 else 0
689
+ lines.append(_box_row(f" {label} {bar} ~{_fmt_tok(val):>6} tok ({pct:>2}%)"))
690
+ lines.append("└──────────────────────────────────────────────────────────────┘")
691
+
692
+ heaviest = rep.get("skills", {}).get("heaviest_skills", [])
693
+ if heaviest:
694
+ lines.append("")
695
+ lines.append(f"Top {len(heaviest)} Skill Token Consumers (always-on frontmatter):")
696
+ for idx, sk in enumerate(heaviest[:10], start=1):
697
+ p_disp = sk.get("display_path") or ""
698
+ lines.append(f" {idx:>2}. {sk['name']:<28} ~{sk['tokens_est']:>4} tok {p_disp}")
699
+
700
+ if rep["findings"]:
701
+ lines.append("")
702
+ lines.append("Top Actionable Fixes:")
703
+ icons = {"critical": "[CRIT]", "high": "[HIGH]", "medium": "[WARN]", "low": "[TIP] ", "info": "[INFO]"}
704
+ for f in rep["findings"][:6]:
705
+ ic = icons.get(f["severity"], "[INFO]")
706
+ lines.append(f" {ic} {f['message']}")
707
+ lines.append(f" -> {f['fix']}")
708
+ else:
709
+ lines.append("\nAll checks clean! Always-on context overhead is tight and cache-friendly.")
710
+ return "\n".join(lines)
711
+
712
+
713
+ def format_doctor_compact(rep: Dict[str, Any]) -> str:
714
+ ao = rep["always_on_tokens_per_turn"]
715
+ out = [
716
+ f"# AgentEfficiency Doctor ({Path(rep['repo']).name}) — Grade {rep['grade']} ({rep['health_score']}/100)",
717
+ f"- Always-on overhead: ~{ao['total']:,} tok/turn (rules={ao['rules']:,}, skills={ao['skills']:,}, mcp={ao['mcp_schemas']:,}; ~${ao['est_monthly_overhead_usd']:.2f}/mo)",
718
+ f"- Repo readiness: index={'yes' if rep['repo_hygiene']['has_index'] else 'no'}, git_exclude={'yes' if rep['repo_hygiene']['has_git_exclude'] else 'no'}, tree_sitter={'yes' if rep['repo_hygiene']['tree_sitter_installed'] else 'no'}",
719
+ ]
720
+ heaviest = rep.get("skills", {}).get("heaviest_skills", [])
721
+ if heaviest:
722
+ out.append("## Top Skill Token Consumers")
723
+ for idx, sk in enumerate(heaviest[:10], start=1):
724
+ out.append(f"{idx}. `{sk['name']}` (~{sk['tokens_est']} tok) — `{sk.get('display_path', '')}`")
725
+ if rep["findings"]:
726
+ out.append("## Findings")
727
+ for f in rep["findings"]:
728
+ out.append(f"- [{f['severity']}] {f['message']} Fix: {f['fix']}")
729
+ return "\n".join(out)
730
+
731
+
732
+ def main(argv: Optional[Sequence[str]] = None) -> int:
733
+ configure_utf8_stdio()
734
+ ap = argparse.ArgumentParser(description="Audit always-on context bloat, MCP schema tax, cache-busters, secrets & repo readiness.")
735
+ ap.add_argument("repo", nargs="?", type=Path, default=Path.cwd())
736
+ ap.add_argument("--repo-only", action="store_true", help="Inspect only repository-local files (skip ~/.claude, ~/.gemini, etc.)")
737
+ ap.add_argument("--home", type=Path, default=None, help="Override home directory (useful for testing)")
738
+ ap.add_argument("--prune", action="store_true", help="Safely archive heavy/unused non-AE skills (dry-run by default; pass --apply to move)")
739
+ ap.add_argument("--prune-skills", default="", help="Comma-separated skill names to archive with --prune")
740
+ ap.add_argument("--prune-top", type=int, default=5, help="Archive top N heaviest non-AE skills when --prune is used without --prune-skills")
741
+ ap.add_argument("--min-tokens", type=int, default=0, help="Only prune skills consuming >= N description tokens")
742
+ ap.add_argument("--restore", default="", help="Restore previously archived skill(s) (comma-separated, pass --apply to execute)")
743
+ ap.add_argument("--apply", action="store_true", help="Execute --prune / --restore file moves (without --apply, dry-run preview only)")
744
+ ap.add_argument("--format", choices=["card", "compact", "json"], default="card")
745
+ args = ap.parse_args(argv)
746
+
747
+ if args.prune or args.restore:
748
+ res = prune_skills(
749
+ home=args.home,
750
+ skill_names=[x.strip() for x in args.prune_skills.split(",") if x.strip()],
751
+ top_n=args.prune_top,
752
+ min_tokens=args.min_tokens,
753
+ apply=args.apply,
754
+ restore=[x.strip() for x in args.restore.split(",") if x.strip()],
755
+ )
756
+ if args.format == "json":
757
+ print(json.dumps(res, indent=2, ensure_ascii=False))
758
+ else:
759
+ mode_lbl = "APPLIED" if res["apply"] else "DRY-RUN (pass --apply to archive/restore)"
760
+ print(f"# AgentEfficiency Skill {res['mode'].title()} [{mode_lbl}]")
761
+ if res["mode"] == "prune":
762
+ print(f"- Archive dir: `{res.get('archive_dir')}` | Skills: {res['selected_skills']} | Reclaimed: ~{res['tokens_reclaimed_est']:,} tok/turn")
763
+ for act in res["actions"]:
764
+ print(f"- [{act['action']}] `{act.get('name', '')}` ({act.get('runtime', '')}): {act['from']} -> {act['to']}")
765
+ if not res["actions"]:
766
+ print("- No matching non-AE skills found.")
767
+ return 0
768
+
769
+ rep = run_doctor(args.repo, home=args.home, include_global=not args.repo_only)
770
+ if args.format == "json":
771
+ print(json.dumps(rep, indent=2, ensure_ascii=False))
772
+ elif args.format == "compact":
773
+ print(format_doctor_compact(rep))
774
+ else:
775
+ print(format_doctor_card(rep))
776
+ return 0
777
+
778
+
779
+ if __name__ == "__main__":
780
+ raise SystemExit(main())