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,440 @@
1
+ """Persistent state schema v2, atomic locked storage, git snapshot, SHA drift & ownership checks."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ import json
6
+ import os
7
+ import posixpath
8
+ import re
9
+ import stat
10
+ import sys
11
+ import time
12
+ from pathlib import Path
13
+ from typing import Any, Dict, List, Optional, Sequence, Tuple
14
+
15
+ from _ae_core import (
16
+ atomic_write_json,
17
+ atomic_write_text,
18
+ ensure_git_info_exclude,
19
+ estimate_tokens,
20
+ git_cmd,
21
+ is_secret_path,
22
+ is_within,
23
+ sanitize_inline,
24
+ )
25
+ from state_render import (
26
+ build_brief_dossier,
27
+ cache_summary as _cache_summary,
28
+ index_summary_for_files as _index_summary_for_files,
29
+ render_all,
30
+ )
31
+
32
+ SCHEMA_VERSION = 2
33
+ MAX_HASH_FILE_BYTES = 2_000_000
34
+ VALID_TASK_ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
35
+ TIER_TO_ALIAS = {"low": "fast", "medium": "balanced", "high": "reasoning", "critical": "reasoning"}
36
+
37
+
38
+ def now_iso() -> str:
39
+ return time.strftime("%Y-%m-%dT%H:%M:%S%z")
40
+
41
+
42
+ def normalize_rel_path(raw: str) -> str:
43
+ norm = raw.replace("\\", "/")
44
+ while norm.startswith("./"):
45
+ norm = norm[2:]
46
+ if norm.startswith("/"):
47
+ raise SystemExit(f"Expected repo-relative path, got absolute path: {raw!r}")
48
+ norm = posixpath.normpath(norm)
49
+ if norm in ("", ".") or norm == ".." or norm.startswith("../"):
50
+ raise SystemExit(f"Invalid repo-relative path: {raw!r}")
51
+ if is_secret_path(norm):
52
+ raise SystemExit(f"Refusing to record sensitive/secret file path in state: {norm}")
53
+ return norm
54
+
55
+
56
+ def _parse_rel_paths(csv_text: str) -> List[str]:
57
+ return sorted({normalize_rel_path(x.strip()) for x in csv_text.split(",") if x.strip()})
58
+
59
+
60
+ def _validate_task_id(tid: str) -> str:
61
+ if not VALID_TASK_ID_RE.fullmatch(tid):
62
+ raise SystemExit(f"Invalid task ID {tid!r}: must match ^[A-Za-z0-9_-]{{1,64}}$.")
63
+ return tid
64
+
65
+
66
+ def _safe_state_dir(repo: Path) -> Path:
67
+ repo_r = repo.resolve()
68
+ sd = repo_r / ".agent-state"
69
+ if sd.is_symlink() or (sd.exists() and not is_within(sd, repo_r)):
70
+ raise SystemExit("Refusing to use symlinked or out-of-repo .agent-state directory.")
71
+ return sd
72
+
73
+
74
+ def _read_state_json(sf: Path) -> Dict[str, Any]:
75
+ try:
76
+ data = json.loads(sf.read_text(encoding="utf-8"))
77
+ if not isinstance(data, dict):
78
+ raise SystemExit(f"Corrupted state file (expected JSON object): {sf}")
79
+ return data
80
+ except json.JSONDecodeError as exc:
81
+ raise SystemExit(f"Corrupted .agent-state/state.json ({exc}); inspect or restore before continuing.")
82
+
83
+
84
+ def _empty_telemetry() -> Dict[str, Any]:
85
+ return {
86
+ "calls": 0, "input_tokens": 0, "cached_input_tokens": 0, "cache_write_tokens": 0,
87
+ "output_tokens": 0, "estimated_cost_usd": 0.0,
88
+ "estimated_savings_vs_uncached_reasoning_usd": 0.0, "model_switches": 0, "by_tier": {},
89
+ }
90
+
91
+
92
+ def _empty_state(repo: Path) -> Dict[str, Any]:
93
+ return {
94
+ "schema_version": SCHEMA_VERSION,
95
+ "project": {"name": repo.name, "root": str(repo)},
96
+ "active_task": None, "tasks": {}, "decisions": [], "blockers": [],
97
+ "telemetry": _empty_telemetry(), "updated_at": now_iso(),
98
+ }
99
+
100
+
101
+ def _migrate_state(st: Dict[str, Any], repo: Path) -> Dict[str, Any]:
102
+ st.setdefault("project", {"name": repo.name, "root": str(repo)})
103
+ st.setdefault("active_task", None)
104
+ st.setdefault("tasks", {})
105
+ st.setdefault("decisions", [])
106
+ st.setdefault("blockers", [])
107
+ telem = st.setdefault("telemetry", {})
108
+ if not isinstance(telem, dict):
109
+ telem = {}
110
+ st["telemetry"] = telem
111
+ for k, dv in _empty_telemetry().items():
112
+ telem.setdefault(k, dict(dv) if isinstance(dv, dict) else dv)
113
+
114
+ clean_tasks: Dict[str, Any] = {}
115
+ for tid, t in st["tasks"].items():
116
+ if not VALID_TASK_ID_RE.fullmatch(str(tid)):
117
+ continue
118
+ t.setdefault("id", tid)
119
+ t.setdefault("priority", "normal")
120
+ t.setdefault("model_tier", "medium")
121
+ t.setdefault("model_alias", TIER_TO_ALIAS.get(t["model_tier"], "balanced"))
122
+ t.setdefault("human_approval_required", t["model_tier"] == "critical")
123
+ t.setdefault("owned_files", [])
124
+ if "files_touched" not in t:
125
+ t["files_touched"] = list(t.get("files", []))
126
+ t.setdefault("files", t["files_touched"])
127
+ for k, dv in (
128
+ ("files_inspected", {}), ("verified_checks", []), ("attempted_approaches", []),
129
+ ("progress_log", []), ("routing_history", []), ("tests", []),
130
+ ):
131
+ t.setdefault(k, dict(dv) if isinstance(dv, dict) else list(dv))
132
+ t.setdefault("owner_history", [{"agent": t.get("owner", "agent"), "model_alias": t["model_alias"], "started_at": t.get("created_at", now_iso())}])
133
+ t.setdefault("failures_count", 0)
134
+ t.setdefault("handoff_count", 0)
135
+ t.setdefault("created_at", now_iso())
136
+ t.setdefault("updated_at", now_iso())
137
+ clean_tasks[tid] = t
138
+ st["tasks"] = clean_tasks
139
+ if st.get("active_task") and st["active_task"] not in clean_tasks:
140
+ st["active_task"] = None
141
+ st["schema_version"] = SCHEMA_VERSION
142
+ return st
143
+
144
+
145
+ def _is_internal_artifact_status(status_line: str) -> bool:
146
+ if len(status_line) < 4:
147
+ return False
148
+ raw_p = status_line[3:].strip().split(" -> ", 1)[-1].strip('"').replace("\\", "/")
149
+ while raw_p.startswith("./"):
150
+ raw_p = raw_p[2:]
151
+ raw_p = raw_p.rstrip("/")
152
+ return raw_p in (".agent-index", ".agent-state") or raw_p.startswith((".agent-index/", ".agent-state/"))
153
+
154
+
155
+ def _git_snapshot(repo: Path) -> Dict[str, Any]:
156
+ snap: Dict[str, Any] = {"is_git": False}
157
+ try:
158
+ r_br = git_cmd(repo, ["rev-parse", "--abbrev-ref", "HEAD"], timeout=3)
159
+ if r_br.returncode != 0:
160
+ return snap
161
+ snap["is_git"] = True
162
+ snap["branch"] = sanitize_inline(r_br.stdout)
163
+ r_hd = git_cmd(repo, ["rev-parse", "--short", "HEAD"], timeout=3)
164
+ if r_hd.returncode == 0:
165
+ snap["head"] = sanitize_inline(r_hd.stdout)
166
+ r_st = git_cmd(repo, ["status", "--porcelain"], timeout=3)
167
+ if r_st.returncode == 0:
168
+ raw_dirty = [ln for ln in r_st.stdout.splitlines() if ln.strip() and not _is_internal_artifact_status(ln)]
169
+ snap["dirty_count"] = len(raw_dirty)
170
+ snap["dirty_files"] = [sanitize_inline(ln) for ln in raw_dirty[:25]]
171
+ snap["dirty_paths"] = [
172
+ ln[3:].strip().split(" -> ", 1)[-1].strip('"')
173
+ for ln in raw_dirty[:40]
174
+ if len(ln) >= 4
175
+ ]
176
+ r_df = git_cmd(repo, ["diff", "--no-ext-diff", "--no-textconv", "--stat"], timeout=3)
177
+ if r_df.returncode == 0 and r_df.stdout.strip():
178
+ snap["diff_stat"] = "\n".join(r_df.stdout.strip().splitlines()[:20])
179
+ snap["state_git_tracked"] = git_cmd(repo, ["ls-files", "--error-unmatch", ".agent-state/state.json"], timeout=3).returncode == 0
180
+ except Exception:
181
+ pass
182
+ return snap
183
+
184
+
185
+ def _file_sha12(repo: Path, rel_path: str) -> Optional[str]:
186
+ repo_r = repo.resolve()
187
+ try:
188
+ norm = normalize_rel_path(rel_path)
189
+ except SystemExit:
190
+ return None
191
+ raw_fp = repo_r / norm
192
+ if raw_fp.is_symlink():
193
+ return None
194
+ fp = raw_fp.resolve()
195
+ try:
196
+ resolved_rel = fp.relative_to(repo_r).as_posix()
197
+ except ValueError:
198
+ return None
199
+ if is_secret_path(resolved_rel):
200
+ return None
201
+ try:
202
+ st = fp.stat()
203
+ if not stat.S_ISREG(st.st_mode) or st.st_size > MAX_HASH_FILE_BYTES:
204
+ return None
205
+ h = hashlib.sha256()
206
+ with fp.open("rb") as f:
207
+ while True:
208
+ chunk = f.read(65536)
209
+ if not chunk:
210
+ break
211
+ h.update(chunk)
212
+ return h.hexdigest()[:12]
213
+ except OSError:
214
+ return None
215
+
216
+
217
+ def load_state_readonly(repo: Path) -> Tuple[Path, Dict[str, Any], bool]:
218
+ repo_r = repo.resolve()
219
+ sd = _safe_state_dir(repo_r)
220
+ sf = sd / "state.json"
221
+ if sf.is_symlink():
222
+ raise SystemExit("Refusing to follow symlinked state.json.")
223
+ if not sf.is_file():
224
+ return sd, _empty_state(repo_r), False
225
+ return sd, _migrate_state(_read_state_json(sf), repo_r), True
226
+
227
+
228
+ def init_state(repo: Path, *, auto_git_exclude: bool = True) -> Tuple[Path, Dict[str, Any]]:
229
+ repo_r = repo.resolve()
230
+ sd = _safe_state_dir(repo_r)
231
+ sd.mkdir(parents=True, exist_ok=True)
232
+ if auto_git_exclude:
233
+ ensure_git_info_exclude(repo_r, (".agent-state/",))
234
+ sf = sd / "state.json"
235
+ if sf.is_symlink():
236
+ raise SystemExit("Refusing to follow symlinked state.json.")
237
+ if sf.is_file():
238
+ return sd, _migrate_state(_read_state_json(sf), repo_r)
239
+ st = _empty_state(repo_r)
240
+ atomic_write_json(sf, st)
241
+ render_all(sd, st)
242
+ if not (sd / "HANDOFF.md").exists():
243
+ atomic_write_text(sd / "HANDOFF.md", "# Agent Handoff\n\nNo handoff prepared.\n")
244
+ return sd, st
245
+
246
+
247
+ def save_state(state_dir: Path, st: Dict[str, Any]) -> None:
248
+ st["updated_at"] = now_iso()
249
+ atomic_write_json(state_dir / "state.json", st)
250
+ render_all(state_dir, st)
251
+
252
+
253
+ def _promote_next_active(st: Dict[str, Any]) -> None:
254
+ rem = [t for t in st["tasks"].values() if t["status"] == "in_progress"]
255
+ rem.sort(key=lambda x: x.get("updated_at", ""), reverse=True)
256
+ st["active_task"] = rem[0]["id"] if rem else None
257
+
258
+
259
+ def _paths_overlap_scope(a: str, b: str) -> bool:
260
+ a_c = a.rstrip("/")
261
+ b_c = b.rstrip("/")
262
+ return a_c == b_c or a_c.startswith(b_c + "/") or b_c.startswith(a_c + "/")
263
+
264
+
265
+ def _check_ownership_conflicts(st: Dict[str, Any], task_id: str, files: Sequence[str]) -> List[Dict[str, str]]:
266
+ want = sorted({normalize_rel_path(f) for f in files})
267
+ conflicts: List[Dict[str, str]] = []
268
+ if not want:
269
+ return conflicts
270
+ for other_id, other in st["tasks"].items():
271
+ if other_id == task_id or other["status"] != "in_progress":
272
+ continue
273
+ other_norm: List[str] = []
274
+ for of in other.get("owned_files", []):
275
+ try:
276
+ other_norm.append(normalize_rel_path(of))
277
+ except SystemExit:
278
+ other_norm.append(of)
279
+ for wf in want:
280
+ for of in sorted(set(other_norm)):
281
+ if _paths_overlap_scope(wf, of):
282
+ conflicts.append({"file": wf, "conflicts_with": of, "conflicting_task": other_id, "owner": other["owner"]})
283
+ return conflicts
284
+
285
+
286
+ def build_brief(repo: Path, st: Dict[str, Any], task_id: Optional[str] = None, max_tokens: int = 1200) -> Dict[str, Any]:
287
+ tid = _validate_task_id(task_id) if task_id else st.get("active_task")
288
+ return build_brief_dossier(repo.resolve(), _safe_state_dir(repo), st, tid, max_tokens, _git_snapshot, _file_sha12)
289
+
290
+
291
+ def _recent_git_activity(repo: Path, limit: int = 5) -> Dict[str, Any]:
292
+ snap = _git_snapshot(repo)
293
+ if not snap.get("is_git"):
294
+ return {"is_git": False, "commits": [], "dirty_files": [], "dirty_count": 0}
295
+ commits: List[str] = []
296
+ try:
297
+ r_log = git_cmd(repo, ["log", f"-n{max(1, limit)}", "--oneline"], timeout=3)
298
+ if r_log.returncode == 0 and r_log.stdout.strip():
299
+ commits = [sanitize_inline(ln) for ln in r_log.stdout.splitlines() if ln.strip()][:limit]
300
+ except Exception:
301
+ pass
302
+ return {
303
+ "is_git": True,
304
+ "branch": snap.get("branch", ""),
305
+ "head": snap.get("head", ""),
306
+ "commits": commits,
307
+ "dirty_count": int(snap.get("dirty_count", 0)),
308
+ "dirty_files": list(snap.get("dirty_files", []))[:15],
309
+ }
310
+
311
+
312
+ def _try_auto_index(repo: Path) -> Optional[Dict[str, Any]]:
313
+ """Incrementally build or refresh sibling `local-context-index` if available (strictly non-fatal)."""
314
+ skills_root = Path(__file__).resolve().parents[2]
315
+ ctx_scripts = skills_root / "local-context-index" / "scripts"
316
+ if not (ctx_scripts / "context_index.py").is_file():
317
+ env_dir = os.getenv("AGENT_EFFICIENCY_SKILLS_DIR", "").strip()
318
+ if env_dir:
319
+ cand = Path(env_dir).expanduser() / "local-context-index" / "scripts"
320
+ if (cand / "context_index.py").is_file():
321
+ ctx_scripts = cand
322
+ if not (ctx_scripts / "context_index.py").is_file():
323
+ return None
324
+ try:
325
+ if str(ctx_scripts) not in sys.path:
326
+ sys.path.insert(0, str(ctx_scripts))
327
+ import context_index # type: ignore[import-not-found]
328
+ return context_index.index(repo)
329
+ except Exception:
330
+ return None
331
+
332
+
333
+ def _read_project_map_excerpt(repo: Path, max_tokens: int) -> str:
334
+ mp = repo / ".agent-index" / "PROJECT_MAP.md"
335
+ if max_tokens < 60 or not mp.is_file() or mp.is_symlink():
336
+ return ""
337
+ try:
338
+ resolved = mp.resolve()
339
+ if not is_within(resolved, repo):
340
+ return ""
341
+ raw = resolved.read_text(encoding="utf-8", errors="replace").strip()
342
+ except OSError:
343
+ return ""
344
+ if not raw:
345
+ return ""
346
+ lines = raw.splitlines()
347
+ kept: List[str] = []
348
+ acc = 0
349
+ truncated = False
350
+ for ln in lines:
351
+ lt = estimate_tokens(ln + "\n")
352
+ if kept and acc + lt > max_tokens:
353
+ truncated = True
354
+ break
355
+ kept.append(ln)
356
+ acc += lt
357
+ if truncated:
358
+ kept.append("... [map truncated to budget — run `ae map` or `ae search \"<q>\"` for more]")
359
+ return "\n".join(kept)
360
+
361
+
362
+ def build_session_start(
363
+ repo: Path,
364
+ max_tokens: int = 1400,
365
+ *,
366
+ include_map: bool = True,
367
+ auto_index: bool = False,
368
+ ) -> Dict[str, Any]:
369
+ """Single-call compound startup dossier: brief + recent git activity + optional auto-index & PROJECT_MAP."""
370
+ repo_r = repo.resolve()
371
+ auto_indexed: Optional[Dict[str, Any]] = None
372
+ if auto_index:
373
+ auto_indexed = _try_auto_index(repo_r)
374
+
375
+ sd, st, exists = load_state_readonly(repo_r)
376
+ brief_budget = max(300, int(max_tokens * 0.50))
377
+ brief = build_brief(repo_r, st, max_tokens=brief_budget)
378
+ idx_info = _index_summary_for_files(repo_r, [])
379
+ cache_info = _cache_summary(repo_r, sd)
380
+ recent_git = _recent_git_activity(repo_r, limit=5)
381
+
382
+ # Assemble single compact markdown dossier so a new window never needs `find`/`ls`/full-file scans
383
+ parts: List[str] = []
384
+ has_state = bool(brief.get("has_task") or brief.get("has_checkpoint") or brief.get("active_decisions_count"))
385
+ if has_state:
386
+ parts.append(brief["markdown"].rstrip())
387
+ else:
388
+ parts.append(f"# Session Resume ({repo_r.name})")
389
+ parts.append("- State: no active task or checkpoint yet (use `ae checkpoint --note \"...\"` before switching windows).")
390
+
391
+ if recent_git.get("is_git"):
392
+ git_lines = [f"## Recent Workspace Activity ({recent_git.get('branch', '')} @ {recent_git.get('head', '')})"]
393
+ if recent_git.get("dirty_files"):
394
+ git_lines.append(f"- Uncommitted changes ({recent_git['dirty_count']}): " + ", ".join(f"`{d}`" for d in recent_git["dirty_files"][:8]))
395
+ if recent_git.get("commits"):
396
+ git_lines.append("- Recent commits:")
397
+ for c in recent_git["commits"][:5]:
398
+ git_lines.append(f" - {c}")
399
+ parts.append("\n".join(git_lines))
400
+
401
+ idx_line = (
402
+ f"- Index: ready ({idx_info.get('indexed_files', 0)} files, {idx_info.get('symbols', 0)} symbols)"
403
+ if idx_info.get("indexed")
404
+ else "- Index: not built yet (run `ae index` or `ae resume`)"
405
+ )
406
+ parts.append(idx_line)
407
+
408
+ footer = '> **Skip repo re-exploration:** Use `ae search "<query>"`, `ae outline <path>`, or `ae slice path:Symbol` directly instead of `find`/`ls` or full-file reads.'
409
+ used_so_far = estimate_tokens("\n\n".join(parts) + "\n\n" + footer)
410
+ map_excerpt = ""
411
+ if include_map and idx_info.get("indexed"):
412
+ rem_for_map = max_tokens - used_so_far - 25
413
+ if rem_for_map >= 80:
414
+ map_excerpt = _read_project_map_excerpt(repo_r, max_tokens=rem_for_map)
415
+ if map_excerpt:
416
+ parts.append(map_excerpt)
417
+
418
+ parts.append(footer)
419
+ markdown = "\n\n".join(parts).strip() + "\n"
420
+ return {
421
+ "initialized": exists,
422
+ "auto_indexed": auto_indexed is not None,
423
+ "index": idx_info,
424
+ "cache": cache_info,
425
+ "recent_git": recent_git,
426
+ "brief": brief,
427
+ "has_map": bool(map_excerpt),
428
+ "markdown": markdown,
429
+ "tokens_est": estimate_tokens(markdown),
430
+ }
431
+
432
+
433
+ def _resolve_task_id(st: Dict[str, Any], supplied: Optional[str]) -> str:
434
+ tid = supplied or st.get("active_task")
435
+ if not tid:
436
+ raise SystemExit("No active task; start one or supply a valid --task-id.")
437
+ _validate_task_id(tid)
438
+ if tid not in st["tasks"]:
439
+ raise SystemExit(f"Unknown task ID: {tid}")
440
+ return tid