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,308 @@
1
+ #!/usr/bin/env python3
2
+ """Install, verify, or uninstall AgentEfficiency skills (and optional standalone MCP server)."""
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import os
8
+ import shutil
9
+ import sys
10
+ from pathlib import Path
11
+ from typing import Dict, List, Optional, Sequence
12
+
13
+ ROOT = Path(__file__).resolve().parents[1]
14
+ SKILLS_DIR = ROOT / "skills"
15
+ MCP_SRC = ROOT / "mcp" / "server.py"
16
+ CLI_SRC = ROOT / "scripts" / "ae_cli.py"
17
+ PRETOOL_SRC = ROOT / "scripts" / "pretool_hook.py"
18
+ MANAGE_SRC = ROOT / "scripts" / "ae_manage.py"
19
+ RULES_SRC = ROOT / "rules" / "AGENT_RULES.md"
20
+ DEFAULT_MCP_TARGET = Path.home() / ".agent-efficiency" / "mcp"
21
+ DEFAULT_HOOKS_TARGET = Path.home() / ".agent-efficiency" / "hooks"
22
+ DEFAULT_CLI_TARGET = Path.home() / ".local" / "bin" / "ae"
23
+
24
+ SKILL_PROFILES: Dict[str, List[str]] = {
25
+ "ide": ["local-context-index", "adaptive-orchestration-handoff"],
26
+ "full": ["local-context-index", "adaptive-orchestration-handoff", "prompt-cache-manager"],
27
+ }
28
+
29
+ RULES_PRESET_TARGETS: Dict[str, Path] = {
30
+ "agents": Path.home() / ".agents" / "AGENTS.md",
31
+ "claude": Path.home() / ".claude" / "CLAUDE.md",
32
+ "gemini": Path.home() / ".gemini" / "GEMINI.md",
33
+ "codex": Path.home() / ".codex" / "AGENTS.md",
34
+ "cursor": Path.home() / ".cursor" / "rules" / "agent-efficiency.mdc",
35
+ "windsurf": Path.home() / ".codeium" / "windsurf" / "memories" / "global_rules.md",
36
+ "opencode": Path.home() / ".config" / "opencode" / "AGENTS.md",
37
+ "copilot": Path.home() / ".copilot" / "copilot-instructions.md",
38
+ }
39
+
40
+ _CURSOR_MDC_HEADER = "---\ndescription: AgentEfficiency minimal-context, log-compression, and session-memory workflow\nalwaysApply: true\n---\n\n"
41
+ _RULES_START = "<!-- agent-efficiency:start -->"
42
+ _RULES_END = "<!-- agent-efficiency:end -->"
43
+
44
+ _SCRIPTS_DIR = str(Path(__file__).resolve().parent)
45
+ if _SCRIPTS_DIR not in sys.path:
46
+ sys.path.insert(0, _SCRIPTS_DIR)
47
+
48
+ import validate_skills # noqa: E402
49
+
50
+ PRESET_TARGETS: Dict[str, Path] = {
51
+ "agents": Path.home() / ".agents" / "skills",
52
+ "claude": Path.home() / ".claude" / "skills",
53
+ "gemini": Path.home() / ".gemini" / "config" / "skills",
54
+ "codex": Path.home() / ".codex" / "skills",
55
+ "cursor": Path.home() / ".cursor" / "skills",
56
+ "windsurf": Path.home() / ".codeium" / "windsurf" / "skills",
57
+ "opencode": Path.home() / ".config" / "opencode" / "skills",
58
+ "copilot": Path.home() / ".copilot" / "skills",
59
+ }
60
+
61
+
62
+ def discover_skills(skills_dir: Path = SKILLS_DIR) -> List[Path]:
63
+ return [
64
+ d
65
+ for d in sorted(skills_dir.iterdir())
66
+ if not d.is_symlink() and d.is_dir() and (d / "SKILL.md").is_file() and not (d / "SKILL.md").is_symlink()
67
+ ]
68
+
69
+
70
+ def _assert_no_escaping_symlinks(src: Path) -> None:
71
+ src_r = src.resolve()
72
+ for dirpath, dirnames, filenames in os.walk(src_r, followlinks=False):
73
+ dp = Path(dirpath)
74
+ for name in list(dirnames) + list(filenames):
75
+ entry = dp / name
76
+ if entry.is_symlink():
77
+ try:
78
+ entry.resolve().relative_to(src_r)
79
+ except ValueError:
80
+ raise SystemExit(f"Refusing to install skill with escaping symlink: {entry}")
81
+
82
+
83
+ def _paths_overlap(src: Path, dst: Path) -> bool:
84
+ src_r = src.resolve()
85
+ dst_r = dst.resolve()
86
+ return src_r == dst_r or src_r in dst_r.parents or dst_r in src_r.parents
87
+
88
+
89
+ def _merge_rules_file(target: Path, snippet: str, *, dry_run: bool = False) -> str:
90
+ import re
91
+ existing = target.read_text(encoding="utf-8", errors="replace") if target.is_file() else ""
92
+ block = snippet.strip() + "\n"
93
+ if _RULES_START in existing and _RULES_END in existing:
94
+ pat = re.compile(rf"{re.escape(_RULES_START)}[\s\S]*?{re.escape(_RULES_END)}\n?", re.MULTILINE)
95
+ updated = pat.sub(block, existing, count=1)
96
+ act = "updated"
97
+ elif existing.strip():
98
+ updated = existing.rstrip() + "\n\n" + block
99
+ act = "appended"
100
+ else:
101
+ updated = (_CURSOR_MDC_HEADER + block) if target.suffix.lower() == ".mdc" else block
102
+ act = "created"
103
+ if not dry_run:
104
+ target.parent.mkdir(parents=True, exist_ok=True)
105
+ target.write_text(updated, encoding="utf-8")
106
+ return f"{'would_' if dry_run else ''}{act}"
107
+
108
+
109
+ def install_skills(
110
+ target_dir: Path,
111
+ *,
112
+ selected: Optional[Sequence[str]] = None,
113
+ profile: str = "full",
114
+ mode: str = "copy",
115
+ force: bool = False,
116
+ dry_run: bool = False,
117
+ verify: bool = True,
118
+ install_mcp: bool = False,
119
+ mcp_target_dir: Path = DEFAULT_MCP_TARGET,
120
+ install_cli: bool = False,
121
+ cli_target: Path = DEFAULT_CLI_TARGET,
122
+ install_rules: bool = False,
123
+ rules_target: Optional[Path] = None,
124
+ ) -> Dict[str, object]:
125
+ available = {d.name: d for d in discover_skills()}
126
+ if selected:
127
+ names = list(selected)
128
+ elif profile in SKILL_PROFILES:
129
+ names = [n for n in SKILL_PROFILES[profile] if n in available]
130
+ else:
131
+ raise SystemExit(f"Unknown profile {profile!r}. Choose from: {', '.join(sorted(SKILL_PROFILES))}")
132
+ unknown = [n for n in names if n not in available]
133
+ if unknown:
134
+ raise SystemExit(f"Unknown skill(s): {', '.join(unknown)}. Available: {', '.join(available.keys())}")
135
+
136
+ if verify:
137
+ failed = []
138
+ for name in names:
139
+ rep = validate_skills.validate_skill(available[name])
140
+ if not rep["ok"]:
141
+ failed.append({"skill": name, "errors": rep["errors"]})
142
+ if failed:
143
+ raise SystemExit(f"Pre-install skill validation failed (pass --no-verify to bypass): {json.dumps(failed, indent=2)}")
144
+
145
+ target_dir = target_dir.expanduser().resolve()
146
+ actions: List[Dict[str, str]] = []
147
+
148
+ for name in names:
149
+ src = available[name]
150
+ dst = target_dir / name
151
+ if _paths_overlap(src, dst) and not dst.is_symlink():
152
+ raise SystemExit(f"Refusing to install into overlapping source path: {dst}")
153
+ if mode == "copy":
154
+ _assert_no_escaping_symlinks(src)
155
+
156
+ if not dry_run:
157
+ target_dir.mkdir(parents=True, exist_ok=True)
158
+
159
+ for name in names:
160
+ src = available[name]
161
+ dst = target_dir / name
162
+ if dst.exists() or dst.is_symlink():
163
+ if not force:
164
+ actions.append({"skill": name, "action": "skipped_exists", "target": str(dst)})
165
+ continue
166
+ if not dry_run:
167
+ if dst.is_symlink() or dst.is_file():
168
+ dst.unlink()
169
+ else:
170
+ shutil.rmtree(dst)
171
+ if not dry_run:
172
+ if mode == "symlink":
173
+ os.symlink(src, dst, target_is_directory=True)
174
+ else:
175
+ shutil.copytree(src, dst, ignore=shutil.ignore_patterns("__pycache__", "*.pyc", ".DS_Store"))
176
+ actions.append({"skill": name, "action": f"{'would_' if dry_run else ''}{mode}", "source": str(src), "target": str(dst)})
177
+
178
+ mcp_installed: Optional[str] = None
179
+ if install_mcp and MCP_SRC.is_file():
180
+ mcp_dst_dir = mcp_target_dir.expanduser().resolve()
181
+ mcp_dst = mcp_dst_dir / "server.py"
182
+ if not dry_run:
183
+ mcp_dst_dir.mkdir(parents=True, exist_ok=True)
184
+ # Rewrite default skills base fallback to the installed target_dir so MCP stays standalone
185
+ src_code = MCP_SRC.read_text(encoding="utf-8")
186
+ marker = 'if not _SKILLS_BASE.is_dir():\n _SKILLS_BASE = ROOT / "skills"'
187
+ repl = f'if not _SKILLS_BASE.is_dir():\n _SKILLS_BASE = Path({str(target_dir)!r})'
188
+ mcp_dst.write_text(src_code.replace(marker, repl), encoding="utf-8")
189
+ mcp_dst.chmod(0o755)
190
+ mcp_installed = str(mcp_dst)
191
+ actions.append({"skill": "mcp-server", "action": f"{'would_' if dry_run else ''}install_mcp", "target": mcp_installed})
192
+
193
+ cli_installed: Optional[str] = None
194
+ hooks_installed: Optional[str] = None
195
+ if install_cli and CLI_SRC.is_file():
196
+ cli_dst = cli_target.expanduser().resolve()
197
+ if not dry_run:
198
+ cli_dst.parent.mkdir(parents=True, exist_ok=True)
199
+ cli_code = CLI_SRC.read_text(encoding="utf-8").replace('_BAKED_SKILLS_DIR = ""', f"_BAKED_SKILLS_DIR = {str(target_dir)!r}", 1)
200
+ cli_dst.write_text(cli_code, encoding="utf-8")
201
+ cli_dst.chmod(0o755)
202
+ if os.name == "nt":
203
+ cmd_shim = cli_dst.with_suffix(".cmd")
204
+ cmd_shim.write_text(f'@echo off\r\n"{sys.executable}" "%~dp0{cli_dst.name}" %*\r\n', encoding="utf-8")
205
+ cli_installed = str(cli_dst)
206
+ actions.append({"skill": "ae-cli", "action": f"{'would_' if dry_run else ''}install_cli", "target": cli_installed})
207
+ # Also install standalone pretool_hook.py & ae_manage.py alongside CLI so hooks/uninstall work even if source repo moves
208
+ hooks_dir = (cli_dst.parent.parent / "share" / "agent-efficiency" / "hooks") if str(cli_target) != str(DEFAULT_CLI_TARGET) else DEFAULT_HOOKS_TARGET
209
+ if PRETOOL_SRC.is_file():
210
+ pt_dst = hooks_dir.expanduser().resolve() / "pretool_hook.py"
211
+ if not dry_run:
212
+ pt_dst.parent.mkdir(parents=True, exist_ok=True)
213
+ shutil.copy2(PRETOOL_SRC, pt_dst)
214
+ pt_dst.chmod(0o755)
215
+ hooks_installed = str(pt_dst)
216
+ actions.append({"skill": "pretool-hook", "action": f"{'would_' if dry_run else ''}install_hook", "target": hooks_installed})
217
+ if MANAGE_SRC.is_file():
218
+ mg_dst = hooks_dir.expanduser().resolve() / "ae_manage.py"
219
+ if not dry_run:
220
+ mg_dst.parent.mkdir(parents=True, exist_ok=True)
221
+ shutil.copy2(MANAGE_SRC, mg_dst)
222
+ mg_dst.chmod(0o755)
223
+ actions.append({"skill": "ae-manage", "action": f"{'would_' if dry_run else ''}install_manage", "target": str(mg_dst)})
224
+
225
+ rules_installed: Optional[str] = None
226
+ if install_rules and RULES_SRC.is_file():
227
+ rt = (rules_target or RULES_PRESET_TARGETS["agents"]).expanduser().resolve()
228
+ act = _merge_rules_file(rt, RULES_SRC.read_text(encoding="utf-8"), dry_run=dry_run)
229
+ rules_installed = str(rt)
230
+ actions.append({"skill": "agent-rules", "action": act, "target": rules_installed})
231
+
232
+ return {"target_dir": str(target_dir), "profile": profile, "mode": mode, "dry_run": dry_run, "verified": verify, "mcp_server": mcp_installed, "cli_bin": cli_installed, "pretool_hook": hooks_installed, "rules_file": rules_installed, "actions": actions}
233
+
234
+
235
+ def uninstall_skills(
236
+ target_dir: Path,
237
+ *,
238
+ selected: Optional[Sequence[str]] = None,
239
+ dry_run: bool = False,
240
+ ) -> Dict[str, object]:
241
+ available_names = [d.name for d in discover_skills()]
242
+ names = list(selected) if selected else available_names
243
+ target_dir = target_dir.expanduser().resolve()
244
+ actions: List[Dict[str, str]] = []
245
+ for name in names:
246
+ dst = target_dir / name
247
+ if not dst.exists() and not dst.is_symlink():
248
+ actions.append({"skill": name, "action": "not_installed", "target": str(dst)})
249
+ continue
250
+ if not dry_run:
251
+ if dst.is_symlink() or dst.is_file():
252
+ dst.unlink()
253
+ else:
254
+ shutil.rmtree(dst)
255
+ actions.append({"skill": name, "action": "would_remove" if dry_run else "removed", "target": str(dst)})
256
+ return {"target_dir": str(target_dir), "dry_run": dry_run, "actions": actions}
257
+
258
+
259
+ def main(argv: Optional[Sequence[str]] = None) -> int:
260
+ ap = argparse.ArgumentParser(description="Install, verify, or uninstall Agent Efficiency Skills.")
261
+ ap.add_argument(
262
+ "--runtime",
263
+ choices=sorted(PRESET_TARGETS.keys()),
264
+ default="agents",
265
+ help="Target preset: agents, claude, codex, copilot, cursor, gemini, opencode, or windsurf",
266
+ )
267
+ ap.add_argument("--target", type=Path, default=None, help="Explicit target directory (overrides --runtime)")
268
+ ap.add_argument("--skill", action="append", default=None, help="Install/uninstall only named skill (repeatable)")
269
+ ap.add_argument("--profile", choices=sorted(SKILL_PROFILES.keys()), default="full", help="Skill bundle: 'ide' (2 core IDE skills, skips pipeline-only prompt-cache-manager) or 'full' (all 3)")
270
+ ap.add_argument("--mode", choices=["copy", "symlink"], default="copy")
271
+ ap.add_argument("--force", action="store_true", help="Overwrite existing installed skill directories")
272
+ ap.add_argument("--dry-run", action="store_true", help="Preview installation/uninstallation without writing files")
273
+ ap.add_argument("--no-verify", action="store_true", help="Skip pre-install validation checks")
274
+ ap.add_argument("--uninstall", action="store_true", help="Remove installed AgentEfficiency skills from target directory")
275
+ ap.add_argument("--install-mcp", action="store_true", help="Also install standalone MCP server to ~/.agent-efficiency/mcp/server.py")
276
+ ap.add_argument("--mcp-target", type=Path, default=DEFAULT_MCP_TARGET, help="Target directory for --install-mcp")
277
+ ap.add_argument("--install-cli", action="store_true", help="Also install short global `ae` CLI wrapper to ~/.local/bin/ae")
278
+ ap.add_argument("--cli-target", type=Path, default=DEFAULT_CLI_TARGET, help="Target path for --install-cli")
279
+ ap.add_argument("--install-rules", action="store_true", help="Non-destructively add concise `ae` workflow rules to GEMINI.md/CLAUDE.md/AGENTS.md")
280
+ ap.add_argument("--rules-target", type=Path, default=None, help="Explicit rules file target (defaults to runtime's GEMINI.md/CLAUDE.md/AGENTS.md)")
281
+ args = ap.parse_args(argv)
282
+
283
+ target = args.target if args.target is not None else PRESET_TARGETS[args.runtime]
284
+ eff_rules_target = args.rules_target if args.rules_target is not None else RULES_PRESET_TARGETS.get(args.runtime)
285
+ if args.uninstall:
286
+ res = uninstall_skills(target, selected=args.skill, dry_run=args.dry_run)
287
+ else:
288
+ res = install_skills(
289
+ target,
290
+ selected=args.skill,
291
+ profile=args.profile,
292
+ mode=args.mode,
293
+ force=args.force,
294
+ dry_run=args.dry_run,
295
+ verify=not args.no_verify,
296
+ install_mcp=args.install_mcp,
297
+ mcp_target_dir=args.mcp_target,
298
+ install_cli=args.install_cli,
299
+ cli_target=args.cli_target,
300
+ install_rules=args.install_rules,
301
+ rules_target=eff_rules_target,
302
+ )
303
+ print(json.dumps(res, indent=2))
304
+ return 0
305
+
306
+
307
+ if __name__ == "__main__":
308
+ raise SystemExit(main())
@@ -0,0 +1,350 @@
1
+ #!/usr/bin/env python3
2
+ """AgentEfficiency — Non-blocking PreToolUse / BeforeTool hook for Claude Code & Gemini CLI.
3
+
4
+ 1. Transparently wraps noisy test/build/typecheck shell commands with `ae run -- <cmd>` (80–95% log
5
+ compression + automatic failing stacktrace slicing) while leaving piped/chained/interactive
6
+ commands completely untouched.
7
+ 2. Detects repeated unchanged full-file reads of large (>150 line) files in the same session and
8
+ injects a gentle non-blocking nudge to use `ae slice` / `ae outline`.
9
+
10
+ Strictly safe: never blocks tool execution and always emits valid JSON on stdout (exit 0).
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import hashlib
16
+ import json
17
+ import os
18
+ import re
19
+ import shlex
20
+ import shutil
21
+ import sys
22
+ import tempfile
23
+ import time
24
+ from pathlib import Path
25
+ from typing import Any, Dict, List, Optional, Sequence, Tuple
26
+
27
+ _SHELL_TOOL_NAMES = {"bash", "run_shell_command", "run_command", "shell", "execute_command"}
28
+ _READ_TOOL_NAMES = {"read", "read_file", "view_file"}
29
+
30
+ # Operators that make transparent argv wrapping unsafe or semantically different
31
+ _UNSAFE_SHELL_RE = re.compile(r"[|><;&`\n\r]|\$\(|\$\{")
32
+ _ALREADY_WRAPPED_RE = re.compile(r"(?:^|\s)(?:ae\s+run\b|context_index\.py\s+run\b|compact_run\.py\b)")
33
+ _ENV_ASSIGN_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=[A-Za-z0-9_./:@+-]*$")
34
+ _INTERACTIVE_FLAGS = {
35
+ "-i", "--interactive", "--pdb", "--ipdb", "--trace", "-w", "--watch", "--watchall",
36
+ "--ui", "--inspect", "--inspect-brk", "--headed", "--debug", "watch",
37
+ }
38
+
39
+ # Known noisy test, build, typecheck, and lint command prefixes (matched after optional ENV=val)
40
+ _WRAPPABLE_SINGLE = {
41
+ "pytest", "py.test", "vitest", "jest", "tsc", "eslint", "mypy", "flake8", "pylint", "pyright", "rspec", "phpunit",
42
+ }
43
+ _WRAPPABLE_PAIRS = {
44
+ ("python", "-m"), ("python3", "-m"),
45
+ ("uv", "run"), ("poetry", "run"), ("pipenv", "run"),
46
+ ("npm", "test"), ("npm", "run"), ("pnpm", "test"), ("pnpm", "run"), ("pnpm", "build"),
47
+ ("yarn", "test"), ("yarn", "build"), ("bun", "test"),
48
+ ("npx", "jest"), ("npx", "vitest"), ("npx", "tsc"), ("npx", "eslint"), ("npx", "playwright"),
49
+ ("cargo", "test"), ("cargo", "check"), ("cargo", "build"), ("cargo", "clippy"),
50
+ ("go", "test"), ("go", "build"), ("go", "vet"),
51
+ ("ruff", "check"), ("mvn", "test"), ("gradle", "test"), ("./gradlew", "test"),
52
+ ("dotnet", "test"), ("dotnet", "build"), ("bundle", "exec"), ("mix", "test"),
53
+ }
54
+ _PYTHON_MOD_ALLOW = {"pytest", "unittest", "mypy", "ruff", "flake8", "pylint"}
55
+ _NPM_SCRIPT_ALLOW = {"test", "tests", "build", "lint", "typecheck", "check", "ci", "e2e"}
56
+ _RUNNER_SUB_ALLOW = {"pytest", "unittest", "mypy", "ruff", "vitest", "jest", "rspec", "tsc"}
57
+
58
+ LARGE_FILE_MIN_LINES = 150
59
+ _READ_CACHE_TTL_S = 6 * 3600
60
+
61
+
62
+ def should_wrap_command(command: str) -> bool:
63
+ """Return True if `command` is a clean single noisy test/build/lint invocation safe to wrap."""
64
+ cmd = (command or "").strip()
65
+ if not cmd or len(cmd) > 600:
66
+ return False
67
+ if _ALREADY_WRAPPED_RE.search(cmd) or _UNSAFE_SHELL_RE.search(cmd):
68
+ return False
69
+ try:
70
+ tokens = shlex.split(cmd)
71
+ except ValueError:
72
+ return False
73
+ if not tokens:
74
+ return False
75
+
76
+ # Skip leading simple environment assignments (e.g. `CI=1 pytest -v`); reject complex/many env prefixes
77
+ idx = 0
78
+ while idx < len(tokens) and "=" in tokens[idx] and not tokens[idx].startswith("-"):
79
+ if not _ENV_ASSIGN_RE.match(tokens[idx]) or idx >= 2:
80
+ return False
81
+ idx += 1
82
+ if idx >= len(tokens):
83
+ return False
84
+ # Never wrap interactive, watch-mode, or debugger invocations
85
+ if any(t.lower() in _INTERACTIVE_FLAGS for t in tokens[idx + 1 :]):
86
+ return False
87
+ head = Path(tokens[idx]).name.lower()
88
+ rest = tokens[idx + 1 :]
89
+
90
+ if head in _WRAPPABLE_SINGLE:
91
+ return True
92
+ if not rest:
93
+ return False
94
+ sub = rest[0].lower()
95
+ if (head, sub) not in _WRAPPABLE_PAIRS:
96
+ return False
97
+ if head in ("python", "python3") and sub == "-m":
98
+ return len(rest) >= 2 and rest[1].lower() in _PYTHON_MOD_ALLOW
99
+ if head in ("npm", "pnpm") and sub == "run":
100
+ return len(rest) >= 2 and any(k in rest[1].lower() for k in _NPM_SCRIPT_ALLOW)
101
+ if head in ("uv", "poetry", "pipenv", "bundle") and sub in ("run", "exec"):
102
+ return len(rest) >= 2 and Path(rest[1]).name.lower() in _RUNNER_SUB_ALLOW
103
+ return True
104
+
105
+
106
+ def build_wrapped_command(
107
+ command: str,
108
+ *,
109
+ repo: Optional[Path] = None,
110
+ index_script: Optional[Path] = None,
111
+ budget_tokens: int = 800,
112
+ ae_bin: Optional[str] = None,
113
+ ) -> str:
114
+ """Wrap a validated shell command in `ae run` (or direct `context_index.py run` fallback)."""
115
+ cmd = command.strip()
116
+ tokens = shlex.split(cmd)
117
+ env_prefix: List[str] = []
118
+ idx = 0
119
+ while idx < len(tokens) and _ENV_ASSIGN_RE.match(tokens[idx]):
120
+ env_prefix.append(tokens[idx])
121
+ idx += 1
122
+ core_cmd = " ".join(shlex.quote(t) for t in tokens[idx:])
123
+ env_str = (" ".join(shlex.quote(e) for e in env_prefix) + " ") if env_prefix else ""
124
+
125
+ resolved_ae = ae_bin if ae_bin is not None else shutil.which("ae")
126
+ if resolved_ae:
127
+ repo_flag = f"-C {shlex.quote(str(repo.resolve()))} " if repo is not None else ""
128
+ return f"{env_str}{shlex.quote(resolved_ae)} {repo_flag}run --budget-tokens {int(budget_tokens)} -- {core_cmd}"
129
+ if index_script is not None:
130
+ rp = shlex.quote(str((repo or Path.cwd()).resolve()))
131
+ return f"{env_str}{shlex.quote(sys.executable)} {shlex.quote(str(index_script))} run {rp} --budget-tokens {int(budget_tokens)} -- {core_cmd}"
132
+ return f"{env_str}ae run --budget-tokens {int(budget_tokens)} -- {core_cmd}"
133
+
134
+
135
+ def _read_cache_file(session_id: str) -> Path:
136
+ base_override = os.getenv("AGENT_EFFICIENCY_READ_CACHE_DIR", "").strip()
137
+ base = Path(base_override).expanduser() if base_override else (Path(tempfile.gettempdir()) / "ae-read-cache")
138
+ sid = re.sub(r"[^A-Za-z0-9_.-]+", "_", session_id or "default")[:48]
139
+ return base / f"reads_{sid}.json"
140
+
141
+
142
+ def _check_and_record_full_read(
143
+ file_path: str,
144
+ tool_input: Dict[str, Any],
145
+ *,
146
+ session_id: str,
147
+ repo: Optional[Path] = None,
148
+ ) -> Optional[str]:
149
+ """Return a gentle nudge message if `file_path` is a repeated unchanged full read of a large file."""
150
+ # Only flag FULL file reads (if caller already passed line offsets/ranges, they are already being disciplined!)
151
+ for range_key in ("offset", "limit", "StartLine", "EndLine", "start_line", "end_line", "ByteOffset"):
152
+ if tool_input.get(range_key) is not None:
153
+ return None
154
+ if not file_path:
155
+ return None
156
+ try:
157
+ p = Path(file_path).expanduser()
158
+ if not p.is_absolute() and repo is not None:
159
+ p = repo / p
160
+ p = p.resolve()
161
+ if not p.is_file():
162
+ return None
163
+ st = p.stat()
164
+ if st.st_size < 3500 or st.st_size > 2_000_000:
165
+ return None
166
+ text = p.read_text(encoding="utf-8", errors="replace")
167
+ line_count = text.count("\n") + 1
168
+ if line_count < LARGE_FILE_MIN_LINES:
169
+ return None
170
+ tok_est = max(1, (len(text) + 3) // 4)
171
+ sig = f"{st.st_mtime_ns}:{st.st_size}"
172
+ except OSError:
173
+ return None
174
+
175
+ cache_path = _read_cache_file(session_id)
176
+ now = time.time()
177
+ cache: Dict[str, Any] = {}
178
+ try:
179
+ if cache_path.is_file():
180
+ raw = json.loads(cache_path.read_text(encoding="utf-8"))
181
+ if isinstance(raw, dict):
182
+ cache = {k: v for k, v in raw.items() if isinstance(v, dict) and now - float(v.get("ts", 0)) < _READ_CACHE_TTL_S}
183
+ except Exception:
184
+ cache = {}
185
+
186
+ key = hashlib.sha256(str(p).encode("utf-8")).hexdigest()[:16]
187
+ prev = cache.get(key)
188
+ cache[key] = {"sig": sig, "ts": now, "reads": int(prev.get("reads", 0)) + 1 if isinstance(prev, dict) else 1}
189
+ try:
190
+ cache_path.parent.mkdir(parents=True, exist_ok=True)
191
+ cache_path.write_text(json.dumps(cache), encoding="utf-8")
192
+ except OSError:
193
+ pass
194
+
195
+ if isinstance(prev, dict) and prev.get("sig") == sig:
196
+ rel_disp = p.name
197
+ if repo is not None:
198
+ try:
199
+ rel_disp = p.relative_to(repo.resolve()).as_posix()
200
+ except ValueError:
201
+ pass
202
+ return (
203
+ f"AgentEfficiency: `{rel_disp}` ({line_count} lines, ~{tok_est:,} tok) was already read unchanged in this session. "
204
+ f"Prefer `ae slice {rel_disp}:<Symbol>` or `ae outline {rel_disp}` over repeating full-file reads."
205
+ )
206
+ return None
207
+
208
+
209
+ def process_hook_event(
210
+ event: Dict[str, Any],
211
+ *,
212
+ client: str = "claude",
213
+ mode: str = "hint",
214
+ repo: Optional[Path] = None,
215
+ index_script: Optional[Path] = None,
216
+ budget_tokens: int = 800,
217
+ ae_bin: Optional[str] = None,
218
+ ) -> Dict[str, Any]:
219
+ """Process one PreToolUse / BeforeTool JSON payload and return the hook response dict.
220
+
221
+ `mode="hint"` (safe default) NEVER rewrites shell commands silently; it only adds a concise tip.
222
+ `mode="rewrite"` (explicit opt-in via `--auto-wrap`) transparently wraps simple pipe-free,
223
+ non-interactive test/build commands on Claude Code via `updatedInput`.
224
+ """
225
+ if not isinstance(event, dict):
226
+ return {}
227
+ tname = str(event.get("tool_name") or event.get("toolName") or "").strip()
228
+ tinput = event.get("tool_input") or event.get("toolInput") or {}
229
+ if not isinstance(tinput, dict):
230
+ return {}
231
+ tlower = tname.lower()
232
+ eff_repo = repo
233
+ if eff_repo is None and isinstance(event.get("cwd"), str) and event["cwd"].strip():
234
+ cand = Path(event["cwd"].strip())
235
+ if cand.is_dir():
236
+ eff_repo = cand
237
+
238
+ # 1. Shell command hint (default) or opt-in auto-wrap (`mode="rewrite"`) for noisy test/build/lint commands
239
+ if tlower in _SHELL_TOOL_NAMES:
240
+ cmd_key = "command" if "command" in tinput else ("CommandLine" if "CommandLine" in tinput else "cmd")
241
+ raw_cmd = str(tinput.get(cmd_key) or "").strip()
242
+ if not should_wrap_command(raw_cmd):
243
+ return {}
244
+ wrapped = build_wrapped_command(
245
+ raw_cmd,
246
+ repo=eff_repo,
247
+ index_script=index_script,
248
+ budget_tokens=budget_tokens,
249
+ ae_bin=ae_bin,
250
+ )
251
+ if client == "claude" and mode == "rewrite":
252
+ updated = dict(tinput)
253
+ updated[cmd_key] = wrapped
254
+ return {
255
+ "hookSpecificOutput": {
256
+ "hookEventName": "PreToolUse",
257
+ "permissionDecision": "allow",
258
+ "permissionDecisionReason": "AgentEfficiency (opt-in --auto-wrap): wrapped noisy test/build command for 80–95% log compression + trace slicing",
259
+ "updatedInput": updated,
260
+ }
261
+ }
262
+ tip = f"AgentEfficiency tip: prefer `ae run -- {raw_cmd}` to compress noisy test/build logs by 80–95% and auto-slice failing stacktraces."
263
+ if client == "claude":
264
+ return {
265
+ "hookSpecificOutput": {
266
+ "hookEventName": "PreToolUse",
267
+ "permissionDecision": "allow",
268
+ "additionalContext": tip,
269
+ }
270
+ }
271
+ return {
272
+ "decision": "allow",
273
+ "hookSpecificOutput": {
274
+ "hookEventName": "BeforeTool",
275
+ "additionalContext": tip,
276
+ },
277
+ }
278
+
279
+ # 2. Duplicate full-file read detection (non-blocking nudge)
280
+ if tlower in _READ_TOOL_NAMES:
281
+ fpath = str(tinput.get("file_path") or tinput.get("Path") or tinput.get("path") or "").strip()
282
+ sid = str(event.get("session_id") or event.get("sessionId") or os.getenv("CLAUDE_SESSION_ID", "default"))
283
+ nudge = _check_and_record_full_read(fpath, tinput, session_id=sid, repo=eff_repo)
284
+ if not nudge:
285
+ return {}
286
+ if client == "claude":
287
+ return {
288
+ "hookSpecificOutput": {
289
+ "hookEventName": "PreToolUse",
290
+ "permissionDecision": "allow",
291
+ "additionalContext": nudge,
292
+ }
293
+ }
294
+ return {
295
+ "decision": "allow",
296
+ "hookSpecificOutput": {
297
+ "hookEventName": "BeforeTool",
298
+ "additionalContext": nudge,
299
+ },
300
+ }
301
+
302
+ return {}
303
+
304
+
305
+ def main(argv: Optional[Sequence[str]] = None) -> int:
306
+ for stream in (sys.stdout, sys.stderr):
307
+ reconf = getattr(stream, "reconfigure", None)
308
+ if callable(reconf):
309
+ try:
310
+ reconf(encoding="utf-8", errors="replace")
311
+ except Exception:
312
+ pass
313
+ ap = argparse.ArgumentParser(description="AgentEfficiency PreToolUse/BeforeTool hook (hint by default; opt-in --mode rewrite for simple test/build commands).")
314
+ ap.add_argument("--client", choices=["claude", "gemini"], default="claude")
315
+ ap.add_argument("--mode", choices=["hint", "rewrite"], default="hint", help="hint (default, never mutates commands) or rewrite (opt-in auto-wrap for simple pipe-free test/build commands)")
316
+ ap.add_argument("--repo", type=Path, default=None)
317
+ ap.add_argument("--index-script", type=Path, default=None)
318
+ ap.add_argument("--budget-tokens", type=int, default=800)
319
+ args = ap.parse_args(argv)
320
+
321
+ raw_stdin = ""
322
+ try:
323
+ if not sys.stdin.isatty():
324
+ raw_stdin = sys.stdin.read()
325
+ except Exception:
326
+ raw_stdin = ""
327
+
328
+ event: Dict[str, Any] = {}
329
+ if raw_stdin.strip():
330
+ try:
331
+ parsed = json.loads(raw_stdin)
332
+ if isinstance(parsed, dict):
333
+ event = parsed
334
+ except Exception:
335
+ event = {}
336
+
337
+ resp = process_hook_event(
338
+ event,
339
+ client=args.client,
340
+ mode=args.mode,
341
+ repo=args.repo,
342
+ index_script=args.index_script,
343
+ budget_tokens=args.budget_tokens,
344
+ )
345
+ print(json.dumps(resp, ensure_ascii=False))
346
+ return 0
347
+
348
+
349
+ if __name__ == "__main__":
350
+ raise SystemExit(main())