pantheon-opencode 1.3.4 → 1.3.5-beta.52.c75b04d

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.
package/AGENTS.md CHANGED
@@ -1,3 +1,6 @@
1
+ <!-- Generated by scripts/build-agents-md.mjs — do not edit directly. -->
2
+ <!-- Source of truth: src/instructions/*.instructions.md (AGENTS.md is a committed build artifact). -->
3
+
1
4
  # Pantheon Agent System — OpenCode
2
5
 
3
6
  This project uses the Pantheon multi-agent framework with 14 specialized agents.
@@ -45,3 +48,919 @@ Para validar a instalação global do pacote pantheon-opencode COMO UM USUÁRIO
45
48
  - Async/await on all I/O
46
49
  - Type hints on all functions
47
50
  - PRs always update the README — every pull request must document newly added features, behaviors, env vars, or commands in the README before being opened.
51
+
52
+ ---
53
+
54
+ # Agent Instructions
55
+
56
+ The following sections are consolidated from `src/instructions/*.instructions.md`
57
+ so both OpenCode V1 (auto-loads AGENTS.md) and V2 (loads AGENTS.md, ignores the
58
+ `instructions` config key) receive identical instruction content.
59
+
60
+ <!-- Source: src/instructions/agent-return-format.instructions.md -->
61
+ ## Agent Return Format
62
+
63
+
64
+ # Agent Return Format
65
+
66
+ All implementation agents (Hermes, Aphrodite, Demeter, Hephaestus, Prometheus) MUST return results to Zeus in this format:
67
+
68
+ ## subtask_summary
69
+ **files_changed:** [list of file paths, one per line]
70
+ **summary:** What was done, in 2-3 sentences
71
+ **tests:** ✅ All passing / ⚠️ X failing / ❌ Not run (reason)
72
+ **coverage:** X% (if applicable)
73
+ **tokens:** ~N input / ~M output (estimated)
74
+ **status:** complete | partial (reason) | escalated (reason)
75
+ **blockers:** [list any blockers or null]
76
+
77
+ For investigation agents (Apollo, Athena), return structured findings with:
78
+ - Key findings as bullet points
79
+ - File paths with line numbers
80
+ - Relevant code snippets (max 3 lines each)
81
+
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
+ ## 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
219
+
220
+ <!-- Source: src/instructions/memory-protocol.instructions.md -->
221
+ ## Memory Protocol
222
+
223
+
224
+ # 🧠 Memory Protocol — Universal Rules
225
+
226
+ These rules apply to ALL Pantheon agents. Agent-specific overrides are defined
227
+ in each agent's `## 🧠 Memory Protocol` section.
228
+
229
+ ## Universal Rules
230
+
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(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: {agent, background, pattern}
279
+ - metadata: {type: "decision", score: N}
280
+
281
+ 4. **kv_store("deleg:<pattern>", ...)** para padroes recorrentes de delegacao
282
+ 5. **kv_get("deleg:<pattern>")** para reusar decisoes ja tomadas
283
+
284
+ Isso elimina ~300 tokens de reasoning por delegacao quando o cache acerta.
285
+
286
+ ## Council Decisions Namespace
287
+
288
+ Council synthesis decisions are persisted in a dedicated `council_decisions` namespace for precedent fast-path retrieval:
289
+
290
+ ### Write Path
291
+ After every `/pantheon` council synthesis completes, Zeus stores:
292
+ ```
293
+ memory_store({
294
+ namespace: "council_decisions",
295
+ key: "council:<yyyy-mm-dd>:<slug>",
296
+ value: {
297
+ question: "original question",
298
+ specialists: ["@agent1", "@agent2"],
299
+ recommendation: "final recommendation",
300
+ confidence: "High|Medium|Low",
301
+ agreements: ["point1", "point2"],
302
+ divergences: [{"issue": "...", "resolution": "..."}],
303
+ response_rate: "X of Y",
304
+ themis_audit: "approved|issues"
305
+ },
306
+ metadata: {
307
+ type: "council_decision",
308
+ specialist_count: N,
309
+ model_tier_used: "premium|default|fast"
310
+ }
311
+ })
312
+ ```
313
+
314
+ ### Read Path (Precedent Fast-Path)
315
+ Before dispatching a new council, Zeus runs:
316
+ ```
317
+ memory_search(question, top_k=2, namespace="council_decisions")
318
+ ```
319
+
320
+ Result interpretation:
321
+ | Score | Age | Action |
322
+ |-------|-----|--------|
323
+ | > 0.85 | < 30 days | Return precedent as fast-path answer. Skip council dispatch entirely. |
324
+ | > 0.85 | >= 30 days | Return with warning "Reavaliar se contexto mudou" + proceed with council |
325
+ | 0.5 - 0.85 | Any | Include as context for specialists but still dispatch council |
326
+ | < 0.5 | Any | Ignore, proceed with fresh council |
327
+
328
+ ### TTL & Maintenance
329
+ - Council decisions are LONG-TERM (no TTL or TTL = 365 days)
330
+ - Stale decisions (age > 90 days) should be flagged but NOT deleted — they remain as historical record
331
+ - Purge only via explicit namespace cleanup when decisions are superseded by ADRs
332
+
333
+ ### When NOT to Use
334
+ - Routine task summaries → use `default` namespace (auto-store by Zeus)
335
+ - Sprint/progress tracking → use `session` namespace
336
+ - ADR-level architecture decisions → delegate to @mnemosyne for permanent documentation
337
+
338
+ <!-- Source: src/instructions/yagni.instructions.md -->
339
+ ## YAGNI Anti-overengineering
340
+
341
+
342
+ ## YAGNI Principles
343
+
344
+ 1. **Don't add abstractions before the third repetition** — Two similar pieces of code are a coincidence. Three are a pattern.
345
+ 2. **Prefer duplication over the wrong abstraction** — A bad abstraction is worse than copy-paste.
346
+ 3. **Solve today's problem, not tomorrow's** — You don't know what tomorrow looks like.
347
+ 4. **If it's not tested, it doesn't exist** — Code without tests is not "done".
348
+ 5. **The simplest working solution is the best** — Fancy patterns add cognitive load.
349
+ 6. **Don't optimize prematurely** — Measure first, then optimize.
350
+ 7. **Remove unused code immediately** — Dead code is debt.
351
+ 8. **Prefer standard library over dependencies** — One less dependency = one less vulnerability.
352
+ 9. **Avoid configuration systems until something needs to vary** — Hard-coded values are fine until you have at least 3 different values.
353
+ 10. **Don't build for scale you don't have** — YAGNI applies to infrastructure too.
354
+ 11. **Delete more than you add** — Every line of code is a liability.
355
+ 12. **If you're not sure you need it, you don't need it** — Trust your gut.
356
+
357
+ When reviewing code, always ask: "Is this YAGNI? Could we solve this more simply?"
358
+
359
+ <!-- Source: src/instructions/zeus-anti-stall.instructions.md -->
360
+ ## Zeus Anti-Stall
361
+
362
+
363
+ # 🛑 ANTI-STALL & STALL DETECTION
364
+
365
+ You MUST proactively detect and recover from stalled states. Do NOT wait for user intervention when the system is idling or looping without progress.
366
+
367
+ ## Stall Detection Protocol
368
+
369
+ You MUST self-monitor for these stall conditions:
370
+
371
+ | Symptom | Detection Rule | Recovery Action |
372
+ |---------|---------------|-----------------|
373
+ | 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." |
374
+ | Delegation black hole | Agent dispatched but no response after 2x the timeout from routing.yml | Log the hang, cancel via `cancel_task`, dispatch to fallback agent, report to user |
375
+ | Circular delegation | Same specialist re-dispatched for same task 2+ times without progress | Break cycle: dispatch to different specialist OR escalate to user |
376
+ | 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 |
377
+ | Context thrash | Re-reading same files repeatedly without new action | Stop re-reading. State: "Already have context on [file]. Proceeding with [action]." |
378
+
379
+ ## Phase Reminder
380
+
381
+ After dispatching background specialists, you MUST:
382
+ 1. DO NOT poll running jobs or consume their partial output
383
+ 2. DO NOT advance dependent work until terminal results arrive
384
+ 3. Continue orchestration ONLY on non-overlapping independent work
385
+ 4. If nothing independent remains, briefly report what was launched and WAIT
386
+
387
+ Self-check every 3 turns: "Am I waiting on a delegate? Have I polled without need? Is there independent work I can do?"
388
+
389
+ ## Delegate Retry Enhancement
390
+
391
+ When a delegation fails (timeout, empty response, error):
392
+
393
+ 1. **FIRST:** Check if the error is a known pattern:
394
+ - "Agent not responding" → verify agent name matches routing.yml
395
+ - "Context exceeded" → reduce scope, split into smaller tasks
396
+ - "Permission denied" → verify agent has correct tools/permissions
397
+
398
+ 2. **Retry ONCE** with rephrased prompt — add: "Previous attempt failed with: [error]. Adjusted approach: [what changed]."
399
+
400
+ 3. **If retry also fails** → DO NOT retry a third time blindly. Instead:
401
+ - Dispatch to fallback agent (from routing.yml)
402
+ - If no fallback, escalate to user with: "Task [X] failed after retry. Options: (a) simplify, (b) different agent, (c) manual intervention."
403
+
404
+ ## Progress Checkpoint
405
+
406
+ On tasks expected to run > 5 turns:
407
+ - After turn 5: output `[CHECKPOINT] Completed so far: [summary]. Remaining: [list].`
408
+ - After turn 10: re-evaluate. If < 50% done, consider splitting or escalating.
409
+ - If 3 consecutive turns produce no tool calls: trigger Stall Detection Protocol (see above).
410
+
411
+ ## Heartbeat & Checkpoint Integration
412
+
413
+ All session state lives in **pantheon-persistence** (namespace `checkpoint:<slug>`).
414
+ No file I/O, no checkpoint_session.py — TTL (4h) handles cleanup automatically.
415
+
416
+ ### Heartbeat Check
417
+ - If `context_get(slug, "heartbeat")` returns a checkin older than 300s, log a stall warning and resume
418
+ - Write heartbeat after every anti-stall recovery action:
419
+ ```
420
+ context_save(slug, "heartbeat", json({"status": "alive", "last_action": "...", "turn_count": N}))
421
+ ```
422
+
423
+ ### Checkpoint Auto-Save (Pré-Compactação)
424
+ Before ANY delegate dispatch, save a checkpoint:
425
+ ```
426
+ context_save(slug, "phase:N", json({
427
+ "phase": N, "turn_count": N, "agent": "...", "summary": "..."
428
+ }), session_id=SESSION_ID)
429
+ ```
430
+ All checkpoints auto-expire after 4h (TTL=14400).
431
+
432
+ ### Gatilho de Pré-Compactação (Anti-perda de estado)
433
+ Antes da compactação nativa do OpenCode disparar (75-96% do context window),
434
+ o Zeus DEVE salvar o estado atual:
435
+ 1. Capture session_id do primeiro `context_save` da sessão
436
+ 2. Salve heartbeat + phase atual + tarefas pendentes
437
+ 3. Só então permita que a compactação prossiga
438
+ ```
439
+ # Ao iniciar sessão:
440
+ result = context_save(slug, "init", session_state)
441
+ SESSION_ID = result.session_id # ← guarde para toda a sessão
442
+
443
+ # Antes de CADA delegação:
444
+ context_save(slug, f"pre:{agent}", current_state, session_id=SESSION_ID)
445
+
446
+ # Após retorno do agente:
447
+ context_save(slug, f"post:{agent}", result_state, session_id=SESSION_ID)
448
+ ```
449
+ Isso garante que o estado sobreviva à compactação — o "latest" pointer
450
+ sempre aponta para o checkpoint mais recente, mesmo após compactação.
451
+
452
+
453
+ ### Context Retrieval
454
+ Next-phase agents retrieve previous context via:
455
+ ```
456
+ context_get(slug, "latest") # most recent checkpoint
457
+ context_get(slug, "phase:3") # specific phase
458
+ context_list(slug) # all checkpoints
459
+ ```
460
+
461
+ ### Long-Session Progress
462
+ Every 5 turns during a long session, update STATUS.md with:
463
+ - Current phase
464
+ - Completed tasks
465
+ - Pending tasks
466
+ - Any blockers
467
+
468
+ <!-- Source: src/instructions/zeus-communication-rules.instructions.md -->
469
+ ## Zeus Communication Rules
470
+
471
+
472
+ # 🗣️ COMMUNICATION RULES
473
+
474
+ These rules apply to Zeus and all agents in the system:
475
+
476
+ - **No Flattery**: Never start a response with compliments or affirmations ("Great question!", "Absolutely!", "Sure!"). Begin directly with the answer or action.
477
+ - **Honest Pushback**: If a request is technically unsound or will cause problems, say so clearly and explain why. Offer a better approach. Agreeing to avoid friction is worse than a useful correction.
478
+ - **Concise Execution**: Skip lengthy preambles. State what you're doing in one line, do it, report the outcome. Avoid verbose commentary around trivial steps.
479
+ - **No Padding**: Don't add filler sentences, summaries of what was just said, or redundant confirmations. Every sentence must carry information.
480
+ - **Uncertainty = Ask**: If requirements are ambiguous, ask one targeted question. Don't guess and implement the wrong thing.
481
+
482
+ <!-- Source: src/instructions/zeus-council-synthesis.instructions.md -->
483
+ ## Zeus Council Synthesis
484
+
485
+
486
+ # 🏛️ INLINE COUNCIL SYNTHESIS — /pantheon
487
+
488
+ 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.
489
+
490
+ ## Trigger Patterns (detect ANY)
491
+ - Trade-off questions: "which is better?", "should we use X or Y?", "compare A and B"
492
+ - Architecture decisions with long-term impact
493
+ - Security/compliance choices
494
+ - Technology selection (databases, frameworks, providers, libraries)
495
+ - "Is this safe?", "trade-offs of...", "what are the risks?"
496
+ - Cost vs quality decisions
497
+ - Multi-stakeholder concerns (frontend + backend + infra)
498
+
499
+ ```mermaid
500
+ ---
501
+ config:
502
+ look: classic
503
+ theme: dark
504
+ ---
505
+ sequenceDiagram
506
+ participant U as User
507
+ participant Z as Zeus
508
+ participant M as Memory (Precedent)
509
+ participant A as Apollo (Research)
510
+ participant B as BackgroundJobBoard
511
+ participant S1 as Specialist 1
512
+ participant S2 as Specialist 2
513
+ participant S3 as Specialist 3
514
+ participant W as Web Search
515
+ participant T as Themis (Audit + Moderator)
516
+
517
+ U->>Z: /pantheon [--research] question
518
+ Z->>M: memory_search(council_decisions)
519
+ alt Precedent found (score > 0.85)
520
+ M-->>Z: ⚠️ Cached decision
521
+ Z->>U: Fast-path precedent
522
+ else No precedent
523
+ opt --research flag
524
+ Z->>A: 30s pre-scan
525
+ A-->>Z: Context brief
526
+ end
527
+ Z->>B: registerLaunch({council session})
528
+ par Dispatch all specialists
529
+ Z->>S1: Domain query + shared context
530
+ Z->>S2: Domain query + shared context
531
+ Z->>S3: Domain query + shared context
532
+ end
533
+ par Collect responses
534
+ S1-->>Z: Structured response
535
+ S2-->>Z: Structured response
536
+ S3-->>Z: Structured response
537
+ end
538
+ Note over Z: Cross-validate confidence
539
+ alt Agreement rate < 50%
540
+ Z->>S1: Rebuttal round
541
+ Z->>S2: Rebuttal round
542
+ Z->>S3: Rebuttal round
543
+ S1-->>Z: Refined response
544
+ S2-->>Z: Refined response
545
+ S3-->>Z: Refined response
546
+ Note over Z: Ainda divergência?
547
+ alt Agreement rate STILL < 50%
548
+ Z->>W: browser_search() for each divergence point
549
+ W-->>Z: Evidence brief with sources
550
+ Z->>T: Dispatches as moderator
551
+ Note over T: Reviews evidence + specialist responses
552
+ T-->>Z: Moderator verdict
553
+ end
554
+ end
555
+ Z->>Z: Synthesize (with evidence if tie-broken)
556
+ Z->>T: Audit synthesis fidelity
557
+ T-->>Z: ✅ / ⚠️ Issues
558
+ Z->>M: Store decision
559
+ Z->>B: Mark reconciled
560
+ Z->>U: 🏛️ Council Synthesis
561
+ end
562
+ ```
563
+
564
+ ## Dispatch Sequence (9-Step Protocol)
565
+
566
+ ### Step 0 — Precedent Fast-Path (Fase 1)
567
+ Before any dispatch: `memory_search(query, top_k=2, namespace="council_decisions")`
568
+ - Score > 0.85 AND age < 30 days → return precedent verbatim with note "⚠️ Decisão de [data] — reavaliar se contexto mudou". SKIP entire dispatch.
569
+ - Score > 0.85 AND age > 30 days → return precedent with ⚠️ "Reavaliar se contexto mudou — decisão tem mais de 30 dias"
570
+ - Else → proceed to Step 0b
571
+
572
+ ### Step 0b — Apollo Pre-Scan (Fase 2, --research flag)
573
+ If `/pantheon --research <question>`: dispatch @apollo with 30s timeout. Inject findings as `shared_context` into ALL specialist prompts. Skip if flag absent.
574
+
575
+ ### Step 1 — Register on BackgroundJobBoard (Fase 1)
576
+ Before dispatching specialists:
577
+ ```
578
+ board.registerLaunch({
579
+ taskID: "council:<uuid>",
580
+ parentSessionID: "<session-id>",
581
+ agent: "zeus",
582
+ description: "Council: <question>",
583
+ objective: "Synthesize specialist recommendations"
584
+ })
585
+ ```
586
+ Enables crash recovery — if context is lost mid-synthesis, the board preserves session state.
587
+
588
+ ### Step 2 — Select Specialists
589
+ Use domain-to-specialist mapping table (below). Max 3 specialists.
590
+
591
+ ### Step 3 — Dispatch ALL task() calls in ONE message
592
+ Each specialist prompt MUST include:
593
+ - Structured output template (see Specialist Output Format below)
594
+ - `shared_context` if Apollo pre-scan was done
595
+ - Timeout per role: 120s for reviewers, 60s for explorers/implementers
596
+
597
+ ### Step 4 — Collect Responses
598
+ Wait for all responses. Note TIMEOUT agents. Partial results OK only for read-only specialists (@apollo, @gaia).
599
+
600
+ ### Step 5 — Confidence Cross-Validation (Fase 2)
601
+ For each specialist response, validate confidence claims:
602
+
603
+ | Reported | Minimum Required | Action |
604
+ |----------|-----------------|--------|
605
+ | High | ≥ 3 specific claims | If fewer → downgrade to Medium, annotate "(auto-downgraded from High: only N specific claims)" |
606
+ | Medium | ≥ 1 specific claim | Pass |
607
+ | Low | Any response | Pass |
608
+
609
+ "Specific claim" = statement with evidence, data point, or verifiable fact (not opinion).
610
+
611
+ ### Step 6 — Divergence-Gated Rebuttal Round (Fase 2, conditional)
612
+ Calculate agreement rate = `min(agreements, divergences) / total_points` from structured `agreement_signals`. If < 50% agreement:
613
+ - Dispatch ONE rebuttal round: specialists see ALL other responses and refine their own
614
+ - Updated responses treated as final
615
+ - Hard cap: MAX 3 total rounds (initial + 2 rebuttals)
616
+ - Skip if any TIMEOUT occurred (can't rebuttal without all voices)
617
+
618
+ ### Step 6b — Modo Desempate com Evidência (Fase 2, conditional)
619
+
620
+ If after Step 6 the agreement rate is STILL < 50% (rebuttal did not resolve divergence):
621
+
622
+ 1. **Identify divergence points** — Parse all specialist responses (initial + rebuttal) and extract specific issues where positions differ
623
+ 2. **Web research** — For EACH divergence point, Zeus calls `browser_search()` or `webfetch()` to find factual evidence:
624
+ - Benchmarks, documentation, GitHub issues, official sources
625
+ - At least 2 independent sources per point when possible
626
+ - Focus on factual data, not opinion
627
+ 3. **Compile Evidence Brief** — Structure findings as:
628
+ ```
629
+ ## evidence_brief
630
+ **divergence_point_1:** <description>
631
+ **evidence_found:** <facts from web, max 3 sentences>
632
+ **sources:** [URL1, URL2]
633
+
634
+ **divergence_point_2:** ...
635
+ ```
636
+ 4. **Dispatch @themis as moderator** — Send ONE task with:
637
+ - All specialist responses (initial + rebuttal)
638
+ - The evidence brief
639
+ - 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."
640
+ 5. **Themis returns moderator verdict** in this format:
641
+ ```
642
+ ## moderator_verdict
643
+ **divergence_points_analyzed:** <count>
644
+ **verdicts:**
645
+ - <point 1>: <decision> — evidence: <citation>
646
+ - <point 2>: <decision> — evidence: <citation>
647
+ **overall_direction:** <which approach is better supported by evidence>
648
+ **confidence:** High | Medium | Low
649
+ **unresolved:** <any points still unclear despite evidence>
650
+ ```
651
+ 6. **Zeus incorporates verdict** into synthesis (Step 7), showing which evidence supported which conclusion
652
+
653
+ **Rules:**
654
+ - Only triggers when agreement rate < 50% AFTER rebuttal round
655
+ - Skip if NO divergence points are web-researchable (purely subjective/opinion-based disagreements)
656
+ - Max 3 web searches per council (prevents runaway)
657
+ - If Themis confidence is Low or points remain unresolved, note this explicitly in synthesis
658
+ - Themis moderator role is SEPARATE from the Themis Audit Gate (Step 8) — they serve different functions
659
+
660
+ ### Step 7 — Zeus Synthesize
661
+ Use structured `agreement_signals` to auto-detect agreements/divergences. Output synthesis template (see below).
662
+
663
+ ### Step 8 — Themis Audit Gate (Fase 1)
664
+ Post-synthesis, dispatch @themis:
665
+ ```
666
+ 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.")
667
+ ```
668
+ - If ✅ → proceed
669
+ - If issues → fix each issue before delivering to user
670
+
671
+ ### Step 9 — Persist & Reconcile (Fase 1)
672
+ ```
673
+ memory_store({
674
+ namespace: "council_decisions",
675
+ key: "council:<yyyy-mm-dd>:<slug>",
676
+ value: JSON.stringify({
677
+ question, specialists, recommendation, confidence,
678
+ agreements, divergences, precedent_used, timestamp
679
+ }),
680
+ metadata: {type: "council_decision", specialist_count: N}
681
+ })
682
+ board.markReconciled("<task-id>")
683
+ ```
684
+
685
+ ## Specialist Output Format (Fase 1 — machine-parseable structured fields)
686
+
687
+ Specialists MUST return these structured fields in their response:
688
+
689
+ ```
690
+ ## specialist_response
691
+ **position:** <clear one-sentence position>
692
+ **reasoning:** <2-4 sentences>
693
+ **trade_offs:** <what's gained vs lost>
694
+ **risks:** <what could go wrong>
695
+ **confidence:** High | Medium | Low
696
+ **agreement_signals:** agree: @agent1, @agent2 on [issue] | disagree: @agent3 on [issue]
697
+ **specific_claims:** <count of specific factual claims in response>
698
+ ```
699
+
700
+ ## Domain-to-Specialist Mapping
701
+
702
+ | Domain | Specialists |
703
+ |--------|-------------|
704
+ | Architecture | hermes, demeter, themis, athena |
705
+ | Security | themis, hermes, prometheus, nyx |
706
+ | Database | demeter, hermes, prometheus |
707
+ | AI/RAG | hephaestus, nyx |
708
+ | Infrastructure | prometheus, hermes, themis |
709
+ | Frontend/UX | aphrodite, themis, hermes |
710
+ | Observability | nyx, hermes |
711
+ | General | athena, themis, hermes |
712
+
713
+ ## Synthesis Output Template (enhanced)
714
+
715
+ ```
716
+ ## 🏛️ Council Synthesis
717
+
718
+ **Question:** <original question>
719
+ **Date:** <date>
720
+ **Response rate:** X of Y specialists responded
721
+ **Timed out:** @agent1, @agent2 (if any)
722
+ **Precedent used:** yes/no (which one, date)
723
+ **Research context:** <shared_context summary> (if --research)
724
+
725
+ ### Specialist Perspectives
726
+ | Agent | Position | Trade-offs | Confidence |
727
+ |-------|----------|------------|------------|
728
+ | @agent1 | ... | ... | High/Med/Low |
729
+
730
+ ### Agreements
731
+ - <what 2+ specialists agree on>
732
+
733
+ ### Divergences
734
+ | Issue | Side A | Side B | Resolution |
735
+ |-------|--------|--------|------------|
736
+
737
+ ### Evidence & Moderation (if tie-break activated)
738
+ **Divergence points researched:** <list>
739
+ **Evidence summary:** <key findings from web>
740
+ **Moderator verdict:** <Themis final determination>
741
+ **Sources:** <citations>
742
+
743
+ ### Recommendation
744
+ <decisive conclusion>
745
+
746
+ ### Audit Gate
747
+ **Status:** ✅ Themis approved | ⚠️ Issues corrected
748
+
749
+ ### Decision Gate
750
+ **Confidence:** High/Medium/Low (adjusted for response rate)
751
+ ```
752
+
753
+ ## Themis Audit Gate Rules (Fase 1)
754
+
755
+ 1. Every specialist mentioned in synthesis? → ✅
756
+ 2. Divergences from raw responses preserved (not softened/hidden)? → ✅
757
+ 3. No specialist attributed a position they didn't state? → ✅
758
+ 4. Confidence claims match response specificity? → ✅
759
+ 5. If any ❌, list specific issues for Zeus to fix before delivery
760
+
761
+ ## Rebuttal Round Rules (Fase 2)
762
+
763
+ 1. Only triggers when agreement rate < 50%
764
+ 2. MAX 3 rounds total (including initial dispatch)
765
+ 3. Skip if any TIMEOUT (can't rebuttal without all voices)
766
+ 4. Each rebuttal round: specialist sees ALL other responses + current synthesis draft
767
+ 5. Refined responses replace originals for the final synthesis
768
+ 6. If agreement rate STILL < 50% after rebuttal → Step 6b (Modo Desempate com Evidência)
769
+
770
+ ## Crash Recovery via BackgroundJobBoard (Fase 1)
771
+
772
+ If Zeus context crashes mid-council:
773
+ 1. On restart, `board.recoverRunningJobs()` marks running jobs as error
774
+ 2. Check `board.formatForPrompt()` for unreconciled terminal jobs
775
+ 3. Re-dispatch council with same question, noting: "⚠️ Retry — previous council session crashed. Using same question."
776
+
777
+ ## Performance Budget
778
+
779
+ | Step | Latency | Phase |
780
+ |------|---------|-------|
781
+ | Precedent fast-path | < 500ms | Fase 1 |
782
+ | Apollo pre-scan | +30s (optional, --research) | Fase 2 |
783
+ | Specialist dispatch | bounded by slowest (60-120s) | — |
784
+ | Rebuttal round | +60s (conditional, < 50% agreement) | Fase 2 |
785
+ | Web search (tie-break) | +15s (conditional, < 50% after rebuttal) | Fase 2 |
786
+ | Themis moderator | +15s (conditional, tie-break activated) | Fase 2 |
787
+ | Themis audit | +15s | Fase 1 |
788
+ | **Total worst case** (research + rebuttal + tie-break) | ~255s | — |
789
+ | **Total typical** (no research, no rebuttal, no tie-break) | ~45-90s | — |
790
+
791
+ > **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.
792
+
793
+ ## Modo Desempate Rules (Fase 2)
794
+
795
+ 1. Only triggers when agreement rate < 50% AFTER rebuttal round
796
+ 2. If no divergence points are web-researchable (pure opinion disagreement), skip — Zeus synthesizes with lower confidence
797
+ 3. Max 3 web searches per council invocation
798
+ 4. Themis moderator role is DISTINCT from Themis audit gate:
799
+ - Moderator: resolves substantive disagreement between specialists (reads evidence, gives verdict)
800
+ - Audit gate: checks synthesis fidelity against raw responses (quality assurance)
801
+ Both run in the same council invocation, at different steps
802
+ 5. If Themis moderator confidence is Low, mark as "unresolved tie" in the synthesis output
803
+ 6. Evidence from web search must be cited with source URL or document reference — no anonymous claims
804
+
805
+ <!-- Source: src/instructions/zeus-timeout-retry.instructions.md -->
806
+ ## Zeus Timeout & Retry
807
+
808
+
809
+ # ⏱️ TIMEOUT & RETRY ENFORCEMENT
810
+
811
+ When a delegated agent does not respond in time, enforce the timeout policy from `routing.yml`.
812
+
813
+ ## Timeout Behavior by Agent Role
814
+
815
+ | Agent Role | Timeout | Retry Policy | Fallback Chain | Partial Results OK? | Reasoning Effort |
816
+ |------------|---------|-------------|----------|---------------------|------------------|
817
+ | Explorer (@apollo) | 60s | 2 retries, exp backoff | @athena (plan) → @hermes (impl) | ✅ Yes | low |
818
+ | Implementer (@hermes, @aphrodite, @demeter) | 180s | 3 retries, exp backoff | @talos (hotfix) → @athena (replan) | ❌ No | medium |
819
+ | Reviewer (@themis) | 120s | 3 retries, exp backoff | @zeus (escalate) → user | ❌ No | high |
820
+ | Infrastructure (@prometheus) | 300s | 3 retries, exp backoff | @hermes (config) → @zeus (escalate) | ❌ No | medium |
821
+ | Hotfix (@talos) | 30s | 2 retries, no backoff | @hermes (full fix) | ✅ Yes | low |
822
+ | Remote Sensing (@gaia) | 120s | 2 retries, exp backoff | @hermes (generic) | ✅ Yes | high |
823
+
824
+ ## Retry Flow
825
+
826
+ ```
827
+ Task dispatch → timeout elapsed → log timeout
828
+ ├─ retry_count > 0 → retry with exponential backoff → decrement retry_count
829
+ │ └─ still failing? → retry again (up to retry_count limit)
830
+ │
831
+ ├─ retries exhausted → FALLBACK CHAIN:
832
+ │ ├─ fallback[0] exists? → dispatch to fallback agent
833
+ │ │ └─ keep original task spec + context; add error context
834
+ │ ├─ fallback[1] exists? → dispatch to second fallback
835
+ │ └─ all fallbacks failed? → ESCALATE
836
+ │
837
+ ├─ no fallbacks defined → return TIMEOUT error to user
838
+ │
839
+ └─ ESCALATE: "Agent X failed after N retries. Fallbacks Y, Z also failed.
840
+ Options: (a) try different agent, (b) simplify scope, (c) manual"
841
+ ```
842
+
843
+
844
+
845
+ ## Fallback Chain Definitions
846
+
847
+ Each fallback chain is evaluated left-to-right: if the first fallback fails, try the second, etc.
848
+
849
+ | Agent | Fallback[0] | Fallback[1] | Escalate To |
850
+ |-------|------------|------------|-------------|
851
+ | @apollo | @athena (plan scoped task) | @hermes (implement search) | @zeus |
852
+ | @hermes | @talos (minimal fix) | @athena (replan + simplify) | @zeus |
853
+ | @aphrodite | @talos (CSS/UX fix) | @hermes (generic fallback) | @zeus |
854
+ | @demeter | @hermes (generic backend) | @athena (replan schema) | @zeus |
855
+ | @themis | @zeus (direct escalation) | — | user |
856
+ | @prometheus | @hermes (config/deploy) | @zeus | user |
857
+ | @talos | @hermes (full implementation) | — | @zeus |
858
+ | @hephaestus | @nyx (observability debug) | @hermes (generic) | @zeus |
859
+ | @nyx | @hermes (generic) | — | @zeus |
860
+ | @iris | @zeus (manual override) | — | user |
861
+ | @mnemosyne | @zeus (manual) | — | user |
862
+
863
+ ### Escalation Protocol
864
+ When ALL fallbacks fail:
865
+ 1. Log the full failure chain: which agents were tried, what error each returned
866
+ 2. Report to user: "Task [X] failed. Tried: [agent list]. Error: [summary]."
867
+ 3. Offer options: (a) try different approach, (b) simplify scope, (c) manual fix
868
+ 4. NEVER retry the same chain automatically — break the cycle
869
+
870
+ ### Session Reuse Check
871
+ Before dispatching a task, check if a reusable session exists:
872
+
873
+ ```
874
+ @hermes — continuing from previous session.
875
+ Files already explored: backend/routers/auth.py, backend/services/auth_service.py.
876
+ New task: add refresh token rotation.
877
+ ```
878
+
879
+ Use `session_max` from routing.yml to determine how many sessions to keep per agent.
880
+
881
+ ---
882
+
883
+ # 📦 SUBTASK DISPATCH (Lightweight Delegation)
884
+
885
+ 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.
886
+
887
+ ## When to Use Subtask vs Full Task
888
+
889
+ > **REGRA DE OURO:** Quando em dúvida, use full task. Subtask é para o que você tem 100% de certeza que é seguro pular revisão.
890
+
891
+ ### Subtask Decision Tree (run BEFORE every delegation)
892
+
893
+ ```
894
+ □ Scope: ≤2 files AND ≤10 lines changed? [YES→continue | NO→full task]
895
+ □ Risk: No schema change, no security impact? [YES→continue | NO→full task]
896
+ □ Auth: No authentication/authorization logic? [YES→continue | NO→full task]
897
+ □ Data: No data loss risk, no migration? [YES→continue | NO→full task]
898
+ □ Review: Output does NOT feed into Themis review? [YES→continue | NO→full task]
899
+
900
+ ALL YES → subtask (skip artifact + Themis)
901
+ ANY NO → full task (IMPL artifact + Themis review mandatory)
902
+ ```
903
+
904
+ ### Comparison Table
905
+
906
+ | Aspect | Subtask | Full Task |
907
+ |--------|---------|-----------|
908
+ | Scope | Single file, <10 lines, read-only | Feature, multi-file, schema change |
909
+ | Risk | Low (no security/data implications) | Any risk level |
910
+ | Artifact | ❌ No IMPL artifact | ✅ IMPL artifact required |
911
+ | Themis review | ❌ None | ✅ Mandatory |
912
+ | Use case | Apollo discovery, Talos hotfix, bounded fix | Feature implementation, migration, API change |
913
+
914
+ ### Concrete Examples
915
+
916
+ | Task | Scope | Risk | Subtask? | Why |
917
+ |------|-------|------|----------|-----|
918
+ | Fix typo in CSS class | 1 file, 1 line | None | ✅ | Bounded, no security impact |
919
+ | Add error handling to existing endpoint | 1 file, 5 lines | Low | ✅ | No schema change |
920
+ | Implement login endpoint | 2+ files, 50+ lines | High (auth) | ❌ | Security-critical, needs Themis |
921
+ | Database migration | 1 file, 15 lines | High (data) | ❌ | Data loss risk, needs rollback |
922
+ | Apollo codebase search | 0 files | None | ✅ | Read-only investigation |
923
+ | Update README | 1 file, 3 lines | None | ✅ | Documentation only |
924
+
925
+ ### Safety Rules
926
+ 1. **Bounded scope** — single file or read-only investigation
927
+ 2. **Low risk** — no security implications, no data loss, no breaking changes
928
+ 3. **No Themis dependency** — output doesn't feed into a phase that requires review
929
+
930
+ ## Subtask Return Format
931
+ Expect a `subtask_summary` response with:
932
+ ```
933
+ ## subtask_summary
934
+ **files_changed:** [paths]
935
+ **summary:** What was done
936
+ **tests:** ✅ or N/A
937
+ **status:** complete | partial | escalated
938
+ ```
939
+
940
+ ## Timeout Parcial (Partial Results)
941
+
942
+ Timeout parcial is ONLY for read-only, independent agents:
943
+ - ✅ @apollo — can return partial file list ("found 7 of 12 files before timeout")
944
+ - ✅ @gaia — can return partial literature findings
945
+
946
+ - ✅ @talos — can confirm progress if hotfix times out
947
+ - ❌ Never for implementers or reviewers — must complete or fail
948
+
949
+ When dispatching with partial-OK, set expectation:
950
+ ```
951
+ @apollo Search for auth files. Timeout parcial OK — return whatever you have.
952
+ ```
953
+
954
+ ---
955
+
956
+ # 📊 TIMEOUT TRACKING
957
+
958
+ Maintain awareness of in-flight delegations:
959
+
960
+ | Agent | Timeout | Status | Partial OK? |
961
+ |-------|---------|--------|-------------|
962
+ | @apollo | 60s | ✅ complete | ✅ |
963
+ | @hermes | 180s | ⏳ in progress | ❌ |
964
+ | @themis | 120s | ⏳ in progress | ❌ |
965
+
966
+ Log timeouts to `/memories/session/timeout-log.md` for later analysis.