pantheon-opencode 1.6.0-beta.6 → 1.6.0-beta.7

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 (58) hide show
  1. package/AGENTS.md +27 -820
  2. package/CHANGELOG.md +116 -0
  3. package/README.md +132 -39
  4. package/README.pt-BR.md +47 -23
  5. package/package.json +6 -1
  6. package/plugin.json +1 -1
  7. package/pyproject.toml +3 -1
  8. package/scripts/build-agents-md.mjs +162 -28
  9. package/scripts/doctor.mjs +104 -22
  10. package/scripts/install/agents-md.mjs +2 -2
  11. package/scripts/install/config-migration.mjs +154 -7
  12. package/scripts/install/opencode.mjs +202 -40
  13. package/scripts/install/shared.mjs +115 -7
  14. package/scripts/install/strings.mjs +8 -0
  15. package/scripts/probe-pantheon-cost.mjs +16 -3
  16. package/scripts/sync-artifacts.mjs +2 -2
  17. package/scripts/test-opencode-v2-sandbox.sh +820 -86
  18. package/skills-lock.json +6 -5
  19. package/src/agents/aphrodite.md +17 -28
  20. package/src/agents/demeter.md +8 -18
  21. package/src/agents/hephaestus.md +10 -11
  22. package/src/agents/hermes.md +15 -30
  23. package/src/agents/prometheus.md +16 -10
  24. package/src/agents/talos.md +4 -1
  25. package/src/agents/themis.md +4 -3
  26. package/src/agents/zeus.md +16 -280
  27. package/src/instructions/agent-return-format.instructions.md +4 -50
  28. package/src/instructions/backend-standards.instructions.md +2 -0
  29. package/src/instructions/frontend-standards.instructions.md +3 -1
  30. package/src/instructions/memory-protocol.instructions.md +12 -121
  31. package/src/instructions/zeus-anti-stall.instructions.md +8 -111
  32. package/src/instructions/zeus-communication-rules.instructions.md +0 -1
  33. package/src/instructions/zeus-memory-operations.instructions.md +26 -0
  34. package/src/instructions/zeus-timeout-retry.instructions.md +9 -130
  35. package/src/pantheon/secret-scanner.ts +489 -0
  36. package/src/pantheon/v2-delegation-enforce.ts +86 -0
  37. package/src/pantheon/v2-execute-after.ts +186 -0
  38. package/src/pantheon/v2-unsupported.mjs +0 -23
  39. package/src/plugin-v2.ts +254 -102
  40. package/src/plugins/pantheon-hooks.ts +82 -35
  41. package/src/plugins/tui/README.md +14 -0
  42. package/src/plugins/tui/dist/tui.d.ts +11 -8
  43. package/src/plugins/tui/dist/tui.d.ts.map +1 -1
  44. package/src/plugins/tui/dist/tui.js +102 -62
  45. package/src/plugins/tui/package-lock.json +30 -33
  46. package/src/plugins/tui/package.json +5 -1
  47. package/src/plugins/tui/src/index.tsx +163 -107
  48. package/src/plugins/tui/tsdown.config.ts +17 -0
  49. package/src/routing.yml +12 -9
  50. package/src/skills/README.md +9 -4
  51. package/src/skills/agent-coordination/SKILL.md +13 -83
  52. package/src/skills/artifact-management/SKILL.md +12 -5
  53. package/src/skills/auto-continue/SKILL.md +37 -27
  54. package/src/skills/code-review-checklist/SKILL.md +5 -5
  55. package/src/skills/council-synthesis/SKILL.md +29 -0
  56. package/src/skills/tdd-with-agents/SKILL.md +18 -10
  57. package/scripts/hooks/scan-secrets.sh +0 -97
  58. package/src/instructions/zeus-council-synthesis.instructions.md +0 -299
package/AGENTS.md CHANGED
@@ -9,19 +9,19 @@ This project uses the Pantheon multi-agent framework with 14 specialized agents.
9
9
 
10
10
  | Agent | Role |
11
11
  |-------|------|
12
- | @aphrodite | Frontend specialist — React 19, TypeScript strict, WCAG accessibility, responsive design, TDD, modern API patterns, deprecated npm detection. Calls apollo for discovery, sends to themis for review. |
12
+ | @aphrodite | Frontend specialist — React 19, TypeScript strict, WCAG accessibility, responsive design, TDD, modern API patterns, deprecated npm detection. Uses discovery/review proportionally to scope and risk. |
13
13
  | @apollo | Read-only investigation scout — 3–10 parallel searches across codebase, external docs, and GitHub. Called by: athena, zeus, hermes, aphrodite, demeter. No edits, no commands. |
14
14
  | @athena | Strategic planner & architect — research-first, plan-only, never implements. Plans include quality gates (ruff/Biome, dep detection, LTS policy). Calls apollo for discovery. |
15
- | @demeter | Database specialist — SQLAlchemy 2.0, Alembic, query optimization, N+1 prevention, TDD migrations, modern DB libs. Calls apollo for discovery, sends to themis. |
15
+ | @demeter | Database specialist — SQLAlchemy 2.0, Alembic, query optimization, N+1 prevention, TDD migrations, modern DB libs. Preserves review gates for schema/data changes. |
16
16
  | @gaia | Remote sensing domain specialist — satellite image processing, spectral analysis, SAR, change detection, time series, ML/DL classification. Read-only analysis of geospatial data. |
17
17
  | @hephaestus | AI tooling & pipelines specialist — LangChain/LangGraph chains, RAG architecture, vector stores, embedding strategies. Forges AI infrastructure. Calls apollo, sends to themis. |
18
- | @hermes | Backend specialist — FastAPI, Python, async, TDD (RED→GREEN→REFACTOR), modern Python stdlib, obsolete lib detection. Calls apollo for discovery, sends to themis. |
18
+ | @hermes | Backend specialist — FastAPI, Python, async, TDD (RED→GREEN→REFACTOR), modern Python stdlib, obsolete lib detection. Uses discovery/review proportionally to scope and risk. |
19
19
  | @iris | GitHub operations specialist — branches, pull requests, issues, releases, tags. Called by zeus after review. Never pushes or merges without explicit human approval. Integrates with VS Code GitHub Pull Requests extension. |
20
20
  | @mnemosyne | Memory bank quality owner — initializes .pantheon/memory-bank/, writes ADRs and task records on explicit request. Called by zeus. Never invoked automatically after phases. |
21
21
  | @nyx | Observability & monitoring specialist — OpenTelemetry tracing, token/cost tracking, agent performance analytics, LangSmith integration. Calls apollo for discovery, sends to themis. |
22
22
  | @prometheus | Infrastructure + model provider specialist — Docker, CI/CD, multi-model routing, cost optimization, provider abstraction |
23
23
  | @talos | Hotfix express lane — direct fixes for small bugs, CSS, typos, minor logic. No TDD ceremony, no orchestration overhead. Standalone, no subagents. Escalates complex issues to zeus. |
24
- | @themis | Quality & security gate — ruff/Biome linting, dead/legacy code detection, OWASP Top 10, coverage >80%, correctness, deprecation audit. Called by implementers; escalates blockers to zeus. |
24
+ | @themis | Quality & security gate — ruff/Biome linting, dead/legacy code detection, OWASP Top 10, applicable coverage requirements, correctness, deprecation audit. Reviews material/sensitive changes. |
25
25
  | @zeus | Central orchestrator — never implements. Delegates to: athena, apollo, hermes, aphrodite, demeter, prometheus, themis, iris, mnemosyne, talos, hephaestus, nyx |
26
26
 
27
27
  ## OpenCode Setup
@@ -38,13 +38,14 @@ Para validar a instalação global do pacote pantheon-opencode COMO UM USUÁRIO
38
38
 
39
39
  - Rodar: `bash ~/pantheon-sandbox/run-test.sh` (opencode mcp list 5/5 connected + doctor 0 erros + abre TUI isolado)
40
40
  - Regra para agentes: ao validar instalação global (npm pack, `init`, MCPs, hooks), usar o sandbox — NUNCA testar no ambiente de dev
41
- - Descarte: `rm -rf ~/pantheon-sandbox`
42
- - Detalhes: ver `~/pantheon-sandbox/README.md`
41
+ - Prepare/atualize com `bash scripts/test-opencode-v2-sandbox.sh --prepare`; isso gera `run-test.sh`, `start-pantheon.sh` e o README do sandbox
42
+ - Descarte somente pelo reset com guardas: `bash scripts/test-opencode-v2-sandbox.sh --reset` (nunca use `rm -rf` manualmente)
43
+ - Detalhes: ver `~/pantheon-sandbox/README.md` após o prepare
43
44
 
44
45
  ## Conventions
45
46
 
46
- - TDD: Write failing test first, then implement
47
- - Coverage minimum: 80%
47
+ - TDD: RED→GREEN→REFACTOR for testable behavior; use focused checks for micro-edits
48
+ - Honor repository coverage thresholds when relevant; preserve stronger auth/security/data-integrity gates
48
49
  - Async/await on all I/O
49
50
  - Type hints on all functions
50
51
  - PRs always update the README — every pull request must document newly added features, behaviors, env vars, or commands in the README before being opened.
@@ -55,7 +56,8 @@ Para validar a instalação global do pacote pantheon-opencode COMO UM USUÁRIO
55
56
 
56
57
  The following sections are consolidated from `src/instructions/*.instructions.md`
57
58
  so both OpenCode V1 (auto-loads AGENTS.md) and V2 (loads AGENTS.md, ignores the
58
- `instructions` config key) receive identical instruction content.
59
+ `instructions` config key) receive identical shared rules. Agent-scoped rules
60
+ are rendered into only the matching installed agent prompts.
59
61
 
60
62
  <!-- Source: src/instructions/agent-return-format.instructions.md -->
61
63
  ## Agent Return Format
@@ -63,7 +65,7 @@ so both OpenCode V1 (auto-loads AGENTS.md) and V2 (loads AGENTS.md, ignores the
63
65
 
64
66
  # Agent Return Format
65
67
 
66
- All implementation agents (Hermes, Aphrodite, Demeter, Hephaestus, Prometheus) MUST return results to Zeus in this format:
68
+ Implementation agents (Hermes, Aphrodite, Demeter, Hephaestus, Prometheus) return:
67
69
 
68
70
  ## subtask_summary
69
71
  **files_changed:** [list of file paths, one per line]
@@ -74,148 +76,13 @@ All implementation agents (Hermes, Aphrodite, Demeter, Hephaestus, Prometheus) M
74
76
  **status:** complete | partial (reason) | escalated (reason)
75
77
  **blockers:** [list any blockers or null]
76
78
 
77
- For investigation agents (Apollo, Athena), return structured findings with:
79
+ Investigation agents (Apollo, Athena) return structured findings with:
78
80
  - Key findings as bullet points
79
81
  - File paths with line numbers
80
82
  - Relevant code snippets (max 3 lines each)
81
83
 
82
- ## Council Specialist Response Format
83
-
84
- When responding to a `/pantheon` council synthesis invocation, specialists MUST return this structured format:
85
-
86
- ```
87
- ## specialist_response
88
- **position:** <clear one-sentence position answering the question>
89
- **reasoning:** <2-4 sentences with logical chain>
90
- **trade_offs:** <what's gained vs lost, specific>
91
- **risks:** <what could go wrong, max 3 items>
92
- **confidence:** High | Medium | Low
93
- **agreement_signals:** agree:@agent1 on <issue>, agree:@agent2 on <issue> | disagree:@agent3 on <issue>
94
- **specific_claims:** <count of specific factual claims in response>
95
- ```
96
-
97
- ### Field Rules
98
-
99
- | Field | Required | Validation |
100
- |-------|----------|------------|
101
- | position | ✅ | Single sentence, must directly answer the question |
102
- | reasoning | ✅ | 2-4 sentences with logical chain |
103
- | trade_offs | ✅ | At least one gain and one loss, specific to context |
104
- | risks | ✅ | Max 3 bullet points |
105
- | confidence | ✅ | One of: High, Medium, Low |
106
- | agreement_signals | Optional | Format: `agree:@agent on issue \| disagree:@agent on issue`. Use only when you can reference other specialists expected positions. |
107
- | specific_claims | ✅ | Integer count of verifiable factual statements in the response |
108
-
109
- ### Confidence Guidelines
110
-
111
- - **High**: Position backed by 3+ specific claims with evidence or direct experience
112
- - **Medium**: Position backed by 1-2 specific claims
113
- - **Low**: Position is opinion-based or speculative
114
-
115
- ### Example
116
- ```
117
- ## specialist_response
118
- **position:** The BackgroundJobBoard should be used for council crash recovery
119
- **reasoning:** The board already supports running→completed→reconciled state machine with persistence. Registering council dispatches there adds ~50ms overhead but prevents total session loss on context crash. The WAL pattern ensures no data loss on restart.
120
- **trade_offs:** Gain: crash recovery for multi-minute council sessions. Lose: ~50ms registration overhead per council.
121
- **risks:** Board persistence failure could block council start — implement with fire-and-forget error handling
122
- **confidence:** High
123
- **agreement_signals:** agree:@themis on persist-before-notify
124
- **specific_claims:** 3
125
- ```
126
-
127
84
  ## Memory Context
128
- If this agent used `memory_recall` or `memory_search`, include the relevant memory entries
129
- used as context for the response.
130
-
131
- <!-- Source: src/instructions/backend-standards.instructions.md -->
132
- ## Backend Development Standards
133
-
134
-
135
- # Backend Development Standards (Hermes)
136
-
137
- ## Async/Await
138
- - Use async/await for ALL I/O operations (database, external APIs, file operations)
139
- - Never block on async operations
140
- - Use `asyncio.gather()` for parallel operations
141
-
142
- ## Test-Driven Development
143
- - RED: Write a failing test
144
- - GREEN: Write minimal code to pass
145
- - REFACTOR: Improve without breaking tests
146
-
147
- ## Type Safety
148
- - Type hints on all function parameters
149
- - Type hints on all return types
150
- - Use Pydantic for request/response validation
151
-
152
- ## Code Organization
153
- - Maximum 300 lines per file
154
- - Separate: routes → services → models
155
- - Docstrings on public functions (Google format)
156
-
157
- ## Error Handling
158
- - Never silent failures (catch and log)
159
- - Use appropriate HTTP status codes
160
- - Return friendly error messages (no stack traces)
161
- - Implement retry logic with exponential backoff
162
-
163
- ## Performance
164
- - Avoid N+1 queries (use eager loading/joins)
165
- - Implement pagination for list endpoints
166
- - Cache frequently accessed data
167
- - Monitor for async deadlocks
168
-
169
- ## Security
170
- - Input validation on all endpoints
171
- - CSRF protection
172
- - Rate limiting for sensitive endpoints
173
- - Sanitize logs (never log passwords/tokens)
174
-
175
- <!-- Source: src/instructions/frontend-standards.instructions.md -->
176
- ## Frontend Development Standards
177
-
178
-
179
- # Frontend Development Standards (Aphrodite)
180
-
181
- ## TypeScript
182
- - Strict mode always (no `any` types)
183
- - Props interfaces on all components
184
- - Return type annotations on all functions
185
-
186
- ## Components
187
- - Single Responsibility Principle
188
- - Reusable and composable
189
- - Max 300 lines per component
190
- - Atomic Design pattern
191
-
192
- ## Accessibility
193
- - ARIA labels on interactive elements
194
- - Keyboard navigation support
195
- - Color contrast WCAG AA
196
- - Semantic HTML
197
-
198
- ## Responsive Design
199
- - Mobile-first approach
200
- - Breakpoints: 640px, 768px, 1024px, 1280px
201
- - Test on multiple devices
202
-
203
- ## State Management
204
- - Hooks (useState, useContext, useReducer)
205
- - Centralized state for app-wide data
206
- - Local state for component-specific needs
207
-
208
- ## Testing
209
- - React Testing Library (no snapshot testing)
210
- - Test behavior not implementation
211
- - >80% coverage requirement
212
- - Test user workflows
213
-
214
- ## Styling
215
- - Tailwind CSS + custom CSS when needed
216
- - Design tokens for colors/spacing
217
- - Responsive classes
218
- - No inline styles
85
+ If this agent used `memory_recall` or `memory_search`, include the relevant memory entries used as context for the response.
219
86
 
220
87
  <!-- Source: src/instructions/memory-protocol.instructions.md -->
221
88
  ## Memory Protocol
@@ -223,131 +90,22 @@ used as context for the response.
223
90
 
224
91
  # 🧠 Memory Protocol — Universal Rules
225
92
 
226
- These rules apply to ALL Pantheon agents. Agent-specific overrides are defined
227
- in each agent's `## 🧠 Memory Protocol` section.
93
+ These rules apply to all agents; each agent file may add domain-specific rules.
228
94
 
229
95
  ## Universal Rules
230
96
 
231
- ### 1. Pre-Work Read-Only Recall
232
- **Call `memory_search()` at task start before any file reads.**
233
- - Use domain-specific context matching your agent's focus area
234
- - Single call per task, not per turn
235
- - Agents have **read-only** memory access — only `memory_search()` is available
236
-
237
- ### 2. Auto-Store by Zeus on Subtask Summary
238
- **`memory_store()` is called AUTOMATICALLY by Zeus when you return a subtask_summary.**
239
- - Include a clear `summary` field in your return — no explicit `memory_store()` call needed
240
- - This is the **ONLY** persistence path: agent → subtask_summary → Zeus → memory_store
241
- - Zeus persists ALL agent returns (implementers and read-only agents alike)
242
-
243
- ### 3. Write-Ahead Log (WAL)
244
- Before Zeus calls `memory_store()`, it writes a write-ahead log to:
245
- ```
246
- .pantheon/memory-wal/<agent>/<timestamp>.json
247
- ```
248
- - WAL format: `{ agent, phase, summary, files_changed, status, timestamp }`
249
- - WAL is written **before** the store operation — if store crashes, WAL is recovered on next session start
250
- - WAL files are ephemeral (auto-cleaned after 7 days)
251
-
252
- ### 4. Relevance Threshold
253
- **Skip search results if relevance score < 0.3.**
254
- - Prevents noise from unrelated past entries
255
- - Applies to `memory_search()` results only
256
-
257
- ### 5. Permanent Documentation
258
- **ADR-level decisions → delegate to `@mnemosyne`.**
259
- - Use for: architecture decisions, significant trade-offs, pattern changes
260
- - Not for: routine task summaries (handled by Auto-Store)
261
-
262
- ## Per-Agent Overrides
263
-
264
- Each agent file defines overrides in its `## 🧠 Memory Protocol` section:
265
- - Domain-specific `memory_search()` context string
266
- - Read-only access via `memory_search()` only — no `memory_store` for subagents
267
- - Agent-specific rules (session-end, sprint close, quick-index, etc.)
268
-
269
-
270
- ## Delegation Cache
271
-
272
- Para otimizar decisoes de delegacao e reduzir gasto de tokens:
273
-
274
- 1. **memory_search(query=task_prompt, top_k=2)** antes de aplicar a arvore de roteamento
275
- 2. Se score > 0.85 → reutiliza agente + background_mode do cache
276
- 3. Se score ≤ 0.85 → aplica regras estaticas e memory_store() com:
277
- - key: deleg:<task_type>
278
- - value: JSON.stringify({agent, background, pattern})
279
- - metadata: JSON.stringify({type: "decision", score: N})
280
-
281
- `value` E `metadata` sao JSON-encoded strings — o runtime exige que o
282
- chamador serialize os dois. Objeto cru em `metadata` e rejeitado pelo
283
- `BeforeValidator` do servidor com `metadata must be a JSON object encoded
284
- as a string (got object). json.dumps it first. Example: metadata='{"type":
285
- "decision", "score": 0.9}'`.
286
-
287
- 4. **kv_store(namespace="deleg", key="deleg:<pattern>", value=...)** para padroes recorrentes de delegacao
288
- 5. **kv_get(namespace="deleg", key="deleg:<pattern>")** para reusar decisoes ja tomadas
289
-
290
- Isso elimina ~300 tokens de reasoning por delegacao quando o cache acerta.
291
-
292
- ## Council Decisions Namespace
293
-
294
- Council synthesis decisions are persisted in a dedicated `council_decisions` namespace for precedent fast-path retrieval:
295
-
296
- ### Write Path
297
- After every `/pantheon` council synthesis completes, Zeus stores:
298
- ```
299
- memory_store({
300
- namespace: "council_decisions",
301
- key: "council:<yyyy-mm-dd>:<slug>",
302
- value: JSON.stringify({
303
- question: "original question",
304
- specialists: ["@agent1", "@agent2"],
305
- recommendation: "final recommendation",
306
- confidence: "High|Medium|Low",
307
- agreements: ["point1", "point2"],
308
- divergences: [{"issue": "...", "resolution": "..."}],
309
- response_rate: "X of Y",
310
- themis_audit: "approved|issues",
311
- precedent_used: false,
312
- timestamp: "<ISO-8601>"
313
- }),
314
- metadata: JSON.stringify({
315
- type: "council_decision",
316
- specialist_count: N,
317
- model_tier_used: "premium|default|fast"
318
- })
319
- })
320
- ```
321
- `value` is JSON-serialized before storing (the MCP `memory_store.value` argument is a string).
322
- `metadata` works the same way — it is a JSON object encoded as a **string**, so pass
323
- `JSON.stringify({...})`. A raw object is rejected with `metadata must be a JSON object
324
- encoded as a string (got object). json.dumps it first. Example: metadata='{"type":
325
- "decision", "score": 0.9}'` (enforced by a `BeforeValidator` in
326
- `memory_mcp.py`). **Both `value` and `metadata` must be serialized by the caller.**
327
-
328
- ### Read Path (Precedent Fast-Path)
329
- Before dispatching a new council, Zeus runs:
330
- ```
331
- memory_search(query=question, top_k=2, namespace="council_decisions")
332
- ```
333
-
334
- Result interpretation:
335
- | Score | Age | Action |
336
- |-------|-----|--------|
337
- | > 0.85 | < 30 days | Return precedent verbatim (note "⚠️ Decisão de [data] — reavaliar se contexto mudou") as fast-path answer. Skip council dispatch entirely. |
338
- | > 0.85 | >= 30 days | Return with warning "Reavaliar se contexto mudou — decisão tem mais de 30 dias" + proceed with council |
339
- | 0.5 - 0.85 | Any | Include as context for specialists but still dispatch council |
340
- | < 0.5 | Any | Ignore, proceed with fresh council |
341
-
342
- ### TTL & Maintenance
343
- - Council decisions are LONG-TERM (no TTL or TTL = 365 days)
344
- - Stale decisions (age > 90 days) should be flagged but NOT deleted — they remain as historical record
345
- - Purge only via explicit namespace cleanup when decisions are superseded by ADRs
346
-
347
- ### When NOT to Use
348
- - Routine task summaries → use `default` namespace (auto-store by Zeus)
349
- - Sprint/progress tracking → use `session` namespace
350
- - ADR-level architecture decisions → delegate to @mnemosyne for permanent documentation
97
+ ### Task-start search
98
+ **Before any file reads, call exactly once at task start:** `memory_search(query=task_prompt, top_k=2)`.
99
+ - Reuse the same result for task context and delegation routing. A KV cache hit does not skip this search or trigger another task FTS search.
100
+ - Council-precedent lookup is separate. Use domain-relevant context; do not issue another task-memory search for routing.
101
+ - Agents have read-only memory access: only `memory_search()` is available.
102
+
103
+ ### Summary persistence and WAL
104
+ `memory_store()` is called automatically by Zeus when an agent returns a `subtask_summary`; include a clear `summary`. This is the only persistence path, for implementers and read-only agents alike.
105
+ Before storing, Zeus writes `.pantheon/memory-wal/<agent>/<timestamp>.json` with `{agent, phase, summary, files_changed, status, timestamp}`. The WAL precedes storage, is recovered next session if storage fails, and expires after 7 days.
106
+
107
+ ### Relevance and permanent records
108
+ Skip `memory_search()` results below 0.3 relevance. Delegate ADR-level architecture decisions, significant trade-offs, and pattern changes to @mnemosyne; routine summaries use auto-store.
351
109
 
352
110
  <!-- Source: src/instructions/yagni.instructions.md -->
353
111
  ## YAGNI Anti-overengineering
@@ -370,121 +128,6 @@ Result interpretation:
370
128
 
371
129
  When reviewing code, always ask: "Is this YAGNI? Could we solve this more simply?"
372
130
 
373
- <!-- Source: src/instructions/zeus-anti-stall.instructions.md -->
374
- ## Zeus Anti-Stall
375
-
376
-
377
- # 🛑 ANTI-STALL & STALL DETECTION
378
-
379
- You MUST proactively detect and recover from stalled states. Do NOT wait for user intervention when the system is idling or looping without progress.
380
-
381
- ## Stall Detection Protocol
382
-
383
- You MUST self-monitor for these stall conditions:
384
-
385
- | Symptom | Detection Rule | Recovery Action |
386
- |---------|---------------|-----------------|
387
- | Silent loop | 3+ consecutive turns with no tool call AND no visible progress | Output `[STALL_DETECTED]` and re-read your task definition. If still stuck, escalate to user with: "I appear to be stuck on [task]. Options: (1) retry with different approach, (2) delegate to specialist, (3) simplify scope." |
388
- | Delegation black hole | Agent dispatched but no response after 2x the timeout from routing.yml | Log the hang, cancel via `cancel_task`, then follow the fallback chain in `## ⏱️ Timeout & Retry Enforcement` |
389
- | Circular delegation | Same specialist re-dispatched for same task 2+ times without progress | Break cycle: dispatch to different specialist OR escalate to user |
390
- | Idle after completion | All background tasks completed but no synthesis/next step for 2+ turns | Force synthesis: summarize all completed results and propose next action |
391
- | Context thrash | Re-reading same files repeatedly without new action | Stop re-reading. State: "Already have context on [file]. Proceeding with [action]." |
392
-
393
- ## Phase Reminder
394
-
395
- After dispatching background specialists, you MUST:
396
- 1. DO NOT poll running jobs or consume their partial output
397
- 2. DO NOT advance dependent work until terminal results arrive
398
- 3. Continue orchestration ONLY on non-overlapping independent work
399
- 4. If nothing independent remains, briefly report what was launched and WAIT
400
-
401
- Self-check every 3 turns: "Am I waiting on a delegate? Have I polled without need? Is there independent work I can do?"
402
-
403
- ## Delegate Retry Enhancement
404
-
405
- When a delegation fails (timeout, empty response, error):
406
-
407
- 1. **FIRST:** Check if the error is a known pattern:
408
- - "Agent not responding" → verify agent name matches routing.yml
409
- - "Context exceeded" → reduce scope, split into smaller tasks
410
- - "Permission denied" → verify agent has correct tools/permissions
411
-
412
- 2. **Retry ONCE** with rephrased prompt — add: "Previous attempt failed with: [error]. Adjusted approach: [what changed]."
413
-
414
- 3. **If retry also fails** → do NOT retry blindly; follow the fallback chain and escalation protocol in `## ⏱️ Timeout & Retry Enforcement`.
415
-
416
- ## Progress Checkpoint
417
-
418
- On tasks expected to run > 5 turns:
419
- - After turn 5: output `[CHECKPOINT] Completed so far: [summary]. Remaining: [list].`
420
- - After turn 10: re-evaluate. If < 50% done, consider splitting or escalating.
421
- - If 3 consecutive turns produce no tool calls: trigger Stall Detection Protocol (see above).
422
-
423
- ## Heartbeat & Checkpoint Integration
424
-
425
- All session state lives in **pantheon-persistence** (namespace `checkpoint:<slug>`).
426
- No file I/O, no checkpoint_session.py — TTL (4h) handles cleanup automatically.
427
-
428
- ### Heartbeat Check
429
- - If `context_get(slug=slug, key="heartbeat", session_id=SESSION_ID)` returns a checkin older than 300s, log a stall warning and resume
430
- - Write heartbeat after every anti-stall recovery action:
431
- ```
432
- context_save(slug=slug, key="heartbeat", content=JSON.stringify({"status": "alive", "last_action": "...", "turn_count": N}), session_id=SESSION_ID)
433
- ```
434
-
435
- ### Checkpoint Auto-Save (Pré-Compactação)
436
- Before ANY delegate dispatch, save a checkpoint:
437
- ```
438
- context_save(slug=slug, key="phase:N", content=JSON.stringify({
439
- "phase": {"current": N, "total": M, "name": "..."},
440
- "turn_count": N, "agent": "...", "summary": "..."
441
- }), session_id=SESSION_ID)
442
- ```
443
- **`content.phase` must be an OBJECT, not a bare number.** `{"phase": 1}` is rejected with
444
- `context_save: content.phase must be an object (got number)`. The server reads `current`
445
- and `total` (non-negative ints) and `name` (string, max 256 **bytes** — the guard
446
- measures `len(value.encode())`, so multi-byte characters count as more than one). That
447
- set is not closed: any other key inside `phase` is accepted and ignored, never an
448
- error. The `"phase:N"` slot KEY above is unrelated to `content.phase` and stays a plain
449
- string.
450
- All checkpoints auto-expire after 4h (TTL=14400).
451
-
452
- ### Gatilho de Pré-Compactação (Anti-perda de estado)
453
- Antes da compactação nativa do OpenCode disparar (75-96% do context window),
454
- o Zeus DEVE salvar o estado atual:
455
- 1. Capture session_id do primeiro `context_save` da sessão
456
- 2. Salve heartbeat + phase atual + tarefas pendentes
457
- 3. Só então permita que a compactação prossiga
458
- ```
459
- # Ao iniciar sessão (session_id é REQUIRED — use o id da sessão corrente):
460
- result = context_save(slug=slug, key="init", content=JSON.stringify(session_state), session_id=SESSION_ID)
461
- SESSION_ID = result.session_id # ← guarde para toda a sessão
462
-
463
- # Antes de CADA delegação:
464
- context_save(slug=slug, key=f"pre:{agent}", content=JSON.stringify(current_state), session_id=SESSION_ID)
465
-
466
- # Após retorno do agente:
467
- context_save(slug=slug, key=f"post:{agent}", content=JSON.stringify(result_state), session_id=SESSION_ID)
468
- ```
469
- Isso garante que o estado sobreviva à compactação — o "latest" pointer
470
- sempre aponta para o checkpoint mais recente, mesmo após compactação.
471
-
472
-
473
- ### Context Retrieval
474
- Next-phase agents retrieve previous context via:
475
- ```
476
- context_get(slug=slug, session_id=SESSION_ID) # most recent checkpoint ("latest" is the default key)
477
- context_get(slug=slug, key="phase:3", session_id=SESSION_ID) # specific phase
478
- context_list(slug=slug, session_id=SESSION_ID) # all checkpoints
479
- ```
480
-
481
- ### Long-Session Progress
482
- Every 5 turns during a long session, update STATUS.md with:
483
- - Current phase
484
- - Completed tasks
485
- - Pending tasks
486
- - Any blockers
487
-
488
131
  <!-- Source: src/instructions/zeus-communication-rules.instructions.md -->
489
132
  ## Zeus Communication Rules
490
133
 
@@ -498,439 +141,3 @@ These rules apply to Zeus and all agents in the system:
498
141
  - **Concise Execution**: Skip lengthy preambles. State what you're doing in one line, do it, report the outcome. Avoid verbose commentary around trivial steps.
499
142
  - **No Padding**: Don't add filler sentences, summaries of what was just said, or redundant confirmations. Every sentence must carry information.
500
143
  - **Uncertainty = Ask**: If requirements are ambiguous, ask one targeted question. Don't guess and implement the wrong thing.
501
-
502
- <!-- Source: src/instructions/zeus-council-synthesis.instructions.md -->
503
- ## Zeus Council Synthesis
504
-
505
-
506
- # 🏛️ INLINE COUNCIL SYNTHESIS — /pantheon
507
-
508
- When a question requires multiple expert perspectives on a trade-off or architecture decision, **dispatch specialists inline** (visible to user) instead of delegating to a hidden subagent.
509
-
510
- ## Trigger Patterns (detect ANY)
511
- - Trade-off questions: "which is better?", "should we use X or Y?", "compare A and B"
512
- - Architecture decisions with long-term impact
513
- - Security/compliance choices
514
- - Technology selection (databases, frameworks, providers, libraries)
515
- - "Is this safe?", "trade-offs of...", "what are the risks?"
516
- - Cost vs quality decisions
517
- - Multi-stakeholder concerns (frontend + backend + infra)
518
-
519
- ```mermaid
520
- ---
521
- config:
522
- look: classic
523
- theme: dark
524
- ---
525
- sequenceDiagram
526
- participant U as User
527
- participant Z as Zeus
528
- participant M as Memory (Precedent)
529
- participant A as Apollo (Research)
530
- participant B as BackgroundJobBoard
531
- participant S1 as Specialist 1
532
- participant S2 as Specialist 2
533
- participant S3 as Specialist 3
534
- participant W as Web Search
535
- participant T as Themis (Audit + Moderator)
536
-
537
- U->>Z: /pantheon [--research] question
538
- Z->>M: memory_search(query, namespace="council_decisions")
539
- alt Precedent found (score > 0.85)
540
- M-->>Z: ⚠️ Cached decision
541
- Z->>U: Fast-path precedent
542
- else No precedent
543
- opt --research flag
544
- Z->>A: 30s pre-scan
545
- A-->>Z: Context brief
546
- end
547
- Z->>B: registerLaunch({council session})
548
- par Dispatch all specialists
549
- Z->>S1: Domain query + shared context
550
- Z->>S2: Domain query + shared context
551
- Z->>S3: Domain query + shared context
552
- end
553
- par Collect responses
554
- S1-->>Z: Structured response
555
- S2-->>Z: Structured response
556
- S3-->>Z: Structured response
557
- end
558
- Note over Z: Cross-validate confidence
559
- alt Agreement rate < 50%
560
- Z->>S1: Rebuttal round
561
- Z->>S2: Rebuttal round
562
- Z->>S3: Rebuttal round
563
- S1-->>Z: Refined response
564
- S2-->>Z: Refined response
565
- S3-->>Z: Refined response
566
- Note over Z: Ainda divergência?
567
- alt Agreement rate STILL < 50%
568
- Z->>W: browser_search() for each divergence point
569
- W-->>Z: Evidence brief with sources
570
- Z->>T: Dispatches as moderator
571
- Note over T: Reviews evidence + specialist responses
572
- T-->>Z: Moderator verdict
573
- end
574
- end
575
- Z->>Z: Synthesize (with evidence if tie-broken)
576
- Z->>T: Audit synthesis fidelity
577
- T-->>Z: ✅ / ⚠️ Issues
578
- Z->>M: Store decision
579
- Z->>B: Mark reconciled
580
- Z->>U: 🏛️ Council Synthesis
581
- end
582
- ```
583
-
584
- ## Dispatch Sequence (9-Step Protocol)
585
-
586
- ### Step 0 — Precedent Fast-Path (Fase 1)
587
- Run the precedent read path defined in `## Memory Protocol > Council Decisions Namespace` (`memory_search(query=question, top_k=2, namespace="council_decisions")`). If no precedent applies, proceed to Step 0b.
588
-
589
- ### Step 0b — Apollo Pre-Scan (Fase 2, --research flag)
590
- If `/pantheon --research <question>`: dispatch @apollo with 30s timeout. Inject findings as `shared_context` into ALL specialist prompts. Skip if flag absent.
591
-
592
- ### Step 1 — Register on BackgroundJobBoard (Fase 1)
593
- Before dispatching specialists:
594
- ```
595
- board.registerLaunch({
596
- taskID: "council:<uuid>",
597
- parentSessionID: "<session-id>",
598
- agent: "zeus",
599
- description: "Council: <question>",
600
- objective: "Synthesize specialist recommendations"
601
- })
602
- ```
603
- Enables crash recovery — if context is lost mid-synthesis, the board preserves session state.
604
-
605
- ### Step 2 — Select Specialists
606
- Use domain-to-specialist mapping table (below). Max 3 specialists.
607
-
608
- ### Step 3 — Dispatch ALL task() calls in ONE message
609
- Each specialist prompt MUST include:
610
- - Structured output template (see Specialist Output Format below)
611
- - `shared_context` if Apollo pre-scan was done
612
- - Timeout per role: 120s for reviewers, 60s for explorers/implementers
613
-
614
- ### Step 4 — Collect Responses
615
- Wait for all responses. Note TIMEOUT agents. Partial results OK only for read-only specialists (@apollo, @gaia).
616
-
617
- ### Step 5 — Confidence Cross-Validation (Fase 2)
618
- For each specialist response, validate confidence claims:
619
-
620
- | Reported | Minimum Required | Action |
621
- |----------|-----------------|--------|
622
- | High | ≥ 3 specific claims | If fewer → downgrade to Medium, annotate "(auto-downgraded from High: only N specific claims)" |
623
- | Medium | ≥ 1 specific claim | Pass |
624
- | Low | Any response | Pass |
625
-
626
- "Specific claim" = statement with evidence, data point, or verifiable fact (not opinion).
627
-
628
- ### Step 6 — Divergence-Gated Rebuttal Round (Fase 2, conditional)
629
- Calculate agreement rate = `min(agreements, divergences) / total_points` from structured `agreement_signals`. If < 50% agreement:
630
- - Dispatch ONE rebuttal round: specialists see ALL other responses and refine their own
631
- - Updated responses treated as final
632
- - Hard cap: MAX 3 total rounds (initial + 2 rebuttals)
633
- - Skip if any TIMEOUT occurred (can't rebuttal without all voices)
634
-
635
- ### Step 6b — Modo Desempate com Evidência (Fase 2, conditional)
636
-
637
- If after Step 6 the agreement rate is STILL < 50% (rebuttal did not resolve divergence):
638
-
639
- 1. **Identify divergence points** — Parse all specialist responses (initial + rebuttal) and extract specific issues where positions differ
640
- 2. **Web research** — For EACH divergence point, Zeus calls `browser_search()` or `webfetch()` to find factual evidence:
641
- - Benchmarks, documentation, GitHub issues, official sources
642
- - At least 2 independent sources per point when possible
643
- - Focus on factual data, not opinion
644
- 3. **Compile Evidence Brief** — Structure findings as:
645
- ```
646
- ## evidence_brief
647
- **divergence_point_1:** <description>
648
- **evidence_found:** <facts from web, max 3 sentences>
649
- **sources:** [URL1, URL2]
650
-
651
- **divergence_point_2:** ...
652
- ```
653
- 4. **Dispatch @themis as moderator** — Send ONE task with:
654
- - All specialist responses (initial + rebuttal)
655
- - The evidence brief
656
- - Prompt: "Act as impartial moderator. These specialists disagree on [points]. Here is web evidence on each point. Issue a final verdict for each divergence point, citing specific evidence. Return structured verdict."
657
- 5. **Themis returns moderator verdict** in this format:
658
- ```
659
- ## moderator_verdict
660
- **divergence_points_analyzed:** <count>
661
- **verdicts:**
662
- - <point 1>: <decision> — evidence: <citation>
663
- - <point 2>: <decision> — evidence: <citation>
664
- **overall_direction:** <which approach is better supported by evidence>
665
- **confidence:** High | Medium | Low
666
- **unresolved:** <any points still unclear despite evidence>
667
- ```
668
- 6. **Zeus incorporates verdict** into synthesis (Step 7), showing which evidence supported which conclusion
669
-
670
- **Rules:**
671
- - Only triggers when agreement rate < 50% AFTER rebuttal round
672
- - Skip if NO divergence points are web-researchable (purely subjective/opinion-based disagreements)
673
- - Max 3 web searches per council (prevents runaway)
674
- - If Themis confidence is Low or points remain unresolved, note this explicitly in synthesis
675
- - Themis moderator role is SEPARATE from the Themis Audit Gate (Step 8) — they serve different functions
676
-
677
- ### Step 7 — Zeus Synthesize
678
- Use structured `agreement_signals` to auto-detect agreements/divergences. Output synthesis template (see below).
679
-
680
- ### Step 8 — Themis Audit Gate (Fase 1)
681
- Post-synthesis, dispatch @themis:
682
- ```
683
- task(subagent_type: "themis", prompt: "Audit this council synthesis for fidelity. Compare raw specialist responses against the synthesized output. Check: (1) Any specialist misrepresented? (2) Divergences hidden or softened? (3) Confidence claims match response specificity? Return ✅ or list specific issues.")
684
- ```
685
- - If ✅ → proceed
686
- - If issues → fix each issue before delivering to user
687
-
688
- ### Step 9 — Persist & Reconcile (Fase 1)
689
- Persist the decision using the write path in `## Memory Protocol > Council Decisions Namespace`, then `board.markReconciled("<task-id>")`.
690
-
691
- ## Specialist Output Format (Fase 1 — machine-parseable structured fields)
692
-
693
- Specialists MUST return the structured `## specialist_response` format (position, reasoning, trade_offs, risks, confidence, agreement_signals, specific_claims) defined in `## Agent Return Format > Council Specialist Response Format`.
694
-
695
- ## Domain-to-Specialist Mapping
696
-
697
- | Domain | Specialists |
698
- |--------|-------------|
699
- | Architecture | hermes, demeter, themis, athena |
700
- | Security | themis, hermes, prometheus, nyx |
701
- | Database | demeter, hermes, prometheus |
702
- | AI/RAG | hephaestus, nyx |
703
- | Infrastructure | prometheus, hermes, themis |
704
- | Frontend/UX | aphrodite, themis, hermes |
705
- | Observability | nyx, hermes |
706
- | General | athena, themis, hermes |
707
-
708
- ## Synthesis Output Template (enhanced)
709
-
710
- ```
711
- ## 🏛️ Council Synthesis
712
-
713
- **Question:** <original question>
714
- **Date:** <date>
715
- **Response rate:** X of Y specialists responded
716
- **Timed out:** @agent1, @agent2 (if any)
717
- **Precedent used:** yes/no (which one, date)
718
- **Research context:** <shared_context summary> (if --research)
719
-
720
- ### Specialist Perspectives
721
- | Agent | Position | Trade-offs | Confidence |
722
- |-------|----------|------------|------------|
723
- | @agent1 | ... | ... | High/Med/Low |
724
-
725
- ### Agreements
726
- - <what 2+ specialists agree on>
727
-
728
- ### Divergences
729
- | Issue | Side A | Side B | Resolution |
730
- |-------|--------|--------|------------|
731
-
732
- ### Evidence & Moderation (if tie-break activated)
733
- **Divergence points researched:** <list>
734
- **Evidence summary:** <key findings from web>
735
- **Moderator verdict:** <Themis final determination>
736
- **Sources:** <citations>
737
-
738
- ### Recommendation
739
- <decisive conclusion>
740
-
741
- ### Audit Gate
742
- **Status:** ✅ Themis approved | ⚠️ Issues corrected
743
-
744
- ### Decision Gate
745
- **Confidence:** High/Medium/Low (adjusted for response rate)
746
- ```
747
-
748
- ## Themis Audit Gate Rules (Fase 1)
749
-
750
- 1. Every specialist mentioned in synthesis? → ✅
751
- 2. Divergences from raw responses preserved (not softened/hidden)? → ✅
752
- 3. No specialist attributed a position they didn't state? → ✅
753
- 4. Confidence claims match response specificity? → ✅
754
- 5. If any ❌, list specific issues for Zeus to fix before delivery
755
-
756
- ## Rebuttal Round Rules (Fase 2)
757
-
758
- 1. Only triggers when agreement rate < 50%
759
- 2. MAX 3 rounds total (including initial dispatch)
760
- 3. Skip if any TIMEOUT (can't rebuttal without all voices)
761
- 4. Each rebuttal round: specialist sees ALL other responses + current synthesis draft
762
- 5. Refined responses replace originals for the final synthesis
763
- 6. If agreement rate STILL < 50% after rebuttal → Step 6b (Modo Desempate com Evidência)
764
-
765
- ## Crash Recovery via BackgroundJobBoard (Fase 1)
766
-
767
- If Zeus context crashes mid-council:
768
- 1. On restart, `board.recoverRunningJobs()` marks running jobs as error
769
- 2. Check `board.formatForPrompt()` for unreconciled terminal jobs
770
- 3. Re-dispatch council with same question, noting: "⚠️ Retry — previous council session crashed. Using same question."
771
-
772
- ## Performance Budget
773
-
774
- | Step | Latency | Phase |
775
- |------|---------|-------|
776
- | Precedent fast-path | < 500ms | Fase 1 |
777
- | Apollo pre-scan | +30s (optional, --research) | Fase 2 |
778
- | Specialist dispatch | bounded by slowest (60-120s) | — |
779
- | Rebuttal round | +60s (conditional, < 50% agreement) | Fase 2 |
780
- | Web search (tie-break) | +15s (conditional, < 50% after rebuttal) | Fase 2 |
781
- | Themis moderator | +15s (conditional, tie-break activated) | Fase 2 |
782
- | Themis audit | +15s | Fase 1 |
783
- | **Total worst case** (research + rebuttal + tie-break) | ~255s | — |
784
- | **Total typical** (no research, no rebuttal, no tie-break) | ~45-90s | — |
785
-
786
- > **Note**: The user can explicitly invoke this via `/pantheon <question>`. The `--research` flag adds Apollo pre-scan. All decisions are stored in `council_decisions` memory namespace for fast-path retrieval on future councils.
787
-
788
- ## Modo Desempate Rules (Fase 2)
789
-
790
- 1. Only triggers when agreement rate < 50% AFTER rebuttal round
791
- 2. If no divergence points are web-researchable (pure opinion disagreement), skip — Zeus synthesizes with lower confidence
792
- 3. Max 3 web searches per council invocation
793
- 4. Themis moderator role is DISTINCT from Themis audit gate:
794
- - Moderator: resolves substantive disagreement between specialists (reads evidence, gives verdict)
795
- - Audit gate: checks synthesis fidelity against raw responses (quality assurance)
796
- Both run in the same council invocation, at different steps
797
- 5. If Themis moderator confidence is Low, mark as "unresolved tie" in the synthesis output
798
- 6. Evidence from web search must be cited with source URL or document reference — no anonymous claims
799
-
800
- <!-- Source: src/instructions/zeus-timeout-retry.instructions.md -->
801
- ## Zeus Timeout & Retry
802
-
803
-
804
- # ⏱️ TIMEOUT & RETRY ENFORCEMENT
805
-
806
- When a delegated agent does not respond in time, enforce the timeout policy from `routing.yml`.
807
-
808
- ## Timeout Behavior by Agent Role
809
-
810
- | Agent Role | Timeout | Retry Policy | Fallback Chain | Partial Results OK? | Reasoning Effort |
811
- |------------|---------|-------------|----------|---------------------|------------------|
812
- | Explorer (@apollo) | 60s | 2 retries, exp backoff | @athena (plan) → @hermes (impl) | ✅ Yes | low |
813
- | Implementer (@hermes, @aphrodite, @demeter) | 180s | 3 retries, exp backoff | @talos (hotfix) → @athena (replan) | ❌ No | medium |
814
- | Reviewer (@themis) | 120s | 3 retries, exp backoff | @zeus (escalate) → user | ❌ No | high |
815
- | Infrastructure (@prometheus) | 300s | 3 retries, exp backoff | @hermes (config) → @zeus (escalate) | ❌ No | medium |
816
- | Hotfix (@talos) | 30s | 2 retries, no backoff | @hermes (full fix) | ✅ Yes | low |
817
- | Remote Sensing (@gaia) | 120s | 2 retries, exp backoff | @hermes (generic) | ✅ Yes | high |
818
-
819
- ## Retry Flow
820
-
821
- ```
822
- Task dispatch → timeout elapsed → log timeout
823
- ├─ retry_count > 0 → retry with exponential backoff → decrement retry_count
824
- │ └─ still failing? → retry again (up to retry_count limit)
825
- │
826
- ├─ retries exhausted → FALLBACK CHAIN:
827
- │ ├─ fallback[0] exists? → dispatch to fallback agent
828
- │ │ └─ keep original task spec + context; add error context
829
- │ ├─ fallback[1] exists? → dispatch to second fallback
830
- │ └─ all fallbacks failed? → ESCALATE
831
- │
832
- ├─ no fallbacks defined → return TIMEOUT error to user
833
- │
834
- └─ ESCALATE: "Agent X failed after N retries. Fallbacks Y, Z also failed.
835
- Options: (a) try different agent, (b) simplify scope, (c) manual"
836
- ```
837
-
838
-
839
-
840
- ## Fallback Chain Definitions
841
-
842
- Each fallback chain is evaluated left-to-right: if the first fallback fails, try the second, etc.
843
-
844
- | Agent | Fallback[0] | Fallback[1] | Escalate To |
845
- |-------|------------|------------|-------------|
846
- | @apollo | @athena (plan scoped task) | @hermes (implement search) | @zeus |
847
- | @hermes | @talos (minimal fix) | @athena (replan + simplify) | @zeus |
848
- | @aphrodite | @talos (CSS/UX fix) | @hermes (generic fallback) | @zeus |
849
- | @demeter | @hermes (generic backend) | @athena (replan schema) | @zeus |
850
- | @themis | @zeus (direct escalation) | — | user |
851
- | @prometheus | @hermes (config/deploy) | @zeus | user |
852
- | @talos | @hermes (full implementation) | — | @zeus |
853
- | @hephaestus | @nyx (observability debug) | @hermes (generic) | @zeus |
854
- | @nyx | @hermes (generic) | — | @zeus |
855
- | @iris | @zeus (manual override) | — | user |
856
- | @mnemosyne | @zeus (manual) | — | user |
857
-
858
- ### Escalation Protocol
859
- When ALL fallbacks fail:
860
- 1. Log the full failure chain: which agents were tried, what error each returned
861
- 2. Report to user: "Task [X] failed. Tried: [agent list]. Error: [summary]."
862
- 3. Offer options: (a) try different approach, (b) simplify scope, (c) manual fix
863
- 4. NEVER retry the same chain automatically — break the cycle
864
-
865
- ### Session Reuse Check
866
- Before dispatching a task, check if a reusable session exists:
867
-
868
- ```
869
- @hermes — continuing from previous session.
870
- Files already explored: backend/routers/auth.py, backend/services/auth_service.py.
871
- New task: add refresh token rotation.
872
- ```
873
-
874
- Use `session_max` from routing.yml to determine how many sessions to keep per agent.
875
-
876
- ---
877
-
878
- # 📦 SUBTASK DISPATCH (Lightweight Delegation)
879
-
880
- Subtask is a bounded, low-risk delegation mode that **skips** the standard artifact lifecycle. Use it for focused work that doesn't need Themis review.
881
-
882
- ## When to Use Subtask vs Full Task
883
-
884
- > **REGRA DE OURO:** Quando em dúvida, use full task. Subtask é para o que você tem 100% de certeza que é seguro pular revisão.
885
-
886
- ### Subtask Decision Tree (run BEFORE every delegation)
887
-
888
- ```
889
- □ Scope: ≤2 files AND ≤10 lines changed? [YES→continue | NO→full task]
890
- □ Risk: No schema change, no security impact? [YES→continue | NO→full task]
891
- □ Auth: No authentication/authorization logic? [YES→continue | NO→full task]
892
- □ Data: No data loss risk, no migration? [YES→continue | NO→full task]
893
- □ Review: Output does NOT feed into Themis review? [YES→continue | NO→full task]
894
-
895
- ALL YES → subtask (skip artifact + Themis)
896
- ANY NO → full task (IMPL artifact + Themis review mandatory)
897
- ```
898
-
899
- ### Comparison Table
900
-
901
- | Aspect | Subtask | Full Task |
902
- |--------|---------|-----------|
903
- | Scope | Single file, <10 lines, read-only | Feature, multi-file, schema change |
904
- | Risk | Low (no security/data implications) | Any risk level |
905
- | Artifact | ❌ No IMPL artifact | ✅ IMPL artifact required |
906
- | Themis review | ❌ None | ✅ Mandatory |
907
- | Use case | Apollo discovery, Talos hotfix, bounded fix | Feature implementation, migration, API change |
908
-
909
- ### Concrete Examples
910
-
911
- | Task | Scope | Risk | Subtask? | Why |
912
- |------|-------|------|----------|-----|
913
- | Fix typo in CSS class | 1 file, 1 line | None | ✅ | Bounded, no security impact |
914
- | Add error handling to existing endpoint | 1 file, 5 lines | Low | ✅ | No schema change |
915
- | Implement login endpoint | 2+ files, 50+ lines | High (auth) | ❌ | Security-critical, needs Themis |
916
- | Database migration | 1 file, 15 lines | High (data) | ❌ | Data loss risk, needs rollback |
917
- | Apollo codebase search | 0 files | None | ✅ | Read-only investigation |
918
- | Update README | 1 file, 3 lines | None | ✅ | Documentation only |
919
-
920
- ### Safety Rules
921
- 1. **Bounded scope** — single file or read-only investigation
922
- 2. **Low risk** — no security implications, no data loss, no breaking changes
923
- 3. **No Themis dependency** — output doesn't feed into a phase that requires review
924
-
925
- ## Subtask Return Format
926
- Return the standard `## subtask_summary` defined in `## Agent Return Format` (files_changed, summary, tests, coverage, tokens, status, blockers).
927
-
928
- ## Timeout Parcial (Partial Results)
929
-
930
- Only agents marked ✅ in the Timeout Behavior table above may return partial results: @apollo (partial file list, e.g. "found 7 of 12 files before timeout"), @gaia (partial literature findings) and @talos (confirm progress if a hotfix times out). Never for implementers or reviewers — they must complete or fail. When dispatching with partial-OK, set the expectation: `@apollo Search for auth files. Timeout parcial OK — return whatever you have.`
931
-
932
- ---
933
-
934
- # 📊 TIMEOUT TRACKING
935
-
936
- Track in-flight delegations against the Timeout Behavior table above. Log timeouts to `/memories/session/timeout-log.md` for later analysis.