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,327 @@
1
+ #!/usr/bin/env python3
2
+ """`ae` — Short global CLI wrapper for AgentEfficiency Skills.
3
+
4
+ Defaults `<repo>` to the current working directory (override with `-C <dir>` / `--repo <dir>`):
5
+ ae init [--hooks] [--auto-wrap] [--mcp]
6
+ ae audit [--limit 10] [--format card|compact|json]
7
+ ae doctor [--repo-only] [--format card|compact|json]
8
+ ae savings [--days 7] [--statusline]
9
+ ae index [--force]
10
+ ae search "<query>"
11
+ ae slice a.py:foo b.py:10-40 --max-tokens 1200
12
+ ae diff-pack [--base HEAD]
13
+ ae trace-pack [--file err.log]
14
+ ae tests-for [paths...]
15
+ ae run -- pytest -q
16
+ ae checkpoint [--note "..."]
17
+ ae brief
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import argparse
22
+ import json
23
+ import os
24
+ import sys
25
+ from pathlib import Path
26
+ from typing import List, Optional, Sequence, Tuple
27
+
28
+ AE_VERSION = "1.4.2"
29
+ _BAKED_SKILLS_DIR = ""
30
+
31
+
32
+ def _resolve_skills_dir() -> Path:
33
+ candidates: List[Path] = []
34
+ env_dir = os.getenv("AGENT_EFFICIENCY_SKILLS_DIR", "").strip()
35
+ if env_dir:
36
+ candidates.append(Path(env_dir).expanduser())
37
+ if _BAKED_SKILLS_DIR:
38
+ candidates.append(Path(_BAKED_SKILLS_DIR).expanduser())
39
+ here = Path(__file__).resolve()
40
+ home = Path.home()
41
+ parent_root = here.parents[1] if len(here.parents) > 1 else here.parent
42
+ candidates.extend([
43
+ parent_root / "skills",
44
+ parent_root / "agent_efficiency" / "_bundle" / "skills",
45
+ home / ".gemini" / "config" / "skills",
46
+ home / ".claude" / "skills",
47
+ home / ".codex" / "skills",
48
+ home / ".cursor" / "skills",
49
+ home / ".config" / "opencode" / "skills",
50
+ home / ".codeium" / "windsurf" / "skills",
51
+ home / ".agents" / "skills",
52
+ ])
53
+ for cand in candidates:
54
+ if (cand / "local-context-index" / "scripts" / "context_index.py").is_file():
55
+ return cand
56
+ raise SystemExit(
57
+ "AgentEfficiency skills not found. Install via `python3 scripts/install.py --runtime claude --profile ide --install-cli --install-rules --force` "
58
+ "or set AGENT_EFFICIENCY_SKILLS_DIR."
59
+ )
60
+
61
+
62
+ def _resolve_scripts_dir(required_file: Optional[str] = None) -> Optional[Path]:
63
+ here = Path(__file__).resolve()
64
+ parent_root = here.parents[1] if len(here.parents) > 1 else here.parent
65
+ cands = (
66
+ here.parent,
67
+ here.parent.parent / "share" / "agent-efficiency" / "hooks",
68
+ parent_root / "scripts",
69
+ parent_root / "agent_efficiency" / "_bundle" / "scripts",
70
+ Path.home() / ".agent-efficiency" / "hooks",
71
+ )
72
+ for cand in cands:
73
+ if required_file:
74
+ if (cand / required_file).is_file():
75
+ return cand
76
+ elif (cand / "pretool_hook.py").is_file() or (cand / "ae_init.py").is_file() or (cand / "ae_manage.py").is_file():
77
+ return cand
78
+ return None
79
+
80
+
81
+ def _usage() -> str:
82
+ return (
83
+ f"ae {AE_VERSION} — AgentEfficiency CLI (defaults <repo> to cwd; override with `-C <dir>`)\n\n"
84
+ "Onboarding, Diagnostics & Telemetry:\n"
85
+ " ae init [--hooks] [--auto-wrap] [--mcp] 1-command IDE setup (auto-detects clients)\n"
86
+ " ae install-status [--format card|json] Show active skills, rules, hooks & MCP setup\n"
87
+ " ae uninstall [--dry-run] [--purge-repo-state] Cleanly remove rules, hooks, skills & CLI\n"
88
+ " ae audit [--limit 6 --format card] Visual IDE transcript audit (waste, $, trend)\n"
89
+ " ae doctor [--prune] [--apply] Audit bloat, top-10 skills, cache-busters & prune\n"
90
+ " ae savings [--days 7] [--statusline] Show recorded token & USD savings receipt\n"
91
+ " ae rules-snippet Print workflow rules snippet\n"
92
+ "\nContext Index:\n"
93
+ " ae index [--force] Incrementally index repo & update PROJECT_MAP.md\n"
94
+ " ae status [--check-stale | --setup] Index stats (or pass `--setup` for install status)\n"
95
+ " ae map [--max-tokens N] Print compact PROJECT_MAP.md\n"
96
+ " ae search <query> [flags] FTS5 + identifier-split search (compact default)\n"
97
+ " ae symbols [pattern] [flags] List/search extracted symbols\n"
98
+ " ae outline <path> File outline without implementation bodies\n"
99
+ " ae slice <target...> [--with-header] Slice 1+ targets (`a.py:foo b.py:10-40`)\n"
100
+ " ae deps <path> [--depth 2] Import blast radius (compact default)\n"
101
+ " ae callgraph <symbol> [--depth 2] Symbol-level callers/callees\n"
102
+ " ae refs <target> Find importers and references\n"
103
+ " ae changed [--base HEAD] Git-changed files + symbols\n"
104
+ " ae pack <query> [--budget-tokens N] Token-budgeted context bundle\n"
105
+ " ae diff-pack [--base HEAD] Token-budgeted diff + symbols + callers\n"
106
+ " ae trace-pack [--file log | --text ..] Stacktrace -> in-repo failing function slices\n"
107
+ " ae tests-for [paths...] [--format cmd] Find minimal affected test files\n"
108
+ " ae run [--verbose] -- <cmd...> Run cmd, compress log, keep warnings & trace\n"
109
+ "\nState, Handoff, Routing & Cache:\n"
110
+ " ae resume [--max-tokens 1400] 1-call new-window resume (auto-index + map + git + brief)\n"
111
+ " ae session-start [--readonly] Alias for `ae resume` (pass `--readonly` to skip auto-index)\n"
112
+ " ae brief [--max-tokens 1200] 1-call state/checkpoint brief with SHA drift check\n"
113
+ " ae checkpoint [--note '...'] Zero-friction auto-checkpoint\n"
114
+ " ae handoff --summary '...' --next '..' Prepare zero-reexploration HANDOFF.md\n"
115
+ " ae state <subcmd...> Pass through to agent_state.py\n"
116
+ " ae route <subcmd...> Pass through to route_task.py\n"
117
+ " ae cache <subcmd...> Pass through to prompt_cache.py\n"
118
+ " ae hook pretool [flags] Run PreToolUse/BeforeTool hook handler\n"
119
+ )
120
+
121
+
122
+ def _split_global_flags(argv: Sequence[str]) -> Tuple[Path, bool, List[str]]:
123
+ repo = Path.cwd()
124
+ explicit_repo = False
125
+ i = 0
126
+ args = list(argv)
127
+ while i < len(args):
128
+ tok = args[i]
129
+ if tok in ("-C", "--repo") and i + 1 < len(args):
130
+ repo = Path(args[i + 1]).expanduser().resolve()
131
+ explicit_repo = True
132
+ i += 2
133
+ elif tok.startswith("--repo="):
134
+ repo = Path(tok.split("=", 1)[1]).expanduser().resolve()
135
+ explicit_repo = True
136
+ i += 1
137
+ else:
138
+ break
139
+ return repo, explicit_repo, args[i:]
140
+
141
+
142
+ def _has_flag(rest: Sequence[str], flag: str) -> bool:
143
+ return any(t == flag or t.startswith(flag + "=") for t in rest)
144
+
145
+
146
+ def _maybe_insert_repo(rest: List[str], repo: Path, explicit_repo: bool, allow_positional_dir: bool) -> List[str]:
147
+ if not explicit_repo and allow_positional_dir and rest and not rest[0].startswith("-"):
148
+ cand = Path(rest[0]).expanduser()
149
+ if cand.is_dir():
150
+ return rest
151
+ return [str(repo), *rest]
152
+
153
+
154
+ def _run_savings_cmd(tail: Sequence[str], orch_dir: str) -> int:
155
+ if orch_dir not in sys.path:
156
+ sys.path.insert(0, orch_dir)
157
+ from _ae_core import ( # type: ignore[import-not-found]
158
+ DEFAULT_RATE_PER_1M_USD,
159
+ format_savings_card,
160
+ format_statusline,
161
+ summarize_savings,
162
+ )
163
+
164
+ ap = argparse.ArgumentParser(prog="ae savings", description="Show recorded AgentEfficiency token & USD savings.")
165
+ ap.add_argument("--days", type=int, default=7, help="Time window in days (0 = all-time, default: 7)")
166
+ ap.add_argument("--all", dest="all_time", action="store_true", help="Show all-time savings")
167
+ ap.add_argument("--repo-name", default=None, help="Filter by repository basename")
168
+ ap.add_argument("--rate", type=float, default=DEFAULT_RATE_PER_1M_USD, help="Reference input $/1M tokens (default: 3.00)")
169
+ ap.add_argument("--statusline", action="store_true", help="Print 1-line status string for Claude Code statusLine or shell prompt")
170
+ ap.add_argument("--format", choices=["card", "compact", "json"], default="card")
171
+ args = ap.parse_args(tail)
172
+
173
+ days = None if (args.all_time or args.days <= 0) else args.days
174
+ summary = summarize_savings(days=days, rate_per_1m_usd=args.rate, repo_filter=args.repo_name)
175
+ if args.statusline:
176
+ print(format_statusline(summary))
177
+ elif args.format == "json":
178
+ print(json.dumps(summary, indent=2, ensure_ascii=False))
179
+ elif args.format == "compact":
180
+ print(format_statusline(summary))
181
+ else:
182
+ print(format_savings_card(summary))
183
+ return 0
184
+
185
+
186
+ def _configure_utf8_stdio() -> None:
187
+ for stream in (sys.stdout, sys.stderr):
188
+ reconf = getattr(stream, "reconfigure", None)
189
+ if callable(reconf):
190
+ try:
191
+ reconf(encoding="utf-8", errors="replace")
192
+ except Exception:
193
+ pass
194
+
195
+
196
+ def main(argv: Optional[Sequence[str]] = None) -> int:
197
+ _configure_utf8_stdio()
198
+ raw = list(sys.argv[1:] if argv is None else argv)
199
+ repo, explicit_repo, rest = _split_global_flags(raw)
200
+ if not rest or rest[0] in ("-h", "--help", "help"):
201
+ print(_usage(), end="")
202
+ return 0
203
+ if rest[0] in ("-V", "--version", "version"):
204
+ print(f"ae {AE_VERSION}")
205
+ return 0
206
+ if rest[0] == "rules-snippet":
207
+ print(
208
+ "<!-- agent-efficiency:start -->\n"
209
+ "## Agent Efficiency Workflow (`ae`)\n"
210
+ "- **START OF EVERY NEW CHAT / WINDOW (FIRST CALL):** On repos with ≥15 files (or whenever `.agent-index/` or `.agent-state/` exists), run `ae resume` FIRST before any `find`, `ls`, `grep`, or `read_file`. It loads checkpoints/handoffs, recent git changes, and `PROJECT_MAP.md` (auto-indexing incrementally) in 1 call — do NOT re-explore the repo afterward.\n"
211
+ "- **CODE READING:** Use `ae search`, `ae outline`, and multi-target `ae slice a.py:foo b.py:10-40 --max-tokens 1200` over full-file reads (skip index ceremony on tiny <15-file single-file edits). Never re-read unchanged files already inspected in the session.\n"
212
+ "- **TESTS & DEBUGGING:** Wrap noisy test/build commands via `ae run -- <cmd>` (compresses logs, keeps fixture/setup warnings, archives `full_log` + auto-slices failing stacktraces); run `ae tests-for` first before the full suite; use `ae diff-pack` for reviews and `ae trace-pack` for stacktraces.\n"
213
+ "- **ANTI-TUNNEL-VISION ESCALATION:** If a bug's root cause isn't visible in the slice/log or a fix fails once, stop narrow-slicing — widen context via `ae slice --with-header`, `ae run --verbose`, the archived `full_log`, or a full file/fixture read.\n"
214
+ "- **BEFORE COMPACTION / NEW WINDOW / FINISHING MULTI-STEP WORK:** Run `ae checkpoint --note \"<what changed + exact next step>\"` (or `ae handoff`) so the next window resumes in 1 call with zero re-exploration. Never `@import` `.agent-state/*` or `CHECKPOINT.md` in always-on rules (breaks prompt caching).\n"
215
+ "- **DIAGNOSTICS:** Audit real local session waste & always-on overhead read-only via `ae audit` and `ae doctor`.\n"
216
+ "<!-- agent-efficiency:end -->"
217
+ )
218
+ return 0
219
+
220
+ cmd, tail = rest[0], rest[1:]
221
+
222
+ if cmd == "init":
223
+ sdir = _resolve_scripts_dir("ae_init.py")
224
+ if sdir is None:
225
+ raise SystemExit("`ae init` requires the full AgentEfficiency package or repository checkout.")
226
+ if str(sdir) not in sys.path:
227
+ sys.path.insert(0, str(sdir))
228
+ import ae_init # type: ignore[import-not-found]
229
+ forwarded = _maybe_insert_repo(tail, repo, explicit_repo, allow_positional_dir=True) if explicit_repo else tail
230
+ return int(ae_init.main(forwarded))
231
+
232
+ if cmd in ("uninstall", "install-status") or (cmd == "status" and "--setup" in tail):
233
+ sdir = _resolve_scripts_dir("ae_manage.py")
234
+ if sdir is None:
235
+ raise SystemExit(f"`ae {cmd}` requires scripts/ae_manage.py (re-run `ae init` or `install.py --install-cli`).")
236
+ if str(sdir) not in sys.path:
237
+ sys.path.insert(0, str(sdir))
238
+ import ae_manage # type: ignore[import-not-found]
239
+ sub_name = "uninstall" if cmd == "uninstall" else "status"
240
+ clean_tail = [t for t in tail if t != "--setup"]
241
+ forwarded = _maybe_insert_repo(clean_tail, repo, explicit_repo, allow_positional_dir=True)
242
+ return int(ae_manage.main([sub_name, *forwarded]))
243
+
244
+ if cmd == "hook":
245
+ if not tail or tail[0] != "pretool":
246
+ raise SystemExit("Usage: ae hook pretool [--client claude|gemini] [--mode hint|rewrite] [--repo <dir>]")
247
+ sdir = _resolve_scripts_dir("pretool_hook.py")
248
+ if sdir is None:
249
+ raise SystemExit("pretool_hook.py not found. Re-run `ae init` or `install.py --install-cli`.")
250
+ if str(sdir) not in sys.path:
251
+ sys.path.insert(0, str(sdir))
252
+ import pretool_hook # type: ignore[import-not-found]
253
+ return int(pretool_hook.main(tail[1:]))
254
+
255
+ skills_dir = _resolve_skills_dir()
256
+ ctx_dir = str(skills_dir / "local-context-index" / "scripts")
257
+ orch_dir = str(skills_dir / "adaptive-orchestration-handoff" / "scripts")
258
+ cache_dir = str(skills_dir / "prompt-cache-manager" / "scripts")
259
+
260
+ if cmd == "savings":
261
+ return _run_savings_cmd(tail, orch_dir)
262
+
263
+ if cmd == "doctor":
264
+ if orch_dir not in sys.path:
265
+ sys.path.insert(0, orch_dir)
266
+ import context_doctor # type: ignore[import-not-found]
267
+ forwarded_tail = _maybe_insert_repo(tail, repo, explicit_repo, allow_positional_dir=True)
268
+ return int(context_doctor.main(forwarded_tail))
269
+
270
+ ctx_no_pos = {"index", "status", "map", "changed", "diff-pack", "watch"}
271
+ ctx_with_pos = {"search", "symbols", "outline", "slice", "refs", "deps", "callgraph", "pack", "trace-pack", "tests-for", "show"}
272
+ ctx_compact_default = {"search", "symbols", "outline", "refs", "deps"}
273
+
274
+ if cmd in ctx_no_pos or cmd in ctx_with_pos or cmd == "run":
275
+ if ctx_dir not in sys.path:
276
+ sys.path.insert(0, ctx_dir)
277
+ import context_index # type: ignore[import-not-found]
278
+
279
+ if cmd == "run":
280
+ forwarded_tail = _maybe_insert_repo(tail, repo, explicit_repo, allow_positional_dir=True)
281
+ return int(context_index.main(["run", *forwarded_tail]))
282
+ forwarded_tail = _maybe_insert_repo(tail, repo, explicit_repo, allow_positional_dir=(cmd in ctx_no_pos))
283
+ if cmd in ctx_compact_default and not _has_flag(forwarded_tail, "--format"):
284
+ forwarded_tail = [*forwarded_tail, "--format", "compact"]
285
+ return int(context_index.main([cmd, *forwarded_tail]))
286
+
287
+ if cmd in ("resume", "brief", "session-start", "checkpoint", "handoff", "accept", "complete", "state", "audit"):
288
+ if orch_dir not in sys.path:
289
+ sys.path.insert(0, orch_dir)
290
+ if cmd == "audit":
291
+ import transcript_audit # type: ignore[import-not-found]
292
+ audit_tail = list(tail)
293
+ if not _has_flag(audit_tail, "--format") and not any(t in ("-h", "--help") for t in audit_tail):
294
+ audit_tail.extend(["--format", "card"])
295
+ return int(transcript_audit.main(audit_tail))
296
+ import agent_state # type: ignore[import-not-found]
297
+ if cmd == "state":
298
+ if not tail:
299
+ return int(agent_state.main(["--help"]))
300
+ return int(agent_state.main(tail))
301
+ if cmd in ("resume", "session-start"):
302
+ readonly = "--readonly" in tail
303
+ clean_tail = [t for t in tail if t != "--readonly"]
304
+ forwarded_tail = _maybe_insert_repo(clean_tail, repo, explicit_repo, allow_positional_dir=True)
305
+ if not readonly and not _has_flag(forwarded_tail, "--auto-index") and not any(t in ("-h", "--help") for t in forwarded_tail):
306
+ forwarded_tail = [*forwarded_tail, "--auto-index"]
307
+ return int(agent_state.main(["session-start", *forwarded_tail]))
308
+ forwarded_tail = _maybe_insert_repo(tail, repo, explicit_repo, allow_positional_dir=(cmd in ("brief", "checkpoint")))
309
+ return int(agent_state.main([cmd, *forwarded_tail]))
310
+
311
+ if cmd == "route":
312
+ if orch_dir not in sys.path:
313
+ sys.path.insert(0, orch_dir)
314
+ import route_task # type: ignore[import-not-found]
315
+ return int(route_task.main(tail or ["--help"]))
316
+
317
+ if cmd == "cache":
318
+ if cache_dir not in sys.path:
319
+ sys.path.insert(0, cache_dir)
320
+ import prompt_cache # type: ignore[import-not-found]
321
+ return int(prompt_cache.main(tail or ["--help"]))
322
+
323
+ raise SystemExit(f"Unknown ae command: {cmd!r}. Run `ae --help` for available commands.")
324
+
325
+
326
+ if __name__ == "__main__":
327
+ raise SystemExit(main())
@@ -0,0 +1,267 @@
1
+ #!/usr/bin/env python3
2
+ """AgentEfficiency — 1-command onboarding wizard (`ae init`).
3
+
4
+ Auto-detects installed coding agents (Claude Code, Gemini/Antigravity, Codex, Cursor, OpenCode,
5
+ Windsurf, Copilot, generic ~/.agents), installs skills + short `ae` CLI + non-destructive workflow
6
+ rules, optionally configures repo hooks (hint-only by default; opt-in `--auto-wrap`) and lean
7
+ 7-tool MCP server (`--mcp --mcp-profile core`), and builds the initial repo index.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import sys
14
+ from pathlib import Path
15
+ from typing import Any, Dict, List, Optional, Sequence
16
+
17
+ _SCRIPTS_DIR = str(Path(__file__).resolve().parent)
18
+ if _SCRIPTS_DIR not in sys.path:
19
+ sys.path.insert(0, _SCRIPTS_DIR)
20
+
21
+ import install as installer # noqa: E402
22
+ import setup_hooks # noqa: E402
23
+
24
+
25
+ def _runtime_targets_for_home(home: Path) -> Dict[str, Dict[str, Path]]:
26
+ return {
27
+ "claude": {"probe": home / ".claude", "skills": home / ".claude" / "skills", "rules": home / ".claude" / "CLAUDE.md"},
28
+ "gemini": {"probe": home / ".gemini", "skills": home / ".gemini" / "config" / "skills", "rules": home / ".gemini" / "GEMINI.md"},
29
+ "codex": {"probe": home / ".codex", "skills": home / ".codex" / "skills", "rules": home / ".codex" / "AGENTS.md"},
30
+ "cursor": {"probe": home / ".cursor", "skills": home / ".cursor" / "skills", "rules": home / ".cursor" / "rules" / "agent-efficiency.mdc"},
31
+ "opencode": {"probe": home / ".config" / "opencode", "skills": home / ".config" / "opencode" / "skills", "rules": home / ".config" / "opencode" / "AGENTS.md"},
32
+ "windsurf": {"probe": home / ".codeium" / "windsurf", "skills": home / ".codeium" / "windsurf" / "skills", "rules": home / ".codeium" / "windsurf" / "memories" / "global_rules.md"},
33
+ "copilot": {"probe": home / ".copilot", "skills": home / ".copilot" / "skills", "rules": home / ".copilot" / "copilot-instructions.md"},
34
+ "agents": {"probe": home / ".agents", "skills": home / ".agents" / "skills", "rules": home / ".agents" / "AGENTS.md"},
35
+ }
36
+
37
+
38
+ def detect_runtimes(home: Optional[Path] = None) -> List[str]:
39
+ h = (home or Path.home()).expanduser().resolve()
40
+ table = _runtime_targets_for_home(h)
41
+ found = [name for name in ("claude", "gemini", "codex", "cursor", "opencode", "windsurf", "copilot") if table[name]["probe"].exists()]
42
+ if not found:
43
+ return ["agents"]
44
+ return found
45
+
46
+
47
+ def run_init(
48
+ repo: Optional[Path] = None,
49
+ *,
50
+ runtimes: Optional[Sequence[str]] = None,
51
+ profile: str = "ide",
52
+ home: Optional[Path] = None,
53
+ install_cli: bool = True,
54
+ install_rules: bool = True,
55
+ install_mcp: bool = False,
56
+ mcp_profile: str = "core",
57
+ setup_runtime_hooks: bool = False,
58
+ auto_wrap: bool = False,
59
+ setup_git_hooks: bool = False,
60
+ run_index: bool = True,
61
+ dry_run: bool = False,
62
+ ) -> Dict[str, Any]:
63
+ h = (home or Path.home()).expanduser().resolve()
64
+ repo_r = (repo or Path.cwd()).expanduser().resolve()
65
+ table = _runtime_targets_for_home(h)
66
+
67
+ if runtimes:
68
+ chosen: List[str] = []
69
+ for raw_r in runtimes:
70
+ for part in str(raw_r).split(","):
71
+ p = part.strip().lower()
72
+ if not p:
73
+ continue
74
+ if p == "all":
75
+ chosen.extend(table.keys())
76
+ elif p in table:
77
+ chosen.append(p)
78
+ else:
79
+ raise SystemExit(f"Unknown runtime {p!r}. Choose from: {', '.join(sorted(table))} or 'all'.")
80
+ chosen = list(dict.fromkeys(chosen))
81
+ else:
82
+ chosen = detect_runtimes(h)
83
+
84
+ cli_target = h / ".local" / "bin" / "ae"
85
+ mcp_target = h / ".agent-efficiency" / "mcp"
86
+ installed_results: List[Dict[str, Any]] = []
87
+ primary_skills_dir: Optional[Path] = None
88
+ pretool_hook_path: Optional[Path] = None
89
+
90
+ for idx_i, rt in enumerate(chosen):
91
+ spec = table[rt]
92
+ is_first = idx_i == 0
93
+ res = installer.install_skills(
94
+ spec["skills"],
95
+ profile=profile,
96
+ mode="copy",
97
+ force=True,
98
+ dry_run=dry_run,
99
+ verify=True,
100
+ install_mcp=(install_mcp and is_first),
101
+ mcp_target_dir=mcp_target,
102
+ install_cli=(install_cli and is_first),
103
+ cli_target=cli_target,
104
+ install_rules=install_rules,
105
+ rules_target=spec["rules"],
106
+ )
107
+ res["runtime"] = rt
108
+ installed_results.append(res)
109
+ if primary_skills_dir is None:
110
+ primary_skills_dir = spec["skills"]
111
+ if res.get("pretool_hook"):
112
+ pretool_hook_path = Path(str(res["pretool_hook"]))
113
+
114
+ # Optional repo-level setup (only if target repo looks like a project directory)
115
+ is_git = (repo_r / ".git").exists()
116
+ hooks_results: List[Dict[str, Any]] = []
117
+ if setup_runtime_hooks or auto_wrap:
118
+ hook_clients = [c for c in ("claude", "gemini") if c in chosen] or ["claude"]
119
+ for hc in hook_clients:
120
+ hcfg = setup_hooks.generate_runtime_hooks(
121
+ hc,
122
+ repo_r,
123
+ skills_dir=primary_skills_dir if not dry_run else None,
124
+ include_pretool=True,
125
+ auto_wrap=auto_wrap,
126
+ pretool_script=pretool_hook_path if (pretool_hook_path and pretool_hook_path.is_file()) else None,
127
+ )
128
+ written = False
129
+ if not dry_run:
130
+ target = Path(hcfg["target_file"])
131
+ target.parent.mkdir(parents=True, exist_ok=True)
132
+ existing = json.loads(target.read_text(encoding="utf-8")) if target.is_file() else {}
133
+ merged = setup_hooks.merge_runtime_hooks(existing, hcfg["config"]["hooks"])
134
+ target.write_text(json.dumps(merged, indent=2) + "\n", encoding="utf-8")
135
+ written = True
136
+ hooks_results.append({"client": hc, "target_file": hcfg["target_file"], "auto_wrap": auto_wrap, "written": written})
137
+
138
+ git_hooks_res: Optional[Dict[str, Any]] = None
139
+ if setup_git_hooks and is_git:
140
+ git_hooks_res = setup_hooks.manage_git_hooks(
141
+ repo_r,
142
+ dry_run=dry_run,
143
+ skills_dir=primary_skills_dir if not dry_run else None,
144
+ )
145
+
146
+ index_res: Optional[Dict[str, Any]] = None
147
+ if run_index and is_git and not dry_run:
148
+ ctx_dir = str(installer.SKILLS_DIR / "local-context-index" / "scripts")
149
+ if ctx_dir not in sys.path:
150
+ sys.path.insert(0, ctx_dir)
151
+ import context_index # type: ignore[import-not-found]
152
+ index_res = context_index.index(repo_r)
153
+
154
+ mcp_cfg: Optional[Dict[str, Any]] = None
155
+ if install_mcp:
156
+ mcp_cfg = setup_hooks.generate_mcp_config(
157
+ client=chosen[0] if chosen[0] in ("claude", "cursor", "gemini", "codex") else "generic",
158
+ server_path=mcp_target / "server.py",
159
+ skills_dir=primary_skills_dir,
160
+ profile=mcp_profile,
161
+ )
162
+
163
+ return {
164
+ "dry_run": dry_run,
165
+ "profile": profile,
166
+ "runtimes": chosen,
167
+ "repo": str(repo_r),
168
+ "is_git_repo": is_git,
169
+ "cli_bin": str(cli_target) if install_cli else None,
170
+ "installs": installed_results,
171
+ "runtime_hooks": hooks_results,
172
+ "git_hooks": git_hooks_res,
173
+ "index": index_res,
174
+ "mcp_config": mcp_cfg,
175
+ }
176
+
177
+
178
+ def _box_row(text: str, width: int = 62) -> str:
179
+ clipped = text if len(text) <= width else (text[: max(1, width - 1)] + "…")
180
+ return f"│{clipped:<{width}}│"
181
+
182
+
183
+ def format_init_summary(res: Dict[str, Any]) -> str:
184
+ mode_tag = " [DRY-RUN]" if res["dry_run"] else ""
185
+ rts = ", ".join(res["runtimes"])
186
+ lines = [
187
+ "┌──────────────────────────────────────────────────────────────┐",
188
+ _box_row(f" AgentEfficiency Init Complete{mode_tag}"),
189
+ "├──────────────────────────────────────────────────────────────┤",
190
+ _box_row(f" Runtimes : {rts}"),
191
+ _box_row(f" Profile : {res['profile']}"),
192
+ ]
193
+ if res.get("cli_bin"):
194
+ lines.append(_box_row(f" CLI : {res['cli_bin']}"))
195
+ if res.get("runtime_hooks"):
196
+ for h in res["runtime_hooks"]:
197
+ mode_s = "opt-in auto-wrap" if h["auto_wrap"] else "safe hint-only"
198
+ lines.append(_box_row(f" Hooks : {h['client']} ({mode_s}, SessionStart=ae resume)"))
199
+ if res.get("index"):
200
+ idx = res["index"]
201
+ lines.append(_box_row(f" Indexed : {idx.get('indexed', 0)} files, {idx.get('symbols', 0)} symbols"))
202
+ if res.get("mcp_config"):
203
+ lines.append(_box_row(f" MCP : profile={res['mcp_config']['profile']} (lean schema)"))
204
+ lines.extend([
205
+ "├──────────────────────────────────────────────────────────────┤",
206
+ _box_row(" Try right now:"),
207
+ _box_row(" ae audit See your real IDE token waste"),
208
+ _box_row(" ae doctor Check bloat & top-10 skills"),
209
+ _box_row(" ae install-status Verify active hooks/rules/MCP"),
210
+ _box_row(" ae savings --statusline Live savings counter"),
211
+ "└──────────────────────────────────────────────────────────────┘",
212
+ ])
213
+ return "\n".join(lines)
214
+
215
+
216
+ def main(argv: Optional[Sequence[str]] = None) -> int:
217
+ for stream in (sys.stdout, sys.stderr):
218
+ reconf = getattr(stream, "reconfigure", None)
219
+ if callable(reconf):
220
+ try:
221
+ reconf(encoding="utf-8", errors="replace")
222
+ except Exception:
223
+ pass
224
+ ap = argparse.ArgumentParser(description="1-command AgentEfficiency setup: auto-detect IDEs, install skills/CLI/rules, optional hooks & lean MCP.")
225
+ ap.add_argument("repo", nargs="?", type=Path, default=Path.cwd(), help="Target repository directory (defaults to cwd)")
226
+ ap.add_argument("--runtime", action="append", default=None, help="Explicit runtime(s) (comma-separated or repeatable): claude,gemini,codex,cursor,opencode,windsurf,copilot,agents,all")
227
+ ap.add_argument("--profile", choices=sorted(installer.SKILL_PROFILES.keys()), default="ide", help="Skill bundle: 'ide' (2 core skills, default) or 'full' (adds pipeline prompt-cache-manager)")
228
+ ap.add_argument("--hooks", action="store_true", help="Write non-destructive runtime hooks (SessionStart, PostToolUse, PreCompact, Stop + safe hint-only PreToolUse)")
229
+ ap.add_argument("--auto-wrap", action="store_true", help="Opt-in: enable PreToolUse shell rewrite for simple pipe-free test/build commands (implies --hooks)")
230
+ ap.add_argument("--git-hooks", action="store_true", help="Install worktree-aware Git post-commit/checkout/merge auto-reindex hooks")
231
+ ap.add_argument("--mcp", action="store_true", help="Install standalone MCP server and print lean `--profile core` config")
232
+ ap.add_argument("--mcp-profile", choices=["core", "ide", "full"], default="core", help="MCP tool profile when --mcp is set (default: core = 7 tools)")
233
+ ap.add_argument("--no-cli", action="store_true", help="Skip installing ~/.local/bin/ae")
234
+ ap.add_argument("--no-rules", action="store_true", help="Skip merging 6-line workflow rules into CLAUDE.md/GEMINI.md/AGENTS.md/Cursor .mdc")
235
+ ap.add_argument("--no-index", action="store_true", help="Skip building initial repository index")
236
+ ap.add_argument("--home", type=Path, default=None, help="Override home directory (useful for isolated testing)")
237
+ ap.add_argument("--dry-run", action="store_true", help="Preview all actions without modifying files")
238
+ ap.add_argument("--json", dest="as_json", action="store_true", help="Emit JSON output")
239
+ args = ap.parse_args(argv)
240
+
241
+ res = run_init(
242
+ args.repo,
243
+ runtimes=args.runtime,
244
+ profile=args.profile,
245
+ home=args.home,
246
+ install_cli=not args.no_cli,
247
+ install_rules=not args.no_rules,
248
+ install_mcp=args.mcp,
249
+ mcp_profile=args.mcp_profile,
250
+ setup_runtime_hooks=args.hooks,
251
+ auto_wrap=args.auto_wrap,
252
+ setup_git_hooks=args.git_hooks,
253
+ run_index=not args.no_index,
254
+ dry_run=args.dry_run,
255
+ )
256
+ if args.as_json:
257
+ print(json.dumps(res, indent=2, ensure_ascii=False))
258
+ else:
259
+ print(format_init_summary(res))
260
+ if res.get("mcp_config"):
261
+ print("\nMCP Server Config (paste into your client settings):")
262
+ print(json.dumps({"mcpServers": res["mcp_config"]["mcpServers"]}, indent=2))
263
+ return 0
264
+
265
+
266
+ if __name__ == "__main__":
267
+ raise SystemExit(main())