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,150 @@
1
+ #!/usr/bin/env python3
2
+ """Validate all skills in this repository against agentskills.io & efficiency standards."""
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import py_compile
8
+ import re
9
+ import subprocess
10
+ import sys
11
+ from pathlib import Path
12
+ from typing import Any, Dict, List, Tuple
13
+
14
+ ROOT = Path(__file__).resolve().parents[1]
15
+ SKILLS_DIR = ROOT / "skills"
16
+
17
+ NAME_RE = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
18
+ LINK_RE = re.compile(r"\[[^\]]+\]\(([^)]+)\)")
19
+
20
+
21
+ def parse_frontmatter(text: str) -> Tuple[Dict[str, str], str]:
22
+ norm = text.replace("\r\n", "\n")
23
+ if not norm.startswith("---\n"):
24
+ return {}, norm
25
+ end = norm.find("\n---\n", 4)
26
+ if end == -1:
27
+ return {}, norm
28
+ raw_fm = norm[4:end]
29
+ body = norm[end + 5 :]
30
+ meta: Dict[str, str] = {}
31
+ for line in raw_fm.splitlines():
32
+ if ":" in line:
33
+ k, v = line.split(":", 1)
34
+ meta[k.strip()] = v.strip().strip('"').strip("'")
35
+ return meta, body
36
+
37
+
38
+ def validate_skill(skill_dir: Path) -> Dict[str, Any]:
39
+ errors: List[str] = []
40
+ warnings: List[str] = []
41
+ skill_dir_r = skill_dir.resolve()
42
+ skill_md = skill_dir_r / "SKILL.md"
43
+ if not skill_md.is_file():
44
+ return {"skill": skill_dir.name, "ok": False, "errors": ["Missing SKILL.md"], "warnings": []}
45
+
46
+ raw = skill_md.read_text(encoding="utf-8")
47
+ if "\\n" in raw and raw.count("\n") < 5:
48
+ errors.append("SKILL.md appears to contain escaped literal \\n newlines.")
49
+
50
+ meta, body = parse_frontmatter(raw)
51
+ name = meta.get("name", "")
52
+ desc = meta.get("description", "")
53
+
54
+ if not name:
55
+ errors.append("Missing required frontmatter field: name")
56
+ elif not NAME_RE.match(name):
57
+ errors.append(f"Invalid skill name '{name}': use lowercase letters, digits, and hyphens only.")
58
+ elif name != skill_dir.name:
59
+ errors.append(f"Frontmatter name '{name}' does not match directory name '{skill_dir.name}'.")
60
+
61
+ if not desc:
62
+ errors.append("Missing required frontmatter field: description")
63
+ else:
64
+ if len(desc) > 1024:
65
+ errors.append(f"Description exceeds 1024 chars ({len(desc)}).")
66
+ if len(desc) > 400:
67
+ warnings.append(f"Description is {len(desc)} chars; keep concise (<400 chars) to minimize permanent context load.")
68
+ if not desc.startswith("Use when"):
69
+ errors.append("Description must start with 'Use when' to focus on trigger conditions.")
70
+ if re.search(r"\bI\b", desc) or re.search(r"(?i)\b(?:you|your)\b", desc):
71
+ warnings.append("Description should be third-person.")
72
+
73
+ words = len(body.split())
74
+ lines = len(raw.splitlines())
75
+ if lines > 500:
76
+ errors.append(f"SKILL.md has {lines} lines (>500 max).")
77
+ if words > 850:
78
+ warnings.append(f"SKILL.md body has {words} words; consider pushing heavy reference to references/.")
79
+
80
+ for target in LINK_RE.findall(body):
81
+ if target.startswith(("http://", "https://", "#", "mailto:")):
82
+ continue
83
+ clean_target = target.split("#", 1)[0]
84
+ resolved = (skill_dir_r / clean_target).resolve()
85
+ try:
86
+ resolved.relative_to(skill_dir_r)
87
+ except ValueError:
88
+ errors.append(f"Relative link escapes skill directory (breaks standalone install): {target}")
89
+ continue
90
+ if not resolved.exists():
91
+ errors.append(f"Broken relative link in SKILL.md: {target}")
92
+ elif resolved.is_file() and resolved.suffix == ".md":
93
+ ref_text = resolved.read_text(encoding="utf-8", errors="replace")
94
+ if len(ref_text.splitlines()) > 100 and "## Contents" not in ref_text:
95
+ warnings.append(f"Long reference '{clean_target}' (>100 lines) should include a '## Contents' TOC.")
96
+
97
+ scripts_dir = skill_dir_r / "scripts"
98
+ checked_scripts: List[str] = []
99
+ if scripts_dir.is_dir():
100
+ for py in sorted(scripts_dir.glob("*.py")):
101
+ checked_scripts.append(py.name)
102
+ try:
103
+ py_compile.compile(str(py), doraise=True)
104
+ except py_compile.PyCompileError as e:
105
+ errors.append(f"Syntax error in {py.name}: {e}")
106
+ continue
107
+ src = py.read_text(encoding="utf-8")
108
+ if 'if __name__ == "__main__"' in src or "if __name__=='__main__'" in src:
109
+ try:
110
+ r = subprocess.run([sys.executable, str(py), "--help"], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=5)
111
+ except subprocess.TimeoutExpired:
112
+ errors.append(f"{py.name} --help timed out after 5s")
113
+ continue
114
+ if r.returncode != 0:
115
+ errors.append(f"{py.name} --help failed (exit {r.returncode}): {r.stderr.strip()[:200]}")
116
+
117
+ return {
118
+ "skill": skill_dir.name,
119
+ "ok": len(errors) == 0,
120
+ "description_chars": len(desc),
121
+ "body_words": words,
122
+ "lines": lines,
123
+ "scripts": checked_scripts,
124
+ "errors": errors,
125
+ "warnings": warnings,
126
+ }
127
+
128
+
129
+ def validate_all(skills_dir: Path = SKILLS_DIR) -> Dict[str, Any]:
130
+ results = [validate_skill(d) for d in sorted(skills_dir.iterdir()) if d.is_dir() and not d.name.startswith(".")]
131
+ total_desc_chars = sum(r.get("description_chars", 0) for r in results)
132
+ return {
133
+ "ok": all(r["ok"] for r in results) and len(results) > 0,
134
+ "skill_count": len(results),
135
+ "always_loaded_description_tokens_est": max(1, (total_desc_chars + 3) // 4),
136
+ "results": results,
137
+ }
138
+
139
+
140
+ def main() -> int:
141
+ ap = argparse.ArgumentParser(description="Validate skill frontmatter, progressive disclosure, links, and scripts.")
142
+ ap.add_argument("--skills-dir", type=Path, default=SKILLS_DIR)
143
+ args = ap.parse_args()
144
+ report = validate_all(args.skills_dir.resolve())
145
+ print(json.dumps(report, indent=2))
146
+ return 0 if report["ok"] else 1
147
+
148
+
149
+ if __name__ == "__main__":
150
+ raise SystemExit(main())
@@ -0,0 +1,80 @@
1
+ ---
2
+ name: adaptive-orchestration-handoff
3
+ description: Use when resuming work, before context compaction, handing off between agents (`checkpoint`/`brief`/`handoff`), auditing IDE token waste or always-on context bloat (`audit`/`doctor`), or routing subagent/pipeline model tiers.
4
+ ---
5
+
6
+ # Adaptive Orchestration & Handoff
7
+
8
+ **Primary IDE focus — durable session memory & anti-duplication** in `<repo>/.agent-state/` (`CHECKPOINT.md`, `CURRENT_STATE.md`, `DECISIONS.md`, `HANDOFF.md`, `state.json`) plus local IDE token-waste auditing (`audit-sessions`). Optional subagent & custom-pipeline model routing lives separately in `route_task.py` / `llm_adapter.py`. Invoke scripts via `python3 <skill-dir>/scripts/<script>.py` (or short `ae brief` / `ae checkpoint` / `ae audit`).
9
+
10
+ ## Core IDE Workflow (Session Memory, Checkpoints & Handoffs)
11
+
12
+ 1. **Resume in 1 call at the start of EVERY new chat/window** (loads objective, checkpoint/handoff, active decisions, failed dead ends, recent git commits/dirty files, live SHA drift, and compact `PROJECT_MAP.md` — `ae resume` auto-indexes incrementally if missing):
13
+ ```bash
14
+ ae resume
15
+ # or standalone script: python3 <skill-dir>/scripts/agent_state.py session-start <repo> --auto-index
16
+ ```
17
+ *(Do NOT run `find`/`ls` or dump full files after `ae resume` — jump straight to `ae search` / `ae slice`.)*
18
+ - If a task is `handed_off`, `queued`, or `blocked`, claim ownership first:
19
+ ```bash
20
+ python3 <skill-dir>/scripts/agent_state.py accept <repo> --owner <agent-id> [--task-id <T-id>]
21
+ ```
22
+ - For multi-step, multi-session, or multi-agent work, start a tracked task (use `--queue` to defer, or `--parallel --own-files "a.py,b.py"` for disjoint ownership):
23
+ ```bash
24
+ python3 <skill-dir>/scripts/agent_state.py start <repo> --objective "<goal>" --criteria "<done>" --own-files "src/a.py"
25
+ ```
26
+ - *(Skip formal `start` for trivial 1-turn edits; use zero-friction `checkpoint` anytime.)*
27
+ 2. **Never re-read or repeat dead ends**:
28
+ - Skip re-reading files listed under `Already Inspected` unless `brief` flags SHA drift.
29
+ - **Never repeat a recorded `failed`/`rejected` approach** without a new root-cause hypothesis.
30
+ - **1-call auto-checkpoint** before compaction or stopping (captures git diff, touched symbols, optional note/check; `.agent-state/` is auto-added to local `.git/info/exclude`):
31
+ `agent_state.py checkpoint <repo> --note "..." [--cmd "<test>" --exit-code 0]`
32
+ - **IDE token-waste, repeat-read, USD cost & trend audit** (read-only across Antigravity/Claude/Codex/Gemini/Cursor/OpenCode/Cline transcripts):
33
+ `agent_state.py audit-sessions --source auto --limit 6` *(or visual `ae audit`)*
34
+ - **Always-on context bloat, top-10 skills & safe pruning** (read-only by default):
35
+ `python3 <skill-dir>/scripts/context_doctor.py <repo>` *(or `ae doctor` / `ae doctor --prune --apply` / `ae savings --statusline`)*
36
+ - Granular logs when needed: `record-inspection`, `record-attempt` (`worked|failed|rejected`), `decision` (`--supersedes D-001`), `record-check`.
37
+ 3. **Finish or hand off cleanly**:
38
+ - Lifecycle: `block`, `cancel`, `reopen`, `switch`, `prune`.
39
+ - Done (also clears stale `HANDOFF.md`): `agent_state.py complete <repo> --result "<verified summary>"`
40
+ - Hand off to another agent / reviewer:
41
+ ```bash
42
+ python3 <skill-dir>/scripts/agent_state.py handoff <repo> --recipient "<next-agent>" \
43
+ --summary "<what changed>" --next "<exact next step>" --entry-points "src/auth.py:42-90"
44
+ ```
45
+
46
+ ## Optional: Subagent & Custom Pipeline Routing (`route_task.py`)
47
+
48
+ *Skip this section during standard single-model IDE chat where the IDE selects the model. Use it when spawning subagents (`--runtime antigravity|claude|codex|gemini`) or running custom API pipelines (`llm_adapter.py`).*
49
+
50
+ ```bash
51
+ python3 <skill-dir>/scripts/route_task.py route <repo> --runtime antigravity --task "<subtask>" \
52
+ --phase debug --risk high --touched-paths "src/auth.py" --dependents-count 6 --record
53
+ ```
54
+
55
+ - **2-Attempt Rule**: 1 failure on `low` → `medium`; 2 failures on `medium` → `high`; 2 failures on `high` → stop tweaking and escalate (`escalate <repo> --reason "..."`).
56
+ - **Down-shift** (`downshift <repo> --task "<step>" --phase format`) respects warm-cache hysteresis and **refuses to downgrade `critical`/human-gated tasks** unless `--isolated-subtask` or `--override-critical` is supplied.
57
+
58
+ ## Tier Matrix
59
+
60
+ | Tier | Alias | Use For | Gate |
61
+ |---|---|---|---|
62
+ | `low` | `fast` | Triage, formatting, lint, docs, summaries, 1-line edits | Auto |
63
+ | `medium` | `balanced` | Standard feature work, unit tests, localized bug fixes | Auto |
64
+ | `high` | `reasoning` | Architecture, security/auth code fixes, concurrency, root-cause debug, ≥2 failures | Independent review (`handoff` to reviewer) |
65
+ | `critical` | `reasoning` | Prod deploy, destructive ops, secret/key rotation, schema drops | **Explicit human approval required** |
66
+
67
+ Map aliases via `AGENT_MODEL_FAST`, `AGENT_MODEL_BALANCED`, `AGENT_MODEL_REASONING` (+ optional `*_FALLBACK`). Check via `route_task.py check-models`.
68
+
69
+ ## Detailed References
70
+
71
+ - Multi-signal scoring, escalation/down-shift, cache-affinity math & `llm_adapter.py`: [references/routing-and-escalation.md](references/routing-and-escalation.md)
72
+ - State schema v2, locking, parallel file ownership, anti-duplication & handoff protocol: [references/state-and-handoff.md](references/state-and-handoff.md)
73
+ - End-to-end multi-agent handoff walkthrough: [examples/workflow.md](examples/workflow.md)
74
+
75
+ ## Safety
76
+
77
+ - Code fixes for prod/auth bugs run on `high` + independent review; actual prod deploys, secret rotation, and destructive ops are `critical` and require human approval.
78
+ - Never `@import` mutable `.agent-state/*` (`CHECKPOINT.md`, `HANDOFF.md`, `CURRENT_STATE.md`) into always-on `CLAUDE.md`/`AGENTS.md` files — it invalidates the provider prompt-cache prefix on every checkpoint (`ae doctor` flags this). Always load state on demand via `ae brief`.
79
+ - Never write secrets to state, decisions, or handoffs (`agent_state.py` auto-redacts hardcoded secret literals).
80
+ - Never claim tests passed without running them and logging `record-check --exit-code 0`.
@@ -0,0 +1,237 @@
1
+ {
2
+ "schema_version": 2,
3
+ "default_tier": "medium",
4
+ "tier_order": ["low", "medium", "high", "critical"],
5
+ "runtime_presets": {
6
+ "antigravity": {
7
+ "low": "flash_lite",
8
+ "medium": "flash",
9
+ "high": "pro",
10
+ "critical": "pro"
11
+ },
12
+ "claude": {
13
+ "low": "haiku",
14
+ "medium": "sonnet",
15
+ "high": "opus",
16
+ "critical": "opus"
17
+ },
18
+ "codex": {
19
+ "low": "gpt-5-mini",
20
+ "medium": "gpt-5",
21
+ "high": "o3",
22
+ "critical": "o3"
23
+ },
24
+ "gemini": {
25
+ "low": "gemini-2.5-flash-lite",
26
+ "medium": "gemini-2.5-flash",
27
+ "high": "gemini-2.5-pro",
28
+ "critical": "gemini-2.5-pro"
29
+ }
30
+ },
31
+ "tiers": {
32
+ "low": {
33
+ "alias": "fast",
34
+ "env_var": "AGENT_MODEL_FAST",
35
+ "fallback_env_var": "AGENT_MODEL_FAST_FALLBACK",
36
+ "description": "Routine mechanical edits, triage, formatting, docs, log summarization",
37
+ "cost_per_1m": {
38
+ "input": 1.0,
39
+ "cached_input": 0.1,
40
+ "output": 5.0
41
+ },
42
+ "max_recommended_context_tokens": 64000
43
+ },
44
+ "medium": {
45
+ "alias": "balanced",
46
+ "env_var": "AGENT_MODEL_BALANCED",
47
+ "fallback_env_var": "AGENT_MODEL_BALANCED_FALLBACK",
48
+ "description": "General feature implementation, unit tests, localized bug fixes, bounded refactors",
49
+ "cost_per_1m": {
50
+ "input": 3.0,
51
+ "cached_input": 0.3,
52
+ "output": 15.0
53
+ },
54
+ "max_recommended_context_tokens": 128000
55
+ },
56
+ "high": {
57
+ "alias": "reasoning",
58
+ "env_var": "AGENT_MODEL_REASONING",
59
+ "fallback_env_var": "AGENT_MODEL_REASONING_FALLBACK",
60
+ "description": "Architecture, security, concurrency, root-cause debugging, large cross-module refactors, post-failure escalation",
61
+ "cost_per_1m": {
62
+ "input": 15.0,
63
+ "cached_input": 1.5,
64
+ "output": 75.0
65
+ },
66
+ "max_recommended_context_tokens": 200000
67
+ },
68
+ "critical": {
69
+ "alias": "reasoning",
70
+ "env_var": "AGENT_MODEL_REASONING",
71
+ "fallback_env_var": "AGENT_MODEL_REASONING_FALLBACK",
72
+ "description": "Irreversible, destructive, production-impacting, credential, or schema-drop work — requires human approval and independent review",
73
+ "cost_per_1m": {
74
+ "input": 15.0,
75
+ "cached_input": 1.5,
76
+ "output": 75.0
77
+ },
78
+ "max_recommended_context_tokens": 200000
79
+ }
80
+ },
81
+ "phase_bias": {
82
+ "triage": -2,
83
+ "explore": -2,
84
+ "summarize": -2,
85
+ "format": -2,
86
+ "docs": -1,
87
+ "implement": 0,
88
+ "test": 0,
89
+ "review": 1,
90
+ "debug": 2,
91
+ "architect": 3,
92
+ "security": 3,
93
+ "migrate": 3,
94
+ "deploy": 5
95
+ },
96
+ "escalation": {
97
+ "upshift_after_failures": 1,
98
+ "high_tier_after_failures": 2,
99
+ "human_escalation_after_high_failures": 2,
100
+ "dependents_medium_threshold": 4,
101
+ "dependents_high_threshold": 10,
102
+ "files_medium_threshold": 3,
103
+ "files_high_threshold": 8,
104
+ "diff_lines_medium_threshold": 150,
105
+ "diff_lines_high_threshold": 450,
106
+ "assumed_turn_output_tokens": 1200,
107
+ "assumed_volatile_input_tokens": 1500
108
+ },
109
+ "routing": {
110
+ "critical_keywords": [
111
+ "drop table",
112
+ "delete production",
113
+ "production deploy",
114
+ "prod deploy",
115
+ "force push",
116
+ "rotate secret",
117
+ "rotate credential",
118
+ "irreversible",
119
+ "wipe database",
120
+ "truncate table",
121
+ "billing charge",
122
+ "iam policy",
123
+ "tabelle löschen",
124
+ "datenbank löschen",
125
+ "produktion löschen",
126
+ "in produktion löschen",
127
+ "produktions-deploy",
128
+ "secret rotieren",
129
+ "unwiderruflich"
130
+ ],
131
+ "high_risk_keywords": [
132
+ "security",
133
+ "cryptograph",
134
+ "encryption",
135
+ "authentication",
136
+ "authorization",
137
+ "oauth",
138
+ "jwt",
139
+ "session",
140
+ "payment",
141
+ "billing",
142
+ "migration",
143
+ "schema change",
144
+ "production",
145
+ "concurrency",
146
+ "deadlock",
147
+ "data loss",
148
+ "privacy",
149
+ "pii",
150
+ "rbac",
151
+ "permission",
152
+ "sql injection",
153
+ "xss",
154
+ "csrf",
155
+ "sandbox",
156
+ "secret",
157
+ "sicherheit",
158
+ "sicherheitslücke",
159
+ "authentifizierung",
160
+ "autorisierung",
161
+ "verschlüsselung",
162
+ "passwort",
163
+ "zahlung",
164
+ "abrechnung",
165
+ "produktion",
166
+ "datenschutz",
167
+ "berechtigung",
168
+ "datenverlust"
169
+ ],
170
+ "high_complexity_keywords": [
171
+ "architecture",
172
+ "redesign",
173
+ "refactor",
174
+ "distributed",
175
+ "performance",
176
+ "race condition",
177
+ "root cause",
178
+ "memory leak",
179
+ "state machine",
180
+ "compiler",
181
+ "parser",
182
+ "consensus",
183
+ "multi-agent",
184
+ "zero-downtime",
185
+ "backwards compat",
186
+ "architektur",
187
+ "neugestaltung",
188
+ "speicherleck",
189
+ "ursachenanalyse",
190
+ "nebenläufigkeit",
191
+ "abwärtskompatibel"
192
+ ],
193
+ "low_complexity_keywords": [
194
+ "typo",
195
+ "format",
196
+ "lint",
197
+ "rename",
198
+ "documentation",
199
+ "readme",
200
+ "docstring",
201
+ "comment",
202
+ "changelog",
203
+ "simple",
204
+ "one-line",
205
+ "trivial",
206
+ "boilerplate",
207
+ "sort imports",
208
+ "summarize",
209
+ "triage",
210
+ "tippfehler",
211
+ "formatieren",
212
+ "dokumentation",
213
+ "kommentar",
214
+ "einfach",
215
+ "umbenennen",
216
+ "zusammenfassen"
217
+ ],
218
+ "sensitive_path_keywords": [
219
+ "auth",
220
+ "security",
221
+ "crypto",
222
+ "billing",
223
+ "payment",
224
+ "migration",
225
+ "migrations",
226
+ "schema",
227
+ "infra",
228
+ "terraform",
229
+ "k8s",
230
+ "kubernetes",
231
+ "iam",
232
+ "rbac",
233
+ "deploy",
234
+ ".github/workflows"
235
+ ]
236
+ }
237
+ }
@@ -0,0 +1,77 @@
1
+ # End-to-End Multi-Agent Efficiency Workflow
2
+
3
+ Scenario: Agent A starts a security-sensitive feature (refresh-token rotation), escalates on a concurrency failure, caches the project prefix, and hands off to Agent B for review + final test verification with **zero re-exploration**.
4
+
5
+ ## 1. Index Once & Register Cacheable Project Prefix (Agent A)
6
+ ```bash
7
+ python3 ../local-context-index/scripts/context_index.py index /work/repo
8
+ python3 ../local-context-index/scripts/context_index.py search /work/repo "refresh token" --format compact
9
+ python3 ../local-context-index/scripts/context_index.py deps /work/repo src/auth.py --depth 2
10
+
11
+ python3 ../prompt-cache-manager/scripts/prompt_cache.py register /work/repo \
12
+ --name auth-sprint --l0-file AGENTS.md --include-map --include-decisions --provider anthropic --strict
13
+ ```
14
+
15
+ ## 2. Start Task & Route Model Tier Dynamically (Agent A)
16
+ ```bash
17
+ python3 scripts/agent_state.py start /work/repo \
18
+ --owner agent-a \
19
+ --objective "Implement rotating refresh tokens with replay detection" \
20
+ --criteria "Rotation works; replay revokes family; concurrent refresh is race-free; tests pass" \
21
+ --own-files "src/auth.py,tests/test_auth.py"
22
+
23
+ python3 scripts/route_task.py route \
24
+ --task "Implement rotating refresh tokens with replay detection" \
25
+ --phase implement --touched-paths "src/auth.py" --dependents-count 6 --repo /work/repo --record
26
+ ```
27
+
28
+ ## 3. Targeted Slices + Anti-Duplication Logging (Agent A)
29
+ ```bash
30
+ python3 ../local-context-index/scripts/context_index.py outline /work/repo src/auth.py --format compact
31
+ python3 ../local-context-index/scripts/context_index.py slice /work/repo src/auth.py --symbol issue_refresh_token
32
+
33
+ python3 scripts/agent_state.py record-inspection /work/repo \
34
+ --path src/auth.py --lines 35-92 \
35
+ --finding "issue_refresh_token writes directly to TokenStore without lock; family_id column already exists"
36
+
37
+ python3 scripts/agent_state.py decision /work/repo \
38
+ --title "Revoke entire token family on replay" \
39
+ --rationale "Limits stolen-token window when either legitimate user or attacker replays a spent token" \
40
+ --alternatives "Single-token invalidation (rejected: leaves rotated child valid)" \
41
+ --files "src/auth.py"
42
+
43
+ python3 scripts/agent_state.py record-attempt /work/repo \
44
+ --approach "Optimistic check-then-set without DB transaction" \
45
+ --outcome failed --reason "Concurrent refresh test produced duplicate active children"
46
+ ```
47
+
48
+ ## 4. Automatic Escalation After Failure, Then Handoff (Agent A)
49
+ ```bash
50
+ python3 scripts/route_task.py escalate /work/repo --reason "Concurrency race under parallel refresh requests"
51
+
52
+ python3 scripts/agent_state.py record-check /work/repo \
53
+ --cmd "python3 -m unittest tests/test_auth.py" --exit-code 0 --summary "12 passed after transactional lock"
54
+
55
+ python3 ../local-context-index/scripts/context_index.py index /work/repo
56
+
57
+ python3 scripts/agent_state.py handoff /work/repo \
58
+ --recipient review-agent \
59
+ --summary "Implemented transactional rotation & family revocation; 12 auth tests pass." \
60
+ --next "Audit lock ordering in src/auth.py:60-115 and run full regression suite." \
61
+ --entry-points "src/auth.py:60-115,tests/test_auth.py:80-140"
62
+ ```
63
+
64
+ ## 5. Zero-Reexploration Takeover & Down-Shift for Docs (Agent B)
65
+ ```bash
66
+ # Single call gives objective, drift check, active decisions, failed dead ends, verified checks, and entry points:
67
+ python3 scripts/agent_state.py brief /work/repo
68
+ python3 scripts/agent_state.py accept /work/repo --owner review-agent
69
+
70
+ # Slice ONLY the entry points instead of scanning the repo:
71
+ python3 ../local-context-index/scripts/context_index.py slice /work/repo src/auth.py --start 60 --end 115
72
+
73
+ # Down-shift to fast tier for changelog update (respects warm-cache hysteresis):
74
+ python3 scripts/route_task.py downshift /work/repo --task "Update CHANGELOG.md" --phase docs --record
75
+
76
+ python3 scripts/agent_state.py complete /work/repo --result "Concurrency verified; full test suite passed (48/48); changelog updated."
77
+ ```
@@ -0,0 +1,63 @@
1
+ # Model Routing, Dynamic Switching & Escalation Reference
2
+
3
+ ## Contents
4
+ - Multi-Signal Scoring Model
5
+ - Escalation & Down-Shift Rules
6
+ - Cache-Affinity Hysteresis
7
+ - Planning Multi-Step Routes
8
+ - Programmatic Adapter (`llm_adapter.py`)
9
+
10
+ ## Multi-Signal Scoring Model
11
+
12
+ `python3 scripts/route_task.py route` combines five objective signal classes (configured in `config/models.json`):
13
+
14
+ 1. **Keyword Risk & Complexity**:
15
+ - `critical_keywords` (+6, forces `critical` + human approval): `drop table`, `production deploy`, `rotate secret`, `irreversible`, `iam policy`, etc.
16
+ - `high_risk_keywords` (+3 each): `security`, `authentication`, `payment`, `migration`, `concurrency`, `privacy`, `sql injection`, etc.
17
+ - `high_complexity_keywords` (+2 each): `architecture`, `redesign`, `refactor`, `distributed`, `race condition`, `root cause`, `state machine`, etc.
18
+ - `low_complexity_keywords` (-1 each): `typo`, `format`, `lint`, `rename`, `docstring`, `readme`, `summarize`, `triage`, etc.
19
+ 2. **Sensitive File Paths** (`--touched-paths`): automatically adds +3 and enforces a `high` tier floor when touching paths containing `auth`, `security`, `crypto`, `billing`, `payment`, `migration`, `infra`, `terraform`, `k8s`, `iam`, `.github/workflows`.
20
+ 3. **Task Phase** (`--phase`):
21
+ - Down-bias: `triage` (-2), `explore` (-2), `summarize` (-2), `format` (-2), `docs` (-1)
22
+ - Neutral: `implement` (0), `test` (0)
23
+ - Up-bias: `review` (+1), `debug` (+2), `architect` (+3), `security` (+3), `migrate` (+3), `deploy` (+5)
24
+ 4. **Structural Blast Radius**:
25
+ - `--files-count`: ≥3 (+1), ≥8 (+3)
26
+ - `--dependents-count` (from `context_index.py deps`): ≥4 (+1), ≥10 (+3)
27
+ - `--diff-lines`: ≥150 (+1), ≥450 (+2)
28
+ - `--context-tokens`: ≥40,000 (+1)
29
+ - `--uncertainty`: `medium` (+1), `high` (+2)
30
+ 5. **Budget Mode** (`--budget-mode normal|frugal|strict`): raises the `high` score threshold from 3 → 4 (`frugal`) or 5 (`strict`), **without ever overriding** `critical`, explicit `--risk high`, or sensitive-path floors.
31
+
32
+ ## Escalation & Down-Shift Rules
33
+
34
+ ### Automatic Up-Shift (2-Attempt Rule)
35
+ - **1 failure on `low`** → escalates to `medium` (`balanced`).
36
+ - **2+ failures on `low` or `medium`** → escalates to `high` (`reasoning`).
37
+ - **2+ failures on `high` or `critical`** → sets `action: "require_human"` and `human_approval_required: true` (stop tweaking; trigger root-cause reset or human review).
38
+
39
+ ### Automatic Down-Shift
40
+ - Run `python3 scripts/route_task.py downshift <repo> --task "<step>" --phase format --expected-turns 1 --record`.
41
+ - Safely shifts `high`/`medium` → `low` for bounded routine subtasks when failure count is 0 and risk is low.
42
+
43
+ ## Cache-Affinity Hysteresis
44
+
45
+ When `--repo` is provided (or `--warm-cache-tier` + `--warm-prefix-tokens`), `route_task.py` reads `.agent-state/cache_registry.json`:
46
+ - If a down-shift is proposed while a large prefix (≥1,024 tok) is **warm within TTL** on the current tier, the router compares:
47
+ - **Stay cost**: `warm_prefix × cached_input_price + volatile + output` over `expected_turns`
48
+ - **Cold-switch cost**: `warm_prefix × uncached_input_price` (turn 1) + cached (turns 2..N)
49
+ - If staying warm is cheaper, it returns `action: "stay_warm_cache"` and recommends down-shifting only for an isolated fresh-context subagent.
50
+ - **Safety invariant**: cache-affinity NEVER delays an up-shift.
51
+
52
+ ## Planning Multi-Step Routes
53
+
54
+ Route an entire plan in one call and see estimated savings vs always-reasoning:
55
+ ```bash
56
+ python3 scripts/route_task.py plan --steps "Explore auth module|Implement token rotation|Add unit tests|Format changelog"
57
+ ```
58
+
59
+ ## Programmatic Adapter (`llm_adapter.py`)
60
+
61
+ - `prepare_request(model, stable_prefix, dynamic_context, user_task, project_prefix=...)`: zero-dependency payload builder injecting Anthropic/Bedrock `cache_control`, OpenAI `prompt_cache_key`, deterministic prefix canonicalization, and cache-buster linting.
62
+ - `LLMAdapter.complete(...)`: uses optional `litellm`, automatically retries via `AGENT_MODEL_<ALIAS>_FALLBACK`, normalizes provider cache usage via `parse_provider_usage()`, and optionally writes telemetry to `<repo>/.agent-state/cache_registry.json`.
63
+ - `LLMAdapter.complete_with_escalation(start_alias, ..., validator=fn)`: starts cheap and walks `fast -> balanced -> reasoning` only when `validator(content)` fails.