pantheon-opencode 2.0.3 → 2.1.0

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 (48) hide show
  1. package/AGENTS.global.md +1 -1
  2. package/AGENTS.md +1 -1
  3. package/CHANGELOG.md +68 -0
  4. package/README.md +13 -6
  5. package/README.pt-BR.md +12 -5
  6. package/commands/pantheon-deepwork.md +11 -2
  7. package/package.json +2 -1
  8. package/plugin.json +1 -1
  9. package/prompts/orchestrate-with-zeus.prompt.md +2 -0
  10. package/pyproject.toml +1 -1
  11. package/scripts/cost.mjs +4 -5
  12. package/scripts/decision-router-budget.mjs +27 -6
  13. package/scripts/decision-router.mjs +76 -34
  14. package/scripts/doctor.mjs +74 -0
  15. package/scripts/install/decision-router-config.mjs +32 -7
  16. package/src/agents/apollo.md +6 -53
  17. package/src/agents/athena.md +1 -0
  18. package/src/agents/talos.md +10 -40
  19. package/src/agents/themis.md +9 -0
  20. package/src/agents/zeus.md +29 -2
  21. package/src/mcp/pantheon_vision.py +33 -2
  22. package/src/pantheon/background-job-board.ts +33 -0
  23. package/src/pantheon/bus.ts +190 -0
  24. package/src/pantheon/cost-command.ts +4 -1
  25. package/src/pantheon/deepwork/deepwork-tool.ts +370 -0
  26. package/src/pantheon/deepwork/plan-projection.ts +274 -0
  27. package/src/pantheon/deepwork/plan-schema.ts +93 -0
  28. package/src/pantheon/deepwork/plan-tracker.ts +336 -0
  29. package/src/pantheon/execution-receipt.ts +113 -0
  30. package/src/pantheon/jev-decision-tool.ts +8 -2
  31. package/src/pantheon/local-decision-budget.ts +36 -6
  32. package/src/pantheon/model-command.ts +2 -4
  33. package/src/pantheon/native-vision.ts +3 -1
  34. package/src/pantheon/prompt-cache-order.ts +89 -0
  35. package/src/pantheon/skill-search-tool.ts +2 -2
  36. package/src/pantheon/themis-reflex.ts +164 -0
  37. package/src/pantheon/tools.ts +2 -0
  38. package/src/plugin/index.js +979 -60
  39. package/src/plugins/tui/dist/tui.js +461 -289
  40. package/src/plugins/tui/dist/tui.js.map +1 -1
  41. package/src/plugins/tui/package-lock.json +2 -2
  42. package/src/plugins/tui/package.json +1 -1
  43. package/src/plugins/tui/src/autonomy-state.ts +14 -16
  44. package/src/plugins/tui/src/decision-router-state.ts +22 -10
  45. package/src/plugins/tui/src/pantheon-settings-state.ts +119 -35
  46. package/src/plugins/tui/src/pantheon-settings.tsx +142 -48
  47. package/src/plugins/tui/src/preset-state.ts +96 -6
  48. package/src/plugins/tui/src/update-status.ts +62 -22
package/AGENTS.global.md CHANGED
@@ -1,7 +1,7 @@
1
1
  <!-- pantheon:generated:begin — Pantheon-managed region; regenerated on install/upgrade, never edit inside -->
2
2
  <!-- Generated by scripts/build-agents-md.mjs — do not edit directly. -->
3
3
  <!-- Source of truth: src/instructions/*.instructions.md + the static sections in this script. -->
4
- <!-- pantheon:agents-md v2 artifact=global generated-at=2026-11-11T10:16:35-03:00 sha=d5466bf -->
4
+ <!-- pantheon:agents-md v2 artifact=global generated-at=2026-11-12T20:41:50-03:00 sha=c84abe9 -->
5
5
 
6
6
  # Pantheon Agent System — OpenCode
7
7
 
package/AGENTS.md CHANGED
@@ -1,7 +1,7 @@
1
1
  <!-- pantheon:generated:begin — Pantheon-managed region; regenerated on install/upgrade, never edit inside -->
2
2
  <!-- Generated by scripts/build-agents-md.mjs — do not edit directly. -->
3
3
  <!-- Source of truth: project sections in scripts/build-agents-md.mjs. -->
4
- <!-- pantheon:agents-md v2 artifact=project generated-at=2026-11-11T10:16:35-03:00 sha=d5466bf -->
4
+ <!-- pantheon:agents-md v2 artifact=project generated-at=2026-11-12T20:41:50-03:00 sha=c84abe9 -->
5
5
 
6
6
  # Pantheon — Repository Setup
7
7
 
package/CHANGELOG.md CHANGED
@@ -5,6 +5,74 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
6
6
 
7
7
 
8
+ ## [Unreleased]
9
+
10
+ <!-- Add new changes here.
11
+ Canonical sections (docs/RELEASING.md): ### 🆕 What's New (curated highlights, ≤6 bullets ≤140 chars) →
12
+ ### Added / Changed / Deprecated / Removed / Fixed / Security → ### ⚠️ Known Issues / ### ✅ Closed Issues.
13
+ `node scripts/versioning.mjs apply --notes` pre-fills the generated sections from conventional commits.
14
+ Running apply will move this section to a versioned entry and reset the template below. -->
15
+
16
+ ## [v2.1.0] - 2026-11-12
17
+
18
+ ### 🆕 What's New
19
+
20
+ - **Deepwork Canonical Plan**: Structured JSON ground truth (`plan.json`) and append-only event log with Mermaid DAG and zero HTML.
21
+ - **Vision Modernization**: Configurable Vision Model row in TUI Settings synced to `opencode-vision.json` and explicit `vision_describe`.
22
+ - **Project Skill Decision**: Proactive interactive question gate for external skills, strictly isolated into `.agents/skills/`.
23
+ - **TUI Settings Polish**: Full pt-BR localization across tabs, formatted status badges, and resolved title collision in Changelog tab.
24
+
25
+ ### Added
26
+
27
+ - **deepwork** — canonical JSON-driven plan architecture, `pantheon_deepwork` tool, fail-first acceptance criteria, native `question` gates, and Mermaid DAG projections.
28
+ - **vision** — configurable vision model in TUI Settings (`Preset` tab), `.opencode/opencode-vision.json` support in Python MCP server, and explicit `vision_describe` guidance.
29
+ - **skills** — proactive interactive question gate for 1-click project-scoped installation (`.agents/skills/`) with execution delegated to `@hermes`/`@talos`.
30
+ - **tui** — Portuguese localization across tabs, rich system metadata in About tab, and formatted status badges (`< ativado >`, `< desativado >`).
31
+
32
+ ### Changed
33
+
34
+ - **agents** — updated Zeus rules in `src/agents/zeus.md` and prompts to forbid manual terminal commands and enforce project-isolated `.agents/skills/`.
35
+
36
+ ### Fixed
37
+
38
+ - **vision** — eliminate prompt context clutter and raw HTML comment dumps (`<!-- pantheon-v2-visual-context -->`), ensuring models invoke `vision_describe`.
39
+ - **tui** — resolved title collision visual bug in Changelog tab by splitting on delimiters and omitting empty middle box for highlight rows.
40
+
41
+ ## [v2.0.4] - 2026-11-12
42
+
43
+ ### 🆕 What's New
44
+
45
+ - **Container & JupyterHub Support**: Auto-detect environments and relax directory trust checks via `PANTHEON_ALLOW_GROUP_WRITABLE=1`.
46
+ - **Decision Router Diagnostics**: New Section L in `doctor` validating router configuration and fault-tolerant CLI diagnostics.
47
+ - **Reactive Event Bus**: Zero-latency in-memory event bus replacing disk file polling for background job status updates.
48
+ - **Themis Local Reflex**: Self-healing loop enabling implementers to remediate lint and test slice issues without coordinator.
49
+ - **Execution Proof Receipts**: Cryptographic verification receipts with SHA-256 fingerprinting for completed agent subtasks.
50
+ - **Prefix Cache & Prompt Diet**: Deterministic prompt layering and distilled instructions maximizing KV-cache hit rate.
51
+
52
+ ### Added
53
+
54
+ - **routing** — add `PANTHEON_ALLOW_GROUP_WRITABLE` environment variable and auto-detection for container environments (JupyterHub, Docker, Kubernetes).
55
+ - **doctor** — add Section L to `scripts/doctor.mjs` checking Decision Router configuration trust and budget ledger accessibility.
56
+ - **orchestration** — in-memory `PantheonBus` event dispatcher with zero-latency reactive notifications for background job lifecycles.
57
+ - **orchestration** — `ThemisReflexController` bounding inline implementer self-healing to 2 retries before escalating to Zeus.
58
+ - **orchestration** — `createExecutionReceipt` and `verifyExecutionReceipt` with SHA-256 content hashes and verifiable test slices.
59
+ - **orchestration** — `buildPrefixCachedPrompt` aligning agent prompts with provider KV-cache prefix retention specifications.
60
+
61
+ ### Changed
62
+
63
+ - **agents** — distilled system prompts for Talos and Apollo stripping generic MCP governance to maximize fast-path throughput.
64
+
65
+ ### Removed
66
+
67
+ - **cli** — remove obsolete V1 legacy wizard documentation and comments in `model-command.ts`.
68
+
69
+ ### Fixed
70
+
71
+ - **routing** — relax `assertTrustedDirectoryChain` and `validateDirectoryTrust` to accept root/sticky ownership and permitted group-writable ancestors.
72
+ - **cli** — wrap `readUserDecisionRouterConfig` in `status` and `doctor` commands to report clean errors instead of crashing.
73
+ - **jev** — surface specific failure details for `CONFIG_UNAVAILABLE` in `runGatedNativeJevCall`.
74
+
75
+
8
76
  ## [v2.0.3] - 2026-11-11
9
77
 
10
78
  ### 🆕 What's New
package/README.md CHANGED
@@ -57,6 +57,10 @@ flowchart LR
57
57
 
58
58
  - **Fast-Track execution:** Bounded micro-edits (<= 2 files, <= 50 lines) bypass all heavy ceremony and verify in < 10 seconds.
59
59
  - **Mandatory test slicing:** Sub-second targeted test execution instead of running sluggish repository-wide test suites during dev loops.
60
+ - **Execution proof receipts:** Cryptographic SHA-256 fingerprinting on modified files and test slice exit codes prevents false-positive task reports.
61
+ - **KV-cache prefix optimization:** Strict invariant-first prompt layering maximizes LLM cache hits (up to 90% cost and latency savings).
62
+ - **Reactive event bus & zero polling:** Process-wide in-memory event bus delivers instant updates across jobs and agents without disk polling.
63
+ - **Themis local reflex loops:** Specialist self-healing resolves isolated lint and test slice discrepancies before escalating to Zeus.
60
64
  - **Assertive council (`/pantheon`):** Parallel specialist consultations resolved decisively via domain authority and JEV multi-criteria decisions without endless debate turns.
61
65
  - **You stay in charge:** Pantheon supports your judgment; it never silently alters permissions or runs unapproved destructive actions.
62
66
  - **Non-destructive upgrades:** Updating Pantheon (`pantheon-opencode update`) refreshes skills, MCPs, and instructions while strictly preserving all user models, presets, permissions, and custom configs.
@@ -84,7 +88,7 @@ pantheon-opencode init --yes
84
88
  ```bash
85
89
  pantheon-opencode doctor
86
90
  ```
87
- Runs a 28-point diagnostic checking MCP initialization, Python virtual environments, Node version, permissions, and config integrity.
91
+ Runs a diagnostic checking Decision Router & budget ledger accessibility, MCP initialization, Python virtual environments, Node version, permissions, and config integrity. In containerized or JupyterHub environments with group-writable homes, set `PANTHEON_ALLOW_GROUP_WRITABLE=1` if needed.
88
92
 
89
93
  ### 3. Updating Pantheon Without Overwriting Settings
90
94
  When a new version is released:
@@ -133,16 +137,19 @@ For multi-phase tasks spanning 10+ turns or multiple sessions:
133
137
  ```text
134
138
  /pantheon-deepwork "Implement OAuth2 PKCE authentication flow"
135
139
  ```
136
- - **Phase 0 (Plan):** Athena maps affected modules and returns a complete Markdown plan displayed directly in the main conversation.
137
- - **Phase 1 (Discovery):** Apollo performs structured exploration.
138
- - **Phase 2–N (Implementation):** Specialists implement features in parallel phases.
139
- - **Phase Gates:** Themis audits each phase (`PASS` or `FAIL`).
140
+ - **The Plan is the Artifact:** The canonical ground truth is stored in `.pantheon/deepwork/<slug>/plan.json` with an append-only event log (`journal.ndjson`) for resilient crash recovery.
141
+ - **Native OpenCode Gates (Strictly No HTML):** Approvals (Gate 1) and decision resolutions use OpenCode's native interactive `question` tool directly in the chat UI.
142
+ - **Dependency DAG:** Automatically projects task dependencies into live Mermaid diagrams (`flowchart LR`) inside `PLAN.md` and chat status.
143
+ - **Fail-First Acceptance:** Every task defines concrete acceptance criteria (`kind: test|command|file|manual`, `fails_now: true`) verified with cryptographic receipts.
144
+ - **Tool Automation (`pantheon_deepwork`):** Structured tool for `init`, `status`, `update_task`, `verify_acceptance`, and `resolve_decision`.
140
145
  - **Resumability:** Checkpoints persisted to `.pantheon/deepwork/<slug>/`. Resume anytime with `/pantheon-deepwork --resume <slug>`.
141
146
 
142
147
  ---
143
148
 
144
149
  ## The 14 Specialized Agents
145
150
 
151
+ For a complete breakdown of permissions, tools, MCP access, and boundary constraints per agent, see the [Agent Capability Matrix](docs/AGENT-CAPABILITY-MATRIX.md).
152
+
146
153
  Every root dispatch carries a concise handoff brief — objective, bounded scope, relevant inputs, constraints, expected return format, and verification. Work is routed qualitatively — uncertainty, domain expertise, dependencies, risk, and verification — not by fixed file or line thresholds. Return contracts are role-specific: implementation uses `## subtask_summary`, investigation returns structured findings, Athena returns the complete plan, and council responses use `## specialist_response`.
147
154
 
148
155
  | Agent | Domain Authority | Core Responsibilities |
@@ -166,7 +173,7 @@ Every root dispatch carries a concise handoff brief — objective, bounded scope
166
173
 
167
174
  ## Skills & MCP Tooling
168
175
 
169
- - **In-Process Skill Search (`pantheon_skill_search`):** Quickly discovers local skills and external ecosystem skills without requiring shell execution permissions.
176
+ - **In-Process Skill Search (`pantheon_skill_search`) & Proactive Installation:** Quickly discovers local and external ecosystem skills; when gaps are identified, Zeus proactively invokes the interactive `question` tool for 1-click project-scoped installation into `.agents/skills/` (via `npx skills add <skill> -a opencode -y`), delegated to execution specialists with zero manual shell typing required.
170
177
  - **25 Production Skills:** Includes `test-slicing`, `fast-path-execution`, `tdd-with-agents`, `instruction-forge`, and `incremental-implementation`.
171
178
  - **5 Local MCP Servers:**
172
179
  - `pantheon-memory`: Shared project memory with atomic SQLite locking.
package/README.pt-BR.md CHANGED
@@ -53,6 +53,10 @@ flowchart LR
53
53
 
54
54
  - **Execução Fast-Track:** Micro-edições delimitadas (<= 2 arquivos, <= 50 linhas) pulam cerimônias pesadas e validam em < 10 segundos.
55
55
  - **Fatiamento mandatório de testes (test slicing):** Execução direcionada em submissegundos em vez de rodar suites lentas do repositório inteiro durante loops de desenvolvimento.
56
+ - **Recibos de execução comprováveis:** Assinatura criptográfica SHA-256 sobre arquivos modificados e fatias de teste elimina relatórios falsos-positivos de conclusão.
57
+ - **Otimização de prefixo de cache KV:** Estruturação estrita de prompts invariantes maximiza reaproveitamento de cache em modelos modernos.
58
+ - **Barramento reativo de eventos sem polling:** Event bus em memória distribui atualizações de jobs e agentes em tempo real com latência zero.
59
+ - **Loops de reflexo local Themis:** Auto-remediação direta de falhas isoladas de lint ou fatias de teste antes de escalar para o Zeus.
56
60
  - **Conselho assertivo (`/pantheon`):** Consultas paralelas entre especialistas resolvidas decisivamente via autoridade de domínio e decisões multi-critério JEV sem loops infinitos de debate.
57
61
  - **Você no comando:** O Pantheon apoia seu julgamento; ele nunca altera permissões silenciosamente nem executa ações destrutivas sem aprovação.
58
62
  - **Atualizações não-destrutivas:** Atualizar o Pantheon (`pantheon-opencode update`) renova skills, MCPs e instruções preservando rigorosamente todos os modelos do usuário, presets ativos, permissões e regras customizadas no `AGENTS.md`.
@@ -129,16 +133,19 @@ Para tarefas complexas com mais de 10 turnos ou distribuídas em várias sessõe
129
133
  ```text
130
134
  /pantheon-deepwork "Implementar autenticação OAuth2 PKCE"
131
135
  ```
132
- - **Fase 0 (Plano):** Athena mapeia os módulos e devolve o plano completo em Markdown exibido diretamente na conversa principal.
133
- - **Fase 1 (Descoberta):** Apollo realiza exploração estruturada.
134
- - **Fases 2–N (Implementação):** Especialistas implementam os módulos em fases paralelas.
135
- - **Gates de Revisão:** Themis audita cada fase (`PASS` ou `FAIL`).
136
+ - **O Plano é o Artefato:** O estado canônico é salvo em `.pantheon/deepwork/<slug>/plan.json` acompanhado do log append-only de eventos (`journal.ndjson`) para recuperação resiliente contra falhas.
137
+ - **Gates Nativos do OpenCode (Sem HTML):** Aprovações (Portão 1) e resoluções de decisão utilizam a ferramenta interativa nativa `question` do OpenCode diretamente no chat.
138
+ - **Grafo de Dependências (DAG):** Projeção automática das tarefas em diagrama Mermaid vivo (`flowchart LR`) dentro do `PLAN.md` e nos resumos de status do chat.
139
+ - **Critérios de Aceite Fail-First:** Cada tarefa define verificações concretas (`kind: test|command|file|manual`, `fails_now: true`) validadas com recibos criptográficos de execução.
140
+ - **Automação via Ferramenta (`pantheon_deepwork`):** Ferramenta estruturada para `init`, `status`, `update_task`, `verify_acceptance` e `resolve_decision`.
136
141
  - **Resumibilidade:** Progresso salvo em `.pantheon/deepwork/<slug>/`. Retome a qualquer momento com `/pantheon-deepwork --resume <slug>`.
137
142
 
138
143
  ---
139
144
 
140
145
  ## Os 14 Agentes Especializados
141
146
 
147
+ Para uma matriz detalhada de permissões, ferramentas, acesso a MCPs e restrições absolutas de cada agente, consulte a [Matriz de Capacidades dos Agentes](docs/AGENT-CAPABILITY-MATRIX.md).
148
+
142
149
  Toda delegação raiz carrega um brief conciso — objetivo, escopo delimitado, entradas relevantes, restrições, formato de retorno esperado e critérios de verificação. O trabalho é roteado de forma qualitativa — incerteza, especialidade de domínio, dependências, risco e verificação — nunca por limites arbitrários de linhas. Os contratos de retorno são específicos por papel: implementação usa `## subtask_summary`, investigações retornam achados estruturados, Athena entrega o plano completo e respostas ao conselho usam `## specialist_response`.
143
150
 
144
151
  | Agente | Autoridade de Domínio | Responsabilidades Principais |
@@ -162,7 +169,7 @@ Toda delegação raiz carrega um brief conciso — objetivo, escopo delimitado,
162
169
 
163
170
  ## Skills & Ferramental MCP
164
171
 
165
- - **Busca de Skills In-Process (`pantheon_skill_search`):** Encontra rapidamente skills locais e do ecossistema aberto sem depender de permissões de shell.
172
+ - **Busca de Skills In-Process (`pantheon_skill_search`) e Instalação Proativa:** Encontra rapidamente skills locais e do ecossistema aberto; ao detectar lacunas de capacidade, Zeus abre proativamente a ferramenta interativa `question` para instalação em 1 clique isolada no projeto em `.agents/skills/` (via `npx skills add <skill> -a opencode -y`), delegando a execução a especialistas sem exigir comandos manuais no terminal.
166
173
  - **25 Skills de Produção:** Inclui `test-slicing`, `fast-path-execution`, `tdd-with-agents`, `instruction-forge` e `incremental-implementation`.
167
174
  - **5 Servidores MCP Locais:**
168
175
  - `pantheon-memory`: Memória compartilhada com travas atômicas SQLite.
@@ -45,15 +45,24 @@ Phase FINAL: VERIFICATION
45
45
  └─ All tests pass, coverage >80%
46
46
  ```
47
47
 
48
- ## Checkpoints
48
+ ## Checkpoints & Canonical Storage
49
49
 
50
50
  ```
51
51
  Usage: --resume <slug> | --status <slug> | --list
52
52
 
53
53
  .pantheon/deepwork/<slug>/
54
- ├── PLAN.md DISCOVERY.md IMPL-phase-*-*.md phase-*-review.md REVIEW.md STATUS.md
54
+ ├── plan.json # Canonical ground truth (JSON DAG, tasks, acceptance criteria, decisions)
55
+ ├── journal.ndjson # Append-only crash recovery event log (task updates, verified proofs)
56
+ ├── PLAN.md # Markdown projection with Mermaid DAG (zero HTML, renders in TUI & Desktop)
57
+ ├── DISCOVERY.md IMPL-phase-*-*.md phase-*-review.md REVIEW.md STATUS.md
55
58
  ```
56
59
 
60
+ ### Native OpenCode Gates & Acceptance
61
+
62
+ - **Approval Gate (Gate 1):** Uses OpenCode native `question` tool to prompt user approval directly in chat.
63
+ - **Fail-First Acceptance:** Every task defines concrete acceptance criteria (`kind: test|command|file|manual`, `fails_now: true`). Verification is recorded with execution proof receipts.
64
+ - **Deepwork Tool:** Managed natively via `pantheon_deepwork` tool (`init`, `status`, `update_task`, `verify_acceptance`, `resolve_decision`, `list`).
65
+
57
66
  ## Full-Auto Mode (`--full-auto`)
58
67
 
59
68
  > [!WARNING] Automates only eligible review gates. Gate 1 and commit/deploy gates still require approval.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pantheon-opencode",
3
- "version": "2.0.3",
3
+ "version": "2.1.0",
4
4
  "description": "Multi-agent orchestration for OpenCode \u2014 14 specialized agents, TDD, Themis review gates.",
5
5
  "type": "module",
6
6
  "workspaces": [
@@ -49,6 +49,7 @@
49
49
  "hooks:install": "pre-commit install",
50
50
  "hooks:update": "pre-commit autoupdate",
51
51
  "test:security": "npm run secret-scan",
52
+ "test:quick": "node --test tests/skill-decision-proactive.test.mjs tests/plan-visibility-contract.test.mjs tests/proportional-execution-contract.test.mjs tests/memory-delegation-prompt.test.mjs tests/tui-settings-draft.test.mjs tests/tui-settings-i18n.test.mjs",
52
53
  "test:node": "node scripts/run-node-tests.mjs --label 'test:node' --exclude 'tests/install-opencode.test.mjs' --exclude 'tests/install-e2e.test.mjs' 'tests/*.mjs' 'tests/pantheon/*.mjs' 'tests/eval/*.mjs'",
53
54
  "test:install": "PANTHEON_RUN_INSTALL_TESTS=1 node scripts/run-node-tests.mjs --label 'test:install' 'tests/install-opencode.test.mjs' 'tests/install-e2e.test.mjs'",
54
55
  "coverage": "echo 'Node coverage (report-only, NO threshold is enforced).' && echo 'Covers: the .mjs/.js modules under scripts/, src/ and bin/ that test:node exercises.' && echo 'Does NOT cover: test:ts (hand-rolled tsx loop, no node --test runner) and test:ci (pytest).' && echo ' TypeScript under src/ (41 files) is therefore entirely unmeasured here.' && echo '' && node scripts/run-node-tests.mjs --label 'coverage' --exclude 'tests/install-opencode.test.mjs' --exclude 'tests/install-e2e.test.mjs' -- --experimental-test-coverage --test-coverage-include='scripts/**/*.mjs' --test-coverage-include='src/**/*.mjs' --test-coverage-include='src/**/*.js' --test-coverage-include='bin/**/*.mjs' 'tests/*.mjs' 'tests/pantheon/*.mjs'",
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pantheon",
3
3
  "publisher": "ils15",
4
- "version": "2.0.3",
4
+ "version": "2.1.0",
5
5
  "displayName": "Pantheon",
6
6
  "description": "Conductor-Delegate orchestration platform with 14 specialized agents, 25 skills, and OpenCode support.",
7
7
  "agents": "./src/agents",
@@ -174,10 +174,12 @@ DO: Choose the smallest safe track (Fast-Track for <= 2 files; Deep-Track only f
174
174
  DO: Run focused test slicing (target exact test file) rather than full test suites
175
175
  DO: Use Athena planning and Apollo discovery only when requested or warranted
176
176
  DO: Use in-process `pantheon_skill_search` and `pantheon_jev_decide` for discovery and advisory routing
177
+ DO: For missing capabilities, proactively invoke the `question` tool for 1-click project installation into `.agents/skills/` (via `npx skills add {{SKILL}} -a opencode -y`)
177
178
  DO: Run parallel work only for independent slices
178
179
  DO: Apply Themis review according to risk policy, bypassing for bounded micro-edits
179
180
 
180
181
  DONT: Don't read entire codebase yourself
182
+ DONT: Don't ask the user to run terminal commands for skill installation; never recommend or install global skills (~/.config/opencode/skills/)
181
183
  DONT: Don't force planning, discovery, review, or artifacts onto every task
182
184
  DONT: Don't run full test suites during incremental development
183
185
  DONT: Don't auto-commit or bypass a required safety gate
package/pyproject.toml CHANGED
@@ -4,7 +4,7 @@ build-backend = "setuptools.backends._legacy:_Backend"
4
4
 
5
5
  [project]
6
6
  name = "pantheon"
7
- version = "2.0.3"
7
+ version = "2.1.0"
8
8
  description = "Multi-agent orchestration framework"
9
9
  requires-python = ">=3.11"
10
10
  # Python sources under src/mcp/ import fastmcp/pydantic at runtime, but those
package/scripts/cost.mjs CHANGED
@@ -179,11 +179,10 @@ function readSource(db, source, since) {
179
179
  // too rather than inventing a column the reader never had.
180
180
  const metadata = info.metadata
181
181
  const phase =
182
- source === 'session_message'
183
- ? 'unknown'
184
- : (typeof info.phase === 'string' && info.phase) ||
185
- (typeof metadata?.phase === 'string' && metadata.phase) ||
186
- 'unknown'
182
+ (typeof info.phase === 'string' && info.phase) ||
183
+ (typeof metadata?.phase === 'string' && metadata.phase) ||
184
+ (typeof info.subtask?.phase === 'string' && info.subtask.phase) ||
185
+ 'unknown'
187
186
  const tokensInput = toToken(info.tokens?.input)
188
187
  const tokensOutput = toToken(info.tokens?.output)
189
188
  const key = rowKey(agent, phase)
@@ -4,7 +4,14 @@
4
4
 
5
5
  // src/pantheon/local-decision-budget.ts
6
6
  import { randomUUID } from "node:crypto";
7
- import { chmodSync, closeSync, lstatSync, mkdirSync, openSync } from "node:fs";
7
+ import {
8
+ chmodSync,
9
+ closeSync,
10
+ existsSync,
11
+ lstatSync,
12
+ mkdirSync,
13
+ openSync
14
+ } from "node:fs";
8
15
  import { homedir } from "node:os";
9
16
  import { basename, dirname, isAbsolute, join, parse, resolve, sep } from "node:path";
10
17
  import { performance } from "node:perf_hooks";
@@ -858,20 +865,34 @@ function ensureTrustedDirectoryChain(directoryPath) {
858
865
  }
859
866
  }
860
867
  }
868
+ function isPermittedGroupWritable(env = process.env) {
869
+ if (env.PANTHEON_ALLOW_GROUP_WRITABLE === "1" || env.PANTHEON_ALLOW_GROUP_WRITABLE === "true") {
870
+ return true;
871
+ }
872
+ if (env.JUPYTERHUB_USER || env.JUPYTER_IMAGE || env.JUPYTER_SERVER_ROOT || env.KUBERNETES_SERVICE_HOST || env.container || existsSync("/.dockerenv")) {
873
+ return true;
874
+ }
875
+ return false;
876
+ }
861
877
  function validateDirectoryTrust(stat, uid, isFinalDirectory) {
862
878
  if (!stat.isDirectory() || stat.isSymbolicLink()) {
863
879
  throw new Error("Budget ledger path contains a non-directory or symlink ancestor");
864
880
  }
865
- if (stat.uid !== uid && stat.uid !== 0) {
881
+ const mode = stat.mode & 4095;
882
+ const isSticky = (mode & 512) !== 0;
883
+ const isSystemOrUser = stat.uid === uid || stat.uid === 0 || isSticky && stat.uid === 65534;
884
+ if (!isSystemOrUser) {
866
885
  throw new Error("Budget ledger path contains an untrusted owner");
867
886
  }
868
887
  if (isFinalDirectory && stat.uid !== uid) {
869
888
  throw new Error("Budget ledger directory must be owned by the current user");
870
889
  }
871
- const mode = stat.mode & 4095;
872
- const writableByOthers = (mode & 18) !== 0;
873
- const rootStickyDirectory = stat.uid === 0 && (mode & 512) !== 0;
874
- if (writableByOthers && !rootStickyDirectory) {
890
+ const worldWritable = (mode & 2) !== 0;
891
+ const groupWritable = (mode & 16) !== 0;
892
+ if (worldWritable && !isSticky) {
893
+ throw new Error("Budget ledger path contains a group/other-writable directory");
894
+ }
895
+ if (groupWritable && !isSticky && !isFinalDirectory && !isPermittedGroupWritable()) {
875
896
  throw new Error("Budget ledger path contains a group/other-writable directory");
876
897
  }
877
898
  }
@@ -111,27 +111,50 @@ export async function runDecisionRouterCommand(
111
111
 
112
112
  if (command === 'status') {
113
113
  const options = parseNamedFlags(rest, ['--target'])
114
- const config = readUserDecisionRouterConfig({ env })
114
+ let config = null
115
+ let configError = null
116
+ try {
117
+ config = readUserDecisionRouterConfig({ env })
118
+ } catch (err) {
119
+ configError = err
120
+ }
115
121
  const dbPath = resolveLocalDecisionBudgetDbPath(env)
116
- const inspection = inspectDecisionBudget(dbPath)
122
+ let inspection = null
123
+ let ledgerError = null
124
+ try {
125
+ inspection = inspectDecisionBudget(dbPath)
126
+ } catch (err) {
127
+ ledgerError = err
128
+ }
117
129
  const wallPeriod = utcPeriodOf(Date.now())
118
- const egress = describeEgress(config, inspection, wallPeriod)
130
+ const egress = config && inspection ? describeEgress(config, inspection, wallPeriod) : null
119
131
 
120
132
  stdout(`Config: ${resolveUserDecisionRouterConfigPath(env)}`)
121
133
  stdout(
122
134
  `Config file: ${existsSync(resolveUserDecisionRouterConfigPath(env)) ? 'present' : 'absent'}`,
123
135
  )
124
- stdout(`Enabled: ${config.enabled ? 'yes' : 'no'}`)
125
- stdout(`Selection: ${formatSelection(config.selection)}`)
126
- stdout(`Egress consent: ${config.egress_consent ? 'yes' : 'no'}`)
127
- stdout(
128
- `Enabled candidates: ${config.enabled_candidates.length ? config.enabled_candidates.map(formatCandidate).join(', ') : 'none'}`,
129
- )
130
- stdout(describeEgressLine(egress))
131
- stdout(`Ledger: ${formatLedger(inspection, dbPath)}`)
132
- stdout(`Budget period: ${formatPeriod(inspection)}`)
133
- stdout(`Caps: ${formatCaps(inspection)}`)
134
- if (options['--target'] !== undefined) {
136
+ if (configError) {
137
+ stdout(`Config status: ERROR (${configError.message})`)
138
+ stdout('Enabled: unknown (blocked by security or configuration error)')
139
+ } else {
140
+ stdout(`Enabled: ${config.enabled ? 'yes' : 'no'}`)
141
+ stdout(`Selection: ${formatSelection(config.selection)}`)
142
+ stdout(`Egress consent: ${config.egress_consent ? 'yes' : 'no'}`)
143
+ stdout(
144
+ `Enabled candidates: ${config.enabled_candidates.length ? config.enabled_candidates.map(formatCandidate).join(', ') : 'none'}`,
145
+ )
146
+ }
147
+ if (egress) {
148
+ stdout(describeEgressLine(egress))
149
+ }
150
+ if (ledgerError) {
151
+ stdout(`Ledger: ERROR (${ledgerError.message})`)
152
+ } else if (inspection) {
153
+ stdout(`Ledger: ${formatLedger(inspection, dbPath)}`)
154
+ stdout(`Budget period: ${formatPeriod(inspection)}`)
155
+ stdout(`Caps: ${formatCaps(inspection)}`)
156
+ }
157
+ if (config && options['--target'] !== undefined) {
135
158
  stdout(`Install-state: ${formatInstallState(config, options['--target'])}`)
136
159
  }
137
160
  stdout('Mode: read-only — status and help never create, migrate or write anything.')
@@ -480,50 +503,69 @@ export async function runDecisionRouterCommand(
480
503
  if (command === 'doctor' && rest.length === 0) {
481
504
  // Read-only diagnosis. The host-catalog probe runs `opencode models` with a
482
505
  // timeout; a missing/unavailable binary is a warning, not a failure.
483
- const config = readUserDecisionRouterConfig({ env })
484
- const dbPath = resolveLocalDecisionBudgetDbPath(env)
485
- const inspection = inspectDecisionBudget(dbPath)
486
- const wallPeriod = utcPeriodOf(Date.now())
487
- const egress = describeEgress(config, inspection, wallPeriod)
488
506
  const rows = []
489
507
  const fail = (name, detail, fix) => rows.push({ name, state: 'FAIL', detail, fix })
490
508
  const warn = (name, detail, fix) => rows.push({ name, state: 'WARN', detail, fix })
491
509
  const pass = (name, detail) => rows.push({ name, state: 'PASS', detail })
492
510
 
511
+ let config = null
512
+ try {
513
+ config = readUserDecisionRouterConfig({ env })
514
+ } catch (err) {
515
+ fail(
516
+ 'config',
517
+ `configuration path unreadable: ${err.message}`,
518
+ 'check permissions or set PANTHEON_ALLOW_GROUP_WRITABLE=1',
519
+ )
520
+ }
521
+ const dbPath = resolveLocalDecisionBudgetDbPath(env)
522
+ let inspection = null
523
+ try {
524
+ inspection = inspectDecisionBudget(dbPath)
525
+ } catch (err) {
526
+ fail(
527
+ 'ledger',
528
+ `budget ledger unreadable: ${err.message}`,
529
+ 'check permissions or set PANTHEON_ALLOW_GROUP_WRITABLE=1',
530
+ )
531
+ }
532
+ const wallPeriod = utcPeriodOf(Date.now())
533
+ const egress = config && inspection ? describeEgress(config, inspection, wallPeriod) : null
534
+
493
535
  if (!existsSync(resolveUserDecisionRouterConfigPath(env))) {
494
536
  fail(
495
537
  'config',
496
538
  'no user-level config yet',
497
539
  'decision-router setup-model <provider>/<model> --monthly-usd N --per-decision-usd N',
498
540
  )
499
- } else if (!config.enabled) {
541
+ } else if (config && !config.enabled) {
500
542
  fail('config', 'turn selection is disabled', 'decision-router enable')
501
- } else {
543
+ } else if (config) {
502
544
  pass('config', 'enabled')
503
545
  }
504
- if (config.enabled && !config.egress_consent) {
546
+ if (config?.enabled && !config.egress_consent) {
505
547
  fail(
506
548
  'consent',
507
549
  'egress consent missing',
508
550
  'decision-router consent yes (or rerun setup-model without --no-consent)',
509
551
  )
510
- } else if (config.enabled) {
552
+ } else if (config?.enabled) {
511
553
  pass('consent', 'recorded')
512
554
  }
513
555
 
514
- const selection = config.selection
515
- if (config.enabled && selection.mode === 'local') {
556
+ const selection = config?.selection
557
+ if (config?.enabled && selection?.mode === 'local') {
516
558
  fail('selection', 'selection is local', 'decision-router select <provider>/<model>')
517
- } else if (config.enabled && selection.mode === 'auto') {
518
- if (egress.mode === 'opt-in')
559
+ } else if (config?.enabled && selection?.mode === 'auto') {
560
+ if (egress && egress.mode === 'opt-in')
519
561
  pass('selection', `auto resolved ${egress.provider}/${egress.candidate.model}`)
520
562
  else
521
563
  fail(
522
564
  'selection',
523
- `auto did not resolve (${egress.reason})`,
565
+ `auto did not resolve (${egress ? egress.reason : 'config or ledger unreadable'})`,
524
566
  'enable exactly one cap-valid candidate, or select explicitly',
525
567
  )
526
- } else if (config.enabled && selection.mode === 'explicit') {
568
+ } else if (config?.enabled && selection?.mode === 'explicit') {
527
569
  const enabled = config.enabled_candidates.some(
528
570
  (candidate) =>
529
571
  candidate.provider === selection.provider && candidate.model === selection.model,
@@ -539,16 +581,16 @@ export async function runDecisionRouterCommand(
539
581
  }
540
582
  }
541
583
 
542
- if (config.enabled && egress.mode !== 'opt-in' && config.egress_consent) {
584
+ if (config?.enabled && egress && egress.mode !== 'opt-in' && config.egress_consent) {
543
585
  fail(
544
586
  'budget',
545
587
  `no cap- and period-eligible candidate (${egress.reason})`,
546
588
  'decision-router caps user|provider|model ... and decision-router period confirm',
547
589
  )
548
- } else if (config.enabled && egress.mode === 'opt-in') {
590
+ } else if (config?.enabled && egress && egress.mode === 'opt-in') {
549
591
  pass('budget', `admission open for ${egress.provider}/${egress.candidate.model}`)
550
592
  }
551
- if (inspection.ledger.present && inspection.ledger.readable && inspection.ledger.holds > 0) {
593
+ if (inspection?.ledger.present && inspection.ledger.readable && inspection.ledger.holds > 0) {
552
594
  warn(
553
595
  'holds',
554
596
  `${inspection.ledger.holds} unresolved hold(s) hold budget until reconciled`,
@@ -557,9 +599,9 @@ export async function runDecisionRouterCommand(
557
599
  }
558
600
 
559
601
  const target =
560
- config.enabled && selection.mode === 'explicit'
602
+ config?.enabled && selection?.mode === 'explicit'
561
603
  ? selection
562
- : egress.mode === 'opt-in'
604
+ : egress?.mode === 'opt-in'
563
605
  ? { provider: egress.provider, model: egress.candidate.model }
564
606
  : null
565
607
  if (target !== null) {
@@ -30,8 +30,14 @@ import { basename, dirname, isAbsolute, join, resolve } from 'node:path'
30
30
  import { fileURLToPath } from 'node:url'
31
31
  import { load } from 'js-yaml'
32
32
  import { listV2UnsupportedFeatures } from '../src/pantheon/unsupported.mjs'
33
+ import { resolveLocalDecisionBudgetDbPath } from './decision-router-budget.mjs'
34
+ import { inspectDecisionBudget } from './decision-router-budget-gates.mjs'
33
35
  import { classifyOverrideFiles } from './install/behavior-overrides.bundle.mjs'
34
36
  import { describePluginOptionsReachability } from './install/capabilities.mjs'
37
+ import {
38
+ readUserDecisionRouterConfig,
39
+ resolveUserDecisionRouterConfigPath,
40
+ } from './install/decision-router-config.mjs'
35
41
  import { classifyFileInventory } from './install/file-inventory.mjs'
36
42
  import { staleTuiRefs } from './install/plugin.mjs'
37
43
  import { readState } from './install/state.mjs'
@@ -2902,6 +2908,73 @@ function checkBehaviorOverrides(args) {
2902
2908
  }
2903
2909
  }
2904
2910
 
2911
+ export function checkDecisionRouter(_args = {}) {
2912
+ section('L. Decision Router & JEV Runtime')
2913
+ const env = process.env
2914
+ const configPath = resolveUserDecisionRouterConfigPath(env)
2915
+ if (!existsSync(configPath)) {
2916
+ pass('decision-router.json is not configured (optional JEV routing inactive)', {
2917
+ code: 'decision_router_absent',
2918
+ classification: 'config',
2919
+ })
2920
+ return
2921
+ }
2922
+
2923
+ let config = null
2924
+ try {
2925
+ config = readUserDecisionRouterConfig({ env })
2926
+ pass('decision-router.json is trusted and private', {
2927
+ code: 'decision_router_config_trusted',
2928
+ classification: 'config',
2929
+ })
2930
+ } catch (error) {
2931
+ warn(`decision-router.json directory trust check failed: ${error.message}`, {
2932
+ code: 'decision_router_trust_failed',
2933
+ classification: 'config',
2934
+ })
2935
+ info(
2936
+ 'Hint: in container/JupyterHub environments, export PANTHEON_ALLOW_GROUP_WRITABLE=1 or run: chmod +t <path>',
2937
+ )
2938
+ return
2939
+ }
2940
+
2941
+ if (config.enabled) {
2942
+ if (!config.egress_consent) {
2943
+ warn('decision-router is enabled but egress consent is missing', {
2944
+ code: 'decision_router_consent_missing',
2945
+ classification: 'config',
2946
+ })
2947
+ } else {
2948
+ pass(`decision-router is enabled with selection: ${JSON.stringify(config.selection)}`, {
2949
+ code: 'decision_router_enabled',
2950
+ classification: 'config',
2951
+ })
2952
+ }
2953
+
2954
+ const dbPath = resolveLocalDecisionBudgetDbPath(env)
2955
+ try {
2956
+ const inspection = inspectDecisionBudget(dbPath)
2957
+ if (inspection.ledger.readable) {
2958
+ pass(`decision budget ledger is accessible (${dbPath})`, {
2959
+ code: 'decision_budget_ledger_accessible',
2960
+ classification: 'budget',
2961
+ })
2962
+ } else {
2963
+ warn(`decision budget ledger is not initialized yet (${dbPath})`, {
2964
+ code: 'decision_budget_ledger_uninitialized',
2965
+ classification: 'budget',
2966
+ })
2967
+ }
2968
+ } catch (error) {
2969
+ warn(`decision budget ledger path error: ${error.message}`, {
2970
+ code: 'decision_budget_ledger_error',
2971
+ classification: 'budget',
2972
+ })
2973
+ info('Hint: export PANTHEON_ALLOW_GROUP_WRITABLE=1 or run setup-model')
2974
+ }
2975
+ }
2976
+ }
2977
+
2905
2978
  async function main() {
2906
2979
  const args = parseArgs(process.argv)
2907
2980
  jsonMode = args.json
@@ -2998,6 +3071,7 @@ async function main() {
2998
3071
  checkSubagentDepthPlacement(args)
2999
3072
  checkPermissionTaskPresence(args)
3000
3073
  checkUnsupportedFeatures(args)
3074
+ checkDecisionRouter(args)
3001
3075
 
3002
3076
  printSummary(args.target)
3003
3077
  if (jsonMode) writeDoctorJson(createDoctorJsonReport(args), exitCode)