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,84 @@
1
+ # Persistent Project State & Zero-Reexploration Handoff Reference
2
+
3
+ ## Contents
4
+ - State Directory Layout
5
+ - Anti-Duplication Memory
6
+ - Structured Decisions (ADRs)
7
+ - Parallel Multi-Agent Ownership
8
+ - Zero-Reexploration Handoff Protocol
9
+ - Security & Atomicity
10
+
11
+ ## State Directory Layout
12
+
13
+ Stored in `<repo>/.agent-state/` (keep gitignored unless team explicitly versions task logs):
14
+ - `state.json` — Authoritative schema v2 machine state (auto-migrates prototype v1).
15
+ - `CURRENT_STATE.md` — Compact active-task snapshot (<350 tok).
16
+ - `TASK_QUEUE.md` — Regenerated table of all non-completed tasks.
17
+ - `DECISIONS.md` — Deterministic active decisions (superseded decisions moved to bottom so Layer-1 prompt cache stays stable).
18
+ - `BLOCKERS.md` — Open and recently resolved blockers.
19
+ - `COMPLETED.md` — Completed task history with final verified checks.
20
+ - `HANDOFF.md` & `handoff.json` — Latest human + machine handoff dossier.
21
+ - `handoffs/<task-id>-<n>.md` — Immutable archive of prior handoffs.
22
+ - `cache_registry.json` — Shared warm-prefix & cache-hit telemetry.
23
+
24
+ ## Anti-Duplication Memory
25
+
26
+ Three targeted commands eliminate repeated work across turns and agents:
27
+
28
+ 1. **`record-inspection`** — Records `{path, lines, finding, sha12, agent}`:
29
+ ```bash
30
+ python3 scripts/agent_state.py record-inspection <repo> --path src/auth.py --lines 1-95 --finding "JWT verify uses RS256; refresh store is in-memory dict"
31
+ ```
32
+ When Agent B runs `brief`, `agent_state.py` re-hashes every inspected file on disk:
33
+ - Unchanged SHA → listed under **Already Inspected (Verified Unchanged)** so Agent B skips re-reading.
34
+ - Changed SHA → flagged under **Drift Warning** so Agent B slices only the changed file.
35
+
36
+ 2. **`record-attempt`** — Logs `{approach, outcome: worked|failed|rejected, reason}`:
37
+ ```bash
38
+ python3 scripts/agent_state.py record-attempt <repo> --approach "Store refresh token in cookie" --outcome rejected --reason "CLI clients have no cookie jar"
39
+ ```
40
+ A `failed` outcome automatically increments `failures_count`, feeding `route_task.py`'s 2-Attempt escalation rule.
41
+
42
+ 3. **`record-check`** — Logs `{cmd, exit_code, summary, git_head}`:
43
+ ```bash
44
+ python3 scripts/agent_state.py record-check <repo> --cmd "python3 -m unittest tests/test_auth.py" --exit-code 0 --summary "14 passed"
45
+ ```
46
+ A passing check (`exit_code == 0`) resets `failures_count` to `0`; a failing check increments it.
47
+
48
+ ## Structured Decisions (ADRs)
49
+
50
+ ```bash
51
+ python3 scripts/agent_state.py decision <repo> \
52
+ --title "Use opaque rotating refresh tokens" \
53
+ --rationale "Supports instant server-side revocation and replay detection" \
54
+ --alternatives "Stateless JWT refresh tokens (rejected: cannot revoke cleanly)" \
55
+ --files "src/auth.py,src/store.py"
56
+ ```
57
+ - Assigns stable IDs (`D-001`, `D-002`, ...).
58
+ - Supersede outdated decisions without losing history: `--supersedes D-001`.
59
+ - Query selectively without reading the whole file: `agent_state.py decisions <repo> --file src/auth.py`.
60
+
61
+ ## Parallel Multi-Agent Ownership
62
+
63
+ - Queue non-urgent work: `agent_state.py queue <repo> --objective "..."`.
64
+ - Run parallel workers safely: `agent_state.py start <repo> --parallel --owner worker-2 --own-files "src/ui.py,tests/test_ui.py" --objective "..."`.
65
+ - `start`, `update --own-files`, and `accept` automatically reject overlapping `owned_files` across concurrent `in_progress` tasks.
66
+
67
+ ## Zero-Reexploration Handoff Protocol
68
+
69
+ ### Outgoing Agent (Agent A)
70
+ 1. Refresh index (`context_index.py index <repo>`).
71
+ 2. Ensure key inspections, failed attempts, decisions, and latest checks are recorded.
72
+ 3. Run `agent_state.py handoff <repo> --recipient <id> --summary "..." --next "..." --entry-points "file:L1-L2"`.
73
+ - Automatically embeds live git snapshot (`branch`, `head`, `dirty_files`, `diff_stat`), index symbols for touched files, warm cache prefix hint, relevant active decisions, open blockers, and already-inspected file SHAs.
74
+
75
+ ### Incoming Agent (Agent B)
76
+ 1. Run `python3 scripts/agent_state.py brief <repo>` (1 tool call, ≤1,200 tokens, live SHA drift check!).
77
+ 2. Run `python3 scripts/agent_state.py accept <repo> --owner <agent-b>`.
78
+ 3. Check `context_index.py changed <repo>` and `slice` only the `--entry-points` or drifted files.
79
+ 4. Resume work immediately—no full-repo scan needed.
80
+
81
+ ## Security & Atomicity
82
+
83
+ - All mutations hold an exclusive lock (`.agent-state/.state.lock` via `fcntl.flock`) and write via temp-file + `os.replace()`.
84
+ - All user-supplied text passes through secret redaction (API keys, private keys, bearer tokens, password assignments) before touching disk.
@@ -0,0 +1,90 @@
1
+ """Shared zero-dependency core for AgentEfficiency skills (synced into each skill for standalone use)."""
2
+ from __future__ import annotations
3
+
4
+ from _ae_core.io_lock import (
5
+ atomic_write_json,
6
+ atomic_write_text,
7
+ canonicalize_text,
8
+ compute_prefix_id,
9
+ configure_utf8_stdio,
10
+ ensure_git_info_exclude,
11
+ estimate_tokens,
12
+ file_lock,
13
+ git_cmd,
14
+ sha256_text,
15
+ sources_fresh,
16
+ )
17
+ from _ae_core.security import (
18
+ HARD_SECRET_PATH_RE,
19
+ SECRET_CONTENT_PATTERNS,
20
+ SECRET_PATH_RE,
21
+ SOFT_SECRET_NAME_RE,
22
+ SOURCE_CODE_EXTS,
23
+ find_secret_leak_lines,
24
+ frame_untrusted_data,
25
+ has_secret_leak,
26
+ is_secret_path,
27
+ is_within,
28
+ normalize_rel_path,
29
+ redact_secrets,
30
+ redact_secrets_with_flag,
31
+ sanitize_inline,
32
+ )
33
+ from _ae_core.savings import (
34
+ DEFAULT_RATE_PER_1M_USD,
35
+ default_savings_path,
36
+ format_savings_card,
37
+ format_statusline,
38
+ record_saving,
39
+ summarize_savings,
40
+ )
41
+ from _ae_core.usage import (
42
+ ALIAS_TO_TIER,
43
+ DEFAULT_TIER_PRICES,
44
+ PROVIDER_DEFAULTS,
45
+ detect_provider,
46
+ min_cache_tokens_for_model,
47
+ parse_provider_usage,
48
+ usage_to_dict,
49
+ )
50
+
51
+ __all__ = [
52
+ "ALIAS_TO_TIER",
53
+ "DEFAULT_RATE_PER_1M_USD",
54
+ "DEFAULT_TIER_PRICES",
55
+ "HARD_SECRET_PATH_RE",
56
+ "PROVIDER_DEFAULTS",
57
+ "SECRET_CONTENT_PATTERNS",
58
+ "SECRET_PATH_RE",
59
+ "SOFT_SECRET_NAME_RE",
60
+ "SOURCE_CODE_EXTS",
61
+ "atomic_write_json",
62
+ "atomic_write_text",
63
+ "canonicalize_text",
64
+ "compute_prefix_id",
65
+ "configure_utf8_stdio",
66
+ "default_savings_path",
67
+ "detect_provider",
68
+ "ensure_git_info_exclude",
69
+ "estimate_tokens",
70
+ "file_lock",
71
+ "find_secret_leak_lines",
72
+ "format_savings_card",
73
+ "format_statusline",
74
+ "frame_untrusted_data",
75
+ "git_cmd",
76
+ "has_secret_leak",
77
+ "is_secret_path",
78
+ "is_within",
79
+ "min_cache_tokens_for_model",
80
+ "normalize_rel_path",
81
+ "parse_provider_usage",
82
+ "record_saving",
83
+ "redact_secrets",
84
+ "redact_secrets_with_flag",
85
+ "sanitize_inline",
86
+ "sha256_text",
87
+ "sources_fresh",
88
+ "summarize_savings",
89
+ "usage_to_dict",
90
+ ]
@@ -0,0 +1,199 @@
1
+ """Cross-platform POSIX (fcntl) + Windows (msvcrt) file locking, atomic IO, hashing & git helpers."""
2
+ from __future__ import annotations
3
+
4
+ import contextlib
5
+ import hashlib
6
+ import json
7
+ import os
8
+ import re
9
+ import subprocess
10
+ import sys
11
+ import tempfile
12
+ import time
13
+ from pathlib import Path
14
+ from typing import Any, Dict, Iterator, Sequence, Tuple
15
+
16
+ from _ae_core.security import is_within
17
+
18
+ try:
19
+ import fcntl
20
+ except ImportError: # pragma: no cover (Windows)
21
+ fcntl = None # type: ignore[assignment]
22
+
23
+ try:
24
+ import msvcrt
25
+ except ImportError: # pragma: no cover (POSIX)
26
+ msvcrt = None # type: ignore[assignment]
27
+
28
+
29
+ def configure_utf8_stdio() -> None:
30
+ """Reconfigure stdout/stderr to UTF-8 on Windows/narrow locales so Unicode CLI output never crashes."""
31
+ for stream in (sys.stdout, sys.stderr):
32
+ reconf = getattr(stream, "reconfigure", None)
33
+ if callable(reconf):
34
+ try:
35
+ reconf(encoding="utf-8", errors="replace")
36
+ except Exception:
37
+ pass
38
+
39
+
40
+ def estimate_tokens(text: str) -> int:
41
+ return max(1, (len(text) + 3) // 4) if text else 0
42
+
43
+
44
+ def canonicalize_text(text: str) -> str:
45
+ if not text:
46
+ return ""
47
+ norm = text.replace("\r\n", "\n").replace("\r", "\n")
48
+ lines = [line.rstrip() for line in norm.split("\n")]
49
+ out = "\n".join(lines).strip()
50
+ out = re.sub(r"\n{3,}", "\n\n", out)
51
+ return (out + "\n") if out else ""
52
+
53
+
54
+ def sha256_text(text: str) -> str:
55
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()
56
+
57
+
58
+ def compute_prefix_id(l0: str, l1: str) -> Tuple[str, str]:
59
+ combined_sha = sha256_text(l0 + "\n---LAYER_BOUNDARY---\n" + l1)
60
+ return f"pfx-{combined_sha[:12]}", combined_sha
61
+
62
+
63
+ def _acquire_win_lock(fd: int, timeout_s: float = 10.0) -> None:
64
+ """Acquire an exclusive byte-range lock on Windows via msvcrt.locking with bounded backoff."""
65
+ deadline = time.monotonic() + timeout_s
66
+ delay = 0.01
67
+ while True:
68
+ try:
69
+ os.lseek(fd, 0, os.SEEK_SET)
70
+ msvcrt.locking(fd, msvcrt.LK_NBLCK, 1) # type: ignore[union-attr]
71
+ return
72
+ except OSError:
73
+ if time.monotonic() >= deadline:
74
+ raise TimeoutError(f"Timed out waiting for Windows file lock after {timeout_s}s")
75
+ time.sleep(delay)
76
+ delay = min(0.1, delay * 1.5)
77
+
78
+
79
+ def _release_win_lock(fd: int) -> None:
80
+ try:
81
+ os.lseek(fd, 0, os.SEEK_SET)
82
+ msvcrt.locking(fd, msvcrt.LK_UNLCK, 1) # type: ignore[union-attr]
83
+ except OSError:
84
+ pass
85
+
86
+
87
+ @contextlib.contextmanager
88
+ def file_lock(lock_path: Path, timeout_s: float = 10.0) -> Iterator[None]:
89
+ """Cross-platform exclusive file lock: fcntl.flock on POSIX, msvcrt.locking on Windows."""
90
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
91
+ if lock_path.is_symlink():
92
+ raise SystemExit(f"Refusing to follow symlinked lock file: {lock_path.name}")
93
+ fh = lock_path.open("a+b")
94
+ try:
95
+ try:
96
+ if os.fstat(fh.fileno()).st_size == 0:
97
+ fh.write(b"\0")
98
+ fh.flush()
99
+ except OSError:
100
+ pass
101
+ if fcntl is not None:
102
+ fcntl.flock(fh.fileno(), fcntl.LOCK_EX)
103
+ elif msvcrt is not None:
104
+ _acquire_win_lock(fh.fileno(), timeout_s=timeout_s)
105
+ yield
106
+ finally:
107
+ if fcntl is not None:
108
+ try:
109
+ fcntl.flock(fh.fileno(), fcntl.LOCK_UN)
110
+ except OSError:
111
+ pass
112
+ elif msvcrt is not None:
113
+ _release_win_lock(fh.fileno())
114
+ fh.close()
115
+
116
+
117
+ def atomic_write_text(path: Path, text: str) -> None:
118
+ if path.is_symlink():
119
+ raise SystemExit(f"Refusing to overwrite symlinked file: {path.name}")
120
+ path.parent.mkdir(parents=True, exist_ok=True)
121
+ fd, tmp_name = tempfile.mkstemp(prefix=".tmp_", suffix=path.suffix or ".tmp", dir=str(path.parent))
122
+ try:
123
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
124
+ f.write(text)
125
+ for attempt in range(6):
126
+ try:
127
+ os.replace(tmp_name, path)
128
+ break
129
+ except PermissionError:
130
+ if attempt == 5:
131
+ raise
132
+ time.sleep(0.02 * (attempt + 1))
133
+ except Exception:
134
+ try:
135
+ os.unlink(tmp_name)
136
+ except OSError:
137
+ pass
138
+ raise
139
+
140
+
141
+ def atomic_write_json(path: Path, obj: Any, *, sort_keys: bool = False) -> None:
142
+ atomic_write_text(path, json.dumps(obj, indent=2, ensure_ascii=False, sort_keys=sort_keys) + "\n")
143
+
144
+
145
+ def git_cmd(repo: Path, args: Sequence[str], timeout: int = 4) -> subprocess.CompletedProcess[str]:
146
+ return subprocess.run(
147
+ ["git", "-c", "core.fsmonitor=false", "-c", "core.hooksPath=/dev/null", "-c", "core.quotepath=false", *args],
148
+ cwd=str(repo),
149
+ capture_output=True,
150
+ text=True,
151
+ encoding="utf-8",
152
+ errors="replace",
153
+ timeout=timeout,
154
+ )
155
+
156
+
157
+ def ensure_git_info_exclude(repo: Path, patterns: Sequence[str] = (".agent-index/", ".agent-state/")) -> bool:
158
+ """Ensure local AgentEfficiency dirs are excluded in `.git/info/exclude` (worktree-safe, never touches tracked `.gitignore`)."""
159
+ repo_r = repo.resolve()
160
+ try:
161
+ r = git_cmd(repo_r, ["rev-parse", "--git-path", "info/exclude"], timeout=3)
162
+ if r.returncode != 0 or not r.stdout.strip():
163
+ return False
164
+ raw_p = Path(r.stdout.strip())
165
+ excl_path = raw_p if raw_p.is_absolute() else (repo_r / raw_p).resolve()
166
+ if excl_path.is_symlink():
167
+ return False
168
+ existing = excl_path.read_text(encoding="utf-8", errors="replace") if excl_path.is_file() else ""
169
+ existing_lines = {ln.strip() for ln in existing.splitlines() if ln.strip() and not ln.strip().startswith("#")}
170
+ missing = [p for p in patterns if p not in existing_lines and p.rstrip("/") not in existing_lines]
171
+ if not missing:
172
+ return False
173
+ excl_path.parent.mkdir(parents=True, exist_ok=True)
174
+ header = "# AgentEfficiency local artifacts"
175
+ block = ("\n" if existing and not existing.endswith("\n") else "") + (f"\n{header}\n" if header not in existing else "") + "\n".join(missing) + "\n"
176
+ excl_path.write_text(existing + block, encoding="utf-8")
177
+ return True
178
+ except Exception:
179
+ return False
180
+
181
+
182
+ def sources_fresh(repo: Path, source_files: Dict[str, str]) -> bool:
183
+ repo_r = repo.resolve()
184
+ for rel, old_sha in source_files.items():
185
+ cand = Path(rel)
186
+ if cand.is_absolute() or (repo_r / cand).is_symlink():
187
+ return False
188
+ fp = (repo_r / cand).resolve()
189
+ if not is_within(fp, repo_r) or not fp.is_file():
190
+ return False
191
+ try:
192
+ txt = fp.read_text(encoding="utf-8", errors="replace")
193
+ except OSError:
194
+ return False
195
+ if rel.endswith("DECISIONS.md"):
196
+ txt = txt.split("## Superseded / Archived Decisions", 1)[0].strip()
197
+ if sha256_text(txt)[:16] != old_sha:
198
+ return False
199
+ return True
@@ -0,0 +1,249 @@
1
+ """Persistent local savings counter & statusline formatter (zero-dependency, lock-safe)."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import os
6
+ import tempfile
7
+ import time
8
+ from collections import defaultdict
9
+ from pathlib import Path
10
+ from typing import Any, Dict, List, Optional, Tuple
11
+
12
+ from _ae_core.io_lock import file_lock
13
+
14
+ DEFAULT_RATE_PER_1M_USD = 3.00 # Balanced input token reference rate (e.g., Sonnet-class)
15
+ MAX_HISTORY_LINES = 2500
16
+
17
+
18
+ def default_savings_path() -> Path:
19
+ override = os.getenv("AGENT_EFFICIENCY_SAVINGS_FILE", "").strip()
20
+ if override:
21
+ return Path(override).expanduser()
22
+ return Path.home() / ".agent-efficiency" / "savings.jsonl"
23
+
24
+
25
+ def _is_temp_repo(repo: Optional[Path]) -> bool:
26
+ if repo is None:
27
+ return False
28
+ try:
29
+ rp = str(repo.resolve()).lower()
30
+ td = str(Path(tempfile.gettempdir()).resolve()).lower()
31
+ if rp.startswith(td):
32
+ return True
33
+ for prefix in ("/tmp/", "/private/tmp/", "/var/folders/", "/private/var/folders/"):
34
+ if rp.startswith(prefix):
35
+ return True
36
+ except Exception:
37
+ return False
38
+ return False
39
+
40
+
41
+ def record_saving(
42
+ cmd: str,
43
+ raw_tokens: int,
44
+ compact_tokens: int,
45
+ *,
46
+ repo: Optional[Path] = None,
47
+ savings_path: Optional[Path] = None,
48
+ ) -> Optional[Dict[str, Any]]:
49
+ """Append one compact savings event to local JSONL telemetry (strictly non-fatal)."""
50
+ if os.getenv("AGENT_EFFICIENCY_DISABLE_SAVINGS", "").strip() in ("1", "true", "yes"):
51
+ return None
52
+ raw_t = max(0, int(raw_tokens))
53
+ out_t = max(0, int(compact_tokens))
54
+ saved_t = max(0, raw_t - out_t)
55
+ if saved_t <= 0 and raw_t <= 0:
56
+ return None
57
+
58
+ has_explicit_target = savings_path is not None or bool(os.getenv("AGENT_EFFICIENCY_SAVINGS_FILE", "").strip())
59
+ if not has_explicit_target and _is_temp_repo(repo):
60
+ return None
61
+
62
+ target = (savings_path or default_savings_path()).expanduser()
63
+ rec = {
64
+ "ts": int(time.time()),
65
+ "cmd": str(cmd)[:32],
66
+ "repo": repo.resolve().name[:48] if repo is not None else "",
67
+ "raw_tok": raw_t,
68
+ "out_tok": out_t,
69
+ "saved_tok": saved_t,
70
+ }
71
+ try:
72
+ target.parent.mkdir(parents=True, exist_ok=True)
73
+ lock_file = target.parent / ".savings.lock"
74
+ with file_lock(lock_file, timeout_s=1.5):
75
+ with target.open("a", encoding="utf-8") as fh:
76
+ fh.write(json.dumps(rec, separators=(",", ":")) + "\n")
77
+ # Trim periodically if file grows large
78
+ try:
79
+ if target.stat().st_size > 260_000:
80
+ lines = target.read_text(encoding="utf-8", errors="replace").splitlines()
81
+ if len(lines) > MAX_HISTORY_LINES:
82
+ kept = lines[-MAX_HISTORY_LINES:]
83
+ target.write_text("\n".join(kept) + "\n", encoding="utf-8")
84
+ except OSError:
85
+ pass
86
+ return rec
87
+ except Exception:
88
+ return None
89
+
90
+
91
+ def summarize_savings(
92
+ *,
93
+ days: Optional[int] = 7,
94
+ rate_per_1m_usd: float = DEFAULT_RATE_PER_1M_USD,
95
+ savings_path: Optional[Path] = None,
96
+ repo_filter: Optional[str] = None,
97
+ ) -> Dict[str, Any]:
98
+ """Aggregate recorded token & USD savings over the requested time window (`days=None` for all-time)."""
99
+ target = (savings_path or default_savings_path()).expanduser()
100
+ now = int(time.time())
101
+ cutoff = (now - int(days) * 86400) if (days is not None and days > 0) else 0
102
+
103
+ events = 0
104
+ total_raw = 0
105
+ total_out = 0
106
+ total_saved = 0
107
+ by_cmd: Dict[str, Dict[str, int]] = defaultdict(lambda: {"calls": 0, "raw_tok": 0, "out_tok": 0, "saved_tok": 0})
108
+ repos: Dict[str, int] = defaultdict(int)
109
+
110
+ if target.is_file():
111
+ try:
112
+ for line in target.read_text(encoding="utf-8", errors="replace").splitlines():
113
+ line = line.strip()
114
+ if not line:
115
+ continue
116
+ try:
117
+ rec = json.loads(line)
118
+ except Exception:
119
+ continue
120
+ if not isinstance(rec, dict):
121
+ continue
122
+ ts = int(rec.get("ts", 0))
123
+ if cutoff and ts < cutoff:
124
+ continue
125
+ rname = str(rec.get("repo", ""))
126
+ if repo_filter and rname != repo_filter:
127
+ continue
128
+ raw_t = max(0, int(rec.get("raw_tok", 0)))
129
+ out_t = max(0, int(rec.get("out_tok", 0)))
130
+ saved_t = max(0, int(rec.get("saved_tok", max(0, raw_t - out_t))))
131
+ cname = str(rec.get("cmd", "other"))
132
+ events += 1
133
+ total_raw += raw_t
134
+ total_out += out_t
135
+ total_saved += saved_t
136
+ c = by_cmd[cname]
137
+ c["calls"] += 1
138
+ c["raw_tok"] += raw_t
139
+ c["out_tok"] += out_t
140
+ c["saved_tok"] += saved_t
141
+ if rname:
142
+ repos[rname] += saved_t
143
+ except OSError:
144
+ pass
145
+
146
+ pct = round((total_saved / max(1, total_raw)) * 100.0, 1) if total_raw > 0 else 0.0
147
+ est_usd = round((total_saved / 1_000_000.0) * float(rate_per_1m_usd), 4)
148
+ breakdown = [
149
+ {
150
+ "cmd": k,
151
+ "calls": v["calls"],
152
+ "raw_tokens": v["raw_tok"],
153
+ "output_tokens": v["out_tok"],
154
+ "saved_tokens": v["saved_tok"],
155
+ "savings_pct": round((v["saved_tok"] / max(1, v["raw_tok"])) * 100.0, 1) if v["raw_tok"] > 0 else 0.0,
156
+ }
157
+ for k, v in sorted(by_cmd.items(), key=lambda kv: (-kv[1]["saved_tok"], kv[0]))
158
+ ]
159
+ top_repos = [{"repo": r, "saved_tokens": tok} for r, tok in sorted(repos.items(), key=lambda kv: (-kv[1], kv[0]))[:5]]
160
+ window_label = f"{days}d" if (days is not None and days > 0) else "all-time"
161
+ return {
162
+ "window": window_label,
163
+ "days": days,
164
+ "events": events,
165
+ "raw_tokens_est": total_raw,
166
+ "output_tokens_est": total_out,
167
+ "saved_tokens_est": total_saved,
168
+ "savings_pct": pct,
169
+ "est_usd_saved": est_usd,
170
+ "rate_per_1m_usd": rate_per_1m_usd,
171
+ "by_command": breakdown,
172
+ "top_repos": top_repos,
173
+ "savings_file": str(target),
174
+ }
175
+
176
+
177
+ def _fmt_tok(n: int) -> str:
178
+ if n >= 1_000_000:
179
+ return f"{n / 1_000_000:.2f}M"
180
+ if n >= 1_000:
181
+ return f"{n / 1_000:.1f}k"
182
+ return str(n)
183
+
184
+
185
+ def _bar(fraction: float, width: int = 18) -> str:
186
+ frac = max(0.0, min(1.0, fraction))
187
+ filled = int(round(frac * width))
188
+ return "█" * filled + "░" * (width - filled)
189
+
190
+
191
+ def format_statusline(summary: Dict[str, Any]) -> str:
192
+ """Single-line status string for Claude Code statusLine or shell prompt."""
193
+ saved = int(summary.get("saved_tokens_est", 0))
194
+ if saved <= 0:
195
+ return f"ae: 0 tok saved ({summary.get('window', '7d')})"
196
+ usd = float(summary.get("est_usd_saved", 0.0))
197
+ pct = float(summary.get("savings_pct", 0.0))
198
+ win = summary.get("window", "7d")
199
+ usd_str = f"${usd:.2f}" if usd >= 0.01 else f"${usd:.4f}"
200
+ return f"ae: -{_fmt_tok(saved)} tok (-{pct:.0f}%, ~{usd_str} saved / {win})"
201
+
202
+
203
+ def _box_row(text: str, width: int = 60) -> str:
204
+ clipped = text if len(text) <= width else (text[: max(1, width - 1)] + "…")
205
+ return f"│{clipped:<{width}}│"
206
+
207
+
208
+ def format_savings_card(summary: Dict[str, Any]) -> str:
209
+ """Render a crisp, shareable terminal receipt of AgentEfficiency savings."""
210
+ win = summary["window"]
211
+ saved = int(summary["saved_tokens_est"])
212
+ raw = int(summary["raw_tokens_est"])
213
+ out = int(summary["output_tokens_est"])
214
+ pct = float(summary["savings_pct"])
215
+ usd = float(summary["est_usd_saved"])
216
+ events = int(summary["events"])
217
+
218
+ lines: List[str] = [
219
+ "┌────────────────────────────────────────────────────────────┐",
220
+ _box_row(f" AgentEfficiency Savings Receipt ({win})"),
221
+ "├────────────────────────────────────────────────────────────┤",
222
+ ]
223
+ if events == 0:
224
+ lines.extend([
225
+ _box_row(" No savings recorded yet in this window."),
226
+ _box_row(" Try: `ae run -- pytest` or `ae slice path.py:func`"),
227
+ "└────────────────────────────────────────────────────────────┘",
228
+ ])
229
+ return "\n".join(lines)
230
+
231
+ usd_str = f"${usd:.2f}" if usd >= 0.01 else f"${usd:.4f}"
232
+ lines.append(_box_row(f" Tokens saved : {_fmt_tok(saved):>8} tok (-{pct:4.1f}%) [~{usd_str}]"))
233
+ lines.append(_box_row(f" Raw -> Sent : {_fmt_tok(raw):>8} -> {_fmt_tok(out):<8} ({events} calls)"))
234
+ lines.append("├────────────────────────────────────────────────────────────┤")
235
+ max_saved = max((int(c["saved_tokens"]) for c in summary["by_command"]), default=1)
236
+ for item in summary["by_command"][:6]:
237
+ cmd_lbl = str(item["cmd"])[:10]
238
+ bar = _bar(item["saved_tokens"] / max(1, max_saved), width=16)
239
+ tok_s = _fmt_tok(int(item["saved_tokens"]))
240
+ pct_s = f"-{item['savings_pct']:.0f}%"
241
+ lines.append(_box_row(f" {cmd_lbl:<10} {bar} {tok_s:>7} ({pct_s:>4}, {item['calls']}x)"))
242
+ if summary.get("top_repos"):
243
+ repos_str = ", ".join(f"{r['repo']} ({_fmt_tok(r['saved_tokens'])})" for r in summary["top_repos"][:3])
244
+ lines.append("├────────────────────────────────────────────────────────────┤")
245
+ lines.append(_box_row(f" Top repos: {repos_str}"))
246
+ lines.append("├────────────────────────────────────────────────────────────┤")
247
+ lines.append(_box_row(" Note: gross I/O savings; check net cache hits: `ae audit`"))
248
+ lines.append("└────────────────────────────────────────────────────────────┘")
249
+ return "\n".join(lines)