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,578 @@
1
+ #!/usr/bin/env python3
2
+ """AgentEfficiency — Setup inventory (`ae status --setup` / `ae install-status`) & clean rollback (`ae uninstall`).
3
+
4
+ Zero external dependencies (stdlib only) so it runs identically from `pipx`/`uvx`, a repo checkout,
5
+ or copied standalone alongside `~/.local/bin/ae`.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import json
11
+ import os
12
+ import re
13
+ import shutil
14
+ import subprocess
15
+ import sys
16
+ from pathlib import Path
17
+ from typing import Any, Dict, List, Optional, Sequence, Tuple
18
+
19
+ _AE_SKILLS = ("local-context-index", "adaptive-orchestration-handoff", "prompt-cache-manager")
20
+ _RULES_START = "<!-- agent-efficiency:start -->"
21
+ _RULES_END = "<!-- agent-efficiency:end -->"
22
+ _GIT_MARKER_START = "# >>> AgentEfficiency >>>"
23
+ _GIT_MARKER_END = "# <<< AgentEfficiency <<<"
24
+ _EMPTY_SHEBANGS = {"", "#!/bin/sh", "#!/bin/bash", "#!/usr/bin/env sh", "#!/usr/bin/env bash", "#!/usr/bin/env zsh"}
25
+
26
+
27
+ def _runtime_map(home: Path) -> Dict[str, Dict[str, Path]]:
28
+ return {
29
+ "claude": {"probe": home / ".claude", "skills": home / ".claude" / "skills", "rules": home / ".claude" / "CLAUDE.md"},
30
+ "gemini": {"probe": home / ".gemini", "skills": home / ".gemini" / "config" / "skills", "rules": home / ".gemini" / "GEMINI.md"},
31
+ "codex": {"probe": home / ".codex", "skills": home / ".codex" / "skills", "rules": home / ".codex" / "AGENTS.md"},
32
+ "cursor": {"probe": home / ".cursor", "skills": home / ".cursor" / "skills", "rules": home / ".cursor" / "rules" / "agent-efficiency.mdc"},
33
+ "opencode": {"probe": home / ".config" / "opencode", "skills": home / ".config" / "opencode" / "skills", "rules": home / ".config" / "opencode" / "AGENTS.md"},
34
+ "windsurf": {"probe": home / ".codeium" / "windsurf", "skills": home / ".codeium" / "windsurf" / "skills", "rules": home / ".codeium" / "windsurf" / "memories" / "global_rules.md"},
35
+ "copilot": {"probe": home / ".copilot", "skills": home / ".copilot" / "skills", "rules": home / ".copilot" / "copilot-instructions.md"},
36
+ "agents": {"probe": home / ".agents", "skills": home / ".agents" / "skills", "rules": home / ".agents" / "AGENTS.md"},
37
+ }
38
+
39
+
40
+ def _mcp_config_paths(repo: Path, home: Path) -> List[Tuple[str, Path]]:
41
+ return [
42
+ ("repo/.mcp.json", repo / ".mcp.json"),
43
+ ("repo/.cursor/mcp.json", repo / ".cursor" / "mcp.json"),
44
+ ("repo/.claude/settings.local.json", repo / ".claude" / "settings.local.json"),
45
+ ("repo/.gemini/settings.json", repo / ".gemini" / "settings.json"),
46
+ ("~/.claude.json", home / ".claude.json"),
47
+ ("~/.claude/settings.json", home / ".claude" / "settings.json"),
48
+ ("~/.gemini/settings.json", home / ".gemini" / "settings.json"),
49
+ ("~/.cursor/mcp.json", home / ".cursor" / "mcp.json"),
50
+ ("~/.codex/mcp.json", home / ".codex" / "mcp.json"),
51
+ ]
52
+
53
+
54
+ def _resolve_git_hooks_dir(repo: Path) -> Optional[Path]:
55
+ git_entry = repo / ".git"
56
+ if not git_entry.exists():
57
+ return None
58
+ try:
59
+ r = subprocess.run(
60
+ ["git", "-c", "core.fsmonitor=false", "rev-parse", "--git-path", "hooks"],
61
+ cwd=str(repo),
62
+ capture_output=True,
63
+ text=True,
64
+ encoding="utf-8",
65
+ errors="replace",
66
+ timeout=4,
67
+ )
68
+ if r.returncode == 0 and r.stdout.strip():
69
+ hp = Path(r.stdout.strip())
70
+ return hp if hp.is_absolute() else (repo / hp).resolve()
71
+ except Exception:
72
+ pass
73
+ if git_entry.is_dir():
74
+ return git_entry / "hooks"
75
+ if git_entry.is_file():
76
+ txt = git_entry.read_text(encoding="utf-8", errors="replace").strip()
77
+ if txt.lower().startswith("gitdir:"):
78
+ gd = Path(txt.split(":", 1)[1].strip())
79
+ gd = gd if gd.is_absolute() else (repo / gd).resolve()
80
+ return gd / "hooks"
81
+ return None
82
+
83
+
84
+ def _is_ae_hook_group(entry: Any) -> bool:
85
+ raw = json.dumps(entry, sort_keys=True)
86
+ return "agent-efficiency-" in raw or "agent_state.py" in raw or "context_index.py" in raw or "pretool_hook.py" in raw
87
+
88
+
89
+ def _strip_rules_block(text: str) -> str:
90
+ pat = re.compile(rf"\n*{re.escape(_RULES_START)}[\s\S]*?{re.escape(_RULES_END)}\n*", re.MULTILINE)
91
+ cleaned = pat.sub("\n", text).strip()
92
+ return (cleaned + "\n") if cleaned else ""
93
+
94
+
95
+ def _is_empty_mdc(text: str) -> bool:
96
+ stripped = re.sub(r"^---\n[\s\S]*?\n---\n*", "", text.replace("\r\n", "\n")).strip()
97
+ return not stripped
98
+
99
+
100
+ def _strip_git_block(text: str) -> str:
101
+ pat = re.compile(rf"\n*{re.escape(_GIT_MARKER_START)}[\s\S]*?{re.escape(_GIT_MARKER_END)}\n*", re.MULTILINE)
102
+ cleaned = pat.sub("\n", text).rstrip()
103
+ return (cleaned + "\n") if cleaned else ""
104
+
105
+
106
+ def collect_install_status(repo: Optional[Path] = None, *, home: Optional[Path] = None) -> Dict[str, Any]:
107
+ """Inspect all AgentEfficiency skills, rules, runtime hooks, git hooks, MCP servers, CLI & repo artifacts."""
108
+ home_r = (home or Path.home()).expanduser().resolve()
109
+ repo_r = (repo or Path.cwd()).expanduser().resolve()
110
+ rt_map = _runtime_map(home_r)
111
+
112
+ runtimes: List[Dict[str, Any]] = []
113
+ for rt_name, spec in rt_map.items():
114
+ sdir = spec["skills"]
115
+ rfile = spec["rules"]
116
+ installed_skills = [sk for sk in _AE_SKILLS if (sdir / sk / "SKILL.md").is_file() or (sdir / sk).is_symlink()]
117
+ has_rules = False
118
+ if rfile.is_file():
119
+ try:
120
+ has_rules = _RULES_START in rfile.read_text(encoding="utf-8", errors="replace")
121
+ except OSError:
122
+ pass
123
+ if spec["probe"].exists() or installed_skills or has_rules:
124
+ runtimes.append({
125
+ "runtime": rt_name,
126
+ "skills_installed": installed_skills,
127
+ "skills_dir": f"~/{sdir.relative_to(home_r).as_posix()}",
128
+ "rules_active": has_rules,
129
+ "rules_file": f"~/{rfile.relative_to(home_r).as_posix()}",
130
+ })
131
+
132
+ repo_rules_active: List[str] = []
133
+ for cand in (
134
+ repo_r / "CLAUDE.md",
135
+ repo_r / "AGENTS.md",
136
+ repo_r / "GEMINI.md",
137
+ repo_r / ".cursorrules",
138
+ repo_r / ".cursor" / "rules" / "agent-efficiency.mdc",
139
+ ):
140
+ if cand.is_file():
141
+ try:
142
+ if _RULES_START in cand.read_text(encoding="utf-8", errors="replace"):
143
+ repo_rules_active.append(cand.relative_to(repo_r).as_posix())
144
+ except OSError:
145
+ pass
146
+
147
+ runtime_hooks: List[Dict[str, Any]] = []
148
+ for client_lbl, cfg_p in (
149
+ ("claude", repo_r / ".claude" / "settings.local.json"),
150
+ ("gemini", repo_r / ".gemini" / "settings.json"),
151
+ ):
152
+ if not cfg_p.is_file():
153
+ continue
154
+ try:
155
+ data = json.loads(cfg_p.read_text(encoding="utf-8", errors="replace"))
156
+ except Exception:
157
+ continue
158
+ hooks_obj = data.get("hooks") if isinstance(data, dict) else None
159
+ if not isinstance(hooks_obj, dict):
160
+ continue
161
+ ae_events: List[str] = []
162
+ session_start_mode = None
163
+ pretool_mode = None
164
+ for ev_name, entries in hooks_obj.items():
165
+ if not isinstance(entries, list):
166
+ continue
167
+ ae_entries = [e for e in entries if _is_ae_hook_group(e)]
168
+ if ae_entries:
169
+ ae_events.append(ev_name)
170
+ blob = json.dumps(ae_entries)
171
+ if ev_name == "SessionStart":
172
+ session_start_mode = "session-start (ae resume)" if "session-start" in blob else "brief"
173
+ if ev_name in ("PreToolUse", "BeforeTool"):
174
+ pretool_mode = "rewrite (--auto-wrap)" if "--mode rewrite" in blob else "hint"
175
+ if ae_events:
176
+ runtime_hooks.append({
177
+ "client": client_lbl,
178
+ "file": cfg_p.relative_to(repo_r).as_posix(),
179
+ "events": ae_events,
180
+ "session_start_target": session_start_mode,
181
+ "pretool_mode": pretool_mode,
182
+ })
183
+
184
+ git_hooks_active: List[str] = []
185
+ hooks_dir = _resolve_git_hooks_dir(repo_r)
186
+ if hooks_dir and hooks_dir.is_dir():
187
+ for hname in ("post-commit", "post-checkout", "post-merge"):
188
+ hp = hooks_dir / hname
189
+ if hp.is_file():
190
+ try:
191
+ if _GIT_MARKER_START in hp.read_text(encoding="utf-8", errors="replace"):
192
+ git_hooks_active.append(hname)
193
+ except OSError:
194
+ pass
195
+
196
+ mcp_configs: List[Dict[str, str]] = []
197
+ for lbl, p in _mcp_config_paths(repo_r, home_r):
198
+ if not p.is_file():
199
+ continue
200
+ try:
201
+ data = json.loads(p.read_text(encoding="utf-8", errors="replace"))
202
+ except Exception:
203
+ continue
204
+ srv_map = data.get("mcpServers") if isinstance(data, dict) else None
205
+ if not isinstance(srv_map, dict):
206
+ continue
207
+ for k, spec in srv_map.items():
208
+ if str(k).lower() in ("agent-efficiency", "agentefficiency", "ae"):
209
+ args = spec.get("args", []) if isinstance(spec, dict) else []
210
+ prof = "full"
211
+ if isinstance(args, list):
212
+ for i, a in enumerate(args):
213
+ if a == "--profile" and i + 1 < len(args):
214
+ prof = str(args[i + 1])
215
+ elif isinstance(a, str) and a.startswith("--profile="):
216
+ prof = a.split("=", 1)[1]
217
+ mcp_configs.append({"name": str(k), "source": lbl, "profile": prof})
218
+
219
+ cli_bin = home_r / ".local" / "bin" / "ae"
220
+ which_ae = shutil.which("ae")
221
+ hook_dirs = [home_r / ".agent-efficiency" / "hooks", home_r / ".local" / "share" / "agent-efficiency" / "hooks"]
222
+ standalone_hook = next((d / "pretool_hook.py" for d in hook_dirs if (d / "pretool_hook.py").is_file()), None)
223
+ standalone_manage = next((d / "ae_manage.py" for d in hook_dirs if (d / "ae_manage.py").is_file()), None)
224
+ standalone_mcp = home_r / ".agent-efficiency" / "mcp" / "server.py"
225
+ savings_file = home_r / ".agent-efficiency" / "savings.jsonl"
226
+
227
+ git_excl = repo_r / ".git" / "info" / "exclude"
228
+ excl_txt = git_excl.read_text(encoding="utf-8", errors="replace") if git_excl.is_file() else ""
229
+ repo_artifacts = {
230
+ "index_db": (repo_r / ".agent-index" / "index.sqlite3").is_file(),
231
+ "project_map": (repo_r / ".agent-index" / "PROJECT_MAP.md").is_file(),
232
+ "state_json": (repo_r / ".agent-state" / "state.json").is_file(),
233
+ "git_info_exclude_index": ".agent-index/" in excl_txt,
234
+ "git_info_exclude_state": ".agent-state/" in excl_txt,
235
+ }
236
+
237
+ return {
238
+ "repo": str(repo_r),
239
+ "home": str(home_r),
240
+ "cli": {
241
+ "installed_user_bin": str(cli_bin) if cli_bin.is_file() else None,
242
+ "path_resolved": which_ae,
243
+ "standalone_pretool_hook": str(standalone_hook) if standalone_hook else None,
244
+ "standalone_manage": str(standalone_manage) if standalone_manage else None,
245
+ "standalone_mcp_server": str(standalone_mcp) if standalone_mcp.is_file() else None,
246
+ "savings_log": str(savings_file) if savings_file.is_file() else None,
247
+ },
248
+ "runtimes": runtimes,
249
+ "repo_rules_active": repo_rules_active,
250
+ "runtime_hooks": runtime_hooks,
251
+ "git_hooks_active": git_hooks_active,
252
+ "mcp_configs": mcp_configs,
253
+ "repo_artifacts": repo_artifacts,
254
+ }
255
+
256
+
257
+ def _box_row(text: str, width: int = 62) -> str:
258
+ clipped = text if len(text) <= width else (text[: max(1, width - 1)] + "…")
259
+ return f"│{clipped:<{width}}│"
260
+
261
+
262
+ def format_status_card(st: Dict[str, Any]) -> str:
263
+ repo_name = Path(st["repo"]).name
264
+ cli_info = st["cli"]
265
+ cli_state = "installed" if cli_info["installed_user_bin"] else ("on PATH" if cli_info["path_resolved"] else "not installed")
266
+ lines = [
267
+ "┌──────────────────────────────────────────────────────────────┐",
268
+ _box_row(f" AgentEfficiency Setup Status · {repo_name}"),
269
+ "├──────────────────────────────────────────────────────────────┤",
270
+ _box_row(f" CLI (`ae`) : {cli_state}"),
271
+ _box_row(f" Standalone MCP : {'yes' if cli_info['standalone_mcp_server'] else 'no'} | Hook script: {'yes' if cli_info['standalone_pretool_hook'] else 'no'}"),
272
+ ]
273
+ if st["runtimes"]:
274
+ lines.append("├──────────────────────────────────────────────────────────────┤")
275
+ lines.append(_box_row(" Detected Runtimes:"))
276
+ for rt in st["runtimes"]:
277
+ sk_cnt = len(rt["skills_installed"])
278
+ r_tag = "rules=yes" if rt["rules_active"] else "rules=no"
279
+ lines.append(_box_row(f" • {rt['runtime']:<10} skills={sk_cnt}/3 {r_tag}"))
280
+ lines.append("├──────────────────────────────────────────────────────────────┤")
281
+ if st["runtime_hooks"]:
282
+ for rh in st["runtime_hooks"]:
283
+ lines.append(_box_row(f" Hooks ({rh['client']}): {', '.join(rh['events'])}"))
284
+ if rh.get("session_start_target") or rh.get("pretool_mode"):
285
+ lines.append(_box_row(f" SessionStart={rh.get('session_start_target') or 'none'} | PreTool={rh.get('pretool_mode') or 'none'}"))
286
+ else:
287
+ lines.append(_box_row(" Runtime Hooks : none in this repo"))
288
+ gh = ", ".join(st["git_hooks_active"]) if st["git_hooks_active"] else "none"
289
+ lines.append(_box_row(f" Git Hooks : {gh}"))
290
+ if st["mcp_configs"]:
291
+ mcp_s = ", ".join(f"{m['source']}[{m['profile']}]" for m in st["mcp_configs"][:3])
292
+ lines.append(_box_row(f" MCP Configs : {mcp_s}"))
293
+ else:
294
+ lines.append(_box_row(" MCP Configs : none configured"))
295
+ ra = st["repo_artifacts"]
296
+ lines.append(_box_row(f" Repo State : index={'yes' if ra['index_db'] else 'no'}, state={'yes' if ra['state_json'] else 'no'}, git_exclude={'yes' if (ra['git_info_exclude_index'] or ra['git_info_exclude_state']) else 'no'}"))
297
+ lines.append("└──────────────────────────────────────────────────────────────┘")
298
+ return "\n".join(lines)
299
+
300
+
301
+ def run_uninstall(
302
+ repo: Optional[Path] = None,
303
+ *,
304
+ home: Optional[Path] = None,
305
+ runtimes: Optional[Sequence[str]] = None,
306
+ remove_cli: bool = True,
307
+ remove_rules: bool = True,
308
+ remove_hooks: bool = True,
309
+ remove_mcp: bool = True,
310
+ purge_repo_state: bool = False,
311
+ purge_all_data: bool = False,
312
+ dry_run: bool = False,
313
+ ) -> Dict[str, Any]:
314
+ """Cleanly and non-destructively remove AgentEfficiency skills, rules blocks, hooks, CLI, MCP, and optional repo artifacts."""
315
+ home_r = (home or Path.home()).expanduser().resolve()
316
+ repo_r = (repo or Path.cwd()).expanduser().resolve()
317
+ rt_map = _runtime_map(home_r)
318
+
319
+ chosen_rts: List[str] = []
320
+ if runtimes:
321
+ for raw_r in runtimes:
322
+ for part in str(raw_r).split(","):
323
+ p = part.strip().lower()
324
+ if not p:
325
+ continue
326
+ if p == "all":
327
+ chosen_rts.extend(rt_map.keys())
328
+ elif p in rt_map:
329
+ chosen_rts.append(p)
330
+ else:
331
+ raise SystemExit(f"Unknown runtime {p!r}. Choose from: {', '.join(sorted(rt_map))} or 'all'.")
332
+ chosen_rts = list(dict.fromkeys(chosen_rts))
333
+ else:
334
+ chosen_rts = list(rt_map.keys())
335
+
336
+ actions: List[Dict[str, str]] = []
337
+
338
+ def _rec(kind: str, target: Path, act: str) -> None:
339
+ actions.append({"kind": kind, "action": f"{'would_' if dry_run else ''}{act}", "target": str(target)})
340
+
341
+ # 1. Skills directories per runtime
342
+ for rt in chosen_rts:
343
+ sdir = rt_map[rt]["skills"]
344
+ for sk in _AE_SKILLS:
345
+ dst = sdir / sk
346
+ if dst.exists() or dst.is_symlink():
347
+ if not dry_run:
348
+ if dst.is_symlink() or dst.is_file():
349
+ dst.unlink()
350
+ else:
351
+ shutil.rmtree(dst)
352
+ _rec("skill", dst, "removed")
353
+
354
+ # 2. Non-destructive rules-block removal (global + repo)
355
+ if remove_rules:
356
+ rule_targets: List[Path] = [rt_map[rt]["rules"] for rt in chosen_rts] + [
357
+ repo_r / "CLAUDE.md",
358
+ repo_r / "AGENTS.md",
359
+ repo_r / "GEMINI.md",
360
+ repo_r / ".cursorrules",
361
+ repo_r / ".cursor" / "rules" / "agent-efficiency.mdc",
362
+ ]
363
+ seen_r: set[Path] = set()
364
+ for rp in rule_targets:
365
+ if not rp.is_file() or rp.is_symlink():
366
+ continue
367
+ rp_r = rp.resolve()
368
+ if rp_r in seen_r:
369
+ continue
370
+ seen_r.add(rp_r)
371
+ raw = rp.read_text(encoding="utf-8", errors="replace")
372
+ if _RULES_START not in raw:
373
+ continue
374
+ cleaned = _strip_rules_block(raw)
375
+ is_empty = (not cleaned.strip()) or (rp.suffix.lower() == ".mdc" and _is_empty_mdc(cleaned))
376
+ if not dry_run:
377
+ if is_empty:
378
+ rp.unlink()
379
+ else:
380
+ rp.write_text(cleaned, encoding="utf-8")
381
+ _rec("rules", rp, "removed_file" if is_empty else "stripped_block")
382
+
383
+ # 3. Runtime hooks (Claude + Gemini) & Git hooks
384
+ if remove_hooks:
385
+ for cfg_p in (repo_r / ".claude" / "settings.local.json", repo_r / ".gemini" / "settings.json"):
386
+ if not cfg_p.is_file() or cfg_p.is_symlink():
387
+ continue
388
+ try:
389
+ data = json.loads(cfg_p.read_text(encoding="utf-8", errors="replace"))
390
+ except Exception:
391
+ continue
392
+ hooks_obj = data.get("hooks") if isinstance(data, dict) else None
393
+ if not isinstance(hooks_obj, dict):
394
+ continue
395
+ changed = False
396
+ new_hooks: Dict[str, Any] = {}
397
+ for ev_name, entries in hooks_obj.items():
398
+ if not isinstance(entries, list):
399
+ new_hooks[ev_name] = entries
400
+ continue
401
+ kept = [e for e in entries if not _is_ae_hook_group(e)]
402
+ if len(kept) != len(entries):
403
+ changed = True
404
+ if kept:
405
+ new_hooks[ev_name] = kept
406
+ if changed:
407
+ if new_hooks:
408
+ data["hooks"] = new_hooks
409
+ else:
410
+ data.pop("hooks", None)
411
+ if not dry_run:
412
+ if data:
413
+ cfg_p.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
414
+ else:
415
+ cfg_p.unlink()
416
+ _rec("runtime_hooks", cfg_p, "removed_file" if not data else "stripped_ae_hooks")
417
+
418
+ hooks_dir = _resolve_git_hooks_dir(repo_r)
419
+ if hooks_dir and hooks_dir.is_dir():
420
+ for hname in ("post-commit", "post-checkout", "post-merge"):
421
+ hp = hooks_dir / hname
422
+ if not hp.is_file() or hp.is_symlink():
423
+ continue
424
+ raw_h = hp.read_text(encoding="utf-8", errors="replace")
425
+ if _GIT_MARKER_START not in raw_h:
426
+ continue
427
+ cleaned_h = _strip_git_block(raw_h)
428
+ is_empty_h = cleaned_h.strip() in _EMPTY_SHEBANGS
429
+ if not dry_run:
430
+ if is_empty_h:
431
+ hp.unlink()
432
+ else:
433
+ hp.write_text(cleaned_h, encoding="utf-8")
434
+ _rec("git_hook", hp, "removed_file" if is_empty_h else "stripped_block")
435
+
436
+ # 4. MCP config entries + standalone server
437
+ if remove_mcp:
438
+ for _lbl, mp in _mcp_config_paths(repo_r, home_r):
439
+ if not mp.is_file() or mp.is_symlink():
440
+ continue
441
+ try:
442
+ data = json.loads(mp.read_text(encoding="utf-8", errors="replace"))
443
+ except Exception:
444
+ continue
445
+ srv_map = data.get("mcpServers") if isinstance(data, dict) else None
446
+ if not isinstance(srv_map, dict):
447
+ continue
448
+ removed_any = False
449
+ for k in list(srv_map.keys()):
450
+ if str(k).lower() in ("agent-efficiency", "agentefficiency", "ae"):
451
+ del srv_map[k]
452
+ removed_any = True
453
+ if removed_any:
454
+ if not srv_map:
455
+ data.pop("mcpServers", None)
456
+ if not dry_run:
457
+ if data:
458
+ mp.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
459
+ else:
460
+ mp.unlink()
461
+ _rec("mcp_config", mp, "removed_file" if not data else "removed_server_entry")
462
+
463
+ mcp_dir = home_r / ".agent-efficiency" / "mcp"
464
+ if mcp_dir.is_dir():
465
+ if not dry_run:
466
+ shutil.rmtree(mcp_dir)
467
+ _rec("mcp_server", mcp_dir, "removed")
468
+
469
+ # 5. CLI binary & standalone hooks dir
470
+ if remove_cli:
471
+ for bin_p in (home_r / ".local" / "bin" / "ae", home_r / ".local" / "bin" / "ae.cmd"):
472
+ if bin_p.is_file() or bin_p.is_symlink():
473
+ if not dry_run:
474
+ bin_p.unlink()
475
+ _rec("cli", bin_p, "removed")
476
+ for hooks_store in (home_r / ".agent-efficiency" / "hooks", home_r / ".local" / "share" / "agent-efficiency" / "hooks"):
477
+ if hooks_store.is_dir():
478
+ if not dry_run:
479
+ shutil.rmtree(hooks_store)
480
+ _rec("hooks_dir", hooks_store, "removed")
481
+
482
+ if purge_all_data:
483
+ ae_home = home_r / ".agent-efficiency"
484
+ if ae_home.is_dir():
485
+ if not dry_run:
486
+ shutil.rmtree(ae_home)
487
+ _rec("ae_home", ae_home, "removed")
488
+
489
+ # 6. Optional repo artifact purge (.agent-index/, .agent-state/, .git/info/exclude entries)
490
+ if purge_repo_state:
491
+ for dname in (".agent-index", ".agent-state"):
492
+ dp = repo_r / dname
493
+ if dp.is_dir() and not dp.is_symlink():
494
+ if not dry_run:
495
+ shutil.rmtree(dp)
496
+ _rec("repo_state", dp, "removed")
497
+ excl = repo_r / ".git" / "info" / "exclude"
498
+ if excl.is_file() and not excl.is_symlink():
499
+ lines = excl.read_text(encoding="utf-8", errors="replace").splitlines()
500
+ filtered = [ln for ln in lines if ln.strip() not in (".agent-index/", ".agent-state/", "# AgentEfficiency local artifacts")]
501
+ if len(filtered) != len(lines):
502
+ if not dry_run:
503
+ excl.write_text("\n".join(filtered).rstrip() + ("\n" if filtered else ""), encoding="utf-8")
504
+ _rec("git_exclude", excl, "cleaned")
505
+
506
+ return {
507
+ "dry_run": dry_run,
508
+ "repo": str(repo_r),
509
+ "home": str(home_r),
510
+ "actions_count": len(actions),
511
+ "actions": actions,
512
+ }
513
+
514
+
515
+ def format_uninstall_summary(res: Dict[str, Any]) -> str:
516
+ tag = " [DRY-RUN]" if res["dry_run"] else ""
517
+ out = [f"# AgentEfficiency Uninstall{tag} ({res['actions_count']} change(s))"]
518
+ if not res["actions"]:
519
+ out.append("- Nothing to remove (AgentEfficiency is not installed in the target locations).")
520
+ return "\n".join(out)
521
+ for act in res["actions"]:
522
+ out.append(f"- [{act['action']}] ({act['kind']}) `{act['target']}`")
523
+ return "\n".join(out)
524
+
525
+
526
+ def main(argv: Optional[Sequence[str]] = None) -> int:
527
+ for stream in (sys.stdout, sys.stderr):
528
+ reconf = getattr(stream, "reconfigure", None)
529
+ if callable(reconf):
530
+ try:
531
+ reconf(encoding="utf-8", errors="replace")
532
+ except Exception:
533
+ pass
534
+ ap = argparse.ArgumentParser(description="Inspect AgentEfficiency installation status or uninstall cleanly.")
535
+ sub = ap.add_subparsers(dest="cmd", required=True)
536
+
537
+ p_st = sub.add_parser("status", help="Inspect installed skills, rules, hooks, MCP configs & repo artifacts")
538
+ p_st.add_argument("repo", nargs="?", type=Path, default=Path.cwd())
539
+ p_st.add_argument("--home", type=Path, default=None)
540
+ p_st.add_argument("--format", choices=["card", "json"], default="card")
541
+
542
+ p_un = sub.add_parser("uninstall", help="Cleanly remove AgentEfficiency skills, rules blocks, hooks, CLI & MCP")
543
+ p_un.add_argument("repo", nargs="?", type=Path, default=Path.cwd())
544
+ p_un.add_argument("--home", type=Path, default=None)
545
+ p_un.add_argument("--runtime", action="append", default=None, help="Limit skill/rules removal to specific runtime(s)")
546
+ p_un.add_argument("--keep-cli", action="store_true")
547
+ p_un.add_argument("--keep-rules", action="store_true")
548
+ p_un.add_argument("--keep-hooks", action="store_true")
549
+ p_un.add_argument("--keep-mcp", action="store_true")
550
+ p_un.add_argument("--purge-repo-state", action="store_true", help="Also delete .agent-index/ and .agent-state/ in target repo")
551
+ p_un.add_argument("--purge-all", action="store_true", help="Also delete ~/.agent-efficiency/ (savings log & archived skills)")
552
+ p_un.add_argument("--dry-run", action="store_true")
553
+ p_un.add_argument("--format", choices=["text", "json"], default="text")
554
+
555
+ args = ap.parse_args(argv)
556
+ if args.cmd == "status":
557
+ rep = collect_install_status(args.repo, home=args.home)
558
+ print(json.dumps(rep, indent=2, ensure_ascii=False) if args.format == "json" else format_status_card(rep))
559
+ return 0
560
+
561
+ res = run_uninstall(
562
+ args.repo,
563
+ home=args.home,
564
+ runtimes=args.runtime,
565
+ remove_cli=not args.keep_cli,
566
+ remove_rules=not args.keep_rules,
567
+ remove_hooks=not args.keep_hooks,
568
+ remove_mcp=not args.keep_mcp,
569
+ purge_repo_state=args.purge_repo_state,
570
+ purge_all_data=args.purge_all,
571
+ dry_run=args.dry_run,
572
+ )
573
+ print(json.dumps(res, indent=2, ensure_ascii=False) if args.format == "json" else format_uninstall_summary(res))
574
+ return 0
575
+
576
+
577
+ if __name__ == "__main__":
578
+ raise SystemExit(main())