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.
- agent_efficiency/__init__.py +15 -0
- agent_efficiency/_bundle/mcp/server.py +519 -0
- agent_efficiency/_bundle/rules/AGENT_RULES.md +9 -0
- agent_efficiency/_bundle/scripts/ae_cli.py +327 -0
- agent_efficiency/_bundle/scripts/ae_init.py +267 -0
- agent_efficiency/_bundle/scripts/ae_manage.py +578 -0
- agent_efficiency/_bundle/scripts/install.py +308 -0
- agent_efficiency/_bundle/scripts/pretool_hook.py +350 -0
- agent_efficiency/_bundle/scripts/render_demo_svg.py +180 -0
- agent_efficiency/_bundle/scripts/setup_hooks.py +330 -0
- agent_efficiency/_bundle/scripts/sync_shared.py +85 -0
- agent_efficiency/_bundle/scripts/validate_skills.py +150 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/SKILL.md +80 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/config/models.json +237 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/examples/workflow.md +77 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/references/routing-and-escalation.md +63 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/references/state-and-handoff.md +84 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/__init__.py +90 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/io_lock.py +199 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/savings.py +249 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/security.py +235 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/_ae_core/usage.py +195 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/agent_state.py +266 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/context_doctor.py +780 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/llm_adapter.py +306 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/route_task.py +496 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/state_ops.py +580 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/state_render.py +428 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/state_store.py +440 -0
- agent_efficiency/_bundle/skills/adaptive-orchestration-handoff/scripts/transcript_audit.py +854 -0
- agent_efficiency/_bundle/skills/local-context-index/SKILL.md +71 -0
- agent_efficiency/_bundle/skills/local-context-index/references/cli-reference.md +112 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/__init__.py +90 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/io_lock.py +199 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/savings.py +249 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/security.py +235 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/_ae_core/usage.py +195 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/compact_run.py +395 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/context_index.py +341 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_db.py +393 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_ignore.py +184 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_indexer.py +330 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_lsp.py +213 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_parsers.py +769 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_search.py +498 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_slice.py +610 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_trace.py +553 -0
- agent_efficiency/_bundle/skills/local-context-index/scripts/idx_workspace.py +219 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/SKILL.md +52 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/references/provider-caching.md +52 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/__init__.py +90 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/io_lock.py +199 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/savings.py +249 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/security.py +235 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/_ae_core/usage.py +195 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/cache_payload.py +278 -0
- agent_efficiency/_bundle/skills/prompt-cache-manager/scripts/prompt_cache.py +488 -0
- agent_efficiency/cli.py +23 -0
- agent_efficiency/mcp_entry.py +25 -0
- agent_efficiency-1.4.2.dist-info/METADATA +267 -0
- agent_efficiency-1.4.2.dist-info/RECORD +64 -0
- agent_efficiency-1.4.2.dist-info/WHEEL +4 -0
- agent_efficiency-1.4.2.dist-info/entry_points.txt +4 -0
- agent_efficiency-1.4.2.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Generate crisp, zero-dependency dark-mode terminal demo SVGs for README.md."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import html
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import List, Tuple
|
|
8
|
+
|
|
9
|
+
ROOT = Path(__file__).resolve().parents[1]
|
|
10
|
+
ASSETS_DIR = ROOT / "docs" / "assets"
|
|
11
|
+
|
|
12
|
+
# Color palette (GitHub dark-dimmed inspired)
|
|
13
|
+
BG = "#0d1117"
|
|
14
|
+
PANEL_BG = "#161b22"
|
|
15
|
+
BORDER = "#30363d"
|
|
16
|
+
TEXT = "#e6edf3"
|
|
17
|
+
MUTED = "#8b949e"
|
|
18
|
+
RED = "#ff7b72"
|
|
19
|
+
RED_BG = "#3c1618"
|
|
20
|
+
GREEN = "#3fb950"
|
|
21
|
+
GREEN_BG = "#132f1e"
|
|
22
|
+
CYAN = "#58a6ff"
|
|
23
|
+
YELLOW = "#d29922"
|
|
24
|
+
PURPLE = "#bc8cff"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _esc(s: str) -> str:
|
|
28
|
+
return html.escape(s, quote=True)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _render_lines(lines: List[Tuple[str, str]], x: int, start_y: int, line_h: int = 19) -> str:
|
|
32
|
+
out: List[str] = []
|
|
33
|
+
y = start_y
|
|
34
|
+
for color, txt in lines:
|
|
35
|
+
out.append(
|
|
36
|
+
f'<text x="{x}" y="{y}" fill="{color}" font-family="ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace" '
|
|
37
|
+
f'font-size="12.5" xml:space="preserve">{_esc(txt)}</text>'
|
|
38
|
+
)
|
|
39
|
+
y += line_h
|
|
40
|
+
return "\n ".join(out)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def render_before_after_run_svg() -> str:
|
|
44
|
+
left_lines = [
|
|
45
|
+
(CYAN, "$ pytest -v"),
|
|
46
|
+
(MUTED, "tests/test_auth.py::test_login_001 PASSED [ 1%]"),
|
|
47
|
+
(MUTED, "tests/test_auth.py::test_login_002 PASSED [ 2%]"),
|
|
48
|
+
(MUTED, "tests/test_auth.py::test_login_003 PASSED [ 3%]"),
|
|
49
|
+
(MUTED, "... [176 more PASSED lines + fixture teardown] ..."),
|
|
50
|
+
(MUTED, "DEBUG: teardown pool connection #28"),
|
|
51
|
+
(MUTED, "DEBUG: teardown pool connection #29"),
|
|
52
|
+
(RED, "FAILED tests/test_auth.py::test_replay_revokes"),
|
|
53
|
+
(MUTED, " /usr/lib/python3.11/unittest/case.py:59"),
|
|
54
|
+
(MUTED, " /app/.venv/lib/site-packages/pytest/runner.py:114"),
|
|
55
|
+
(TEXT, ' File "src/auth/refresh.py", line 74, in rotate'),
|
|
56
|
+
(RED, "AssertionError: expected family_revoked=True"),
|
|
57
|
+
(MUTED, ""),
|
|
58
|
+
(YELLOW, "-> Agent reads full refresh.py (420 lines)"),
|
|
59
|
+
(YELLOW, "-> 3,395 tokens stay in context every next turn"),
|
|
60
|
+
]
|
|
61
|
+
right_lines = [
|
|
62
|
+
(CYAN, "$ ae run -- pytest -v"),
|
|
63
|
+
(GREEN, "$ pytest -v -> exit 1 (240ms, ~3,395 -> ~210 tok, -94%)"),
|
|
64
|
+
(MUTED, "[compressed 214 lines | full_log=.agent-state/logs/...]"),
|
|
65
|
+
(RED, "FAILED tests/test_auth.py::test_replay_revokes"),
|
|
66
|
+
(RED, "AssertionError: expected family_revoked=True"),
|
|
67
|
+
(MUTED, "--- summary --- 1 failed, 180 passed in 1.18s"),
|
|
68
|
+
(MUTED, ""),
|
|
69
|
+
(PURPLE, "# Trace Code Slices (1/1 frame, budget 210 tok)"),
|
|
70
|
+
(CYAN, "## src/auth/refresh.py:74 :: rotate_refresh_token"),
|
|
71
|
+
(TEXT, " 71: if rec['used']:"),
|
|
72
|
+
(TEXT, " 72: self.store.revoke_family(rec['family_id'])"),
|
|
73
|
+
(RED, ">>> 74: raise PermissionError('replay detected')"),
|
|
74
|
+
(MUTED, ""),
|
|
75
|
+
(GREEN, "-> Root-cause line already sliced in 1 tool call"),
|
|
76
|
+
(GREEN, "-> Saved ~3,185 tok (~94%) across every follow-up turn"),
|
|
77
|
+
]
|
|
78
|
+
|
|
79
|
+
return f"""<svg xmlns="http://www.w3.org/2000/svg" width="960" height="404" viewBox="0 0 960 404" role="img" aria-label="Before and after comparison of pytest output vs ae run">
|
|
80
|
+
<rect width="960" height="404" rx="14" fill="{BG}"/>
|
|
81
|
+
|
|
82
|
+
<!-- Left Panel: Without ae -->
|
|
83
|
+
<rect x="16" y="16" width="456" height="372" rx="10" fill="{PANEL_BG}" stroke="{BORDER}" stroke-width="1"/>
|
|
84
|
+
<circle cx="36" cy="36" r="5" fill="#ff5f56"/>
|
|
85
|
+
<circle cx="52" cy="36" r="5" fill="#ffbd2e"/>
|
|
86
|
+
<circle cx="68" cy="36" r="5" fill="#27c93f"/>
|
|
87
|
+
<text x="86" y="40" fill="{TEXT}" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="13" font-weight="600">Without ae (raw shell + full file read)</text>
|
|
88
|
+
<rect x="358" y="24" width="102" height="22" rx="11" fill="{RED_BG}" stroke="{RED}" stroke-width="0.8"/>
|
|
89
|
+
<text x="409" y="39" text-anchor="middle" fill="{RED}" font-family="ui-monospace,SFMono-Regular,Menlo,monospace" font-size="11.5" font-weight="700">~3,395 tok</text>
|
|
90
|
+
<line x1="16" y1="56" x2="472" y2="56" stroke="{BORDER}" stroke-width="1"/>
|
|
91
|
+
{_render_lines(left_lines, 28, 82, 19)}
|
|
92
|
+
|
|
93
|
+
<!-- Right Panel: With ae -->
|
|
94
|
+
<rect x="488" y="16" width="456" height="372" rx="10" fill="{PANEL_BG}" stroke="{GREEN}" stroke-width="1.2"/>
|
|
95
|
+
<circle cx="508" cy="36" r="5" fill="#ff5f56"/>
|
|
96
|
+
<circle cx="524" cy="36" r="5" fill="#ffbd2e"/>
|
|
97
|
+
<circle cx="540" cy="36" r="5" fill="#27c93f"/>
|
|
98
|
+
<text x="558" y="40" fill="{TEXT}" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="13" font-weight="600">With ae run (compressed + crash sliced)</text>
|
|
99
|
+
<rect x="802" y="24" width="130" height="22" rx="11" fill="{GREEN_BG}" stroke="{GREEN}" stroke-width="0.8"/>
|
|
100
|
+
<text x="867" y="39" text-anchor="middle" fill="{GREEN}" font-family="ui-monospace,SFMono-Regular,Menlo,monospace" font-size="11.5" font-weight="700">~210 tok (-94%)</text>
|
|
101
|
+
<line x1="488" y1="56" x2="944" y2="56" stroke="{BORDER}" stroke-width="1"/>
|
|
102
|
+
{_render_lines(right_lines, 500, 82, 19)}
|
|
103
|
+
</svg>
|
|
104
|
+
"""
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def render_audit_doctor_svg() -> str:
|
|
108
|
+
left_lines = [
|
|
109
|
+
(CYAN, "$ ae audit --limit 6"),
|
|
110
|
+
(TEXT, "┌───────────────────────────────────────────┐"),
|
|
111
|
+
(TEXT, "│ AgentEfficiency Session Audit · 6 sess │"),
|
|
112
|
+
(TEXT, "├───────────────────────────────────────────┤"),
|
|
113
|
+
(YELLOW, "│ Est. Cost : $4.82 (cache saved ~$11.40) │"),
|
|
114
|
+
(GREEN, "│ Cache Hit : ███████████░░░ 78.4% │"),
|
|
115
|
+
(TEXT, "├───────────────────────────────────────────┤"),
|
|
116
|
+
(CYAN, "│ File Reads ███████████████░░ ~48.2k tok │"),
|
|
117
|
+
(RED, "│ Shell/Tests █████████████████ ~54.6k tok │"),
|
|
118
|
+
(YELLOW, "│ Repeat Waste ██████░░░░░░░░░░░ ~19.1k tok │"),
|
|
119
|
+
(TEXT, "├───────────────────────────────────────────┤"),
|
|
120
|
+
(TEXT, "│ Top Repeated Reads: │"),
|
|
121
|
+
(RED, "│ • auth_service.ts 5x (~9.4k waste) │"),
|
|
122
|
+
(TEXT, "│ Trend (older 3 vs newer 3): │"),
|
|
123
|
+
(GREEN, "│ Shell logs 24.1k -> 2.8k ↓ -88.4% │"),
|
|
124
|
+
(GREEN, "│ Cost/sess $1.18 -> $0.42 ↓ -64.4% │"),
|
|
125
|
+
(TEXT, "└───────────────────────────────────────────┘"),
|
|
126
|
+
]
|
|
127
|
+
right_lines = [
|
|
128
|
+
(CYAN, "$ ae doctor"),
|
|
129
|
+
(TEXT, "┌───────────────────────────────────────────┐"),
|
|
130
|
+
(GREEN, "│ AgentEfficiency Doctor · Grade B (78/100) │"),
|
|
131
|
+
(TEXT, "├───────────────────────────────────────────┤"),
|
|
132
|
+
(YELLOW, "│ Always-On : ~6.8k tok/turn (~$4.22/mo) │"),
|
|
133
|
+
(TEXT, "├───────────────────────────────────────────┤"),
|
|
134
|
+
(CYAN, "│ Rules/Prompt ████░░░░░░░░░░ ~1.4k (21%) │"),
|
|
135
|
+
(PURPLE, "│ Skill Descs ██░░░░░░░░░░░░ ~0.6k ( 9%) │"),
|
|
136
|
+
(RED, "│ MCP Schemas ██████████████ ~4.8k (70%) │"),
|
|
137
|
+
(TEXT, "└───────────────────────────────────────────┘"),
|
|
138
|
+
(MUTED, ""),
|
|
139
|
+
(YELLOW, "Top Actionable Fixes:"),
|
|
140
|
+
(RED, "[HIGH] Switch MCP to --profile core (-2.8k/t)"),
|
|
141
|
+
(YELLOW, "[WARN] Cache-buster UUID found in CLAUDE.md"),
|
|
142
|
+
(MUTED, ""),
|
|
143
|
+
(CYAN, "$ ae savings --statusline"),
|
|
144
|
+
(GREEN, "ae: -142.3k tok (-86%, ~$0.43 saved / 7d)"),
|
|
145
|
+
]
|
|
146
|
+
|
|
147
|
+
return f"""<svg xmlns="http://www.w3.org/2000/svg" width="960" height="422" viewBox="0 0 960 422" role="img" aria-label="ae audit session waste receipt and ae doctor context bloat analyzer">
|
|
148
|
+
<rect width="960" height="422" rx="14" fill="{BG}"/>
|
|
149
|
+
|
|
150
|
+
<!-- Left Panel: ae audit -->
|
|
151
|
+
<rect x="16" y="16" width="456" height="390" rx="10" fill="{PANEL_BG}" stroke="{BORDER}" stroke-width="1"/>
|
|
152
|
+
<circle cx="36" cy="36" r="5" fill="#ff5f56"/>
|
|
153
|
+
<circle cx="52" cy="36" r="5" fill="#ffbd2e"/>
|
|
154
|
+
<circle cx="68" cy="36" r="5" fill="#27c93f"/>
|
|
155
|
+
<text x="86" y="40" fill="{TEXT}" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="13" font-weight="600">ae audit — Real IDE Token Waste & Trends</text>
|
|
156
|
+
<line x1="16" y1="56" x2="472" y2="56" stroke="{BORDER}" stroke-width="1"/>
|
|
157
|
+
{_render_lines(left_lines, 28, 80, 19)}
|
|
158
|
+
|
|
159
|
+
<!-- Right Panel: ae doctor + savings -->
|
|
160
|
+
<rect x="488" y="16" width="456" height="390" rx="10" fill="{PANEL_BG}" stroke="{BORDER}" stroke-width="1"/>
|
|
161
|
+
<circle cx="508" cy="36" r="5" fill="#ff5f56"/>
|
|
162
|
+
<circle cx="524" cy="36" r="5" fill="#ffbd2e"/>
|
|
163
|
+
<circle cx="540" cy="36" r="5" fill="#27c93f"/>
|
|
164
|
+
<text x="558" y="40" fill="{TEXT}" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif" font-size="13" font-weight="600">ae doctor & ae savings — Bloat Audit + Counter</text>
|
|
165
|
+
<line x1="488" y1="56" x2="944" y2="56" stroke="{BORDER}" stroke-width="1"/>
|
|
166
|
+
{_render_lines(right_lines, 500, 80, 19)}
|
|
167
|
+
</svg>
|
|
168
|
+
"""
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def main() -> int:
|
|
172
|
+
ASSETS_DIR.mkdir(parents=True, exist_ok=True)
|
|
173
|
+
(ASSETS_DIR / "before-after-run.svg").write_text(render_before_after_run_svg(), encoding="utf-8")
|
|
174
|
+
(ASSETS_DIR / "audit-doctor-card.svg").write_text(render_audit_doctor_svg(), encoding="utf-8")
|
|
175
|
+
print(f"Generated SVGs in {ASSETS_DIR}")
|
|
176
|
+
return 0
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
if __name__ == "__main__":
|
|
180
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""AgentEfficiency — Zero-touch Git hooks (worktree-aware), non-destructive runtime hooks & MCP config generator."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import shlex
|
|
10
|
+
import stat
|
|
11
|
+
import subprocess
|
|
12
|
+
import sys
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any, Dict, List, Optional, Sequence, Tuple
|
|
15
|
+
|
|
16
|
+
ROOT = Path(__file__).resolve().parents[1]
|
|
17
|
+
INDEX_SCRIPT = ROOT / "skills" / "local-context-index" / "scripts" / "context_index.py"
|
|
18
|
+
STATE_SCRIPT = ROOT / "skills" / "adaptive-orchestration-handoff" / "scripts" / "agent_state.py"
|
|
19
|
+
PRETOOL_SCRIPT = ROOT / "scripts" / "pretool_hook.py"
|
|
20
|
+
MCP_SERVER = ROOT / "mcp" / "server.py"
|
|
21
|
+
INSTALLED_MCP_DEFAULT = Path.home() / ".agent-efficiency" / "mcp" / "server.py"
|
|
22
|
+
INSTALLED_PRETOOL_DEFAULT = Path.home() / ".agent-efficiency" / "hooks" / "pretool_hook.py"
|
|
23
|
+
|
|
24
|
+
MARKER_START = "# >>> AgentEfficiency >>>"
|
|
25
|
+
MARKER_END = "# <<< AgentEfficiency <<<"
|
|
26
|
+
GIT_HOOK_NAMES = ("post-commit", "post-checkout", "post-merge")
|
|
27
|
+
_EMPTY_SHEBANGS = {"", "#!/bin/sh", "#!/bin/bash", "#!/usr/bin/env sh", "#!/usr/bin/env bash", "#!/usr/bin/env zsh"}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _resolve_scripts(skills_dir: Optional[Path] = None) -> Tuple[Path, Path]:
|
|
31
|
+
if skills_dir is not None:
|
|
32
|
+
sd = skills_dir.expanduser().resolve()
|
|
33
|
+
return (
|
|
34
|
+
sd / "local-context-index" / "scripts" / "context_index.py",
|
|
35
|
+
sd / "adaptive-orchestration-handoff" / "scripts" / "agent_state.py",
|
|
36
|
+
)
|
|
37
|
+
return INDEX_SCRIPT, STATE_SCRIPT
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _shell_quote(value: str) -> str:
|
|
41
|
+
"""Quote a command token for the active OS shell (`cmd.exe` on Windows, POSIX sh elsewhere)."""
|
|
42
|
+
if os.name == "nt":
|
|
43
|
+
return subprocess.list2cmdline([value])
|
|
44
|
+
return shlex.quote(value)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _resolve_git_hooks_dir(repo: Path) -> Path:
|
|
48
|
+
"""Resolve hooks directory supporting standard repos, Git worktrees, submodules, and core.hooksPath."""
|
|
49
|
+
try:
|
|
50
|
+
r = subprocess.run(
|
|
51
|
+
["git", "-c", "core.fsmonitor=false", "rev-parse", "--git-path", "hooks"],
|
|
52
|
+
cwd=str(repo),
|
|
53
|
+
capture_output=True,
|
|
54
|
+
text=True,
|
|
55
|
+
encoding="utf-8",
|
|
56
|
+
errors="replace",
|
|
57
|
+
timeout=4,
|
|
58
|
+
)
|
|
59
|
+
if r.returncode == 0 and r.stdout.strip():
|
|
60
|
+
hp = Path(r.stdout.strip())
|
|
61
|
+
return hp if hp.is_absolute() else (repo / hp).resolve()
|
|
62
|
+
except Exception:
|
|
63
|
+
pass
|
|
64
|
+
git_dir = repo / ".git"
|
|
65
|
+
if git_dir.is_dir():
|
|
66
|
+
return git_dir / "hooks"
|
|
67
|
+
if git_dir.is_file():
|
|
68
|
+
# Worktree / submodule fallback when git binary is unavailable
|
|
69
|
+
txt = git_dir.read_text(encoding="utf-8", errors="replace").strip()
|
|
70
|
+
if txt.lower().startswith("gitdir:"):
|
|
71
|
+
gd = Path(txt.split(":", 1)[1].strip())
|
|
72
|
+
gd = gd if gd.is_absolute() else (repo / gd).resolve()
|
|
73
|
+
return gd / "hooks"
|
|
74
|
+
raise SystemExit(f"Not a git repository (missing .git directory or gitdir file): {repo}")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _hook_snippet(repo: Path, index_script: Path = INDEX_SCRIPT) -> str:
|
|
78
|
+
py = shlex.quote(sys.executable)
|
|
79
|
+
idx = shlex.quote(str(index_script))
|
|
80
|
+
rp = shlex.quote(str(repo.resolve()))
|
|
81
|
+
return (
|
|
82
|
+
f"{MARKER_START}\n"
|
|
83
|
+
f"{py} {idx} index {rp} --quiet >/dev/null 2>&1 || true\n"
|
|
84
|
+
f"{MARKER_END}\n"
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _strip_managed_block(content: str) -> str:
|
|
89
|
+
pattern = re.compile(rf"\n*{re.escape(MARKER_START)}[\s\S]*?{re.escape(MARKER_END)}\n*", re.MULTILINE)
|
|
90
|
+
cleaned = pattern.sub("\n", content).rstrip()
|
|
91
|
+
return (cleaned + "\n") if cleaned else ""
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def manage_git_hooks(repo: Path, *, remove: bool = False, dry_run: bool = False, skills_dir: Optional[Path] = None) -> Dict[str, Any]:
|
|
95
|
+
repo = repo.resolve()
|
|
96
|
+
hooks_dir = _resolve_git_hooks_dir(repo)
|
|
97
|
+
idx_script, _ = _resolve_scripts(skills_dir)
|
|
98
|
+
snippet = _hook_snippet(repo, idx_script)
|
|
99
|
+
actions: List[Dict[str, str]] = []
|
|
100
|
+
|
|
101
|
+
for hname in GIT_HOOK_NAMES:
|
|
102
|
+
hpath = hooks_dir / hname
|
|
103
|
+
if hpath.is_symlink():
|
|
104
|
+
raise SystemExit(f"Refusing to modify symlinked git hook: {hpath}")
|
|
105
|
+
existing = hpath.read_text(encoding="utf-8", errors="replace") if hpath.is_file() else ""
|
|
106
|
+
|
|
107
|
+
if remove:
|
|
108
|
+
if MARKER_START not in existing:
|
|
109
|
+
actions.append({"hook": hname, "action": "not_installed"})
|
|
110
|
+
continue
|
|
111
|
+
cleaned = _strip_managed_block(existing)
|
|
112
|
+
if not dry_run:
|
|
113
|
+
if cleaned.strip() in _EMPTY_SHEBANGS:
|
|
114
|
+
hpath.unlink()
|
|
115
|
+
else:
|
|
116
|
+
hpath.write_text(cleaned, encoding="utf-8")
|
|
117
|
+
actions.append({"hook": hname, "action": "would_remove" if dry_run else "removed"})
|
|
118
|
+
continue
|
|
119
|
+
|
|
120
|
+
if MARKER_START in existing:
|
|
121
|
+
base = _strip_managed_block(existing).rstrip()
|
|
122
|
+
updated = (base + "\n\n" + snippet) if base else ("#!/bin/sh\n" + snippet)
|
|
123
|
+
act = "updated"
|
|
124
|
+
elif existing.strip():
|
|
125
|
+
updated = existing.rstrip() + "\n\n" + snippet
|
|
126
|
+
act = "appended"
|
|
127
|
+
else:
|
|
128
|
+
updated = "#!/bin/sh\n" + snippet
|
|
129
|
+
act = "created"
|
|
130
|
+
|
|
131
|
+
if not dry_run:
|
|
132
|
+
hooks_dir.mkdir(parents=True, exist_ok=True)
|
|
133
|
+
hpath.write_text(updated, encoding="utf-8")
|
|
134
|
+
mode = hpath.stat().st_mode
|
|
135
|
+
hpath.chmod(mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
|
|
136
|
+
actions.append({"hook": hname, "action": f"{'would_' if dry_run else ''}{act}", "path": str(hpath)})
|
|
137
|
+
|
|
138
|
+
return {"repo": str(repo), "hooks_dir": str(hooks_dir), "dry_run": dry_run, "actions": actions}
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def generate_runtime_hooks(
|
|
142
|
+
client: str,
|
|
143
|
+
repo: Path,
|
|
144
|
+
*,
|
|
145
|
+
skills_dir: Optional[Path] = None,
|
|
146
|
+
include_pretool: bool = True,
|
|
147
|
+
auto_wrap: bool = False,
|
|
148
|
+
pretool_script: Optional[Path] = None,
|
|
149
|
+
) -> Dict[str, Any]:
|
|
150
|
+
repo_r = repo.resolve()
|
|
151
|
+
idx_script, st_script = _resolve_scripts(skills_dir)
|
|
152
|
+
pt_script = (
|
|
153
|
+
pretool_script.expanduser().resolve()
|
|
154
|
+
if pretool_script is not None
|
|
155
|
+
else (INSTALLED_PRETOOL_DEFAULT if INSTALLED_PRETOOL_DEFAULT.is_file() else PRETOOL_SCRIPT)
|
|
156
|
+
)
|
|
157
|
+
py = _shell_quote(sys.executable)
|
|
158
|
+
pt_mode = "rewrite" if auto_wrap else "hint"
|
|
159
|
+
|
|
160
|
+
if client == "claude":
|
|
161
|
+
resume_cmd = f"{py} {_shell_quote(str(st_script))} session-start {_shell_quote(str(repo_r))} --auto-index --format claude-hook"
|
|
162
|
+
index_cmd = f"{py} {_shell_quote(str(idx_script))} index {_shell_quote(str(repo_r))} --hook-format claude"
|
|
163
|
+
cp_cmd = f"{py} {_shell_quote(str(st_script))} checkpoint {_shell_quote(str(repo_r))} --hook-format claude"
|
|
164
|
+
pretool_cmd = f"{py} {_shell_quote(str(pt_script))} --client claude --mode {pt_mode} --repo {_shell_quote(str(repo_r))} --index-script {_shell_quote(str(idx_script))}"
|
|
165
|
+
hooks_map: Dict[str, List[Dict[str, Any]]] = {
|
|
166
|
+
"SessionStart": [{"hooks": [{"type": "command", "command": resume_cmd}]}],
|
|
167
|
+
"PostToolUse": [
|
|
168
|
+
{"matcher": "Edit|Write|MultiEdit", "hooks": [{"type": "command", "command": index_cmd}]}
|
|
169
|
+
],
|
|
170
|
+
"PreCompact": [{"hooks": [{"type": "command", "command": cp_cmd}]}],
|
|
171
|
+
"Stop": [{"hooks": [{"type": "command", "command": cp_cmd}]}],
|
|
172
|
+
}
|
|
173
|
+
if include_pretool:
|
|
174
|
+
hooks_map["PreToolUse"] = [
|
|
175
|
+
{"matcher": "Bash|Read", "hooks": [{"type": "command", "command": pretool_cmd}]}
|
|
176
|
+
]
|
|
177
|
+
return {
|
|
178
|
+
"target_file": str(repo_r / ".claude" / "settings.local.json"),
|
|
179
|
+
"config": {"hooks": hooks_map},
|
|
180
|
+
}
|
|
181
|
+
# Official Gemini CLI hook schema (nested matcher + hooks[] + strict JSON stdout protocol!)
|
|
182
|
+
resume_cmd = f"{py} {_shell_quote(str(st_script))} session-start {_shell_quote(str(repo_r))} --auto-index --format gemini-hook"
|
|
183
|
+
index_cmd = f"{py} {_shell_quote(str(idx_script))} index {_shell_quote(str(repo_r))} --hook-format gemini"
|
|
184
|
+
cp_cmd = f"{py} {_shell_quote(str(st_script))} checkpoint {_shell_quote(str(repo_r))} --hook-format gemini"
|
|
185
|
+
pretool_cmd = f"{py} {_shell_quote(str(pt_script))} --client gemini --mode {pt_mode} --repo {_shell_quote(str(repo_r))} --index-script {_shell_quote(str(idx_script))}"
|
|
186
|
+
g_hooks: Dict[str, List[Dict[str, Any]]] = {
|
|
187
|
+
"SessionStart": [
|
|
188
|
+
{
|
|
189
|
+
"matcher": "startup",
|
|
190
|
+
"hooks": [
|
|
191
|
+
{"name": "agent-efficiency-resume", "type": "command", "command": resume_cmd, "timeout": 10000}
|
|
192
|
+
],
|
|
193
|
+
}
|
|
194
|
+
],
|
|
195
|
+
"AfterTool": [
|
|
196
|
+
{
|
|
197
|
+
"matcher": "write_file|replace",
|
|
198
|
+
"hooks": [
|
|
199
|
+
{"name": "agent-efficiency-reindex", "type": "command", "command": index_cmd, "timeout": 15000}
|
|
200
|
+
],
|
|
201
|
+
}
|
|
202
|
+
],
|
|
203
|
+
"PreCompress": [
|
|
204
|
+
{
|
|
205
|
+
"matcher": "*",
|
|
206
|
+
"hooks": [
|
|
207
|
+
{"name": "agent-efficiency-checkpoint", "type": "command", "command": cp_cmd, "timeout": 5000}
|
|
208
|
+
],
|
|
209
|
+
}
|
|
210
|
+
],
|
|
211
|
+
"AfterAgent": [
|
|
212
|
+
{
|
|
213
|
+
"matcher": "*",
|
|
214
|
+
"hooks": [
|
|
215
|
+
{"name": "agent-efficiency-checkpoint", "type": "command", "command": cp_cmd, "timeout": 5000}
|
|
216
|
+
],
|
|
217
|
+
}
|
|
218
|
+
],
|
|
219
|
+
}
|
|
220
|
+
if include_pretool:
|
|
221
|
+
g_hooks["BeforeTool"] = [
|
|
222
|
+
{
|
|
223
|
+
"matcher": "run_shell_command|read_file",
|
|
224
|
+
"hooks": [
|
|
225
|
+
{"name": "agent-efficiency-pretool", "type": "command", "command": pretool_cmd, "timeout": 5000}
|
|
226
|
+
],
|
|
227
|
+
}
|
|
228
|
+
]
|
|
229
|
+
return {
|
|
230
|
+
"target_file": str(repo_r / ".gemini" / "settings.json"),
|
|
231
|
+
"config": {"hooks": g_hooks},
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _is_ae_hook_group(entry: Any) -> bool:
|
|
236
|
+
raw = json.dumps(entry, sort_keys=True)
|
|
237
|
+
return "agent-efficiency-" in raw or "agent_state.py" in raw or "context_index.py" in raw or "pretool_hook.py" in raw
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def merge_runtime_hooks(existing: Dict[str, Any], new_hooks: Dict[str, List[Dict[str, Any]]]) -> Dict[str, Any]:
|
|
241
|
+
"""Non-destructively merge AgentEfficiency hooks into existing client settings (preserving all user hooks)."""
|
|
242
|
+
merged = json.loads(json.dumps(existing))
|
|
243
|
+
hooks_obj = merged.setdefault("hooks", {})
|
|
244
|
+
if not isinstance(hooks_obj, dict):
|
|
245
|
+
hooks_obj = {}
|
|
246
|
+
merged["hooks"] = hooks_obj
|
|
247
|
+
for event_name, ae_entries in new_hooks.items():
|
|
248
|
+
cur_list = hooks_obj.get(event_name)
|
|
249
|
+
if not isinstance(cur_list, list):
|
|
250
|
+
cur_list = []
|
|
251
|
+
preserved = [item for item in cur_list if not _is_ae_hook_group(item)]
|
|
252
|
+
hooks_obj[event_name] = preserved + list(ae_entries)
|
|
253
|
+
return merged
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def generate_mcp_config(
|
|
257
|
+
client: str = "generic",
|
|
258
|
+
*,
|
|
259
|
+
server_path: Optional[Path] = None,
|
|
260
|
+
skills_dir: Optional[Path] = None,
|
|
261
|
+
profile: str = "core",
|
|
262
|
+
) -> Dict[str, Any]:
|
|
263
|
+
srv = server_path.expanduser().resolve() if server_path else (INSTALLED_MCP_DEFAULT if INSTALLED_MCP_DEFAULT.is_file() else MCP_SERVER)
|
|
264
|
+
args = [str(srv), "--profile", profile]
|
|
265
|
+
entry: Dict[str, Any] = {
|
|
266
|
+
"command": sys.executable,
|
|
267
|
+
"args": args,
|
|
268
|
+
}
|
|
269
|
+
if skills_dir is not None:
|
|
270
|
+
entry["env"] = {"AGENT_EFFICIENCY_SKILLS_DIR": str(skills_dir.expanduser().resolve())}
|
|
271
|
+
return {
|
|
272
|
+
"client": client,
|
|
273
|
+
"profile": profile,
|
|
274
|
+
"mcpServers": {
|
|
275
|
+
"agent-efficiency": entry,
|
|
276
|
+
},
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
|
281
|
+
ap = argparse.ArgumentParser(description="Configure zero-touch Git hooks, agent-runtime hooks, and MCP server config for AgentEfficiency.")
|
|
282
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
283
|
+
|
|
284
|
+
p_g = sub.add_parser("git", help="Install or remove non-destructive Git hooks for auto-reindexing (worktree-aware)")
|
|
285
|
+
p_g.add_argument("repo", type=Path)
|
|
286
|
+
p_g.add_argument("--remove", action="store_true")
|
|
287
|
+
p_g.add_argument("--dry-run", action="store_true")
|
|
288
|
+
p_g.add_argument("--skills-dir", type=Path, default=None, help="Use scripts from an installed skills directory")
|
|
289
|
+
|
|
290
|
+
p_r = sub.add_parser("runtime", help="Generate/merge PreToolUse/BeforeTool + SessionStart + PostToolUse/AfterTool + PreCompact/Stop hooks")
|
|
291
|
+
p_r.add_argument("repo", type=Path)
|
|
292
|
+
p_r.add_argument("--client", choices=["claude", "gemini"], default="claude")
|
|
293
|
+
p_r.add_argument("--skills-dir", type=Path, default=None, help="Use scripts from an installed skills directory")
|
|
294
|
+
p_r.add_argument("--no-pretool", action="store_true", help="Disable PreToolUse/BeforeTool hint & repeat-read nudge hook")
|
|
295
|
+
p_r.add_argument("--auto-wrap", action="store_true", help="Opt-in: allow PreToolUse hook to transparently rewrite simple pipe-free test/build commands via `ae run`")
|
|
296
|
+
p_r.add_argument("--write", action="store_true", help="Non-destructively merge into the target settings JSON file")
|
|
297
|
+
|
|
298
|
+
p_m = sub.add_parser("mcp-config", help="Print ready-to-paste MCP server JSON config (defaults to lean 7-tool `core` profile)")
|
|
299
|
+
p_m.add_argument("--client", choices=["generic", "claude", "cursor", "gemini", "codex", "antigravity"], default="generic")
|
|
300
|
+
p_m.add_argument("--profile", choices=["core", "ide", "full"], default="core", help="Tool profile: core (7 tools, ~87%% smaller schema), ide (14 tools), or full (39 tools)")
|
|
301
|
+
p_m.add_argument("--server-path", type=Path, default=None)
|
|
302
|
+
p_m.add_argument("--skills-dir", type=Path, default=None)
|
|
303
|
+
|
|
304
|
+
args = ap.parse_args(argv)
|
|
305
|
+
|
|
306
|
+
if args.cmd == "git":
|
|
307
|
+
print(json.dumps(manage_git_hooks(args.repo, remove=args.remove, dry_run=args.dry_run, skills_dir=args.skills_dir), indent=2))
|
|
308
|
+
return 0
|
|
309
|
+
|
|
310
|
+
if args.cmd == "runtime":
|
|
311
|
+
res = generate_runtime_hooks(args.client, args.repo, skills_dir=args.skills_dir, include_pretool=not args.no_pretool, auto_wrap=args.auto_wrap)
|
|
312
|
+
if args.write:
|
|
313
|
+
target = Path(res["target_file"])
|
|
314
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
315
|
+
existing = json.loads(target.read_text(encoding="utf-8")) if target.is_file() else {}
|
|
316
|
+
merged = merge_runtime_hooks(existing, res["config"]["hooks"])
|
|
317
|
+
target.write_text(json.dumps(merged, indent=2) + "\n", encoding="utf-8")
|
|
318
|
+
res["written"] = True
|
|
319
|
+
print(json.dumps(res, indent=2))
|
|
320
|
+
return 0
|
|
321
|
+
|
|
322
|
+
if args.cmd == "mcp-config":
|
|
323
|
+
print(json.dumps(generate_mcp_config(args.client, server_path=args.server_path, skills_dir=args.skills_dir, profile=args.profile), indent=2))
|
|
324
|
+
return 0
|
|
325
|
+
|
|
326
|
+
return 0
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
if __name__ == "__main__":
|
|
330
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Sync `shared/_ae_core/` package into every standalone skill folder (or verify with `--check`)."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import hashlib
|
|
7
|
+
import json
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Dict, List, Optional, Sequence
|
|
10
|
+
|
|
11
|
+
ROOT = Path(__file__).resolve().parents[1]
|
|
12
|
+
SOURCE_DIR = ROOT / "shared" / "_ae_core"
|
|
13
|
+
SKILLS_DIR = ROOT / "skills"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def source_files() -> List[Path]:
|
|
17
|
+
return sorted(p for p in SOURCE_DIR.glob("*.py") if p.is_file())
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def skill_script_dirs(skills_dir: Path = SKILLS_DIR) -> List[Path]:
|
|
21
|
+
return [
|
|
22
|
+
d / "scripts"
|
|
23
|
+
for d in sorted(skills_dir.iterdir())
|
|
24
|
+
if d.is_dir() and (d / "SKILL.md").is_file() and (d / "scripts").is_dir()
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def sync_shared(check: bool = False, skills_dir: Path = SKILLS_DIR) -> Dict[str, object]:
|
|
29
|
+
srcs = source_files()
|
|
30
|
+
src_map = {p.name: p.read_bytes() for p in srcs}
|
|
31
|
+
digest = hashlib.sha256()
|
|
32
|
+
for name, raw in sorted(src_map.items()):
|
|
33
|
+
digest.update(name.encode("utf-8") + b":" + raw)
|
|
34
|
+
|
|
35
|
+
results: List[Dict[str, str]] = []
|
|
36
|
+
drifted: List[str] = []
|
|
37
|
+
|
|
38
|
+
for sdir in skill_script_dirs(skills_dir):
|
|
39
|
+
dst_pkg = sdir / "_ae_core"
|
|
40
|
+
if not check:
|
|
41
|
+
dst_pkg.mkdir(parents=True, exist_ok=True)
|
|
42
|
+
# Clean obsolete extra files inside _ae_core
|
|
43
|
+
for old in list(dst_pkg.glob("*.py")):
|
|
44
|
+
if old.name not in src_map:
|
|
45
|
+
old.unlink()
|
|
46
|
+
for name, raw in sorted(src_map.items()):
|
|
47
|
+
dst = dst_pkg / name
|
|
48
|
+
rel = str(dst.relative_to(ROOT))
|
|
49
|
+
if dst.is_file() and dst.read_bytes() == raw:
|
|
50
|
+
results.append({"path": rel, "status": "in_sync"})
|
|
51
|
+
elif check:
|
|
52
|
+
drifted.append(rel)
|
|
53
|
+
results.append({"path": rel, "status": "drifted"})
|
|
54
|
+
else:
|
|
55
|
+
dst.write_bytes(raw)
|
|
56
|
+
results.append({"path": rel, "status": "synced"})
|
|
57
|
+
|
|
58
|
+
# Ensure no stray extra .py files in dst_pkg when checking
|
|
59
|
+
if check and dst_pkg.is_dir():
|
|
60
|
+
for extra in sorted(dst_pkg.glob("*.py")):
|
|
61
|
+
if extra.name not in src_map:
|
|
62
|
+
rel = str(extra.relative_to(ROOT))
|
|
63
|
+
drifted.append(rel)
|
|
64
|
+
results.append({"path": rel, "status": "unexpected_extra"})
|
|
65
|
+
|
|
66
|
+
return {
|
|
67
|
+
"ok": len(drifted) == 0,
|
|
68
|
+
"source_sha": digest.hexdigest()[:12],
|
|
69
|
+
"file_count": len(src_map),
|
|
70
|
+
"drifted": drifted,
|
|
71
|
+
"targets": results,
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
|
76
|
+
ap = argparse.ArgumentParser(description="Sync shared/_ae_core/ into standalone skill scripts directories.")
|
|
77
|
+
ap.add_argument("--check", action="store_true", help="Exit 1 if any skill copy differs from shared/_ae_core/")
|
|
78
|
+
args = ap.parse_args(argv)
|
|
79
|
+
res = sync_shared(check=args.check)
|
|
80
|
+
print(json.dumps(res, indent=2))
|
|
81
|
+
return 0 if res["ok"] else 1
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
if __name__ == "__main__":
|
|
85
|
+
raise SystemExit(main())
|