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,428 @@
1
+ """Markdown renderers, section-prioritized zero-reexploration brief builder, and handoff formatting for agent_state.py."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import sqlite3
6
+ import time
7
+ from pathlib import Path
8
+ from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple
9
+
10
+ from _ae_core import atomic_write_text, estimate_tokens, is_within, sources_fresh
11
+
12
+
13
+ def index_summary_for_files(repo: Path, files: Sequence[str]) -> Dict[str, Any]:
14
+ db_path = repo / ".agent-index" / "index.sqlite3"
15
+ if db_path.is_symlink() or not db_path.is_file() or not is_within(db_path, repo):
16
+ return {"indexed": False}
17
+ try:
18
+ db = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True)
19
+ db.execute("PRAGMA trusted_schema=OFF")
20
+ db.execute("PRAGMA query_only=ON")
21
+ fc = db.execute("SELECT COUNT(*) FROM files").fetchone()[0]
22
+ sc = db.execute("SELECT COUNT(*) FROM symbols").fetchone()[0]
23
+ file_syms: Dict[str, List[str]] = {}
24
+ for rel in files[:10]:
25
+ rows = db.execute("SELECT name, line, end_line FROM symbols WHERE path=? ORDER BY line LIMIT 8", (rel,)).fetchall()
26
+ if rows:
27
+ file_syms[rel] = [f"{r[0]}:L{r[1]}-{r[2]}" for r in rows]
28
+ db.close()
29
+ return {"indexed": True, "indexed_files": fc, "symbols": sc, "touched_file_symbols": file_syms}
30
+ except Exception:
31
+ return {"indexed": False}
32
+
33
+
34
+ def cache_summary(repo: Path, state_dir: Path) -> Optional[Dict[str, Any]]:
35
+ cf = state_dir / "cache_registry.json"
36
+ if cf.is_symlink() or not cf.is_file():
37
+ return None
38
+ try:
39
+ reg = json.loads(cf.read_text(encoding="utf-8"))
40
+ now_ts = time.time()
41
+ warm = []
42
+ for pname, entry in reg.get("prefixes", {}).items():
43
+ cur_pid = entry.get("prefix_id")
44
+ if entry.get("source_files") and not sources_fresh(repo, entry["source_files"]):
45
+ continue
46
+ for skey, s in entry.get("sessions", {}).items():
47
+ exp = s.get("expires_at")
48
+ id_ok = not s.get("prefix_id") or s.get("prefix_id") == cur_pid
49
+ if exp and exp > now_ts and id_ok:
50
+ warm.append(
51
+ {
52
+ "name": pname, "prefix_id": cur_pid, "session": skey,
53
+ "tier": s.get("tier"), "tokens": int(entry.get("combined_tokens_est", 0)),
54
+ "ttl_remaining_s": int(exp - now_ts),
55
+ }
56
+ )
57
+ warm.sort(key=lambda x: (-x["tokens"], -x["ttl_remaining_s"]))
58
+ return {"warm_prefixes": warm, "registered_prefixes": sorted(reg.get("prefixes", {}).keys())}
59
+ except Exception:
60
+ return None
61
+
62
+
63
+ def relevant_decisions(st: Dict[str, Any], files: Sequence[str]) -> List[Dict[str, Any]]:
64
+ fset = set(files)
65
+ active = [d for d in st.get("decisions", []) if d["status"] == "active"]
66
+ if not fset:
67
+ return active[-8:]
68
+ return [d for d in active if not d.get("scope_files") or fset.intersection(d["scope_files"])][-10:]
69
+
70
+
71
+ def render_current_state(state_dir: Path, st: Dict[str, Any]) -> None:
72
+ tid = st.get("active_task")
73
+ lines: List[str] = ["# Current State", ""]
74
+ if not tid or tid not in st["tasks"]:
75
+ pending = [t for t in st["tasks"].values() if t["status"] in ("in_progress", "handed_off", "queued", "blocked")]
76
+ lines.append("No active task.")
77
+ if pending:
78
+ lines.extend(["", "## Active / Pending Tasks"])
79
+ for t in pending[:8]:
80
+ lines.append(f"- `{t['id']}` [{t['status']}] ({t['model_tier']}/{t['model_alias']}): {t['objective']}")
81
+ else:
82
+ t = st["tasks"][tid]
83
+ gate = " | **HUMAN APPROVAL REQUIRED**" if (t.get("human_approval_required") or t["model_tier"] == "critical") else ""
84
+ lines.extend(
85
+ [
86
+ f"- Task: `{t['id']}` | Status: **{t['status']}** | Priority: `{t['priority']}`",
87
+ f"- Owner: `{t['owner']}` | Model Tier: `{t['model_tier']}` (`{t['model_alias']}`) | Failures: `{t['failures_count']}`{gate}",
88
+ f"- Updated: {t['updated_at']}",
89
+ "", "## Objective", t["objective"],
90
+ "", "## Acceptance Criteria", t["criteria"],
91
+ "", "## Next Action", t["next"],
92
+ ]
93
+ )
94
+ if t.get("owned_files"):
95
+ lines.extend(["", "## Owned Files", ", ".join(f"`{f}`" for f in t["owned_files"])])
96
+ if t.get("files_touched"):
97
+ lines.extend(["", "## Files Touched", ", ".join(f"`{f}`" for f in t["files_touched"])])
98
+ other_active = [ot for oid, ot in st["tasks"].items() if oid != tid and ot["status"] == "in_progress"]
99
+ if other_active:
100
+ lines.extend(["", "## Other Parallel Active Tasks"])
101
+ for ot in other_active[:6]:
102
+ lines.append(f"- `{ot['id']}` (owner: `{ot['owner']}`, files: {', '.join(ot.get('owned_files', [])) or 'none'}): {ot['objective']}")
103
+ open_b = [b for b in st.get("blockers", []) if b["status"] == "open" and b.get("task_id") in (None, tid)]
104
+ if open_b:
105
+ lines.extend(["", "## Open Blockers", *[f"- `{b['id']}`: {b['description']}" for b in open_b]])
106
+ if t.get("progress_log"):
107
+ lines.extend(["", "## Recent Progress", *[f"- [{e['at']}] ({e['agent']}): {e['note']}" for e in t["progress_log"][-6:]]])
108
+ atomic_write_text(state_dir / "CURRENT_STATE.md", "\n".join(lines).rstrip() + "\n")
109
+
110
+
111
+ def render_task_queue(state_dir: Path, st: Dict[str, Any]) -> None:
112
+ lines = ["# Task Queue", ""]
113
+ active_list = [t for t in st["tasks"].values() if t["status"] not in ("completed", "cancelled")]
114
+ if not active_list:
115
+ lines.append("No active or queued tasks.")
116
+ else:
117
+ lines.extend(["| ID | Status | Priority | Tier | Owner | Objective |", "|---|---|---|---|---|---|"])
118
+ order = {"in_progress": 0, "handed_off": 1, "blocked": 2, "queued": 3, "cancelled": 4}
119
+ for t in sorted(active_list, key=lambda x: (order.get(x["status"], 9), x["created_at"])):
120
+ obj = t["objective"].replace("|", "/").replace("\n", " ")[:100]
121
+ lines.append(f"| `{t['id']}` | {t['status']} | {t['priority']} | `{t['model_tier']}` | {t['owner']} | {obj} |")
122
+ atomic_write_text(state_dir / "TASK_QUEUE.md", "\n".join(lines).rstrip() + "\n")
123
+
124
+
125
+ def render_decisions(state_dir: Path, st: Dict[str, Any]) -> None:
126
+ active = [d for d in st.get("decisions", []) if d["status"] == "active"]
127
+ archived = [d for d in st.get("decisions", []) if d["status"] != "active"]
128
+ lines = ["# Architectural & Project Decisions", ""]
129
+ if not active:
130
+ lines.append("No active decisions recorded.")
131
+ else:
132
+ for d in active:
133
+ scope = f" | Scope: {', '.join(f'`{f}`' for f in d['scope_files'])}" if d.get("scope_files") else ""
134
+ lines.extend([f"## {d['id']}: {d['title']}", f"- Status: active{scope}", f"- Rationale: {d['rationale']}"])
135
+ if d.get("alternatives_rejected"):
136
+ lines.append(f"- Rejected alternatives: {d['alternatives_rejected']}")
137
+ lines.append("")
138
+ if archived:
139
+ lines.extend(["## Superseded / Archived Decisions", ""])
140
+ for d in archived:
141
+ sup = f" (superseded by `{d['superseded_by']}`)" if d.get("superseded_by") else ""
142
+ lines.append(f"- `{d['id']}` [{d['status']}{sup}]: {d['title']}")
143
+ atomic_write_text(state_dir / "DECISIONS.md", "\n".join(lines).rstrip() + "\n")
144
+
145
+
146
+ def render_blockers(state_dir: Path, st: Dict[str, Any]) -> None:
147
+ open_b = [b for b in st.get("blockers", []) if b["status"] == "open"]
148
+ closed_b = [b for b in st.get("blockers", []) if b["status"] != "open"]
149
+ lines = ["# Blockers", ""]
150
+ if not open_b:
151
+ lines.append("None open.")
152
+ else:
153
+ lines.append("## Open")
154
+ for b in open_b:
155
+ tref = f" (`{b['task_id']}`)" if b.get("task_id") else ""
156
+ lines.append(f"- `{b['id']}`{tref}: {b['description']} _(recorded {b['created_at']})_")
157
+ if closed_b:
158
+ lines.extend(["", "## Resolved"])
159
+ for b in closed_b[-15:]:
160
+ lines.append(f"- `{b['id']}`: {b['description']} -> {b.get('resolution', 'resolved')}")
161
+ atomic_write_text(state_dir / "BLOCKERS.md", "\n".join(lines).rstrip() + "\n")
162
+
163
+
164
+ def render_completed(state_dir: Path, st: Dict[str, Any]) -> None:
165
+ done = [t for t in st["tasks"].values() if t["status"] in ("completed", "cancelled")]
166
+ lines = ["# Completed Work", ""]
167
+ if not done:
168
+ lines.append("No completed tasks yet.")
169
+ else:
170
+ for t in sorted(done, key=lambda x: x.get("completed_at") or x["updated_at"], reverse=True):
171
+ tag = " [CANCELLED]" if t["status"] == "cancelled" else ""
172
+ lines.extend([
173
+ f"## {t['id']}{tag} — {t['objective']}",
174
+ f"- Completed: {t.get('completed_at', t['updated_at'])} | Owner: {t['owner']} | Tier: `{t['model_tier']}`",
175
+ f"- Result: {t.get('result', '')}",
176
+ ])
177
+ if t.get("files_touched"):
178
+ lines.append(f"- Files: {', '.join(f'`{f}`' for f in t['files_touched'])}")
179
+ if t.get("verified_checks"):
180
+ lc = t["verified_checks"][-1]
181
+ lines.append(f"- Last check: `{lc['cmd']}` (exit {lc['exit_code']})")
182
+ lines.append("")
183
+ atomic_write_text(state_dir / "COMPLETED.md", "\n".join(lines).rstrip() + "\n")
184
+
185
+
186
+ def render_checkpoint_markdown(state_dir: Path, cp: Dict[str, Any]) -> None:
187
+ lines = [
188
+ "# Auto Checkpoint", "",
189
+ f"- Recorded: {cp.get('at', '')}",
190
+ f"- Task: `{cp.get('task_id') or 'none'}`",
191
+ ]
192
+ gs = cp.get("git_snapshot") or {}
193
+ if gs.get("is_git"):
194
+ lines.append(f"- Git: `{gs.get('branch')}` @ `{gs.get('head')}` ({gs.get('dirty_count', 0)} dirty)")
195
+ if cp.get("note"):
196
+ lines.extend(["", "## Note", cp["note"]])
197
+ if cp.get("dirty_paths"):
198
+ lines.extend(["", "## Modified Files", ", ".join(f"`{p}`" for p in cp["dirty_paths"][:20])])
199
+ if cp.get("touched_symbols"):
200
+ lines.extend(["", "## Modified File Symbols", *[f"- `{p}`: {', '.join(syms)}" for p, syms in cp["touched_symbols"].items()]])
201
+ if gs.get("diff_stat"):
202
+ lines.extend(["", "## Diff Stat", "```text", gs["diff_stat"], "```"])
203
+ if cp.get("last_check"):
204
+ lc = cp["last_check"]
205
+ lines.extend(["", "## Last Check", f"- `{lc['cmd']}` -> exit `{lc['exit_code']}` ({lc.get('summary', '')})"])
206
+ atomic_write_text(state_dir / "CHECKPOINT.md", "\n".join(lines).rstrip() + "\n")
207
+
208
+
209
+ def render_all(state_dir: Path, st: Dict[str, Any]) -> None:
210
+ render_current_state(state_dir, st)
211
+ render_task_queue(state_dir, st)
212
+ render_decisions(state_dir, st)
213
+ render_blockers(state_dir, st)
214
+ render_completed(state_dir, st)
215
+ if st.get("last_checkpoint"):
216
+ render_checkpoint_markdown(state_dir, st["last_checkpoint"])
217
+
218
+
219
+ def render_handoff_markdown(
220
+ t: Dict[str, Any],
221
+ handoff_data: Dict[str, Any],
222
+ rel_decs: Sequence[Dict[str, Any]],
223
+ open_blockers: Sequence[Dict[str, Any]],
224
+ tests_display: str,
225
+ ) -> str:
226
+ tid = handoff_data["task_id"]
227
+ git_snap = handoff_data["git_snapshot"]
228
+ idx_snap = handoff_data["index_snapshot"]
229
+ cache_snap = handoff_data["cache_snapshot"]
230
+ lines = [
231
+ "# Agent Handoff", "",
232
+ f"- Task: `{tid}` (Handoff #{handoff_data['handoff_number']})",
233
+ f"- Recipient: `{handoff_data['recipient']}` | Previous owner: `{t['owner']}`",
234
+ f"- Model Tier: `{t['model_tier']}` (`{t['model_alias']}`) | Failures: `{t['failures_count']}`",
235
+ f"- Prepared: {handoff_data['prepared_at']}",
236
+ ]
237
+ if git_snap.get("is_git"):
238
+ lines.append(f"- Git Snapshot: `{git_snap.get('branch')}` @ `{git_snap.get('head')}` ({git_snap.get('dirty_count', 0)} dirty)")
239
+ if cache_snap and cache_snap["warm_prefixes"]:
240
+ wp = cache_snap["warm_prefixes"][0]
241
+ lines.append(f"- Reusable Cached Prefix: `{wp['name']}` (`{wp['prefix_id']}`, ~{wp['tokens']} tok, tier `{wp['tier']}`)")
242
+
243
+ lines.extend(["", "## Objective", t["objective"], "", "## Progress Summary", handoff_data["summary"], "", "## Acceptance Criteria", t["criteria"]])
244
+ if handoff_data["entry_points"]:
245
+ lines.extend(["", "## Exact Entry Points (Start Here — Do Not Rescan Repo)", *[f"- `{ep}`" for ep in handoff_data["entry_points"]]])
246
+ lines.extend(["", "## Files Touched", ", ".join(f"`{f}`" for f in handoff_data["files_touched"]) or "Not recorded"])
247
+ if idx_snap.get("touched_file_symbols"):
248
+ lines.extend(["", "## Key Symbols in Touched Files", *[f"- `{p}`: {', '.join(s)}" for p, s in idx_snap["touched_file_symbols"].items()]])
249
+ if t["files_inspected"]:
250
+ lines.append("\n## Already Inspected (With Disk SHA — Skip Re-Reading Unless Drifted)")
251
+ for rel, info in sorted(t["files_inspected"].items()):
252
+ ln = f" L{info['lines']}" if info.get("lines") else ""
253
+ lines.append(f"- `{rel}`{ln} (`{info.get('sha', '?')}`): {info['finding']}")
254
+ if handoff_data["failed_approaches"]:
255
+ lines.extend(["", "## Failed / Rejected Approaches (Do NOT Repeat)", *[f"- **{fa['approach']}** [{fa['outcome']}]: {fa['reason']}" for fa in handoff_data["failed_approaches"][-6:]]])
256
+ lines.extend(["", "## Tests / Checks Actually Run", tests_display])
257
+ if rel_decs:
258
+ lines.extend(["", "## Active Decisions in Scope", *[f"- **{d['id']} {d['title']}**: {d['rationale']}" for d in rel_decs[-6:]]])
259
+ lines.extend(["", "## Warnings / Blockers", handoff_data["warnings"], *[f"- Open blocker `{b['id']}`: {b['description']}" for b in open_blockers]])
260
+ lines.extend([
261
+ "", "## Next Action", handoff_data["next"], "",
262
+ "## Receiving-Agent Protocol (Zero-Reexploration)",
263
+ "1. Run `python3 <skill-dir>/scripts/agent_state.py brief <repo>` (checks workspace SHA drift in 1 call).",
264
+ f"2. Run `python3 <skill-dir>/scripts/agent_state.py accept <repo> --task-id {tid} --owner <your-id>`.",
265
+ "3. Inspect only `context_index.py changed <repo>` and `slice` the exact entry points above (supports `path:start-end`).",
266
+ "4. Reuse registered prompt prefix from `.agent-state/cache_registry.json` if staying on the same tier.",
267
+ "5. Verify target tests directly before claiming pass.",
268
+ ])
269
+ return "\n".join(lines).rstrip() + "\n"
270
+
271
+
272
+ def build_brief_dossier(
273
+ repo: Path,
274
+ state_dir: Path,
275
+ st: Dict[str, Any],
276
+ tid: Optional[str],
277
+ max_tokens: int,
278
+ git_snapshot_fn: Callable[[Path], Dict[str, Any]],
279
+ file_sha12_fn: Callable[[Path, str], Optional[str]],
280
+ ) -> Dict[str, Any]:
281
+ if not tid:
282
+ cands = [t for t in st["tasks"].values() if t["status"] in ("handed_off", "in_progress", "blocked", "queued")]
283
+ if cands:
284
+ cands.sort(key=lambda x: x.get("updated_at", ""), reverse=True)
285
+ tid = cands[0]["id"]
286
+ if not tid or tid not in st["tasks"]:
287
+ cp = st.get("last_checkpoint")
288
+ if cp:
289
+ cp_lines = [
290
+ "# Agent Brief (From Auto-Checkpoint)", "",
291
+ f"- **Checkpoint At**: {cp.get('at', '')}",
292
+ ]
293
+ if cp.get("note"):
294
+ cp_lines.append(f"- **Note**: {cp['note']}")
295
+ if cp.get("dirty_paths"):
296
+ cp_lines.append("- **Modified Files**: " + ", ".join(f"`{p}`" for p in cp["dirty_paths"][:15]))
297
+ if cp.get("touched_symbols"):
298
+ cp_lines.extend(["", "## Modified File Symbols", *[f"- `{p}`: {', '.join(s)}" for p, s in cp["touched_symbols"].items()]])
299
+ if cp.get("last_check"):
300
+ lc = cp["last_check"]
301
+ cp_lines.append(f"\n- **Last Check**: `{lc['cmd']}` -> exit `{lc['exit_code']}`")
302
+ md_cp = "\n".join(cp_lines).rstrip() + "\n"
303
+ return {"has_task": False, "has_checkpoint": True, "tokens_est": estimate_tokens(md_cp), "markdown": md_cp}
304
+ return {"has_task": False, "has_checkpoint": False, "markdown": "# Agent Brief\n\nNo active or handed-off task found.\n"}
305
+
306
+ t = st["tasks"][tid]
307
+ last_handoff: Optional[Dict[str, Any]] = None
308
+ for cand in (state_dir / "handoffs" / f"{tid}.json", state_dir / "handoff.json"):
309
+ if cand.is_file() and not cand.is_symlink():
310
+ try:
311
+ hj = json.loads(cand.read_text(encoding="utf-8"))
312
+ if hj.get("task_id") == tid:
313
+ last_handoff = hj
314
+ break
315
+ except Exception:
316
+ continue
317
+
318
+ live_git = git_snapshot_fn(repo)
319
+ drifted_files: List[Dict[str, str]] = []
320
+ unchanged: List[Dict[str, Any]] = []
321
+ for rel, info in sorted(t.get("files_inspected", {}).items()):
322
+ cur_sha = file_sha12_fn(repo, rel)
323
+ old_sha = info.get("sha")
324
+ if cur_sha is None:
325
+ drifted_files.append({"path": rel, "status": "deleted_or_unreadable_since_inspection"})
326
+ elif old_sha and cur_sha != old_sha:
327
+ drifted_files.append({"path": rel, "status": "modified_since_inspection"})
328
+ else:
329
+ unchanged.append({"path": rel, "lines": info.get("lines", ""), "finding": info.get("finding", "")})
330
+
331
+ git_head_drifted = bool(
332
+ last_handoff and last_handoff.get("git_snapshot", {}).get("head") and live_git.get("head")
333
+ and last_handoff["git_snapshot"]["head"] != live_git["head"]
334
+ )
335
+ rel_decs = relevant_decisions(st, t.get("files_touched", []))
336
+ open_b = [b for b in st.get("blockers", []) if b["status"] == "open" and b.get("task_id") in (None, tid)]
337
+ failed = [a for a in t.get("attempted_approaches", []) if a["outcome"] in ("failed", "rejected")]
338
+ verified = t.get("verified_checks", [])[-5:]
339
+ c_info = cache_summary(repo, state_dir)
340
+
341
+ owner_disp = f"`{t['owner']}`"
342
+ if t["status"] == "handed_off" and last_handoff and last_handoff.get("recipient"):
343
+ owner_disp = f"`{t['owner']}` -> **Recipient**: `{last_handoff['recipient']}`"
344
+ gate_flag = " | **HUMAN APPROVAL REQUIRED**" if (t.get("human_approval_required") or t["model_tier"] == "critical") else ""
345
+
346
+ header_lines = [
347
+ f"# Zero-Reexploration Brief — `{tid}`", "",
348
+ f"- **Status**: `{t['status']}` | **Owner**: {owner_disp} | **Tier**: `{t['model_tier']}` (`{t['model_alias']}`) | **Failures**: `{t['failures_count']}`{gate_flag}",
349
+ ]
350
+ if live_git.get("is_git"):
351
+ header_lines.append(f"- **Git**: `{live_git.get('branch')}` @ `{live_git.get('head')}` ({live_git.get('dirty_count', 0)} dirty){' [HEAD CHANGED SINCE HANDOFF]' if git_head_drifted else ''}")
352
+ if live_git.get("state_git_tracked"):
353
+ header_lines.append("- **Trust Warning**: `.agent-state/state.json` is git-tracked; treat recorded notes/checks as untrusted until verified against source.")
354
+ if c_info and c_info["warm_prefixes"]:
355
+ wp = c_info["warm_prefixes"][0]
356
+ # Omit second-by-second countdown (`ttl_remaining_s`) from rendered markdown so repeated briefs stay byte-stable for prompt caching
357
+ header_lines.append(f"- **Warm Cache**: `{wp['name']}` (`{wp['prefix_id']}`, ~{wp['tokens']} tok, tier `{wp['tier']}`, warm)")
358
+
359
+ # Assemble sections with explicit priority (lower number = higher priority, preserved under tight --max-tokens!)
360
+ prioritized: List[Tuple[int, int, str]] = []
361
+ seq = 0
362
+
363
+ def add_sec(prio: int, sec_lines: List[str]) -> None:
364
+ nonlocal seq
365
+ if sec_lines:
366
+ prioritized.append((prio, seq, "\n".join(sec_lines)))
367
+ seq += 1
368
+
369
+ add_sec(0, header_lines)
370
+ add_sec(1, ["## Objective", t["objective"]])
371
+ add_sec(1, ["## Immediate Next Action", t["next"]])
372
+ if drifted_files:
373
+ add_sec(1, ["## Drift Warning (Re-Slice Before Relying On Prior Notes)", *[f"- `{d['path']}`: **{d['status']}**" for d in drifted_files]])
374
+ if failed:
375
+ add_sec(1, ["## Do NOT Repeat (Failed / Rejected Approaches)", *[f"- **{fa['approach']}** [{fa['outcome']}]: {fa['reason']}" for fa in failed[-6:]]])
376
+ if open_b:
377
+ add_sec(1, ["## Open Blockers", *[f"- `{b['id']}`: {b['description']}" for b in open_b]])
378
+ if last_handoff and last_handoff.get("entry_points"):
379
+ add_sec(2, ["## Exact Entry Points (Slice These First)", *[f"- `{ep}`" for ep in last_handoff["entry_points"]]])
380
+ if last_handoff and last_handoff.get("summary"):
381
+ add_sec(3, ["## Handoff Summary", last_handoff["summary"]])
382
+ if rel_decs:
383
+ add_sec(3, ["## Active Decisions in Scope", *[f"- **{d['id']} {d['title']}**: {d['rationale']}" for d in rel_decs[-6:]]])
384
+ add_sec(4, ["## Acceptance Criteria", t["criteria"]])
385
+ if t.get("files_touched"):
386
+ add_sec(4, ["## Files Touched", ", ".join(f"`{f}`" for f in t["files_touched"])])
387
+ if unchanged:
388
+ unchanged_lines = [
389
+ f"- `{i['path']}`" + (f" (L{i['lines']})" if i["lines"] else "") + f": {i['finding']}"
390
+ for i in unchanged[:10]
391
+ ]
392
+ add_sec(5, ["## Already Inspected (Verified Unchanged on Disk — Do Not Re-Read Full Files)", *unchanged_lines])
393
+ if verified:
394
+ add_sec(5, ["## Verified Checks (Actual Run Evidence)", *[f"- `{c['cmd']}` -> exit `{c['exit_code']}` ({c.get('summary', '')}) @ `{c.get('git_head', 'nogit')}`" for c in verified]])
395
+ cp = st.get("last_checkpoint")
396
+ if cp and (cp.get("task_id") in (None, tid)) and (cp.get("note") or cp.get("touched_symbols")):
397
+ cp_sec = ["## Latest Auto-Checkpoint", f"- Recorded: {cp.get('at', '')}"]
398
+ if cp.get("note"):
399
+ cp_sec.append(f"- Note: {cp['note']}")
400
+ for p, syms in list((cp.get("touched_symbols") or {}).items())[:6]:
401
+ cp_sec.append(f"- `{p}`: {', '.join(syms)}")
402
+ add_sec(4, cp_sec)
403
+
404
+ full_text = "\n\n".join(txt for _p, _s, txt in prioritized).rstrip() + "\n"
405
+ if estimate_tokens(full_text) <= max_tokens:
406
+ md_text = full_text
407
+ else:
408
+ # Select highest-priority sections first while fitting max_tokens, then re-order into original reading order
409
+ selected: List[Tuple[int, str]] = []
410
+ used = 0
411
+ for _prio, order_idx, txt in sorted(prioritized, key=lambda x: (x[0], x[1])):
412
+ t_est = estimate_tokens(txt + "\n\n")
413
+ if used + t_est <= max_tokens or _prio <= 1:
414
+ selected.append((order_idx, txt))
415
+ used += t_est
416
+ selected.sort(key=lambda x: x[0])
417
+ md_text = "\n\n".join(txt for _o, txt in selected).rstrip() + "\n"
418
+ if estimate_tokens(md_text) > max_tokens:
419
+ md_text = md_text[: max(120, max_tokens * 4 - 36)] + "\n... [brief capped to max_tokens]\n"
420
+
421
+ return {
422
+ "has_task": True, "task_id": tid, "status": t["status"],
423
+ "model_tier": t["model_tier"], "model_alias": t["model_alias"],
424
+ "human_approval_required": bool(t.get("human_approval_required", False) or t["model_tier"] == "critical"),
425
+ "drifted_files": drifted_files, "git_head_drifted": git_head_drifted,
426
+ "unchanged_inspected_count": len(unchanged), "failed_approaches_count": len(failed),
427
+ "tokens_est": estimate_tokens(md_text), "markdown": md_text,
428
+ }