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,395 @@
1
+ #!/usr/bin/env python3
2
+ """AgentEfficiency — Token-budgeted terminal/test/build command runner & intelligent log compressor.
3
+
4
+ Executes a command inside a repository, archives the full redacted output to `.agent-state/logs/` (or `.agent-index/logs/`),
5
+ and returns a strictly token-budgeted summary preserving failures, errors, assertions, and in-repo stack frames.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import json
11
+ import os
12
+ import re
13
+ import subprocess
14
+ import sys
15
+ import time
16
+ from pathlib import Path
17
+ from typing import Any, Dict, List, Optional, Sequence, Tuple
18
+
19
+ _SCRIPT_DIR = str(Path(__file__).resolve().parent)
20
+ if _SCRIPT_DIR not in sys.path:
21
+ sys.path.insert(0, _SCRIPT_DIR)
22
+
23
+ from _ae_core import atomic_write_text, configure_utf8_stdio, estimate_tokens, is_within, record_saving, redact_secrets, sanitize_inline # noqa: E402
24
+
25
+ _ANSI_RE = re.compile(r"\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07]*\x07")
26
+ _PY_FAIL_HDR_RE = re.compile(r"^(?:={3,}|-{3,}|FAIL:|ERROR:|FAILED |E\s+|AssertionError|Traceback \(most recent)")
27
+ _JS_TS_ERR_RE = re.compile(r"(?:^FAIL\s+|\berror TS\d+:|^\s*●\s+|Expected:|Received:|AssertionError|TypeError:|ReferenceError:|SyntaxError:)")
28
+ _GO_RUST_ERR_RE = re.compile(r"(?:^---\s+FAIL:|^FAIL\t|^error(?:\[E\d+\])?:|^\s*-->\s+|panic:|thread '.*' panicked)")
29
+ _GEN_ERR_RE = re.compile(r"(?i)(?:\berror\b|\bfailed\b|\bfatal\b|\bexception\b|\btraceback\b|\bpanic\b|\bassertion|\berr!|\bexit code [1-9])")
30
+ _WARN_SETUP_RE = re.compile(
31
+ r"(?i)(?:\b(?:deprecation|user|runtime|resource|future|pytest)?warning\b|\bwarn(?:ing)?\s*:|\berror at (?:setup|teardown) of\b|"
32
+ r"captured (?:stderr|log|stdout)|conftest\.py|\bfixture\b.*(?:not found|error|warning|deprecated))"
33
+ )
34
+ _SUMMARY_RE = re.compile(
35
+ r"(?i)(?:^Ran \d+ test|^OK\b|^FAILED \(|\d+\s+(?:passed|failed|error|skipped|warnings?)|Test Suites:|Tests:|test result:|BUILD (?:SUCCESS|FAIL)|Found \d+ error)"
36
+ )
37
+ _PASS_NOISE_RE = re.compile(r"(?:^\s*(?:✓|✔|PASS|ok\s+\S+|\.\.\. ok$|passing)|^test\s+\S+\s+\.\.\.\s+ok$)")
38
+ _EXTERNAL_FRAME_RE = re.compile(r"(?:/site-packages/|/dist-packages/|/node_modules/|/Library/Frameworks/Python|/usr/lib/python|/lib/python3\.\d+/)")
39
+
40
+
41
+ def _strip_ansi_and_cr(raw: str) -> str:
42
+ no_ansi = _ANSI_RE.sub("", raw)
43
+ # Collapse carriage-return progress-bar updates to final state per line
44
+ cleaned_lines = []
45
+ for line in no_ansi.splitlines():
46
+ if "\r" in line:
47
+ parts = [p for p in line.split("\r") if p]
48
+ line = parts[-1] if parts else ""
49
+ cleaned_lines.append(line.rstrip())
50
+ return "\n".join(cleaned_lines)
51
+
52
+
53
+ def _dedup_consecutive(lines: Sequence[str]) -> List[str]:
54
+ out: List[str] = []
55
+ prev: Optional[str] = None
56
+ count = 0
57
+ for ln in lines:
58
+ if ln == prev and ln != "":
59
+ count += 1
60
+ else:
61
+ if count > 1:
62
+ out.append(f"... [repeated {count} more times]")
63
+ out.append(ln)
64
+ prev = ln
65
+ count = 0
66
+ if count > 1:
67
+ out.append(f"... [repeated {count} more times]")
68
+ return out
69
+
70
+
71
+ def compress_command_output(
72
+ raw_text: str,
73
+ exit_code: int,
74
+ budget_tokens: int = 800,
75
+ repo: Optional[Path] = None,
76
+ *,
77
+ verbose: bool = False,
78
+ ) -> Tuple[str, Dict[str, Any]]:
79
+ """Intelligently compress verbose test/build/CLI output into `<= budget_tokens`.
80
+
81
+ Preserves error anchors, fixture/warning context (preventing tunnel vision), and summary footers.
82
+ Pass `verbose=True` for wider pre-error context and higher warning retention.
83
+ """
84
+ cleaned = redact_secrets(_strip_ansi_and_cr(raw_text))
85
+ raw_tok = estimate_tokens(cleaned)
86
+ lines = _dedup_consecutive(cleaned.splitlines())
87
+ if not lines:
88
+ return "(no output)", {
89
+ "raw_tokens_est": 0, "compact_tokens_est": 3, "token_savings_pct": 0.0,
90
+ "mode": "empty", "warnings_detected": 0, "warnings_included": 0, "warnings_omitted": 0,
91
+ }
92
+
93
+ if raw_tok <= budget_tokens:
94
+ body = "\n".join(lines).strip()
95
+ ctok = estimate_tokens(body)
96
+ return body, {
97
+ "raw_tokens_est": raw_tok, "compact_tokens_est": ctok,
98
+ "token_savings_pct": round(max(0.0, (1.0 - ctok / max(1, raw_tok)) * 100), 1),
99
+ "mode": "passthrough", "warnings_detected": 0, "warnings_included": 0, "warnings_omitted": 0,
100
+ }
101
+
102
+ repo_str = str(repo.resolve()) if repo else ""
103
+ summary_lines: List[str] = []
104
+ error_indices: List[int] = []
105
+ warning_indices: List[int] = []
106
+ for idx, ln in enumerate(lines):
107
+ if _SUMMARY_RE.search(ln):
108
+ summary_lines.append(ln)
109
+ is_err = bool(_PY_FAIL_HDR_RE.search(ln) or _JS_TS_ERR_RE.search(ln) or _GO_RUST_ERR_RE.search(ln) or _GEN_ERR_RE.search(ln))
110
+ if is_err and not _PASS_NOISE_RE.search(ln):
111
+ error_indices.append(idx)
112
+ elif _WARN_SETUP_RE.search(ln) and not _PASS_NOISE_RE.search(ln):
113
+ warning_indices.append(idx)
114
+
115
+ # Deduplicate identical warning lines while keeping earliest line index (e.g. fixture warning 40 lines up)
116
+ unique_warning_indices: List[int] = []
117
+ seen_warn_text: set[str] = set()
118
+ for wi in warning_indices:
119
+ norm_w = lines[wi].strip()
120
+ if norm_w and norm_w not in seen_warn_text:
121
+ seen_warn_text.add(norm_w)
122
+ unique_warning_indices.append(wi)
123
+
124
+ selected: List[str] = []
125
+ warnings_kept_idx: set[int] = set()
126
+ if exit_code == 0:
127
+ mode = "success_summary_verbose" if verbose else "success_summary"
128
+ if summary_lines:
129
+ selected.extend(summary_lines[-10:])
130
+ warn_cap = 8 if verbose else 3
131
+ if unique_warning_indices:
132
+ selected.append("--- warnings/setup ---")
133
+ for wi in unique_warning_indices[:warn_cap]:
134
+ selected.append(lines[wi])
135
+ warnings_kept_idx.add(wi)
136
+ tail = [ln for ln in lines[-12:] if ln.strip() and not _PASS_NOISE_RE.search(ln) and ln not in selected]
137
+ if tail:
138
+ selected.extend(["--- tail ---", *tail[-8:]])
139
+ if not selected:
140
+ selected = lines[-10:]
141
+ else:
142
+ mode = "failure_verbose" if verbose else "failure_focused"
143
+ kept_idx: set[int] = set()
144
+ pre_ctx = 6 if verbose else 3
145
+ post_ctx = 9 if verbose else 6
146
+ # Preserve fixture/setup warnings above errors so root causes outside the traceback stay visible
147
+ warn_cap = 16 if verbose else 6
148
+ warn_pad = 1 if verbose else 0
149
+ for wi in unique_warning_indices[:warn_cap]:
150
+ warnings_kept_idx.add(wi)
151
+ for k in range(max(0, wi - warn_pad), min(len(lines), wi + warn_pad + 1)):
152
+ ln = lines[k]
153
+ if not _PASS_NOISE_RE.search(ln):
154
+ kept_idx.add(k)
155
+ # Keep context windows around error/failure anchors, collapsing noisy external stack frames
156
+ for ei in error_indices[:40]:
157
+ for k in range(max(0, ei - pre_ctx), min(len(lines), ei + post_ctx)):
158
+ ln = lines[k]
159
+ if _EXTERNAL_FRAME_RE.search(ln) and (not repo_str or repo_str not in ln):
160
+ continue
161
+ if _PASS_NOISE_RE.search(ln):
162
+ continue
163
+ kept_idx.add(k)
164
+ # Always include final summary lines
165
+ for idx in range(max(0, len(lines) - 12), len(lines)):
166
+ if lines[idx].strip() and not _PASS_NOISE_RE.search(lines[idx]):
167
+ kept_idx.add(idx)
168
+
169
+ last_i = -2
170
+ for idx in sorted(kept_idx):
171
+ if last_i >= 0 and idx > last_i + 1:
172
+ selected.append(f"... [{idx - last_i - 1} lines omitted] ...")
173
+ selected.append(lines[idx])
174
+ last_i = idx
175
+ if not selected:
176
+ selected = lines[:10] + ["... [middle omitted] ..."] + lines[-20:]
177
+
178
+ warnings_detected = len(unique_warning_indices)
179
+ warnings_omitted_pre_cap = max(0, warnings_detected - len(warnings_kept_idx))
180
+
181
+ # Enforce strict token budget (prioritize summary footer + top failure details)
182
+ header = f"[compressed {len(lines)} lines (~{raw_tok:,} tok) -> budget {budget_tokens} tok | mode={mode}]"
183
+ footer_lines = [s for s in dict.fromkeys(summary_lines[-5:]) if s not in selected[-6:]]
184
+ warn_notice = (
185
+ f"... [{warnings_omitted_pre_cap} warning/setup line(s) omitted; inspect full_log or rerun with --verbose]"
186
+ if warnings_omitted_pre_cap > 0
187
+ else ""
188
+ )
189
+ footer_txt = ("\n--- summary ---\n" + "\n".join(footer_lines)) if footer_lines else ""
190
+ reserve = estimate_tokens(header + "\n" + warn_notice + "\n" + footer_txt + "\n... [truncated; see full log]")
191
+ avail = max(40, budget_tokens - reserve)
192
+
193
+ kept_lines: List[str] = []
194
+ acc = 0
195
+ truncated = False
196
+ # If failure mode has early warnings AND late errors, ensure error anchors aren't starved by warnings
197
+ if exit_code != 0 and unique_warning_indices and error_indices:
198
+ warn_texts = {lines[wi] for wi in warnings_kept_idx}
199
+ # Reserve at least 65% of body budget for error/traceback lines
200
+ warn_budget = max(25, int(avail * 0.30))
201
+ warn_acc = 0
202
+ filtered_selected: List[str] = []
203
+ dropped_warns = 0
204
+ for ln in selected:
205
+ if ln in warn_texts:
206
+ lt = estimate_tokens(ln + "\n")
207
+ if warn_acc + lt > warn_budget:
208
+ dropped_warns += 1
209
+ continue
210
+ warn_acc += lt
211
+ filtered_selected.append(ln)
212
+ if dropped_warns > 0:
213
+ warnings_omitted_pre_cap += dropped_warns
214
+ warn_notice = f"... [{warnings_omitted_pre_cap} warning/setup line(s) omitted; inspect full_log or rerun with --verbose]"
215
+ selected = filtered_selected
216
+
217
+ for ln in selected:
218
+ lt = estimate_tokens(ln + "\n")
219
+ if kept_lines and acc + lt > avail:
220
+ truncated = True
221
+ break
222
+ kept_lines.append(ln)
223
+ acc += lt
224
+
225
+ warnings_actually_included = sum(1 for wi in unique_warning_indices if lines[wi] in kept_lines)
226
+ warnings_omitted = max(0, warnings_detected - warnings_actually_included)
227
+ if warnings_omitted > 0 and not warn_notice:
228
+ warn_notice = f"... [{warnings_omitted} warning/setup line(s) omitted; inspect full_log or rerun with --verbose]"
229
+
230
+ parts = [header, "\n".join(kept_lines)]
231
+ if warn_notice:
232
+ parts.append(warn_notice)
233
+ if truncated:
234
+ parts.append("... [truncated; slice full_log path or rerun with --verbose for full context]")
235
+ if footer_txt:
236
+ parts.append(footer_txt.lstrip("\n"))
237
+ compact = "\n".join(p for p in parts if p).strip()
238
+ ctok = estimate_tokens(compact)
239
+ savings = round(max(0.0, (1.0 - ctok / max(1, raw_tok)) * 100), 1)
240
+ return compact, {
241
+ "raw_tokens_est": raw_tok,
242
+ "compact_tokens_est": ctok,
243
+ "token_savings_pct": savings,
244
+ "mode": mode,
245
+ "truncated": truncated,
246
+ "warnings_detected": warnings_detected,
247
+ "warnings_included": warnings_actually_included,
248
+ "warnings_omitted": warnings_omitted,
249
+ }
250
+
251
+
252
+ def _archive_full_log(repo: Path, cmd_display: str, exit_code: int, raw_text: str) -> Optional[str]:
253
+ repo_r = repo.resolve()
254
+ base_dir = (repo_r / ".agent-state") if (repo_r / ".agent-state").is_dir() else (repo_r / ".agent-index")
255
+ if base_dir.is_symlink() or (base_dir.exists() and not is_within(base_dir, repo_r)):
256
+ return None
257
+ logs_dir = base_dir / "logs"
258
+ logs_dir.mkdir(parents=True, exist_ok=True)
259
+ slug = re.sub(r"[^A-Za-z0-9_-]+", "_", cmd_display)[:36].strip("_") or "cmd"
260
+ fname = f"{time.strftime('%Y%m%d-%H%M%S')}-{slug}.log"
261
+ lp = logs_dir / fname
262
+ atomic_write_text(lp, f"# cmd: {sanitize_inline(cmd_display)}\n# exit_code: {exit_code}\n\n{redact_secrets(raw_text)}\n")
263
+ # Rotate: keep only 20 most recent logs
264
+ old_logs = sorted(logs_dir.glob("*.log"), key=lambda p: p.stat().st_mtime, reverse=True)
265
+ for old in old_logs[20:]:
266
+ try:
267
+ old.unlink()
268
+ except OSError:
269
+ pass
270
+ try:
271
+ return lp.relative_to(repo_r).as_posix()
272
+ except ValueError:
273
+ return str(lp)
274
+
275
+
276
+ def run_compact(
277
+ repo: Path,
278
+ cmd: Sequence[str] | str,
279
+ *,
280
+ budget_tokens: int = 800,
281
+ timeout: int = 120,
282
+ shell: bool = False,
283
+ archive_log: bool = True,
284
+ include_trace_slices: bool = True,
285
+ trace_budget_tokens: Optional[int] = None,
286
+ max_trace_frames: int = 4,
287
+ verbose: bool = False,
288
+ ) -> Dict[str, Any]:
289
+ repo_r = repo.resolve()
290
+ cmd_display = cmd if isinstance(cmd, str) else " ".join(cmd)
291
+ t0 = time.perf_counter()
292
+ timed_out = False
293
+ try:
294
+ child_env = {**os.environ, "PYTHONUTF8": "1", "PYTHONIOENCODING": "utf-8"}
295
+ proc = subprocess.run(
296
+ cmd,
297
+ cwd=str(repo_r),
298
+ shell=shell,
299
+ stdout=subprocess.PIPE,
300
+ stderr=subprocess.STDOUT,
301
+ text=True,
302
+ encoding="utf-8",
303
+ errors="replace",
304
+ env=child_env,
305
+ timeout=timeout,
306
+ )
307
+ exit_code = proc.returncode
308
+ raw_out = proc.stdout or ""
309
+ except subprocess.TimeoutExpired as exc:
310
+ timed_out = True
311
+ exit_code = 124
312
+ partial = exc.stdout or ""
313
+ if isinstance(partial, bytes):
314
+ partial = partial.decode("utf-8", errors="replace")
315
+ raw_out = partial + f"\nERROR: Command timed out after {timeout}s\n"
316
+ duration_ms = round((time.perf_counter() - t0) * 1000, 1)
317
+
318
+ eff_budget = max(budget_tokens, 1600) if verbose and budget_tokens == 800 else budget_tokens
319
+ compact_txt, stats = compress_command_output(raw_out, exit_code, budget_tokens=eff_budget, repo=repo_r, verbose=verbose)
320
+ log_rel = _archive_full_log(repo_r, cmd_display, exit_code, raw_out) if archive_log else None
321
+
322
+ tp_data: Optional[Dict[str, Any]] = None
323
+ tp_md = ""
324
+ if exit_code != 0 and include_trace_slices and raw_out.strip():
325
+ try:
326
+ from idx_trace import format_compact_trace_pack, trace_pack
327
+ eff_tb = trace_budget_tokens if trace_budget_tokens is not None else min(900 if verbose else 650, max(250, eff_budget))
328
+ tp = trace_pack(repo_r, raw_out, budget_tokens=eff_tb, max_frames=max_trace_frames)
329
+ if tp.get("frames_included", 0) > 0:
330
+ tp_data = tp
331
+ tp_md = format_compact_trace_pack(tp)
332
+ except Exception:
333
+ pass
334
+
335
+ res: Dict[str, Any] = {
336
+ "cmd": redact_secrets(cmd_display),
337
+ "exit_code": exit_code,
338
+ "timed_out": timed_out,
339
+ "duration_ms": duration_ms,
340
+ "budget_tokens": eff_budget,
341
+ "verbose": verbose,
342
+ "full_log": log_rel,
343
+ **stats,
344
+ "output": compact_txt,
345
+ }
346
+ if tp_data is not None:
347
+ res["trace_pack"] = tp_data
348
+ res["trace_slices_md"] = tp_md
349
+ record_saving("run", stats["raw_tokens_est"], stats["compact_tokens_est"], repo=repo_r)
350
+ return res
351
+
352
+
353
+ def main(argv: Optional[Sequence[str]] = None) -> int:
354
+ configure_utf8_stdio()
355
+ ap = argparse.ArgumentParser(description="Run a command and compress verbose test/build logs to a strict token budget.")
356
+ ap.add_argument("repo", type=Path)
357
+ ap.add_argument("--budget-tokens", type=int, default=800)
358
+ ap.add_argument("--timeout", type=int, default=120)
359
+ ap.add_argument("--shell", dest="shell_cmd", default=None, help="Run command string via shell (alternative to -- <argv...>)")
360
+ ap.add_argument("--no-trace-slices", action="store_true", help="Disable auto-appending in-repo stacktrace code slices on failure")
361
+ ap.add_argument("--trace-budget-tokens", type=int, default=None, help="Token budget for auto-extracted failure stacktrace code slices")
362
+ ap.add_argument("--verbose", action="store_true", help="Wider pre-error context, higher warning retention & larger default budget (anti-tunnel-vision escalation)")
363
+ ap.add_argument("--format", choices=["compact", "json"], default="compact")
364
+ ap.add_argument("command", nargs=argparse.REMAINDER, help="Command argv after `--`")
365
+ args = ap.parse_args(argv)
366
+
367
+ cmd_argv = list(args.command)
368
+ if cmd_argv and cmd_argv[0] == "--":
369
+ cmd_argv = cmd_argv[1:]
370
+ common_kw = dict(
371
+ budget_tokens=args.budget_tokens,
372
+ timeout=args.timeout,
373
+ include_trace_slices=not args.no_trace_slices,
374
+ trace_budget_tokens=args.trace_budget_tokens,
375
+ verbose=args.verbose,
376
+ )
377
+ if args.shell_cmd:
378
+ res = run_compact(args.repo, args.shell_cmd, shell=True, **common_kw)
379
+ elif cmd_argv:
380
+ res = run_compact(args.repo, cmd_argv, shell=False, **common_kw)
381
+ else:
382
+ raise SystemExit("Provide either `--shell '<cmd>'` or `-- <cmd> [args...]`.")
383
+
384
+ if args.format == "json":
385
+ print(json.dumps(res, indent=2, ensure_ascii=False))
386
+ else:
387
+ log_note = f" | full_log={res['full_log']}" if res.get("full_log") else ""
388
+ print(f"$ {res['cmd']} -> exit {res['exit_code']} ({res['duration_ms']}ms, ~{res['raw_tokens_est']} -> ~{res['compact_tokens_est']} tok, -{res['token_savings_pct']}%){log_note}\n{res['output']}")
389
+ if res.get("trace_slices_md"):
390
+ print(f"\n{res['trace_slices_md']}")
391
+ return int(res["exit_code"])
392
+
393
+
394
+ if __name__ == "__main__":
395
+ raise SystemExit(main())