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,580 @@
1
+ """Task lifecycle, checkpoint, decision, handoff, and read-only query command handlers for agent_state.py."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import os
6
+ import time
7
+ import uuid
8
+ from pathlib import Path
9
+ from typing import Any, Dict, List, Optional
10
+
11
+ from _ae_core import (
12
+ DEFAULT_TIER_PRICES,
13
+ atomic_write_json,
14
+ atomic_write_text,
15
+ estimate_tokens,
16
+ file_lock,
17
+ is_within,
18
+ redact_secrets_with_flag as redact_secrets,
19
+ sanitize_inline,
20
+ )
21
+ from state_render import (
22
+ cache_summary as _cache_summary,
23
+ index_summary_for_files as _index_summary_for_files,
24
+ relevant_decisions as _relevant_decisions,
25
+ render_handoff_markdown,
26
+ )
27
+ from state_store import (
28
+ SCHEMA_VERSION,
29
+ TIER_TO_ALIAS,
30
+ _check_ownership_conflicts,
31
+ _file_sha12,
32
+ _git_snapshot,
33
+ _parse_rel_paths,
34
+ _promote_next_active,
35
+ _resolve_task_id,
36
+ _safe_state_dir,
37
+ _validate_task_id,
38
+ build_brief,
39
+ build_session_start,
40
+ init_state,
41
+ load_state_readonly,
42
+ normalize_rel_path,
43
+ now_iso,
44
+ save_state,
45
+ )
46
+
47
+
48
+ def handle_readonly(repo: Path, args: Any) -> int:
49
+ _sd, st, exists = load_state_readonly(repo)
50
+ if args.subcmd == "list":
51
+ tasks = [t for t in st["tasks"].values() if not args.status or t["status"] == args.status]
52
+ print(json.dumps({"initialized": exists, "active_task": st["active_task"], "count": len(tasks), "tasks": tasks}, indent=2, ensure_ascii=False))
53
+ elif args.subcmd == "status":
54
+ tid = st["active_task"]
55
+ a = st["tasks"].get(tid) if tid else None
56
+ print(json.dumps({
57
+ "initialized": exists, "schema_version": st["schema_version"], "active_task": tid,
58
+ "active_summary": {"objective": a["objective"], "status": a["status"], "owner": a["owner"], "tier": a["model_tier"], "failures": a["failures_count"], "next": a["next"]} if a else None,
59
+ "in_progress_count": sum(1 for t in st["tasks"].values() if t["status"] == "in_progress"),
60
+ "queued_count": sum(1 for t in st["tasks"].values() if t["status"] == "queued"),
61
+ "handed_off_count": sum(1 for t in st["tasks"].values() if t["status"] == "handed_off"),
62
+ "blocked_count": sum(1 for t in st["tasks"].values() if t["status"] == "blocked"),
63
+ "completed_count": sum(1 for t in st["tasks"].values() if t["status"] == "completed"),
64
+ "active_decisions_count": sum(1 for d in st["decisions"] if d["status"] == "active"),
65
+ "open_blockers_count": sum(1 for b in st["blockers"] if b["status"] == "open"),
66
+ "telemetry": st["telemetry"],
67
+ }, indent=2, ensure_ascii=False))
68
+ elif args.subcmd == "brief":
69
+ res = build_brief(repo, st, task_id=args.task_id, max_tokens=args.max_tokens)
70
+ if args.format == "gemini-hook":
71
+ payload = {"hookSpecificOutput": {"additionalContext": res["markdown"]}} if (res.get("has_task") or res.get("has_checkpoint")) else {}
72
+ print(json.dumps(payload, ensure_ascii=False))
73
+ elif args.format == "md":
74
+ print(res["markdown"], end="")
75
+ else:
76
+ print(json.dumps(res, indent=2, ensure_ascii=False))
77
+ elif args.subcmd == "session-start":
78
+ ss = build_session_start(
79
+ repo,
80
+ max_tokens=args.max_tokens,
81
+ include_map=not getattr(args, "no_map", False),
82
+ auto_index=bool(getattr(args, "auto_index", False)),
83
+ )
84
+ has_signal = bool(
85
+ ss.get("initialized")
86
+ or ss.get("index", {}).get("indexed")
87
+ or ss.get("recent_git", {}).get("is_git")
88
+ or ss.get("brief", {}).get("has_task")
89
+ or ss.get("brief", {}).get("has_checkpoint")
90
+ )
91
+ if args.format == "claude-hook":
92
+ payload = (
93
+ {"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": ss["markdown"]}}
94
+ if has_signal
95
+ else {}
96
+ )
97
+ print(json.dumps(payload, ensure_ascii=False))
98
+ elif args.format == "gemini-hook":
99
+ payload = {"hookSpecificOutput": {"additionalContext": ss["markdown"]}} if has_signal else {}
100
+ print(json.dumps(payload, ensure_ascii=False))
101
+ elif args.format == "json":
102
+ print(json.dumps(ss, indent=2, ensure_ascii=False))
103
+ else:
104
+ print(ss["markdown"], end="")
105
+ elif args.subcmd == "decisions":
106
+ decs = st["decisions"] if args.all else [d for d in st["decisions"] if d["status"] == "active"]
107
+ if args.file:
108
+ tf = normalize_rel_path(args.file)
109
+ decs = [d for d in decs if not d.get("scope_files") or tf in d["scope_files"]]
110
+ if args.query:
111
+ q = args.query.lower()
112
+ decs = [d for d in decs if q in d["title"].lower() or q in d["rationale"].lower()]
113
+ print(json.dumps({"count": len(decs), "decisions": decs}, indent=2, ensure_ascii=False))
114
+ elif args.subcmd == "metrics":
115
+ telem = st["telemetry"]
116
+ tot_in = telem["input_tokens"]
117
+ print(json.dumps({**telem, "cache_read_pct": round((telem["cached_input_tokens"] / tot_in) * 100.0, 2) if tot_in > 0 else 0.0}, indent=2, ensure_ascii=False))
118
+ return 0
119
+
120
+
121
+ def handle_checkpoint(repo: Path, args: Any) -> int:
122
+ sd = _safe_state_dir(repo)
123
+ live_git = _git_snapshot(repo)
124
+ dirty_paths: List[str] = []
125
+ for raw_p in live_git.get("dirty_paths", []):
126
+ if raw_p:
127
+ try:
128
+ dirty_paths.append(normalize_rel_path(raw_p))
129
+ except SystemExit:
130
+ pass
131
+ dirty_paths = sorted(set(dirty_paths))
132
+ has_existing = (sd / "state.json").is_file()
133
+ if args.hook_format != "none" and not has_existing and not dirty_paths and not args.note and not args.check_cmd:
134
+ print("{}")
135
+ return 0
136
+ with file_lock(sd / ".state.lock"):
137
+ sd, st = init_state(repo)
138
+ tid = args.task_id or st.get("active_task")
139
+ if tid and tid not in st["tasks"]:
140
+ tid = None
141
+ now = now_iso()
142
+ idx_info = _index_summary_for_files(repo, dirty_paths)
143
+ note_clean, r_note = redact_secrets(args.note) if args.note else ("", False)
144
+ chk_obj: Optional[Dict[str, Any]] = None
145
+ if args.check_cmd is not None and args.exit_code is not None:
146
+ cc, _ = redact_secrets(args.check_cmd)
147
+ sc, _ = redact_secrets(args.summary)
148
+ chk_obj = {"cmd": cc, "exit_code": args.exit_code, "summary": sc, "git_head": live_git.get("head", "nogit"), "at": now, "agent": os.getenv("USER", "agent")}
149
+ if tid:
150
+ t = st["tasks"][tid]
151
+ if dirty_paths:
152
+ t["files_touched"] = sorted(set(t["files_touched"] + dirty_paths))
153
+ t["files"] = t["files_touched"]
154
+ if note_clean:
155
+ t["progress_log"] = (t["progress_log"] + [{"at": now, "agent": t["owner"], "note": f"[checkpoint] {note_clean}"}])[-25:]
156
+ if chk_obj:
157
+ t["verified_checks"].append(chk_obj)
158
+ t["tests"].append(f"{chk_obj['cmd']} (exit {chk_obj['exit_code']})")
159
+ t["failures_count"] = 0 if chk_obj["exit_code"] == 0 else int(t.get("failures_count", 0)) + 1
160
+ t["updated_at"] = now
161
+ st["last_checkpoint"] = {
162
+ "at": now, "task_id": tid, "note": note_clean, "dirty_paths": dirty_paths[:25],
163
+ "touched_symbols": idx_info.get("touched_file_symbols", {}), "git_snapshot": live_git, "last_check": chk_obj,
164
+ }
165
+ save_state(sd, st)
166
+ if args.hook_format in ("gemini", "claude"):
167
+ print("{}")
168
+ else:
169
+ print(json.dumps({"checkpointed": True, "task_id": tid, "dirty_count": len(dirty_paths), "checkpoint_md": str(sd / "CHECKPOINT.md"), "secrets_redacted": r_note}, indent=2))
170
+ return 0
171
+
172
+
173
+ def handle_mutating(repo: Path, args: Any) -> int:
174
+ sd = _safe_state_dir(repo)
175
+ with file_lock(sd / ".state.lock"):
176
+ sd, st = init_state(repo)
177
+ sub = args.subcmd
178
+
179
+ if sub == "init":
180
+ print(sd)
181
+ return 0
182
+ if sub in ("start", "queue"):
183
+ return _op_start(sd, st, args)
184
+ if sub == "decision":
185
+ return _op_decision(sd, st, args)
186
+ if sub == "blocker":
187
+ return _op_blocker(sd, st, args)
188
+ if sub == "prune":
189
+ return _op_prune(sd, st, args)
190
+ if sub == "reopen":
191
+ return _op_reopen(sd, st, args)
192
+ if sub == "switch":
193
+ return _op_switch(sd, st, args)
194
+ if sub == "record-usage":
195
+ return _op_record_usage(sd, st, args)
196
+ if sub == "accept":
197
+ return _op_accept(repo, sd, st, args)
198
+
199
+ tid = _resolve_task_id(st, getattr(args, "task_id", None))
200
+ t = st["tasks"][tid]
201
+ if sub == "block":
202
+ return _op_block(sd, st, tid, t, args)
203
+ if sub == "cancel":
204
+ return _op_cancel(sd, st, tid, t, args)
205
+ if sub == "update":
206
+ return _op_update(sd, st, tid, t, args)
207
+ if sub == "record-inspection":
208
+ return _op_record_inspection(repo, sd, st, tid, t, args)
209
+ if sub == "record-attempt":
210
+ return _op_record_attempt(sd, st, tid, t, args)
211
+ if sub == "record-check":
212
+ return _op_record_check(repo, sd, st, tid, t, args)
213
+ if sub == "complete":
214
+ return _op_complete(sd, st, tid, t, args)
215
+ if sub == "handoff":
216
+ return _op_handoff(repo, sd, st, tid, t, args)
217
+ return 0
218
+
219
+
220
+ def _op_start(sd: Path, st: Dict[str, Any], args: Any) -> int:
221
+ is_q = args.subcmd == "queue" or getattr(args, "queue", False)
222
+ is_p = getattr(args, "parallel", False)
223
+ if not is_q and not is_p and st["active_task"]:
224
+ raise SystemExit(f"Active task '{st['active_task']}' exists. Update, complete, hand off, or pass --queue / --parallel.")
225
+ obj_c, r1 = redact_secrets(args.objective)
226
+ crit_c, r2 = redact_secrets(args.criteria)
227
+ owned = _parse_rel_paths(getattr(args, "own_files", ""))
228
+ tid = "T-" + uuid.uuid4().hex[:8]
229
+ if not is_q and owned:
230
+ conflicts = _check_ownership_conflicts(st, tid, owned)
231
+ if conflicts:
232
+ raise SystemExit(f"File ownership conflict with active task: {json.dumps(conflicts)}")
233
+ tier, alias = args.tier, TIER_TO_ALIAS[args.tier]
234
+ owner = sanitize_inline(getattr(args, "owner", os.getenv("USER", "agent")))
235
+ now = now_iso()
236
+ st["tasks"][tid] = {
237
+ "id": tid, "status": "queued" if is_q else "in_progress", "priority": args.priority,
238
+ "owner": owner, "owner_history": [{"agent": owner, "model_alias": alias, "started_at": now}],
239
+ "objective": obj_c, "criteria": crit_c, "next": "Query local index (`map`/`search`), check active decisions, and slice target symbols.",
240
+ "model_tier": tier, "model_alias": alias, "human_approval_required": tier == "critical",
241
+ "owned_files": owned, "files_touched": [], "files": [],
242
+ "files_inspected": {}, "verified_checks": [], "attempted_approaches": [], "progress_log": [],
243
+ "routing_history": [{"at": now, "from_tier": None, "to_tier": tier, "action": "select", "task": obj_c[:120], "reasons": ["initial task tier"]}],
244
+ "failures_count": 0, "handoff_count": 0, "tests": [], "created_at": now, "updated_at": now,
245
+ }
246
+ if not is_q and (not st["active_task"] or not is_p):
247
+ st["active_task"] = tid
248
+ save_state(sd, st)
249
+ print(tid) if (args.subcmd == "start" and not (r1 or r2)) else print(json.dumps({"task_id": tid, "status": st["tasks"][tid]["status"], "secrets_redacted": r1 or r2}, indent=2))
250
+ return 0
251
+
252
+
253
+ def _op_decision(sd: Path, st: Dict[str, Any], args: Any) -> int:
254
+ tc, r1 = redact_secrets(args.title)
255
+ rc, r2 = redact_secrets(args.rationale)
256
+ ac, r3 = redact_secrets(args.alternatives)
257
+ did = f"D-{len(st['decisions']) + 1:03d}"
258
+ if args.supersedes:
259
+ hit = next((d for d in st["decisions"] if d["id"] == args.supersedes), None)
260
+ if not hit:
261
+ raise SystemExit(f"Decision ID to supersede not found: {args.supersedes}")
262
+ hit["status"], hit["superseded_by"] = "superseded", did
263
+ st["decisions"].append({
264
+ "id": did, "title": tc, "status": "active", "rationale": rc, "alternatives_rejected": ac,
265
+ "scope_files": _parse_rel_paths(args.files), "task_id": args.task_id or st["active_task"],
266
+ "superseded_by": None, "author": sanitize_inline(args.author), "created_at": now_iso(),
267
+ })
268
+ save_state(sd, st)
269
+ print(json.dumps({"decision_id": did, "secrets_redacted": r1 or r2 or r3, "state_dir": str(sd)}, indent=2))
270
+ return 0
271
+
272
+
273
+ def _op_blocker(sd: Path, st: Dict[str, Any], args: Any) -> int:
274
+ if args.add:
275
+ dc, red = redact_secrets(args.add)
276
+ bid = f"B-{len(st['blockers']) + 1:03d}"
277
+ st["blockers"].append({"id": bid, "task_id": args.task_id or st["active_task"], "description": dc, "status": "open", "created_at": now_iso(), "resolved_at": None, "resolution": None})
278
+ save_state(sd, st)
279
+ print(json.dumps({"blocker_id": bid, "status": "open", "secrets_redacted": red}, indent=2))
280
+ return 0
281
+ if args.resolve:
282
+ rc, _ = redact_secrets(args.resolution)
283
+ b = next((x for x in st["blockers"] if x["id"] == args.resolve), None)
284
+ if not b:
285
+ raise SystemExit(f"Blocker ID not found: {args.resolve}")
286
+ b["status"], b["resolved_at"], b["resolution"] = "resolved", now_iso(), rc
287
+ save_state(sd, st)
288
+ print(json.dumps({"blocker_id": b["id"], "status": "resolved"}, indent=2))
289
+ return 0
290
+ raise SystemExit("Supply either --add or --resolve.")
291
+
292
+
293
+ def _op_prune(sd: Path, st: Dict[str, Any], args: Any) -> int:
294
+ keep = max(0, int(args.keep_completed))
295
+ done = [t for t in st["tasks"].values() if t["status"] in ("completed", "cancelled")]
296
+ done.sort(key=lambda x: x.get("completed_at") or x.get("updated_at", ""), reverse=True)
297
+ to_archive = done[keep:]
298
+ if to_archive:
299
+ arch_dir = sd / "archive"
300
+ arch_dir.mkdir(exist_ok=True)
301
+ atomic_write_json(arch_dir / f"tasks-{time.strftime('%Y%m%d-%H%M%S')}.json", to_archive)
302
+ for t_item in to_archive:
303
+ st["tasks"].pop(t_item["id"], None)
304
+ save_state(sd, st)
305
+ print(json.dumps({"pruned": len(to_archive), "remaining_tasks": len(st["tasks"])}, indent=2))
306
+ return 0
307
+
308
+
309
+ def _op_reopen(sd: Path, st: Dict[str, Any], args: Any) -> int:
310
+ tid = _validate_task_id(args.task_id)
311
+ if tid not in st["tasks"]:
312
+ raise SystemExit(f"Unknown task ID: {tid}")
313
+ t = st["tasks"][tid]
314
+ if t["status"] not in ("completed", "cancelled"):
315
+ raise SystemExit(f"Task '{tid}' has status '{t['status']}' (expected completed or cancelled).")
316
+ conflicts = _check_ownership_conflicts(st, tid, t.get("owned_files", []))
317
+ if conflicts:
318
+ raise SystemExit(f"Cannot reopen task due to file ownership conflicts: {json.dumps(conflicts)}")
319
+ now = now_iso()
320
+ t["status"], t["owner"], t["updated_at"] = "in_progress", sanitize_inline(args.owner), now
321
+ t["progress_log"].append({"at": now, "agent": t["owner"], "note": "Reopened task."})
322
+ st["active_task"] = tid
323
+ save_state(sd, st)
324
+ print(json.dumps({"task_id": tid, "status": "in_progress", "owner": t["owner"]}, indent=2))
325
+ return 0
326
+
327
+
328
+ def _op_switch(sd: Path, st: Dict[str, Any], args: Any) -> int:
329
+ tid = _validate_task_id(args.task_id)
330
+ if tid not in st["tasks"]:
331
+ raise SystemExit(f"Unknown task ID: {tid}")
332
+ if st["tasks"][tid]["status"] != "in_progress":
333
+ raise SystemExit(f"Cannot switch to task '{tid}' with status '{st['tasks'][tid]['status']}' (expected in_progress; use `accept` for handed_off/queued/blocked).")
334
+ st["active_task"] = tid
335
+ save_state(sd, st)
336
+ print(json.dumps({"active_task": tid, "objective": st["tasks"][tid]["objective"]}, indent=2))
337
+ return 0
338
+
339
+
340
+ def _op_record_usage(sd: Path, st: Dict[str, Any], args: Any) -> int:
341
+ p_in, p_cached, p_out = DEFAULT_TIER_PRICES[args.tier]
342
+ actual = (max(0, args.input_tokens - args.cached_tokens) * p_in + args.cached_tokens * p_cached + args.cache_write_tokens * (p_in * 0.25) + args.output_tokens * p_out) / 1_000_000.0
343
+ r_in, _rc, r_out = DEFAULT_TIER_PRICES["high"]
344
+ savings = max(0.0, (args.input_tokens * r_in + args.output_tokens * r_out) / 1_000_000.0 - actual)
345
+ telem = st["telemetry"]
346
+ telem["calls"] += 1
347
+ telem["input_tokens"] += args.input_tokens
348
+ telem["cached_input_tokens"] += args.cached_tokens
349
+ telem["cache_write_tokens"] += args.cache_write_tokens
350
+ telem["output_tokens"] += args.output_tokens
351
+ telem["estimated_cost_usd"] = round(telem["estimated_cost_usd"] + actual, 6)
352
+ telem["estimated_savings_vs_uncached_reasoning_usd"] = round(telem["estimated_savings_vs_uncached_reasoning_usd"] + savings, 6)
353
+ tb = telem["by_tier"].setdefault(args.tier, {"calls": 0, "input_tokens": 0, "cached_tokens": 0, "output_tokens": 0})
354
+ tb["calls"] += 1
355
+ tb["input_tokens"] += args.input_tokens
356
+ tb["cached_tokens"] += args.cached_tokens
357
+ tb["output_tokens"] += args.output_tokens
358
+ save_state(sd, st)
359
+ print(json.dumps({"recorded": True, "call_cost_usd": round(actual, 6), "savings_usd": round(savings, 6)}, indent=2))
360
+ return 0
361
+
362
+
363
+ def _op_accept(repo: Path, sd: Path, st: Dict[str, Any], args: Any) -> int:
364
+ tid = args.task_id
365
+ if not tid:
366
+ cands = [x for x in st["tasks"].values() if x["status"] in ("handed_off", "queued", "blocked")]
367
+ if not cands:
368
+ raise SystemExit("No handed_off, queued, or blocked task available to accept.")
369
+ cands.sort(key=lambda x: x.get("updated_at", ""), reverse=True)
370
+ tid = cands[0]["id"]
371
+ _validate_task_id(tid)
372
+ if tid not in st["tasks"]:
373
+ raise SystemExit(f"Unknown task ID: {tid}")
374
+ t = st["tasks"][tid]
375
+ if t["status"] not in ("handed_off", "queued", "blocked"):
376
+ raise SystemExit(f"Cannot accept task '{tid}' with status '{t['status']}' (expected handed_off, queued, or blocked).")
377
+ conflicts = _check_ownership_conflicts(st, tid, t.get("owned_files", []))
378
+ if conflicts:
379
+ raise SystemExit(f"Cannot accept task due to file ownership conflicts: {json.dumps(conflicts)}")
380
+ now = now_iso()
381
+ if t.get("owner_history"):
382
+ t["owner_history"][-1].setdefault("ended_at", now)
383
+ if args.tier:
384
+ if args.tier != t["model_tier"]:
385
+ st["telemetry"]["model_switches"] += 1
386
+ t["model_tier"] = args.tier
387
+ t["model_alias"] = args.model_alias or TIER_TO_ALIAS[args.tier]
388
+ elif args.model_alias:
389
+ t["model_alias"] = args.model_alias
390
+ t["owner"], t["status"], t["updated_at"] = sanitize_inline(args.owner), "in_progress", now
391
+ t["owner_history"].append({"agent": t["owner"], "model_alias": t["model_alias"], "started_at": now})
392
+ t["progress_log"].append({"at": now, "agent": t["owner"], "note": f"Accepted task ownership ({t['model_tier']}/{t['model_alias']})."})
393
+ st["active_task"] = tid
394
+ save_state(sd, st)
395
+ b = build_brief(repo, st, task_id=tid)
396
+ needs_human = bool(t.get("human_approval_required") or t["model_tier"] == "critical")
397
+ print(json.dumps({
398
+ "task_id": tid, "status": "in_progress", "owner": t["owner"],
399
+ "model_tier": t["model_tier"], "model_alias": t["model_alias"],
400
+ "human_approval_required": needs_human,
401
+ "drifted_files": b["drifted_files"], "git_head_drifted": b["git_head_drifted"],
402
+ }, indent=2))
403
+ return 0
404
+
405
+
406
+ def _op_block(sd: Path, st: Dict[str, Any], tid: str, t: Dict[str, Any], args: Any) -> int:
407
+ rc, red = redact_secrets(args.reason)
408
+ now = now_iso()
409
+ bid = f"B-{len(st['blockers']) + 1:03d}"
410
+ st["blockers"].append({"id": bid, "task_id": tid, "description": rc, "status": "open", "created_at": now, "resolved_at": None, "resolution": None})
411
+ t["status"], t["updated_at"] = "blocked", now
412
+ t["progress_log"].append({"at": now, "agent": t["owner"], "note": f"Blocked ({bid}): {rc}"})
413
+ if st["active_task"] == tid:
414
+ _promote_next_active(st)
415
+ save_state(sd, st)
416
+ print(json.dumps({"task_id": tid, "status": "blocked", "blocker_id": bid, "secrets_redacted": red}, indent=2))
417
+ return 0
418
+
419
+
420
+ def _op_cancel(sd: Path, st: Dict[str, Any], tid: str, t: Dict[str, Any], args: Any) -> int:
421
+ rc, red = redact_secrets(args.reason)
422
+ now = now_iso()
423
+ t["status"], t["result"], t["completed_at"], t["updated_at"] = "cancelled", rc, now, now
424
+ t["progress_log"].append({"at": now, "agent": t["owner"], "note": f"Cancelled: {rc}"})
425
+ if st["active_task"] == tid:
426
+ _promote_next_active(st)
427
+ save_state(sd, st)
428
+ print(json.dumps({"task_id": tid, "status": "cancelled", "secrets_redacted": red}, indent=2))
429
+ return 0
430
+
431
+
432
+ def _op_update(sd: Path, st: Dict[str, Any], tid: str, t: Dict[str, Any], args: Any) -> int:
433
+ nc, r1 = redact_secrets(args.next)
434
+ notes_c, r2 = redact_secrets(args.notes)
435
+ t["next"] = nc
436
+ nf = _parse_rel_paths(args.files)
437
+ if nf:
438
+ t["files_touched"] = sorted(set(t["files_touched"] + nf))
439
+ t["files"] = t["files_touched"]
440
+ of = _parse_rel_paths(args.own_files)
441
+ if of:
442
+ conflicts = _check_ownership_conflicts(st, tid, of)
443
+ if conflicts:
444
+ raise SystemExit(f"File ownership conflict: {json.dumps(conflicts)}")
445
+ t["owned_files"] = sorted(set(t["owned_files"] + of))
446
+ if args.tests:
447
+ t["tests"].append(redact_secrets(args.tests)[0])
448
+ if notes_c:
449
+ t["progress_log"] = (t["progress_log"] + [{"at": now_iso(), "agent": t["owner"], "note": notes_c}])[-25:]
450
+ if args.tier and args.tier != t["model_tier"]:
451
+ t["routing_history"].append({"at": now_iso(), "from_tier": t["model_tier"], "to_tier": args.tier, "action": "update", "task": nc[:100], "reasons": ["explicit update"]})
452
+ t["model_tier"], t["model_alias"] = args.tier, TIER_TO_ALIAS[args.tier]
453
+ if args.tier == "critical":
454
+ t["human_approval_required"] = True
455
+ st["telemetry"]["model_switches"] += 1
456
+ if args.failure:
457
+ t["failures_count"] = int(t.get("failures_count", 0)) + 1
458
+ if args.reset_failures:
459
+ t["failures_count"] = 0
460
+ t["updated_at"] = now_iso()
461
+ save_state(sd, st)
462
+ print(json.dumps({"task_id": tid, "command": "update", "failures_count": t["failures_count"], "secrets_redacted": r1 or r2, "state_dir": str(sd)}, indent=2))
463
+ return 0
464
+
465
+
466
+ def _op_record_inspection(repo: Path, sd: Path, st: Dict[str, Any], tid: str, t: Dict[str, Any], args: Any) -> int:
467
+ rel = normalize_rel_path(args.path)
468
+ sha = _file_sha12(repo, rel)
469
+ if sha is None:
470
+ raise SystemExit(f"Cannot inspect missing, symlinked, sensitive, or oversized path: {rel}")
471
+ fc, red = redact_secrets(args.finding)
472
+ ln_clean = sanitize_inline(args.lines)
473
+ now = now_iso()
474
+ prev = t["files_inspected"].get(rel)
475
+ if prev and prev.get("sha") == sha:
476
+ entries = list(prev.get("entries") or [{"lines": prev.get("lines", ""), "finding": prev.get("finding", ""), "inspected_at": prev.get("inspected_at", now), "agent": prev.get("agent", t["owner"])}])
477
+ entries = [e for e in entries if e.get("lines") != ln_clean or not ln_clean]
478
+ entries.append({"lines": ln_clean, "finding": fc, "inspected_at": now, "agent": t["owner"]})
479
+ entries = entries[-8:]
480
+ comb_lines = ", ".join(e["lines"] for e in entries if e.get("lines"))
481
+ comb_finding = " | ".join(f"(L{e['lines']}) {e['finding']}" if e.get("lines") else e["finding"] for e in entries)
482
+ t["files_inspected"][rel] = {"lines": comb_lines, "finding": comb_finding, "sha": sha, "inspected_at": now, "agent": t["owner"], "entries": entries}
483
+ else:
484
+ t["files_inspected"][rel] = {
485
+ "lines": ln_clean, "finding": fc, "sha": sha, "inspected_at": now, "agent": t["owner"],
486
+ "entries": [{"lines": ln_clean, "finding": fc, "inspected_at": now, "agent": t["owner"]}],
487
+ }
488
+ t["updated_at"] = now
489
+ save_state(sd, st)
490
+ print(json.dumps({"task_id": tid, "inspected": rel, "sha": sha, "entries_count": len(t["files_inspected"][rel]["entries"]), "secrets_redacted": red}, indent=2))
491
+ return 0
492
+
493
+
494
+ def _op_record_attempt(sd: Path, st: Dict[str, Any], tid: str, t: Dict[str, Any], args: Any) -> int:
495
+ ac, r1 = redact_secrets(args.approach)
496
+ rc, r2 = redact_secrets(args.reason)
497
+ t["attempted_approaches"].append({"approach": ac, "outcome": args.outcome, "reason": rc, "agent": t["owner"], "at": now_iso()})
498
+ if args.outcome == "failed":
499
+ t["failures_count"] = int(t.get("failures_count", 0)) + 1
500
+ t["updated_at"] = now_iso()
501
+ save_state(sd, st)
502
+ print(json.dumps({"task_id": tid, "outcome": args.outcome, "failures_count": t["failures_count"], "secrets_redacted": r1 or r2}, indent=2))
503
+ return 0
504
+
505
+
506
+ def _op_record_check(repo: Path, sd: Path, st: Dict[str, Any], tid: str, t: Dict[str, Any], args: Any) -> int:
507
+ cc, r1 = redact_secrets(args.check_cmd)
508
+ sc, r2 = redact_secrets(args.summary)
509
+ chk = {"cmd": cc, "exit_code": args.exit_code, "summary": sc, "git_head": _git_snapshot(repo).get("head", "nogit"), "at": now_iso(), "agent": t["owner"]}
510
+ t["verified_checks"].append(chk)
511
+ t["tests"].append(f"{cc} (exit {args.exit_code})")
512
+ t["failures_count"] = 0 if args.exit_code == 0 else int(t.get("failures_count", 0)) + 1
513
+ t["updated_at"] = now_iso()
514
+ save_state(sd, st)
515
+ print(json.dumps({"task_id": tid, "check": chk, "secrets_redacted": r1 or r2}, indent=2))
516
+ return 0
517
+
518
+
519
+ def _op_complete(sd: Path, st: Dict[str, Any], tid: str, t: Dict[str, Any], args: Any) -> int:
520
+ rc, red = redact_secrets(args.result)
521
+ t["status"], t["result"], t["completed_at"] = "completed", rc, now_iso()
522
+ t["updated_at"] = t["completed_at"]
523
+ if st["active_task"] == tid:
524
+ _promote_next_active(st)
525
+ ho_json = sd / "handoff.json"
526
+ if ho_json.is_file() and not ho_json.is_symlink():
527
+ try:
528
+ hj = json.loads(ho_json.read_text(encoding="utf-8"))
529
+ if hj.get("task_id") == tid:
530
+ atomic_write_text(sd / "HANDOFF.md", f"# Agent Handoff\n\nNo active handoff (task `{tid}` completed at {t['completed_at']}).\n")
531
+ except Exception:
532
+ pass
533
+ save_state(sd, st)
534
+ print(json.dumps({"task_id": tid, "command": "complete", "secrets_redacted": red, "state_dir": str(sd)}, indent=2))
535
+ return 0
536
+
537
+
538
+ def _op_handoff(repo: Path, sd: Path, st: Dict[str, Any], tid: str, t: Dict[str, Any], args: Any) -> int:
539
+ sc, r1 = redact_secrets(args.summary)
540
+ nc, r2 = redact_secrets(args.next)
541
+ wc, r3 = redact_secrets(args.warnings)
542
+ tc, r4 = redact_secrets(args.tests)
543
+ now = now_iso()
544
+ touched = sorted(set(t["files_touched"] + ([] if args.files == "Not recorded" else _parse_rel_paths(args.files))))
545
+ t["files_touched"] = t["files"] = touched
546
+ t["status"], t["next"], t["handoff_count"], t["updated_at"] = "handed_off", nc, int(t.get("handoff_count", 0)) + 1, now
547
+ if t.get("owner_history"):
548
+ t["owner_history"][-1]["ended_at"] = now
549
+ rel_decs = _relevant_decisions(st, touched)
550
+ open_b = [b for b in st["blockers"] if b["status"] == "open" and b.get("task_id") in (None, tid)]
551
+ failed = [a for a in t["attempted_approaches"] if a["outcome"] in ("failed", "rejected")]
552
+ handoff_data = {
553
+ "schema_version": SCHEMA_VERSION, "task_id": tid, "handoff_number": t["handoff_count"],
554
+ "recipient": sanitize_inline(args.recipient), "previous_owner": t["owner"],
555
+ "model_tier": t["model_tier"], "model_alias": t["model_alias"], "failures_count": t["failures_count"],
556
+ "prepared_at": now, "objective": t["objective"], "criteria": t["criteria"],
557
+ "summary": sc, "next": nc, "warnings": wc,
558
+ "entry_points": [sanitize_inline(x) for x in args.entry_points.split(",") if x.strip()],
559
+ "files_touched": touched, "owned_files": t["owned_files"], "files_inspected": t["files_inspected"],
560
+ "failed_approaches": failed, "verified_checks": t["verified_checks"][-5:],
561
+ "relevant_decisions": [{"id": d["id"], "title": d["title"], "rationale": d["rationale"]} for d in rel_decs],
562
+ "open_blockers": open_b, "git_snapshot": _git_snapshot(repo),
563
+ "index_snapshot": _index_summary_for_files(repo, touched), "cache_snapshot": _cache_summary(repo, sd),
564
+ }
565
+ tests_disp = tc if args.tests != "Not recorded" else ("; ".join(t["tests"][-5:]) or "Not recorded")
566
+ handoff_md = render_handoff_markdown(t, handoff_data, rel_decs, open_b, tests_disp)
567
+ arch_dir = sd / "handoffs"
568
+ arch_dir.mkdir(exist_ok=True)
569
+ arch_md, arch_json = (arch_dir / f"{tid}-{t['handoff_count']}.md").resolve(), (arch_dir / f"{tid}.json").resolve()
570
+ if not is_within(arch_md, arch_dir) or not is_within(arch_json, arch_dir):
571
+ raise SystemExit("Handoff archive path escaped handoffs directory.")
572
+ atomic_write_text(sd / "HANDOFF.md", handoff_md)
573
+ atomic_write_json(sd / "handoff.json", handoff_data)
574
+ atomic_write_text(arch_md, handoff_md)
575
+ atomic_write_json(arch_json, handoff_data)
576
+ if st["active_task"] == tid:
577
+ _promote_next_active(st)
578
+ save_state(sd, st)
579
+ print(json.dumps({"task_id": tid, "command": "handoff", "handoff_number": t["handoff_count"], "handoff_tokens_est": estimate_tokens(handoff_md), "secrets_redacted": r1 or r2 or r3 or r4, "state_dir": str(sd)}, indent=2))
580
+ return 0