diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index a39a3953..262797e2 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -292,11 +292,15 @@ jobs: env: BASE_VERSION: ${{ steps.version_gate.outputs.version }} RECOVERY_VERSION: ${{ inputs.recovery_version }} + RELEASE_CHANNEL: ${{ steps.type.outputs.channel }} + RELEASE_REPO: ${{ github.repository }} run: | set -euo pipefail mkdir -p "$RUNNER_TEMP/release-artifact" - # Notes come from the committed CHANGELOG.md for BOTH channels. The - # version is committed, so its section is authorable in the bump PR. + # Notes come from the committed CHANGELOG.md for BOTH channels. For + # stable non-recovery builds with a curated docs/releases/vX.Y.Z.md, + # scripts/release-body.mjs composes the visual release page plus the + # canonical CHANGELOG ledger into the single artifact release-notes.md. # Recovery extracts the section at the recovery target as well, so a # republished release keeps the canonical body; the static note is # the last resort for tags predating the CHANGELOG section. @@ -307,8 +311,19 @@ jobs: echo "No CHANGELOG section for v$RECOVERY_VERSION — publishing the static recovery note." printf '%s\n' "Recovery publish for existing tag $RECOVERY_VERSION." > "$RUNNER_TEMP/release-notes.md" fi - elif ! node scripts/changelog-extract.mjs "$BASE_VERSION" > "$RUNNER_TEMP/release-notes.md"; then - echo "::error::CHANGELOG.md has no [$BASE_VERSION] section."; exit 1 + else + if ! node scripts/changelog-extract.mjs "$BASE_VERSION" > "$RUNNER_TEMP/release-notes.md"; then + echo "::error::CHANGELOG.md has no [$BASE_VERSION] section."; exit 1 + fi + if [ "$RELEASE_CHANNEL" = "stable" ] && [ -f "docs/releases/v$BASE_VERSION.md" ]; then + node scripts/release-body.mjs \ + --version "$BASE_VERSION" \ + --channel "$RELEASE_CHANNEL" \ + --changelog-notes "$RUNNER_TEMP/release-notes.md" \ + --repo "$RELEASE_REPO" \ + --ref "v$BASE_VERSION" \ + --out "$RUNNER_TEMP/release-notes.md" + fi fi npm run package:evidence -- --output-dir="$RUNNER_TEMP/release-artifact" --target-sha="$TARGET_SHA" > "$RUNNER_TEMP/package-evidence.json" TARBALLS=("$RUNNER_TEMP/release-artifact"/*.tgz) diff --git a/.zenodo.json b/.zenodo.json index d83752bd..89e21551 100644 --- a/.zenodo.json +++ b/.zenodo.json @@ -8,11 +8,11 @@ "orcid": "0000-0001-7787-7562" } ], - "version": "2.2.0-beta.11", + "version": "2.2.0", "license": "MIT", "language": "eng", "keywords": ["opencode", "ai-agents", "multi-agent", "orchestration", "developer-tools"], - "url": "https://github.com/ils15/pantheon-opencode/releases/tag/v2.2.0-beta.11", + "url": "https://github.com/ils15/pantheon-opencode/releases/tag/v2.2.0", "related_identifiers": [ { "identifier": "https://github.com/ils15/pantheon-opencode", diff --git a/CHANGELOG.md b/CHANGELOG.md index ba4bf8e3..6daf9082 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,44 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). `node scripts/versioning.mjs apply --notes` pre-fills the generated sections from conventional commits. Running apply will move this section to a versioned entry and reset the template below. --> +## [v2.2.0] - 2026-11-19 + +### 🆕 What's New + +- **30 Native TypeScript Tools & Pillars 1–5**: LSP bridge, `ast_search`/`ast_rewrite`, git checkpoints, worktrees, and bugfix gates. +- **TUI Mission Control Cockpit (`/pantheon-cockpit`)**: 3-page dashboard (`Overview`, `Swarm` Gantt, `Flightdeck` gates) via `1–3`/`Tab`. +- **Step-Ledger Checkpoints & Verdict Remediation**: Isolated `ctx.session.create` steps, git rollback, and `pantheon_review_verdict`. +- **Interactive `/pantheon-forge` & Artifacts**: Stack detector (`package.json`, `pyproject.toml`, `Cargo.toml`, `go.mod`) & Mermaid viewer. +- **Live Dispatch Telemetry & Native Todo**: Sidebar counters (`mem`/`ctx`/`code`), child verbs, `?`/`!` badges, and Home/Sidebar links. +- **Worktree Memory, Hashline & Cache Hygiene**: Shared `.pantheon/` store, confined `hashline_edit`, and automatic stale cache cleanup. + +### Added + +- **cockpit** — `cockpit.tsx`, `cockpit-state.ts`, `cockpit-events.ts`: added 3-page `/pantheon-cockpit`, Home `◈ Cockpit` link, `.pantheon/telemetry` bus stream, and Mermaid replay export. +- **lsp-ast** — `lsp-diagnostics.ts`, `ast-tools.ts`: added `tsc`/Pyright/stdio + pooled TCP LSP proxy (`PANTHEON_LSP_TCP_ENDPOINTS`) and workspace-confined `ast_search`/`ast_rewrite`. +- **memory** — `memory-federation.ts`, `native-memory-tools.ts`, `tool-context.ts`: added read-only multi-repo knowledge federation (`PANTHEON_FEDERATED_REPOS`) and worktree-shared `.pantheon/`. +- **ledger** — `git-checkpoint.ts`, `step-runner.ts`, `step-ledger.ts`: added isolated `GIT_INDEX_FILE` snapshots, `execute_step` sub-sessions, `record_reproduction`, `rollback_step`, and auto-rollback. +- **orchestration** — `worktree-orchestrator.ts`, `review-verdict.ts`, `reproduction-gate.ts`: wired `ctx.worktree.transform` + `pantheon_worktree`, `pantheon_review_verdict`, and bugfix `RED` gate. +- **forge** — `scripts/stack-detector.mjs`, `stack-detector.ts`, `pantheon-forge.md`, `agent-forge-tool.ts`: added `/pantheon-forge` wizard, `detect_stack`, and `init --project` hints. +- **tui** — `artifacts.tsx`, `mermaid-ascii.ts`, `legacy-audit.ts`: added `/pantheon-artifacts` Unicode Mermaid viewer, Sidebar/Home quick links, `Native Tools (30)`, and stale npm cache cleanup. + +### Changed + +- **plugin** — `src/plugin.ts`, `tools.ts`, `delegation-enforce.ts`: registers all 30 native tools and 9 server commands, preserves `todowrite`/`todoread`, removes `/pantheon-settings` duplicate. +- **agents** — `src/agents/roster.json`: updated all 14 canonical agents with permissions and prompts for `ast_search`, `pantheon_worktree`, `execute_step`, and `pantheon_review_verdict`. +- **release** — `scripts/version-check.mjs`, `scripts/package-evidence.mjs`: validates `dist/tui.js` version match in `prepack` and package consumer tests. +- **docs** — updated `README.md`, `README.pt-BR.md`, `ROADMAP.md`, `docs/`, and `wiki/` with complete v2.2.0 architecture, 30 tools, Cockpit guides, and live TUI screenshots. + +### Removed + +- **tui** — removed the placeholder `Quotas & Spend` (`Cotas & Gastos`) tab from `/pantheon-settings`. + +### Fixed + +- **execute-after** — `src/pantheon/execute-after.ts`, `plugin.ts`: resolves `ast_rewrite` (`path`/`filesModified`) and relative `hashline_edit` paths against workspace `cwd` for post-edit lint & LSP. +- **sdk-parity** — `step-runner.ts`, `review-verdict.ts`: aligns `SessionApi` calls (`create`, `prompt`, `wait`, `remove`, `synthetic`) with `@opencode/client` and routes `BLOCK` to parent session. +- **hashline** — `src/pantheon/hashline/tool.ts`, `tool-context.ts`: confines relative paths to the active workspace root with symlink traversal checks. +- **tui** — `mermaid-ascii.ts`, `pantheon-settings.tsx`, `whats-new.tsx`, `index.tsx`: fixes CodeQL `js/bad-tag-filter` alert, Home `Tab` in `/pantheon-settings`, and enlarges `What's New` layout. ## [v2.2.0-beta.11] - 2026-11-19 ### 🆕 What's New diff --git a/CITATION.cff b/CITATION.cff index ad0fb860..d27b8cf7 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -5,8 +5,8 @@ abstract: >- Pantheon v2.1.6 is an OpenCode plugin and installer coordinating 14 specialized agents with high-speed direct dispatch, native subagents, and progressive skill disclosure for OpenCode 2.x. -version: 2.2.0-beta.11 -url: https://github.com/ils15/pantheon-opencode/releases/tag/v2.2.0-beta.11 +version: 2.2.0 +url: https://github.com/ils15/pantheon-opencode/releases/tag/v2.2.0 doi: 10.5281/zenodo.22650136 repository-code: https://github.com/ils15/pantheon-opencode license: MIT diff --git a/README.md b/README.md index 2aa9a39e..b88a35a5 100644 --- a/README.md +++ b/README.md @@ -32,14 +32,14 @@ Requirements: [OpenCode](https://opencode.ai/docs/) **2.x** and Node.js **≥ 26 ([compatibility](docs/COMPATIBILITY.md)). ```bash -# Primary (Recommended) — native OpenCode 2.x plugin (global or project, no npx init required) -opencode plugin add pantheon-opencode@beta +# Primary (Recommended) — native OpenCode 2.x plugin (works in any directory, no init required) +opencode plugin add pantheon-opencode -# Check health, updates & clean legacy/obsolete files inside OpenCode: -# /pantheon-settings -> Updates (or Legacy & Drift Cleanup) +# Check health, updates & clean legacy/stale caches inside OpenCode: +# /pantheon-settings -> Updates (or Legacy & Drift Cleanup), /pantheon-updates, /pantheon-whats-new # Deprecated legacy CLI fallback (optional Python MCP runtime only): -# npm install -g pantheon-opencode@beta && pantheon-opencode init --yes +# npm install -g pantheon-opencode && pantheon-opencode init --yes ``` ## Usage @@ -58,6 +58,16 @@ plan with `pantheon_step_ledger` mechanical receipts and gates; and `pantheon_ag creates custom project-specific domain specialists in `.opencode/agents/.md` on demand. You approve each gate and you run every commit. +The OpenCode 2.x TUI surfaces live native-tool domain counters (`mem`, `ctx`, `code`, `edit`, +`shell`), live child activity and attention badges (`?` / `!`) in `Dispatch` and `/dispatch`, +the interactive **Mission Control Cockpit** (`/pantheon-cockpit` · `Overview`, `Swarm`, +`Flightdeck`), `/pantheon-artifacts` for plans/reports/ADRs, interactive `/pantheon-forge` stack +detection, and the full **30-tool native inventory** in `/pantheon-settings` → **About** (including +post-edit LSP diagnostics, `ast_search`/`ast_rewrite`, `pantheon_review_verdict`, bugfix `RED` +reproduction gates, and `ctx.worktree.transform` sibling worktrees). Git worktrees automatically +share the main repository's `.pantheon/memory`, checkpoints, and goals store (set +`PANTHEON_ISOLATE_WORKTREE_MEMORY=1` to keep a worktree's memory store isolated). + ## Structure ``` @@ -82,7 +92,8 @@ tests/ Node and TypeScript test suites | [Installation](docs/INSTALLATION.md) | [Execution modes](docs/guides/execution-modes.md) | | [First project end-to-end](docs/guides/first-project.md) | [Agent Capability Matrix](docs/AGENT-CAPABILITY-MATRIX.md) | | [Settings & TUI window](docs/SETTINGS.md) | [Permissions, gates & delegation](docs/PERMISSIONS-QUALITY-DELEGATION.md) | -| [Release highlights](docs/releases/highlights.md) | [CHANGELOG](CHANGELOG.md) | +| [Artifacts & `/pantheon-artifacts`](docs/ARTIFACTS.md) | [Release highlights](docs/releases/highlights.md) | +| [CHANGELOG](CHANGELOG.md) | [Architecture](docs/ARCHITECTURE.md) | Runnable examples: [SaaS performance dashboard](examples/saas-dashboard/) and [repo health CLI](examples/cli-tool/). Contributing: diff --git a/README.pt-BR.md b/README.pt-BR.md index 665a871b..b71e83ad 100644 --- a/README.pt-BR.md +++ b/README.pt-BR.md @@ -35,14 +35,14 @@ Requisitos: [OpenCode](https://opencode.ai/docs/) **2.x** e Node.js **≥ 26.4.0 ([compatibilidade](docs/COMPATIBILITY.md)). ```bash -# Principal (Recomendado) — plugin nativo do OpenCode 2.x (global ou projeto, sem npx init) -opencode plugin add pantheon-opencode@beta +# Principal (Recomendado) — plugin nativo do OpenCode 2.x (funciona em qualquer pasta, sem init) +opencode plugin add pantheon-opencode -# Verificar atualizações e limpar arquivos legados/obsoletos dentro do OpenCode: -# /pantheon-settings -> Atualizações (seção Legados, Drift & Limpeza) +# Verificar atualizações e limpar arquivos legados/caches obsoletos dentro do OpenCode: +# /pantheon-settings -> Atualizações (seção Legados, Drift & Limpeza), /pantheon-updates, /pantheon-whats-new # Fallback legado via CLI (em descontinuação — apenas se precisar de MCPs Python opcionais): -# npm install -g pantheon-opencode@beta && pantheon-opencode init --yes +# npm install -g pantheon-opencode && pantheon-opencode init --yes ``` ## Uso @@ -61,6 +61,17 @@ executa um plano multifase com recibos mecânicos via `pantheon_step_ledger` e g `pantheon_agent_forge` cria especialistas customizados de domínio em `.opencode/agents/.md` sob demanda. Você aprova cada gate e executa cada commit. +A TUI do OpenCode 2.x exibe contadores ao vivo por domínio de ferramentas nativas (`mem`, +`ctx`, `code`, `edit`, `shell`), atividade ao vivo e badges de atenção (`?` / `!`) no +`Dispatch` e `/dispatch`, o **Mission Control Cockpit** (`/pantheon-cockpit` · `Overview`, +`Swarm`, `Flightdeck`), `/pantheon-artifacts` para planos/relatórios/ADRs, o assistente +`/pantheon-forge` com detecção de stack e o inventário completo de **30 tools nativas** em +`/pantheon-settings` → **Sobre** (incluindo diagnósticos LSP pós-edição, +`ast_search`/`ast_rewrite`, `pantheon_review_verdict`, gate de reprodução `RED` para bugfix e +worktrees nativas via `ctx.worktree.transform`). Worktrees Git compartilham automaticamente o +repositório principal para `.pantheon/memory`, checkpoints e metas (defina +`PANTHEON_ISOLATE_WORKTREE_MEMORY=1` para isolar uma worktree). + ## Estrutura ``` @@ -85,7 +96,8 @@ tests/ suítes de teste em Node e TypeScript | [Instalação](docs/pt-BR/INSTALLATION.md) | [Modos de execução](docs/guides/execution-modes.md) | | [Primeiro projeto ponta a ponta](docs/pt-BR/guides/first-project.md) | [Matriz de capacidade dos agentes](docs/pt-BR/AGENT-CAPABILITY-MATRIX.md) | | [Configurações e janela TUI](docs/SETTINGS.md) | [Permissões, gates e delegação](docs/PERMISSIONS-QUALITY-DELEGATION.md) | -| [Destaques de versões](docs/releases/highlights.md) | [CHANGELOG](CHANGELOG.md) | +| [Artefatos e `/pantheon-artifacts`](docs/ARTIFACTS.md) | [Destaques de versões](docs/releases/highlights.md) | +| [CHANGELOG](CHANGELOG.md) | [Arquitetura](docs/pt-BR/ARCHITECTURE.md) | Exemplos executáveis: [dashboard SaaS](examples/saas-dashboard/) e [CLI de saúde do repositório](examples/cli-tool/). Contribuição: diff --git a/ROADMAP.md b/ROADMAP.md index 66fcbfad..3780f2f2 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,9 +2,9 @@ This roadmap records customer-visible themes, maintenance boundaries, and readiness conditions for stable releases. Internal tracking identifiers, per-item evidence bundles, and per-commit history are intentionally not part of this page. -## Current State: 2.2.0 Beta (`v2.2.0-beta.2`) & 2.1.x Stable (`v2.1.6`) +## Current State: 2.2.0 Stable (`v2.2.0`) & 2.1.x Maintenance (`v2.1.6`) -The `2.2.0-beta.2` release consolidates the **100% Native OpenCode 2.2 (`@opencode/plugin@2.2.5`) Architecture**, eliminating legacy V1/V2 split nomenclature, moving durable memory/persistence/goal/codemap operations in-process via `node:sqlite` FTS5, making the core execution roster (`@hermes`, `@demeter`, `@aphrodite`) **polyglot and stack-agnostic**, and introducing **`pantheon_agent_forge`** for instant creation of custom domain specialists alongside **`pantheon_step_ledger`** for mechanical completion gates. +The `2.2.0` release consolidates the **100% Native OpenCode 2.x (`@opencode/plugin`) Architecture**, eliminating legacy V1/V2 split nomenclature, moving durable memory/persistence/goal/codemap operations in-process via `node:sqlite` FTS5, making the core execution roster (`@hermes`, `@demeter`, `@aphrodite`) **polyglot and stack-agnostic**, and delivering all **5 Orchestration Evolution Pillars** alongside the interactive **TUI Mission Control Cockpit** (`Overview`, `Swarm`, `Flightdeck`). The `2.1.x` release series delivered the canonical Deepwork plan architecture, interactive native Question Gate enforcement, unrestricted `.pantheon/` and worktree access for analytical agents, bilingual documentation portals, live session Todo synchronization, observable test slicing, risk-based validation protocols, unified local/external skill discovery, deepwork resilience normalization, and workspace auto-permissions. @@ -12,38 +12,40 @@ See [Compatibility](docs/COMPATIBILITY.md) for supported hosts and the [releases --- -## 2.2.0-beta.2 Deliveries (Native Quality & Orchestration) +## 2.2.0 Deliveries (Native Quality, Pillars 1–5 & Cockpit) 1. **Clean `./server` vs `./tui` Bundle Separation & Zero-Init Provisioning** - Decoupled `./server` (`src/plugin/index.js`) from `./tui` (`src/plugins/tui/dist/tui.js`) so the server plugin loads in pure Node without pulling `@opentui/solid` into the host runtime. - - Auto-provisioned all 12 core specialist agents (`ctx.agent.transform`) and 8 `/pantheon-*` slash commands (`ctx.command.transform`) with `AGENTS.global.md` reference registration (`ctx.reference.transform`) and KV-cache-preserving session instructions (`ctx.session.instructions.entry.put`). -2. **In-Process Native SQLite FTS5 Memory, Persistence, Goals & Codemap Tools** - - Registered 15 native in-process plugin tools (`memory_store`, `memory_recall`, `memory_search`, `memory_forget`, `memory_list`, `memory_stats`, `context_save`, `context_get`, `goal_create`, `goal_get`, `goal_update`, `goal_done`, `code_index`, `code_query`, `code_neighbors`) backed by `node:sqlite` WAL + FTS5 BM25 ranking and secret redaction—eliminating external stdio MCP cold-start latency. -3. **Polyglot Core Roster + First-Class Custom Specialist Forge (`pantheon_agent_forge`)** - - Upgraded `@hermes` (TypeScript/Node, Python/FastAPI, Go, Rust, Java), `@demeter` (SQL/NoSQL, PostgreSQL, SQLite, Prisma, Drizzle, SQLAlchemy 2.0/Alembic), and `@aphrodite` (React 19, SolidJS, Vue, Svelte, Next.js) to be stack-agnostic by default. - - Added the native `pantheon_agent_forge` tool (`create`, `list`, `inspect`, `remove`) allowing users or `@zeus` to scaffold custom domain specialists in `.opencode/agents/.md` with least-privilege permissions (`read-only`, `implementer`, `reviewer`), automatic MCP governance ladder, and sliced TDD rules while protecting the 12 canonical Pantheon agent names. -4. **Step-Ledger (`pantheon_step_ledger`) & Active Execution Receipts** - - Wired `execution-receipt.ts`, `themis-reflex.ts`, and `prompt-cache-order.ts` into the live `src/plugin.ts` runtime and `pantheon_step_ledger`. - - Enforced mechanical completion gates: a ledger step that mutates files (`edit`, `write`, `hashline_edit`) cannot transition to `done` unless a post-mutation verification command (`bash`/`shell`) exited with `0` and produced a matching SHA-256 execution receipt. -5. **Post-Edit Structural Diagnostics & Hardened Plugin Tool Guards** - - Added immediate post-edit TypeScript/JSON/JS syntax & structural diagnostics in `execute-after.ts` so specialists fix syntax regressions in the same turn. - - Enforced role-based write/exec guards (`NON_EDIT_AGENTS`, `NON_SHELL_AGENTS`), `isDangerousCommand`, and 120s process timeouts on `shell` and `hashline_edit`, plus session-isolated `todowrite`/`todoread` stores. -6. **Multi-File `RED → GREEN` Evaluation Harness (`swe-eval-harness.ts`)** - - Added a deterministic evaluation harness verifying multi-file mutations against both visible test slices and hidden anti-reward-hacking test suites. + - Auto-provisioned all core/specialist agents (`ctx.agent.transform`) and canonical `/pantheon-*` slash commands (`ctx.command.transform`) with `AGENTS.global.md` reference registration (`ctx.reference.transform`) and KV-cache-preserving session instructions (`ctx.session.instructions.entry.put`). +2. **29 In-Process Native TypeScript Tools & SQLite FTS5 Persistence** + - Registered 30 native plugin tools in-process (`memory_*`, `context_*`, `goal_*`, `code_*`, `ast_search`, `ast_rewrite`, `hashline_edit`, `shell`, `todowrite`/`todoread`, `pantheon_cost`, `pantheon_model`, `pantheon_skill_search`, `pantheon_deepwork`, `pantheon_step_ledger`, `pantheon_agent_forge`, `pantheon_local_decision`, `pantheon_review_verdict`, and `pantheon_worktree`) backed by `node:sqlite` WAL + FTS5 BM25 ranking and worktree-shared `.pantheon/` state. +3. **Pillar 1 — Post-Edit LSP Diagnostics Bridge & Structural AST Tools (`ast_search`, `ast_rewrite`)** + - Hooked `execute.after` diagnostics into TypeScript (`tsc --noEmit`), Pyright (`--outputjson`), and optional stdio LSP framing (`PANTHEON_LSP_SERVER`) emitting `'lsp:diagnostics'`. + - Exposed comment-aware, dependency-free `ast_search` and `ast_rewrite` tools with workspace path confinement and pre-write edit guardrail checks. +4. **Pillar 2 — Atomic Git Checkpointing & Sub-Session Step Runner (`ctx.session.create`)** + - Wired isolated temp `GIT_INDEX_FILE` snapshots (`captureGitCheckpoint` / `restoreGitCheckpoint`), SHA-256 execution receipts (`pantheon_step_ledger`), and automatic rollback on `themis:reflex:escalated`. + - Added `runAtomicStepSubSession` using `ctx.session.create` / `prompt` / `wait` / `remove` for single-step isolated execution. +5. **Pillar 3 — Native Worktree Orchestration (`ctx.worktree.transform`) & Typed Review Verdict (`pantheon_review_verdict`)** + - Registered `ctx.worktree.transform` (`create`, `remove`, `list`) enforcing sibling `.pantheon-worktrees//` isolation. + - Exposed `pantheon_review_verdict` emitting `'review:verdict'` and triggering bounded `ctx.session.synthetic` remediation turns (max 2) when `@themis` emits `BLOCK`. +6. **Pillar 4 — Mandatory Fault-Localization & Reproduction Gate** + - Enforces a failing `record_reproduction` (`exitCode !== 0`) on `taskType: 'bugfix'` steps before unlocking production file edits (`edit`/`hashline_edit`/`ast_rewrite`) for `@hermes` or `@talos`, while allowing `RED` test creation first. +7. **Pillar 5 — Interactive `/pantheon-forge` Wizard & Stack Auto-Detection** + - Added `/pantheon-forge` command, `detect_stack` action in `pantheon_agent_forge`, and `--project` stack hints in `bin/pantheon-init.mjs` (`package.json`, `pyproject.toml`, `Cargo.toml`, `go.mod`). +8. **TUI Mission Control Cockpit, `/pantheon-artifacts`, & Telemetry** + - Built the native `@opentui/solid` `/pantheon-cockpit` dialog with `Overview`, `Swarm` (concurrency Gantt + semantic stream), and `Flightdeck` (Gate Matrix + event log) tabs accessible via `1–3` / `Tab`, plus `/pantheon-artifacts` with Unicode Mermaid rendering and Sidebar/Home links. --- -## Next-Generation Orchestration Evolution Plan (2.2 GA → 2.3) +## Architecture Implementation Summary (v2.2.0) -The following high-leverage architectural capabilities are planned for the next iterations of Pantheon: - -| Architectural Pillar | Core Mechanism | Status in Pantheon `2.2.0-beta.2` | Planned Next-Gen Evolution (`2.2 GA` / `2.3`) | -|---|---|---|---| -| **Structural Editing & Diagnostics** | Hash-anchored edits (`LINE#ID`), post-edit `execute.after` diagnostics, structural AST search/rewrite, `experimental.idle` continuation | `hashline_edit` + post-edit syntax/brace diagnostics delivered in `beta.2` | **Full LSP Diagnostics Bridge + Native `ast_search` / `ast_rewrite` Tools**: Hook into workspace TypeScript/Pyright/Biome servers on `execute.after` and expose structural AST pattern rewriting without regex drift. | -| **Step-Ledger & Sub-Session Isolation** | Pre-code validation matrix (Requirement → Test Slice), fresh sub-session per atomic task (`ctx.session.create`), atomic git commit checkpoints | `pantheon_step_ledger` + SHA-256 execution receipt gate delivered in `beta.2` | **Autonomous Sub-Session Step Runner & Atomic Git Checkpointing**: Spawn isolated `ctx.session.create` contexts per ledger step with automatic git tree snapshots and instant rollback on `themis:reflex:escalated`. | -| **Spec-First Review & Worktree Isolation** | Interactive spec-refinement before planning, two-stage independent review (IntentGate → Code Quality), git worktree isolation per task | `>>` Prompt Refinery + `@themis` IntentGate & Layer 1-3 review active | **Native Worktree Orchestration (`ctx.worktree.transform`) & Typed Review Verdict Tool (`pantheon_review_verdict`)**: Provision isolated git worktrees per parallel specialist and trigger automatic `ctx.session.synthetic` remediation turns when `@themis` emits `BLOCK`. | -| **Graph Localization & Reproduction Gates** | Graph-based localization before editing (`code_index` → candidate narrowing → reproduction test before patch) | `code_index`/`code_query`/`code_neighbors` + `swe-eval-harness.ts` delivered in `beta.2` | **Mandatory Fault-Localization & Reproduction Gate for Bugfixes**: Require a failing reproduction slice (`RED`) before unlocking `edit`/`hashline_edit` on bugfix tasks routed to `@hermes` or `@talos`. | -| **Polyglot Core & Domain Extensibility** | Stack-agnostic core agents + zero-friction project specialist creation | Polyglot `@hermes`/`@demeter`/`@aphrodite` + `pantheon_agent_forge` delivered in `beta.2` | **Interactive `/pantheon-forge` Wizard & Stack Auto-Detection**: Automatically detect repository stack (`package.json`, `pyproject.toml`, `Cargo.toml`, `go.mod`) on `init` and suggest tailored project specialists + domain convention docs. | +| Architectural Pillar | Core Mechanism | Status in Pantheon `2.2.0` | +|---|---|---| +| **Structural Editing & Diagnostics** | `hashline_edit`, `execute.after` diagnostics + LSP bridge, `ast_search` / `ast_rewrite` | **Delivered (`v2.2.0`)** — `lsp-diagnostics.ts`, `ast-tools.ts`, `execute-after.ts`. | +| **Step-Ledger & Sub-Session Isolation** | SHA-256 receipts, isolated `ctx.session.create` runner, temp-index git checkpoints & auto-rollback | **Delivered (`v2.2.0`)** — `step-ledger.ts`, `step-runner.ts`, `git-checkpoint.ts`, `themis-reflex.ts`. | +| **Spec-First Review & Worktree Isolation** | `>>` Prompt Refinery, sibling `.pantheon-worktrees/` orchestration, `pantheon_review_verdict` + `ctx.session.synthetic` | **Delivered (`v2.2.0`)** — `worktree-orchestrator.ts`, `review-verdict.ts`, `plugin.ts`. | +| **Graph Localization & Reproduction Gates** | `code_index`/`code_query`/`code_neighbors` auto-pruning, failing `RED` test gate for bugfixes | **Delivered (`v2.2.0`)** — `codemap-tools.ts`, `reproduction-gate.ts`, `swe-eval-harness.ts`. | +| **Polyglot Core & Domain Extensibility** | Polyglot `@hermes`/`@demeter`/`@aphrodite`, `pantheon_agent_forge`, `/pantheon-forge`, deterministic stack detector | **Delivered (`v2.2.0`)** — `stack-detector.ts`, `agent-forge-tool.ts`, `commands/pantheon-forge.md`. | --- @@ -125,41 +127,23 @@ Active development on the `2.1.x` line focuses on operational smoothness and dev --- -## Road to 2.2.0 Minor Milestone - -The `2.2.0` release will be the next minor architectural cycle. It introduces structural enhancements designed to elevate real-time operational visibility, lower token consumption, scale multi-agent coordination, and eliminate runtime overhead. - -### 2.2.0 Workstreams & Themes - -1. **High-Density TUI Mission Control Cockpit (`Overview`, `Swarm`, `Flightdeck`)** - - Full specification: [TUI Mission Control Cockpit Design](docs/design/tui-mission-control-cockpit.md). - - Unified 3-page cockpit built on Ink (React for CLI), navigable via `Tab` / `1-3`: - - **Page 1 (`Overview`)**: Real-time token velocity histogram (Lead vs Subagent differentiation, context window utilization gauge, cache hit ratio, tokens/sec, and turn cost breakdown), live 5-server MCP health grid with latency and error highlighting, and box-drawing system topology work map. - - **Page 2 (`Swarm`)**: Hierarchical specialist delegation tree (`@zeus` → `@athena`, `@demeter`, `@hermes`, `@aphrodite`, `@themis`) with per-agent token burn, duration, and call count; concurrency Gantt timeline visualizing agent overlap; and semantic activity stream table with interactive detail expansion (`Enter`). - - **Page 3 (`Flightdeck`)**: Visual Gate Matrix tracking permission and safety checks (allowed, human-approved, pending approval, denied); active specialist progress gauges; turn-level delta telemetry; and unified semantically aggregated error log. - -2. **Step-Ledger Execution Mode** - - Execute complex workflows via atomic, single-step sub-sessions. - - Each sub-session opens strictly with the active step's summary, objective, ledger key, and completion contract. - - Gated progress: a step may transition to `done` only when a verification command exited 0 since the last file mutation. - - Eliminates cascading context buildup, targeting up to 40x context token savings on large tasks. - -3. **Dynamic Multi-Model & Fallback Routing (Jev)** - - Introduce provider-aware fallback policies in the Jev Decision Router. - - Dynamically route low-complexity or high-volume tasks across providers (Gemini, Claude, GPT) with automated retry on quota exhaustion (HTTP 429) or transient degradation. - - Integrated with the in-memory event bus (`PantheonBus`) for real-time observability of routing decisions and token spend. - -4. **Dynamic Capability Synthesizer & Role Morphing** - - On-the-fly ephemeral specialist generation based on task profile. - - Compiles ad-hoc bounded sub-specialists dynamically from the declarative roster base with tailored tool allowlists. - -5. **Deep Scope Governance & Sandboxing** - - Pre-flight validation of file-tree bounds, command allowlists, and tool grants *before* spawning a child subagent. - - Prevents execution aborts caused by late-discovered permission mismatches. - -6. **Mechanized Code Quality Doctrine** - - Enforce coding standards and anti-pattern detection through deterministic linters and test harnesses rather than advisory prompt instructions. - - Zero tolerance for verbal-only coaxing: every rule must fire a machine-verifiable gate. +## Transitioned to Delivered (`2.2.0`) + +100% of the workstreams chartered under `Road to 2.2.0` and the `2.3.0` evolution backlog are now shipped in **`v2.2.0`**: + +1. **Delivered — High-Density TUI Mission Control Cockpit (`/pantheon-cockpit` · `Overview`, `Swarm`, `Flightdeck`) + Flightdeck Visual Replay Export** + - Implemented natively using OpenCode's `@opentui/solid` UI engine (`1–3` / `Tab`, clickable Home `◈ Cockpit` link) with one-click / `x` **Flightdeck Replay Trace Export** writing Mermaid `sequenceDiagram` + Gantt reports into `.pantheon/reports/` for viewing in `/pantheon-artifacts`. + - Specification reference: [TUI Mission Control Cockpit Design](docs/design/tui-mission-control-cockpit.md). +2. **Delivered — Step-Ledger Execution Mode (`pantheon_step_ledger` + `runAtomicStepSubSession` + Git Checkpoints)** + - Enforces SHA-256 verification receipts, isolated `ctx.session.create` sub-sessions per atomic step, and temp-index git snapshots with automatic rollback on `themis:reflex:escalated`. +3. **Delivered — Multi-Provider Model Overrides, Jev Decision Router & Multi-IDE TCP LSP Proxy Pooling** + - `pantheon_local_decision` + `pantheon_model` + `PantheonBus` structured telemetry (`'lsp:diagnostics'`, `'review:verdict'`, `'step:rollback'`, `'reproduction:gate'`, `'themis:reflex:escalated'`). + - Post-edit diagnostics support `tsc --noEmit`, `pyright`, stdio LSP (`PANTHEON_LSP_SERVER`), and pooled TCP multi-IDE LSP sockets (`PANTHEON_LSP_TCP_ENDPOINTS`). +4. **Delivered — Persistent Multi-Repo Knowledge Federation & Polyglot Custom Specialist Forge** + - Read-only cross-repository FTS5 memory lookup (`PANTHEON_FEDERATED_REPOS` / `~/.pantheon/federation.json`) with provenance in `memory_search` and `memory_stats`. + - Stack auto-detection (`package.json`, `pyproject.toml`, `Cargo.toml`, `go.mod`) and least-privilege specialist scaffolding via `/pantheon-forge` and `pantheon_agent_forge`. +5. **Delivered — Deep Scope Governance & Reproduction Gates** + - Symlink-confined workspace path guards, role-based execution restrictions, pre-edit failing test gates (`record_reproduction`) for bugfixes, and `ctx.worktree.transform` sibling isolation. --- diff --git a/TEST-MATRIX-b8-b9.md b/TEST-MATRIX-b8-b9.md deleted file mode 100644 index 0d0bc1a8..00000000 --- a/TEST-MATRIX-b8-b9.md +++ /dev/null @@ -1,133 +0,0 @@ -# B8/B9 Verification Matrix - -Scope: verify the requested behaviors against the current checkout and record -reproducible checks. This is a test plan/evidence record only; no product code or -live provider was exercised. Isolated host/fixture-MCP evidence is labeled below. -Synthetic tokens/configuration only. - -## Status key - -- **PASS (offline)** — focused automated test or isolated temp-HOME check ran. -- **SOURCE / test gap** — behavior is described or wired in source, but this - checkout does not contain a focused assertion for it. -- **MANUAL — NOT RUN** — requires a real host/process observation; do not treat - this as verified evidence. -- **UNRESOLVED** — the requested exact procedure was not found in tracked - sources; no command sequence is invented. - -## Matrix - -| ID | Setup → action | Expected evidence | Traceability and verification | -|---|---|---|---| -| B8-1a | Feed synthetic high-confidence token-shaped text to the in-process scanner. | Exit code `2`, `[SECRET SCAN]`, block verdict, no raw token; long match uses `first4****last4`. | **PASS (offline):** `./node_modules/.bin/tsx tests/pantheon/v2-hook-engine.test.ts`. `tests/pantheon/v2-hook-engine.test.ts` (`testScanContract`, `testMasking`); implementation `src/pantheon/v2-hook-engine.ts` (`runSecretScanInProcess`, `maskSecretMatch`). | -| B8-1b | Feed a synthetic key-name/value shape that is low-confidence. | Exit code `1` with the advisory marker/message; not the high-confidence block result. | **PASS (offline):** same command as B8-1a. The test asserts code `1` and the “low confidence” marker. | -| B8-1c | Call the scan applicability classifier with read-only and unknown tool names; separately inspect the unexpected-error path. | Read-only tools skip; unknown/missing names remain scanned. Internal scan error is code `1` without the marker and the plugin classifier must fail closed. | **PASS for applicability:** same command as B8-1a checks `read`/`grep`/`glob` skip and unknown/missing names scan. **SOURCE / test gap for error classification:** `src/pantheon/v2-hook-engine.ts` catch path and `src/plugin-v2.ts` `evaluateSecretScanResult`; no focused forced-internal-error classifier assertion was found. | -| B8-1d | Observe a real tool call while checking child processes. | Secret scan is in-process; no bash child is created by the scan. | **MANUAL — NOT RUN:** source path is `runSecretScanInProcess` in `src/plugin-v2.ts`/`src/pantheon/v2-hook-engine.ts`; `ps` was not observed. A source read or unit test is not evidence that `ps` was empty. | -| B8-2a | Build start/stop delegation records with synthetic metadata and append to a temp state directory. | `delegations.log` has one JSON object per line; start/stop fields join on `delegation_id`; empty `task_id` is omitted and `duration_ms` is numeric or omitted when absent. | **PASS (offline):** `./node_modules/.bin/tsx tests/pantheon/v2-hook-engine.test.ts`. `testAuditLines` and `testAuditAppenderAndDir` assert fields and parse an appended line. **Caveat:** the test parses the JSON line; it does not assert byte-for-byte exact serialized text. Source serializes `JSON.stringify(line) + "\n"` in `src/pantheon/v2-hook-engine.ts`. | -| B8-2b | Observe a real delegation audit start/stop and check child processes. | Audit line creation/appending has zero child processes; this is separate from formatting. | **MANUAL — NOT RUN:** `src/pantheon/v2-shell-hooks.ts` default runner directly calls the in-process line builders/appender. No `ps` observation was run. Eligible formatting can still spawn a formatter; do not generalize this row to zero children for every tool call. | -| B8-2c | Exercise edit/write/hashline with supported and unsupported extensions, read/grep, and bash. | File-edit formatting is gated by recognized extension; non-file/read-only calls skip. `bash` remains conservatively eligible even without a file extension. | **PASS (offline predicate):** B8-1 command checks `formatterApplies` for `.ts`, `.py`, `.png`, read/grep, and bash. `docs/reference/performance.md` and `src/pantheon/v2-hook-engine.ts` document the same distinction. **Caveat:** “extension-gated” applies to file tools, not bash. | -| B8-3a | In a temporary HOME/XDG and project, run `init` with a Console decision-model target and explicit caps. | A single init invocation configures route, consent, user/provider/model caps, and period through `setup-model`; no provider request is made by installation. | **PASS (isolated temp-HOME subprocess probe):** arguments `init --project --components agents --no-mcp --yes --headless --opencode-version v2 --decision-model opencode-console-jev/jev-1.13 --decision-monthly-usd 5 --decision-per-decision-usd 0.10`; verified enabled route, consent, three cap scopes, and budget period in the temporary config/ledger. Existing focused test: `node --test tests/decision-router-cli.test.mjs` (11/11 pass). Sources: `bin/pantheon-init.mjs` around `readArgValue` and decision activation; `CHANGELOG.md` beta.8. | -| B8-3b | Repeat the isolated init with `--decision-no-consent`; inspect the temporary decision-router config and output. | Route/caps are configured, but `egress_consent` remains false. | **PASS (isolated temp-HOME subprocess probe):** consent was false. **Caveat found:** output also contains `Unknown option ignored: --decision-no-consent`; the parser allowlist in `bin/pantheon-init.mjs` omits this flag even though the later activation path reads it. Underlying `setup-model --no-consent` is covered by `node --test tests/decision-router-cli.test.mjs` (11/11 pass). | -| B8-3c | Run temp-project `init --dry-run --decision-model typesafe-jev/jev-1.14.0`; inspect output and user config. | No files/config are written. Whether Jev intent must also appear in the preview is unspecified in the handoff. | **PASS for generic dry-run/no writes; caveat for Jev preview:** isolated temp-HOME subprocess left the OpenCode config unchanged, but emitted no decision-model intent. `bin/pantheon-init.mjs` returns from the dry-run branch before the optional Jev activation block (around lines 912–953 versus 1030+). `node --test tests/install-preview-apply.test.mjs` (27/27 pass) covers generic dry-run, not the Jev flag. | -| B8-3d | In a temporary OpenCode config, select TypeSafe through init with an existing unrelated provider/model entry. Also consider a non-JSON config as a separate negative case. | Add `providers.typesafe-ai.models.jev-1.14.0` with `type: "decision"`, preserve existing keys; do not overwrite a non-JSON config. | **PASS for additive JSON merge:** isolated temp-HOME init probe preserved the synthetic existing provider and added the decision model. **SOURCE / test gap for non-JSON case:** `provisionTypesafeProvider` in `bin/pantheon-init.mjs` returns a reason without overwriting; no focused test for that helper was found. No credentials/sign-in/provider call used. | -| B8-4a | Run the interactive prompt contract with the fake prompt adapter. | Choices are exactly Skip, Console Jev, Console free variant, and TypeSafe direct; skip is the initial choice and wizard route caps are explicit. | **PASS (offline):** `node --test tests/install-interactive-prompts.test.mjs` (18/18 pass). `tests/install-interactive-prompts.test.mjs` checks the exact choice values and the three route targets/default caps. | -| B8-4b | Pass legacy spellings (`jev`, `openai-decisions`, `auto`, `local`) through the fake wizard selection. | They degrade to skip/no activation; they do not silently become a native route. | **PASS (offline):** same command as B8-4a; test `choosing a Jev route activates it with explicit caps; unknown legacy values degrade to skip`. | -| B8-4c | Run install truthfulness checks in temporary project/config directories, default and verbose. | Capability notice absent by default and printed once when verbose. | **PASS (offline):** `node --test tests/install-truthfulness.test.mjs` (31/31 pass). Relevant test: `a V2 install keeps the capability block quiet by default and prints it once under --verbose`. | -| B9-1a | Under the real OpenCode host, configure a deny on the measured `shell` action and issue the canary’s twin permission assertions for `shell` then `bash`. | Record both outcomes as `shell → deny/reject | bash → allow` for the historical unruled twin; separately prove the denied command has no side effect. | **MANUAL — NOT RUN in this task.** The beta.9 changelog records the measured host behavior (`CHANGELOG.md` lines 21–22); twin probe is in `tests/canary/plugin-v2-tool-canary.test.mjs`; isolated host runner is `bash tests/canary/run-v2-permission-proof.sh`. This matrix does not claim a fresh host observation. | -| B9-1b | Run the existing all-agent/frontmatter test, then inspect terminal permission fields on all canonical agent files. | Exactly 14 canonical agents; each has a `permission.shell` entry and each `shell: deny` also has `bash: deny`. | **PASS:** `node --test tests/pantheon/delegation-matrix.test.mjs` (64/64 pass) checks the 14 canonical files/frontmatter validity, but not these shell keys. A separate read-only source audit in this task found 14 files, no missing `shell`, and no deny without a bash twin. | -| B9-2 | Ask Zeus to perform a terminal action and inspect the instruction boundary. | Zeus must delegate terminal work; it must not tell the user to type/run terminal commands. | **SOURCE / behavior test gap:** `src/agents/zeus.md` says not to ask the user for terminal commands (around line 102). No automated behavioral/model assertion was found; no live prompt was run. | -| B9-3 | Run the isolated host permission proof with a managed deny and verify attempted command side effects. | A real host permission rejection blocks execution, rather than merely recording a deny. | **MANUAL — NOT RUN:** `bash tests/canary/run-v2-permission-proof.sh` is the available opt-in proof; it requires the configured OpenCode binary and `bwrap`. Source: `tests/canary/run-v2-permission-proof.sh`, `tests/canary/plugin-v2-tool-canary.test.mjs`. | -| B9-4 | Exercise decision-router doctor in an isolated config where no host binary/catalog is available. | Doctor reports config/consent/selection/budget independently and degrades the unavailable catalog probe to a warning with a fix hint; it remains read-only. | **PASS (offline):** `node --test tests/decision-router-cli.test.mjs` (11/11 pass), test `doctor diagnoses the chain read-only and degrades when the host probe fails`. This is not a real host catalog probe. | -| B9-5 | Reproduce the requested “stray hosts”, webhooks, and catalog-without-Jev regression sequence. | Use the exact intended ordered commands, preserve the known caveats, and route an unavailable/missing Jev catalog to `decision-router doctor`. | **UNRESOLVED:** no tracked test/doc defines the exact regression sequence for stray hosts or webhooks; no commands are invented here. The repository does define `npx pantheon-opencode decision-router doctor` and its offline no-host test above. A real `doctor`/catalog check is manual and was not run. Zeus must supply the intended sequence before this row can be marked complete. | - -## Focused checks run for this matrix - -All ran without live provider/MCP calls: - -```sh -./node_modules/.bin/tsx tests/pantheon/v2-hook-engine.test.ts -./node_modules/.bin/tsx tests/pantheon/v2-shell-hooks.test.ts -node --test tests/install-interactive-prompts.test.mjs -node --test tests/decision-router-cli.test.mjs -node --test tests/install-truthfulness.test.mjs -node --test tests/install-preview-apply.test.mjs -node --test tests/pantheon/delegation-matrix.test.mjs -npm run docs:lint -python3 - <<'PY' -from pathlib import Path -import re -files = sorted(Path('src/agents').glob('*.md')) -missing, missing_twin, bash_only_deny = [], [], [] -for path in files: - text = path.read_text() - fm = re.search(r'\A---\n(.*?)\n---', text, re.S) - permission = re.search(r'^permission:\n(.*?)(?=^[^ \n][^\n]*:|\Z)', fm.group(1), re.M | re.S) - body = permission.group(1) if permission else '' - if not re.search(r'^ shell:', body, re.M): missing.append(path.name) - if (re.search(r'^ shell:\s*deny\s*$', body, re.M) - and not re.search(r'^ bash:\s*deny\s*$', body, re.M)): - missing_twin.append(path.name) - if (re.search(r'^ bash:\s*deny\s*$', body, re.M) - and not re.search(r'^ shell:\s*deny\s*$', body, re.M)): - bash_only_deny.append(path.name) -print(f'agents={len(files)} missing_shell={missing} deny_without_bash_twin={missing_twin} bash_only_deny={bash_only_deny}') -PY -``` - -Each listed check passed; the one-off field audit printed -`agents=14 missing_shell=[] deny_without_bash_twin=[] bash_only_deny=[]`. The isolated init probe -used temporary HOME/XDG/project roots and was removed afterward. Initial probe -iterations had harness-only errors (relative CLI path after `cwd` change; an -incorrect expectation for the status caps display); corrected probes passed. -The temporary probes found the two B8 caveats recorded above: the init -no-consent flag is reported as unknown, and decision-model intent is omitted -from dry-run output. - -## Host-side integration boundary - -There is a supported **host-plugin boundary**, not a standalone site API: - -- Native Jev uses the host plugin context’s - `ctx.experimental.generate.decisions({ model, input, questions })`; the native - route is documented as available from OpenCode 2.2.0 and feature-detected in - `src/plugin-v2.ts`. Host-installed skills are read through `ctx.skill.list()`. - See `docs/reference/native-decisions.md`, `src/plugin-v2.ts` around lines - 695–720, and `src/pantheon/jev-decision-tool.ts`. -- MCP servers are configured in the host’s project/user OpenCode config under - `mcp`; the host launches local stdio servers as separate OS processes. See - `docs/MCP.md` and `docs/opencode-v2.md`. A local fixture MCP is therefore - possible without changing production behavior, provided the test host and - config are isolated. -- Existing host-backed precedent: `tests/canary/plugin-v2-tool-canary.test.mjs` - creates a temporary project/plugin and isolates HOME/XDG; it mocks only a local - model endpoint. `tests/canary/run-v2-mcp-gating-proof.sh` uses bwrap with a - private HOME and network namespace, allowing only local stdio MCP. - -The planned pickleball browser site was superseded by the approved host-loaded, -test-only harness now in `dev/tests/`. It runs as an isolated OpenCode project/plugin -under a real host to obtain `ctx`; no browser UI or browser-facing API is claimed. -The harness verifies local fixture behavior, but does **not** prove a live Jev -Decisions call or MCP resource-content read. Such calls remain opt-in/manual and -were not made here. - -## Pickleball development harness addendum - -Verified harness commands and evidence labels (the B9-5 row above remains -**UNRESOLVED**): - -- `node --test dev/tests/harness.test.mjs` — **PASS (stub/offline)**, 5/5. The - typed-decision stub and direct MCP fixture checks are not host evidence. -- `PICKLEBALL_OPENCODE_BIN=/home/ils15/.opencode/bin/opencode bash dev/tests/run-host-runtime.sh` - — **PASS (host)** on OpenCode `v2.2.5`, in bubblewrap's isolated network - namespace, using a synthetic local model and fixture MCP. The host used the - actual skill registry (`ctx.skill.transform` / `ctx.skill.list`) and listed the - fixture through the MCP catalog (`resources/list` and `resources/templates/list`). - MCP resource content was **not read**; no content read is claimed. A live Jev - Decisions call was **not invoked** (`decisions.capability` was available but - `invoked: false`). No external/provider egress was available. -- `node dev/tests/live-jev.mjs --help` — safe usage display only. The separate - interactive `--live-jev` path was **NOT RUN**; no live Jev/provider operation - occurred. - -See `dev/tests/README.md` for isolation controls, exact labels, limitations, and -the explicit live-command disclosure. diff --git a/bin/pantheon-init.mjs b/bin/pantheon-init.mjs index 9d351066..a44861de 100755 --- a/bin/pantheon-init.mjs +++ b/bin/pantheon-init.mjs @@ -76,10 +76,10 @@ function formatUsdCapForRepair(value) { function printUsage() { console.log('Pantheon OpenCode — Multi-agent orchestration platform') console.log('') - console.log('Recommended (OpenCode 2.2+ native plugin, global or project — no npx init needed):') - console.log(' opencode plugin add pantheon-opencode@beta') + console.log('Recommended (OpenCode 2.x native plugin, works in any directory — no init needed):') + console.log(' opencode plugin add pantheon-opencode') console.log('') - console.log('Deprecated CLI installer (legacy fallback — will be retired in future releases):') + console.log('Optional CLI installer (legacy fallback or project AGENTS.md / custom MCP setup):') console.log(' npx pantheon-opencode init # Install globally (legacy)') console.log(' npx pantheon-opencode init --project # Install in project (legacy)') console.log(' npx pantheon-opencode init --dry-run # Preview only') @@ -1052,6 +1052,24 @@ async function main() { if (!isProject) { // The project-local hint only matters when this install was not one. console.log(` ${S.nextProject}`) + } else { + try { + const { detectRepositoryStacks } = await import('../scripts/stack-detector.mjs') + const stackReport = detectRepositoryStacks(targetDir) + if (stackReport.stacks.length > 0) { + console.log('') + console.log( + ` Detected stack(s): ${stackReport.stacks.map((s) => `${s.id} (${s.manifest})`).join(', ')}`, + ) + if (stackReport.suggestedSpecialists.length > 0) { + console.log( + ` Tip: run /pantheon-forge in OpenCode to scaffold: ${stackReport.suggestedSpecialists.map((s) => s.name).join(', ')}`, + ) + } + } + } catch { + /* best-effort stack hint */ + } } if (!decisionTarget) { console.log(` ${S.nextJev}`) diff --git a/commands/pantheon-forge.md b/commands/pantheon-forge.md new file mode 100644 index 00000000..d443d264 --- /dev/null +++ b/commands/pantheon-forge.md @@ -0,0 +1,12 @@ +--- +description: "Interactive specialist forge wizard: auto-detect project stack and scaffold tailored specialists" +agent: zeus +--- + +Run the interactive Pantheon Agent Forge wizard for the current workspace: + +1. Call `pantheon_agent_forge(action="detect_stack")` and `pantheon_agent_forge(action="list")` to inspect detected project manifests (`package.json`, `pyproject.toml`, `Cargo.toml`, `go.mod`), suggested specialists, and existing `.opencode/agents/*.md` files. +2. Use the native `question` tool to ask the user which recommended specialist (or custom domain) they want to scaffold, keeping defaults marked `(Recomendado)`. +3. Upon user confirmation, call `pantheon_agent_forge(action="create", ...)` and summarize the created `.opencode/agents/.md` path and test command. + +$ARGUMENTS diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 92e77040..7b1c60fa 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -92,31 +92,31 @@ control. The matrix itself is documented in There is a single generation: 2.0 removed the V1 plugin line, and the surface below is the only one. -The plugin is registered under the plural `plugins` key as the -`/src/plugin` directory. `src/plugin/index.ts` re-exports the real -entry at `src/plugin.ts`; the tool-hook registration in `src/plugin.ts` is fed -by the tool definitions in `src/pantheon/tools.ts`. - -Four unconditional tools: - -- `hashline_edit` — `src/pantheon/tools.ts` -- `pantheon_cost` — `src/pantheon/tools.ts` -- `pantheon_model` — `src/pantheon/tools.ts` -- `pantheon_local_decision` — `src/pantheon/tools.ts`. The advisory local - selector; it rejects execution unless the host tool context identifies the - caller as Zeus. - -Up to two host-dependent tools: - -- `vision_describe` — added only when `ctx.model.list` is a function - (`src/plugin.ts`; definition at `src/pantheon/native-vision.ts`). -- `pantheon_bounded_read` — added only when the `tool.execute.before` hook - registered and the host exposes the permission and session APIs - (`src/plugin.ts`; definition at `src/pantheon/bounded-read.ts`). Root Zeus - sessions only. - -The three goal tools are absent because the goal loop needs infrastructure the -host's `PluginContext` does not expose. The gap is reported as `goal-tools`. +The plugin is registered under the plural `plugins` key (via +`opencode plugin add pantheon-opencode` or `/src/plugin`). +`src/plugin/index.js` is the bundled entrypoint built from `src/plugin.ts`; the +tool-hook registration in `src/plugin.ts` is fed by the native tool definitions +in `src/pantheon/tools.ts` and sibling TypeScript modules (**26 native tools** +in total): + +- **Core editing, cost, model & routing:** `hashline_edit`, `pantheon_cost`, + `pantheon_model`, `pantheon_local_decision` (Zeus-only advisory selector), + and `shell`. +- **FTS5 memory, checkpoints & goals (`native-memory-tools.ts`, shared across + linked git worktrees):** `memory_store`, `memory_recall`, `memory_search`, + `memory_forget`, `memory_stats`, `context_save`, `context_get`, + `goal_create`, `goal_get`, `goal_update`, and `goal_done`. +- **Structural codemap, Step-Ledger & orchestration:** `code_index`, + `code_query`, `code_neighbors` (with automatic orphan pruning), + `pantheon_step_ledger`, `pantheon_deepwork`, `pantheon_agent_forge`, and + `pantheon_skill_search`. +- **Host-dependent tools:** + - `vision_describe` — added when `ctx.model.list` is exposed (`src/pantheon/native-vision.ts`). + - `pantheon_bounded_read` — added when `tool.execute.before` and host + permission/session APIs are exposed (`src/pantheon/bounded-read.ts`; root + Zeus sessions only). + - Native `todowrite`/`todoread` are preserved from the host whenever already + registered so OpenCode's native Todo panel stays authoritative. The plugin also wires five event subscriptions (`session.created`, `session.idle`, `session.deleted`, `session.error`, `session.compacted`), diff --git a/docs/ARTIFACTS.md b/docs/ARTIFACTS.md new file mode 100644 index 00000000..ecaf76dc --- /dev/null +++ b/docs/ARTIFACTS.md @@ -0,0 +1,75 @@ +# Artifacts & `/pantheon-artifacts` Viewer + +> 🇧🇷 **Versão em Português disponível:** [Leia em Português](pt-BR/ARTIFACTS.md) + +Pantheon stores structured engineering plans, investigation/audit reports, and +Architecture Decision Records (ADRs) as high-density Markdown files inside your +repository, keeping the project root clean and making every decision reviewable +in both **OpenCode CLI (TUI)** and **OpenCode Desktop**. + +--- + +## 1. Where Artifacts Live & Who Creates Them + +| Type | Location | Produced By | Lifecycle | +|---|---|---|---| +| **Plans (`PLAN`)** | `.pantheon/deepwork//PLAN.md` | `@athena` / `/pantheon-deepwork` | Durable per task/sprint (gitignored) | +| **Reports (`REPORT`)** | `.pantheon/reports/-.md` | `@apollo` / `@themis` | Audit & discovery trail | +| **ADRs (`ADR`)** | `docs/adr/-.md` (and `.pantheon/memory-bank/adr/*.md`) | `@mnemosyne` | Permanent architecture decisions | + +> [!TIP] +> Linked git worktrees resolve back to the main repository automatically, so +> `/pantheon-artifacts` inside a task worktree still sees the repository's plans, +> reports, and ADRs. + +--- + +## 2. Viewing Artifacts in OpenCode CLI (`/pantheon-artifacts`) + +Inside any OpenCode terminal session, run `/pantheon-artifacts` (alias +`/artifacts`, or **Pantheon: Artifacts** in the `Ctrl+P` command palette) — or +simply click the **`▸ Plan: ...`** / **`◈ Artefatos (N)`** links directly in +the **Sidebar** or **Home footer** whenever artifacts exist in the workspace: + +![Artifacts list dialog in OpenCode TUI](assets/tui/artifacts-list.png) + +### Selecting and Reading + +- Press `↑` / `↓` (`k` / `j`) or click a row to select an artifact, then press + `Enter` (or click **Abrir / Open**) to open it in the paginated reader. +- If the workspace currently has a single artifact, `/pantheon-artifacts` opens + it directly in reader mode. + +![Paginated artifact reader in OpenCode TUI](assets/tui/artifacts-reader.png) + +### Keyboard & Mouse Controls + +| Context | Key / Action | Effect | +|---|---|---| +| List view | `↑` / `k`, `↓` / `j`, mouse click | Select artifact | +| List view | `Enter` / `Space` / second click | Open selected artifact | +| Reader view | `n` / `→` / click `Próxima ›` | Next page | +| Reader view | `p` / `←` / click `‹ Anterior` | Previous page | +| Reader view | `b` / `Backspace` / click `‹ Lista` | Return to artifact list | +| Any view | `Esc` / `q` / click `[ Esc / Q ]` | Close dialog | + +The reader automatically formats GFM alerts (`[NOTE]`, `[TIP]`, `[IMPORTANT]`, +`[WARNING]`, `[CAUTION]`), renders Mermaid diagrams (`flowchart`, `graph`, +`sequenceDiagram`, `stateDiagram`) as Unicode box-and-arrow graphs, simplifies +`file://` line anchors, and wraps headings/bullets so large plans never overflow +the terminal. + +--- + +## 3. Viewing Artifacts in OpenCode Desktop + +OpenCode Desktop renders GitHub-Flavored Markdown inline: + +- **Clickable file links:** links written as + `[auth.ts](file:///abs/path/to/src/auth.ts#L1-L40)` jump directly to the + referenced file and line range. +- **GFM Alerts & Mermaid diagrams:** `> [!NOTE]`, `> [!IMPORTANT]`, comparison + tables, and quoted Mermaid blocks render natively in the Desktop UI. +- **Clean chat handoffs:** agents persist the full specification in the artifact + file and post only a concise executive summary plus the approval prompt in chat + instead of repeating the entire document. diff --git a/docs/COMPATIBILITY.md b/docs/COMPATIBILITY.md index a254d313..54bf91bf 100644 --- a/docs/COMPATIBILITY.md +++ b/docs/COMPATIBILITY.md @@ -140,14 +140,13 @@ to the client instead (`permission.asked`, `GET /permission`, then ## The OpenCode 2 path -The 2.x path is the only path: it registers tools with `input`/`output` -schemas, event subscriptions, session hooks, a read-only-enforcing -`execute.before` hook (which also denies the orchestrator `read`/`glob`/`grep` -of source, tests and scripts), and — when the host exposes it — a -`permission.evaluate` delegation-matrix hook. It is not full V1 feature parity: -the three goal tools remain unsupported and are reported as `goal-tools`, as are -the host-domain gaps the seed names (`idle-todo-enforcer`, `tool-ceiling`, -`todo-restore`, `board-transitions`). See +The 2.x path is the only path: it registers **26 native TypeScript tools** +(including `memory_*`, `context_*`, `goal_*`, `code_*`, `pantheon_step_ledger`, +`pantheon_agent_forge`, `hashline_edit`, `pantheon_cost`, `pantheon_model`, and +`pantheon_local_decision`), event subscriptions, session hooks, a +read-only-enforcing `execute.before` hook (which also denies the orchestrator +`read`/`glob`/`grep` of source, tests and scripts), and — when the host exposes +it — `permission.evaluate` delegation-matrix enforcement. See [Architecture](ARCHITECTURE.md) for the contract and [OpenCode 2.x](opencode.md) for user-facing behavior. @@ -165,6 +164,7 @@ supported; it is simply unmeasured. | `2.1.0` | 2.x | `bench/results/p05-permission-matrix-2026-10-22.md` | | `2.1.2` | 2.x | `bench/results/p05-permission-matrix-2026-10-22.md`; `docs/internal/validation.md` | | `2.1.3` | 2.x | `bench/results/p05-permission-matrix-2026-10-22.md` | +| `2.3.2` | 2.x | E2E sandbox verification for `v2.2.0` (`memory_*`, `goal_*`, `code_*`, `hashline_edit`, `step_ledger`, `worktrees`, TUI `Dispatch` & `Todo`) | The table above is a measurement record, not a release checklist. A new 2.x minor is supported on release day; measuring it is optional evidence work. diff --git a/docs/INSTALLATION.md b/docs/INSTALLATION.md index fb211bd1..79cf5382 100644 --- a/docs/INSTALLATION.md +++ b/docs/INSTALLATION.md @@ -1,49 +1,52 @@ -# Pantheon Installation Guide — 2.0 (OpenCode 2.x) +# Pantheon Installation Guide — OpenCode 2.x > 🇧🇷 **Versão em Português disponível:** [Leia em Português](pt-BR/INSTALLATION.md) -Pantheon 2.0 **requires OpenCode 2.x** — the OpenCode V1 contract was removed -entirely (1.7.x was the last line with V1 support). There are two complementary -ways to install. Loading the plugin through the host's native flow is the -recommended path; `npx pantheon-opencode init` remains the installer for the -full component set. `pantheon_model` offers only manual `status`, `show`, -`set`, and `reset`, with no preset wizard: the host default stays intact -without an explicit per-agent override, and preset markers and -`PANTHEON_MODEL_PRESET` are ignored and preserved. Without an override, -delegates inherit the parent chat model natively. +Pantheon 2.2 **requires OpenCode 2.x** (the OpenCode V1 contract was removed +entirely; 1.7.x was the last line with V1 support). + +**Best-practice install (`opencode plugin add`):** loading Pantheon directly +through OpenCode's native plugin manager registers all **14 agents, 25 skills, +9 slash commands, 30 native TypeScript tools, and TUI** in-process with zero +copied files on disk — so it works immediately in **any directory** (git repos, +worktrees, or empty folders) and upgrades cleanly without leaving stale copied +assets behind. + +`npx pantheon-opencode init` remains available when you specifically want +file-based `.opencode/` artifacts, `AGENTS.md` injection, or optional legacy +Python MCPs. If migrating from an older `init` install, open +`/pantheon-settings` → **Updates** (**Legacy & Drift Cleanup**) to remove +redundant copied files and stale plugin caches safely. ## TL;DR (Quick Start) ```bash -# Recommended: load the plugin through the host (npm package; a git URL works too) +# Recommended: native OpenCode 2.x plugin (zero copied clutter, works anywhere) opencode plugin add pantheon-opencode -# Full component set: agents, skills, instructions, commands, plugins (+ MCP/TUI) -npx pantheon-opencode init +# Upgrade later (also available interactively inside /pantheon-settings -> Updates) +opencode plugin update pantheon-opencode -# Headless preview; add --yes to authorize applying the same defaults -npx pantheon-opencode init --headless +# Optional CLI installer: explicit file-based install / project AGENTS.md / MCP +npx pantheon-opencode init --project --no-mcp npx pantheon-opencode init --headless --yes -# Separate repository wrapper: config migration review + installer preflight -npm run setup +# Verify installation & clean stale/legacy artifacts +npx pantheon-opencode doctor +node scripts/prune.mjs # preview stale backups/caches/worktrees -# Verify installation -npm run doctor - -# Development & Testing Prerequisites: -# Run `npm install` first! Unit and contract test suites (`npm run test:quick`, -# `npm run test:node`, `npm run test:ts`) require devDependencies (tsx, biome, -# esbuild) to avoid silent UNMET DEPENDENCY failures. +# Development & Testing Prerequisites (repo checkout only): npm install - -# Optional: activate the Jev decision model in the same pass -npx pantheon-opencode init --decision-model opencode-console-jev/jev-1.13 --decision-monthly-usd 5 --decision-per-decision-usd 0.10 +npm run setup # config migration review + installer preflight ``` -- **Requirements:** a supported host — **OpenCode 2.x** (Pantheon 2.0 does not - support an OpenCode 1.x host) — plus **Node.js >=26.4.0** for Pantheon's - CLI/installer/Node tooling and **Python 3.11+** (optional, MCP servers). +- **Requirements:** a supported host — **OpenCode 2.x** (Pantheon 2.x does not + support OpenCode 1.x) — plus **Node.js >=26.4.0** for Pantheon's + CLI/installer/tooling and **Python 3.11+** (optional, legacy Python MCPs only; + the 26 native TypeScript tools require Node.js only). +- **Per-agent model behavior:** `pantheon_model` provides manual `status`, + `show`, `set`, and `reset` overrides; without an explicit override, delegates + natively inherit the parent chat model. - **Known broken:** OpenCode 2.0.22 does not expose `ctx.permission.assert`. Node 22, Node 24, and Node 26.0–26.3 are outside the supported range. - **The host-native plugin flow.** `opencode plugin add ` records the plugin under the plural `plugins` key as an object entry diff --git a/docs/PLATFORMS.md b/docs/PLATFORMS.md index 0b6e21b9..5d84144b 100644 --- a/docs/PLATFORMS.md +++ b/docs/PLATFORMS.md @@ -8,71 +8,67 @@ and links out. It does not restate the support matrix — that is ## Form factors -OpenCode ships as a terminal TUI, a desktop app, and an IDE extension. Pantheon's -agents, skills, and instructions are discovered from the project directory the -same way in each. The desktop app adds integrated diffs, file-tree browsing, and -native notifications; it is not a separate installation model. +OpenCode ships as a terminal TUI (`opencode`), a desktop app, and an IDE +extension. All three share the same `opencode.json` (`plugins: ["pantheon-opencode"]`): + +- **CLI (TUI) & Desktop App (Shared backend `./server`):** all 14 agents, 25 + skills, 8 slash commands, 26 native TypeScript tools, security/edit guardrails, + worktree shared `.pantheon/` stores, and GFM/Mermaid artifacts work in both. +- **CLI-only (`./tui`):** the `@opentui/solid` sidebar (`Context`, `Todo`, + `Dispatch`), `/dispatch`, `/pantheon-settings`, `/pantheon-updates`, and + `/pantheon-whats-new` run in the terminal TUI only; Desktop uses its own native + GUI chrome (and renders Markdown/GFM artifacts inline). +- **Windows:** WSL2 (Linux) is the fully supported environment today; native + `win32` outside WSL2 currently rejects POSIX `getuid`/`0o077` config guards in + `pantheon_model` / `pantheon_local_decision` and assumes `/bin/bash` in `shell`. ## Install -Use the installer, not manual copying: +Use OpenCode's native plugin manager (recommended — zero copied files on disk, +works in any directory) or the optional CLI installer: ```bash -npx pantheon-opencode init # global -npx pantheon-opencode init --project # project-local +# Recommended (global or project, works anywhere without init) +opencode plugin add pantheon-opencode + +# Optional CLI installer (materializes .opencode/ files, AGENTS.md, or legacy MCPs) +npx pantheon-opencode init --project --no-mcp ``` -The installer registers Pantheon's runtime integrations automatically. It -writes the singular `plugin` key for OpenCode V1 and the plural `plugins` key -for OpenCode V2; do not add either key by hand. Flags, backup, uninstall, and -reconcile are in [Installation](INSTALLATION.md). +Flags, backup, uninstall, and reconcile are in [Installation](INSTALLATION.md). ## Configuration -OpenCode reads `opencode.json` (or `opencode.jsonc`) from the project root. The -installer writes `opencode.json`; a V2 host may also merge a sibling -`.jsonc` — see -[Compatibility](COMPATIBILITY.md#config-registration-and-the-hosts-config-merge). +OpenCode reads `opencode.json` (or `opencode.jsonc`) from the global config +directory (`~/.config/opencode/`) or project root. -`default_agent: zeus` and `permission.skill` are seeded by the installer, not -shipped as a template file. The published package carries no `opencode.json` -template. Contributors who keep a project-level config for their own sessions -should leave it untracked. +`default_agent: zeus` and `permission.skill` are seeded automatically in-process +by the plugin (or materialized when running `init`). Contributors who keep a +project-level `opencode.json` for their own sessions should leave it untracked. -Agent definitions live in `src/agents/*.md`; the installer copies them into the -selected config tree. Editing an installed copy does not persist — the next -`init` overwrites it. Edit the canonical source instead. +Agent definitions live in `src/agents/*.md` (loaded natively by the plugin); do +not maintain duplicate manual copies under `.opencode/agents/` unless you +intentionally override an agent locally. ## File locations -Project install: +Runtime state created on demand in any project or linked worktree (main repo +`.pantheon/` is shared automatically across git worktrees): ```text your-project/ -├── opencode.json -├── AGENTS.md -├── .opencode/agents/ -├── .opencode/skills/ -├── .opencode/instructions/ -├── .opencode/prompts/ └── .pantheon/ + ├── memory/memory.db # FTS5 memory, checkpoints & goals + ├── codemap/codemap.db # structural symbol & relation index + ├── ledger/step-ledger.json + ├── deepwork//PLAN.md + └── reports/ ``` -Global install: - -```text -~/.config/opencode/ -├── opencode.json -├── AGENTS.md -├── agents/ -├── skills/ -├── instructions/ -├── scripts/ # installed MCP entrypoints -└── tui.json # V1 TUI registration -``` - -The V2 TUI uses a local plugin directory instead of `tui.json`. See -[OpenCode 2.x](opencode.md). +With the recommended `opencode plugin add pantheon-opencode` install, agents, +skills, commands, and the TUI bundle are loaded directly from OpenCode's npm +plugin cache—no redundant copies in `~/.config/opencode/agents/` or +`plugins/pantheon-tui/` are needed. See [OpenCode 2.x](opencode.md). ## Quick reference diff --git a/docs/QUICKSTART.md b/docs/QUICKSTART.md index d73a5509..0b3796d4 100644 --- a/docs/QUICKSTART.md +++ b/docs/QUICKSTART.md @@ -11,60 +11,45 @@ This guide takes you from zero to your first working result with **Pantheon** in Ensure your environment satisfies the following requirements: 1. **OpenCode:** Version 2.x installed (native OpenCode 2.x host support). -2. **Node.js:** Version `>=26.4.0` (required for Pantheon's CLI, packager, and TUI interface). -3. **Python (Optional):** Version `3.11+` (only needed if using Python-based bundled MCP servers). +2. **Node.js:** Version `>=26.4.0` (required for Pantheon's tooling and TUI). +3. **Python (Optional / Legacy):** Version `3.11+` only if you opt into legacy Python MCP servers (all 26 core Pantheon tools run natively in TypeScript/Node). --- ## 1. Installation -Pantheon is installed and configured using the native CLI installer: +### Native OpenCode Plugin Install (Recommended — Works Anywhere) -### Full Installation via CLI (Recommended) - -Installs all 14 specialized agents, 25 skills, context instructions (TDD, YAGNI), slash commands, bundled MCP servers, and the modern TUI: +One command registers the 14 agents, 25 skills, 8 slash commands, 26 native TypeScript tools, and TUI in-process with zero copied files on disk: ```bash -# Global Installation (recommended — available across all your repositories) -npx pantheon-opencode init - -# Or Project-Scoped Installation (restricted to the current directory) -npx pantheon-opencode init --project +opencode plugin add pantheon-opencode ``` -> **Automation / CI Tip:** Run `npx pantheon-opencode init -y` to apply default settings non-interactively without prompting. +Why this is the best practice: +- Works in **any directory** immediately (existing repos, git worktrees, or new folders) with no `init` step. +- Updates cleanly via `opencode plugin update pantheon-opencode` (or `/pantheon-updates`) without leaving stale copied `.opencode/agents/` or `plugins/pantheon-tui/` files behind. -### OpenCode Plugin Registration +### Optional CLI Setup (`init`) -If you already use OpenCode's plugin manager or want to load the plugin via `opencode.json`, ensure the plugin entry is registered: +Use the CLI installer only when you specifically want project `AGENTS.md` injection, isolated `.opencode/` overrides, or optional legacy Python MCPs: -```json -{ - "plugins": [ - "pantheon-opencode" - ] -} +```bash +npx pantheon-opencode init --project --no-mcp ``` -> [!NOTE] -> `npx pantheon-opencode init` automatically configures `opencode.json` with the required plugin entry, agents, skills, and MCP servers. - --- -## 2. Validate Installation with `doctor` +## 2. Validate Health & Clean Stale Caches + +Inside OpenCode, run `/pantheon-settings` (or `/pantheon-updates`) to inspect **Doctor** health checks and **Legacy & Drift Cleanup** (which scans and removes stale coexisting `@beta`/older plugin caches and redundant copied files). -Before starting work, run Pantheon's health diagnostic: +From the terminal, you can also run: ```bash npx pantheon-opencode doctor ``` -The `doctor` command verifies: -- Connection and health of all bundled MCP servers (`pantheon_resources`, `pantheon_memory`, `pantheon_persistence`, `pantheon_vision`, `pantheon_cost`). -- Proper plugin registration in `opencode.json`. -- Synchronization of agents, skills, and instruction files. -- Local runtime Python and dependencies. - A healthy installation outputs a **PASS** verdict with zero blocking errors. --- @@ -83,8 +68,9 @@ opencode > ``` ### What you will see: -- **Rich Sidebar (TUI):** Displays the active Pantheon version (v2.1.1), the active model preset, Git repository state, and a live **Context** block with token counts, estimated cost, and cache speed. -- **Native Multimodal Vision (Pantheon Vision):** If you capture a screenshot and paste it directly into chat (`Ctrl+V` / `Cmd+V`), Pantheon analyzes the image silently via system context without cluttering the chat with comments or HTML markup. +- **Rich Sidebar (TUI):** Displays the active Pantheon version (`v2.2.0`), active model preset, Git repository state, **Context** with native-tool domain counters (`mem`, `ctx`, `code`, `edit`, `shell`), **Todo**, and **Dispatch** with live child activity verbs and `?`/`!` attention badges. +- **Interactive Update & What's New Dialogs:** Upgrading opens a dismissable **What's New** dialog (`/pantheon-whats-new` to reopen anytime), and clickable `↑ vX.Y.Z` badges jump straight to `/pantheon-updates`. +- **Native Multimodal Vision (Pantheon Vision):** Paste a screenshot (`Ctrl+V` / `Cmd+V`) or call `vision_describe` when exposed by the host model catalog. --- diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 04dc756e..5591e8f3 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -182,8 +182,13 @@ workflow-owned (see below). ## Release Notes -Release notes live in the version's `CHANGELOG.md` section and that section — -verbatim — **is** the GitHub Release body. The canonical format is the hybrid: +Release notes live in the version's `CHANGELOG.md` section and serve as the +canonical GitHub Release body. For **stable** non-recovery releases, when an +optional curated release document exists at `docs/releases/v.md`, +`scripts/release-body.mjs` composes that visual release page (rewriting +relative image/doc links to immutable tag URLs) followed by the verbatim +`CHANGELOG.md` section inside a collapsible ledger. Both formats require a +valid canonical `CHANGELOG.md` section: curated `### 🆕 What's New` highlights on top, Keep a Changelog subsections below, in fixed order, in **English**: diff --git a/docs/SETTINGS.md b/docs/SETTINGS.md index e0312a1d..f3bc9aab 100644 --- a/docs/SETTINGS.md +++ b/docs/SETTINGS.md @@ -1,27 +1,122 @@ -# Settings & TUI window (`/pantheon-settings`) - -> Originally published in the root README. Design background: -> [Pantheon 2.0 — Modern Install, Settings UI, and Update Flow](design/2.0-settings-and-install.md). -> Quota providers inside the TUI: [TUI quota providers](tui-quota-providers.md). - -Run `/pantheon-settings` (or `Pantheon: Settings` in the command palette) to open the -interactive settings window: - -- **Gates & overrides:** toggle named behaviors live; persists to `pantheon-overrides.json`. -- **Model presets:** switch active model tier globally or per project. -- **Decision model selector:** interactive selector to cycle across all remote decision - models (`openrouter-jev`, `typesafe-jev`, `openai-decisions`, `vercel-gateway-jev`, etc.) - directly from the UI. -- **Bilingual settings (PT-BR / EN):** full visual localization for Decision, Autonomy, - and Safety tabs, auto-detecting environment locale with manual toggle in the TUI tab. -- **Updates:** check registry channel (`beta` / `stable`) and trigger upgrades. -- **Doctor:** run inline system health diagnostics. -- **TUI personalization:** adjust spacing (`comfortable` vs `compact`), separators, gauge - bar styles, context display rows, and language. -- **Non-destructive overlay & mouse navigation:** opens as a floating dialog overlay over - the active session without blanking the workspace (configurable via `dialog` vs - `fullscreen`), with full mouse click support for tabs, sidebar, rows, value cyclers, and - actions. -- **Modernized What's New window:** card layout with rounded border, pagination buttons, - and a dedicated `[OK, Entendido]` button with keyboard (`Enter`/`Esc`/`Q`) and mouse - click support. See [The What's-new TUI window](reference/whats-new.md). +# Settings, Command Palette & TUI Surfaces (`/pantheon-settings`) + +> 🇧🇷 **Versão em Português disponível:** [Leia em Português](pt-BR/SETTINGS.md) +> Design background: [Pantheon 2.0 — Modern Install, Settings UI, and Update Flow](design/2.0-settings-and-install.md). + +Pantheon exposes an interactive, non-destructive TUI inside OpenCode 2.x across +the **Home screen**, **Composer autocomplete**, **Session Sidebar**, **`/dispatch` +panel**, **`/pantheon-settings`**, **`/pantheon-artifacts`**, and **`What's New`**. + +--- + +## 1. Entry Points & Command Palette + +- **Home screen:** displays the active `Pantheon v2.2.0` status badge and opens + `/pantheon-settings` directly in a centered large floating dialog. + +![OpenCode Home screen with Pantheon v2.2.0 active](assets/tui/home-status.png) + +- **Slash commands (`/pantheon*`) & `Ctrl+P`:** typing `/pantheon` shows the + native command popup; clicking the `↑ vX.Y.Z` update badge in the Home footer + or Sidebar header also opens **Updates** directly. + +![Pantheon slash commands autocomplete in OpenCode TUI](assets/tui/commands-autocomplete.png) + +| Command | Alias / Palette | What it opens | +|---|---|---| +| `/pantheon-settings` | `Pantheon: Settings` | 10-tab interactive settings window (`docked` / `dialog` / `fullscreen`) | +| `/pantheon-cockpit` | `/cockpit` · `Pantheon: Mission Control Cockpit` | 3-page Mission Control Cockpit (`Overview`, `Swarm`, `Flightdeck`) | +| `/pantheon-updates` | `Pantheon: Updates & Cleanup` | Jumps directly to the **Updates & Legacy Cleanup** tab | +| `/pantheon-whats-new` | `/whats-new` · `Pantheon: What's New` | Reopens the paginated release highlights card dialog | +| `/pantheon-artifacts` | `/artifacts` · `Pantheon: Artifacts` | Lists and paginates `PLAN`, `REPORT`, and `ADR` files | +| `/pantheon-dispatch` | `/dispatch` · `Pantheon: Dispatch` | Full-width delegation & subagent telemetry panel | + +All interactive dialogs support both **keyboard navigation** (`Tab`, `↑`/`↓`, +`←`/`→`, `Enter`, `Ctrl+S`, `Ctrl+R`, `Esc`) and **mouse clicks** (tabs, rows, +value cyclers, action buttons, and sidebar badges). + +--- + +## 2. Tabs Inside `/pantheon-settings` + +### `Gates` — Scoped Behavior & Guardrails +Toggle edit scope (`global` vs `project`), installed governance skills +(`Auto-continue`, `TDD with agents`, `Code review checklist`, `Prompt refinery`), +and execution gates (`Idle todo enforcer`, `Context pruner`, `J1 risk gate`), +persisting atomically to `pantheon-overrides.json`. + +![Pantheon Settings Gates tab](assets/tui/settings-gates.png) + +### `Decisão` / `Decision` — Jev Arbitrage & Routing Credentials +Enable or switch the advisory decision mode (`local`, `auto`, `explicit`), cycle +across configured decision models, inspect cloud access gating, and audit +read-only credential status without ever persisting secrets. + +![Pantheon Settings Decision tab](assets/tui/settings-decision.png) + +### `Preset` — Global Tier & Vision Model +Switch the active global model tier (`none`, `free`, `eco`, `standard`, `teampro`, +`max`, etc.) and configure the default `vision_describe` model (`opencode-vision.json`). + +![Pantheon Settings Preset tab](assets/tui/settings-preset.png) + +### `TUI` — Bilingual UI, Theme, Gauges & Layout +Switch language (`auto` / `pt-BR` / `en`), layout density (`comfortable` vs +`compact`), surface mode (`docked` / `fullscreen` / `dialog`), status separators, +gauge style (`line`, `block`, `smooth`, `ascii`, `dots`, `braille`), and sidebar rows. + +![Pantheon Settings TUI customization tab](assets/tui/settings-tui.png) + +### `Autonomia` / `Autonomy` — Continuation Loop & Decision Budgets +Configure multi-turn continuation limits (`maxContinuations`, cooldown) and Jev +monthly / per-decision USD caps alongside the read-only decision gradient reference. + +![Pantheon Settings Autonomy tab](assets/tui/settings-autonomy.png) + +### `Segurança J1`, `Atualizações` & `Changelog` +- **Segurança J1:** configure risk gate thresholds (`shadow`, `enforce`, or scoped overrides). +- **Atualizações (`Updates`):** check the active npm dist-tag (`latest` / `beta`), + trigger updates, and run **Legacy & Drift Cleanup** to prune obsolete V1 artifacts + and stale coexisting OpenCode npm caches (`~/.cache/opencode/npm/pantheon-opencode*`). + +![Pantheon Settings Updates and Legacy Cleanup tab](assets/tui/settings-updates.png) + +- **Changelog:** browse recent release notes right inside the settings window. + +### `Doctor` & `Sobre` / `About` +- **Doctor:** inline file-derived health check (install state version, Node.js + runtime floor, overrides validity, and decision config presence) complementing + `npx pantheon-opencode doctor`. + +![Pantheon Settings Doctor tab](assets/tui/settings-doctor.png) + +- **Sobre / About:** live summary of runtime, active preset/Jev/J1 state, and + the grouped inventory of all **30 Native TypeScript Tools**. + +![Pantheon Settings About tab showing 30 native tools inventory](assets/tui/settings-about.png) + +--- + +## 3. Related Interactive Dialogs & Panels + +- **TUI Mission Control Cockpit (`/pantheon-cockpit`):** unified 3-page operational + cockpit (`Overview`, `Swarm` Gantt & activity stream, `Flightdeck` Gate Matrix), + navigable via `1–3` or `Tab` and from the Home `◈ Cockpit` badge. + +![Pantheon Mission Control Cockpit Overview tab](assets/tui/cockpit-overview.png) + +![Pantheon Mission Control Cockpit Swarm tab](assets/tui/cockpit-swarm.png) + +![Pantheon Mission Control Cockpit Flightdeck tab](assets/tui/cockpit-flightdeck.png) + +- **What's New (`What's-New`):** rounded card layout with pagination (`‹ Anterior` + / `Próxima ›`) and dedicated close button (`OK, Entendido` / `OK, Got it`). See + [The What's-new TUI window](reference/whats-new.md). + +![What's New dialog in OpenCode TUI](assets/tui/whats-new.png) + +- **Built-in Artifacts Viewer (`/pantheon-artifacts`):** inspect Deepwork `PLAN.md`, + reports, and ADRs in the terminal without leaving your session — see + [Artifacts & `/pantheon-artifacts`](ARTIFACTS.md). +- **Live Sidebar & `/dispatch` Panel:** track token/cache telemetry and subagent + costs in real time — see [OpenCode 2.x](opencode.md#dispatch-sidebar-block). diff --git a/docs/assets/tui/artifacts-list.png b/docs/assets/tui/artifacts-list.png new file mode 100644 index 00000000..ec00058b Binary files /dev/null and b/docs/assets/tui/artifacts-list.png differ diff --git a/docs/assets/tui/artifacts-reader.png b/docs/assets/tui/artifacts-reader.png new file mode 100644 index 00000000..b6fb7926 Binary files /dev/null and b/docs/assets/tui/artifacts-reader.png differ diff --git a/docs/assets/tui/cockpit-flightdeck.png b/docs/assets/tui/cockpit-flightdeck.png new file mode 100644 index 00000000..345c82de Binary files /dev/null and b/docs/assets/tui/cockpit-flightdeck.png differ diff --git a/docs/assets/tui/cockpit-overview.png b/docs/assets/tui/cockpit-overview.png new file mode 100644 index 00000000..48bcef6d Binary files /dev/null and b/docs/assets/tui/cockpit-overview.png differ diff --git a/docs/assets/tui/cockpit-swarm.png b/docs/assets/tui/cockpit-swarm.png new file mode 100644 index 00000000..f1dff5b9 Binary files /dev/null and b/docs/assets/tui/cockpit-swarm.png differ diff --git a/docs/assets/tui/commands-autocomplete.png b/docs/assets/tui/commands-autocomplete.png new file mode 100644 index 00000000..00570d43 Binary files /dev/null and b/docs/assets/tui/commands-autocomplete.png differ diff --git a/docs/assets/tui/dispatch-panel.png b/docs/assets/tui/dispatch-panel.png new file mode 100644 index 00000000..cc856a50 Binary files /dev/null and b/docs/assets/tui/dispatch-panel.png differ diff --git a/docs/assets/tui/home-status.png b/docs/assets/tui/home-status.png new file mode 100644 index 00000000..f05f9d14 Binary files /dev/null and b/docs/assets/tui/home-status.png differ diff --git a/docs/assets/tui/session-sidebar.png b/docs/assets/tui/session-sidebar.png new file mode 100644 index 00000000..74f37b52 Binary files /dev/null and b/docs/assets/tui/session-sidebar.png differ diff --git a/docs/assets/tui/settings-about.png b/docs/assets/tui/settings-about.png new file mode 100644 index 00000000..6f73e014 Binary files /dev/null and b/docs/assets/tui/settings-about.png differ diff --git a/docs/assets/tui/settings-autonomy.png b/docs/assets/tui/settings-autonomy.png new file mode 100644 index 00000000..f27be830 Binary files /dev/null and b/docs/assets/tui/settings-autonomy.png differ diff --git a/docs/assets/tui/settings-decision.png b/docs/assets/tui/settings-decision.png new file mode 100644 index 00000000..adffc194 Binary files /dev/null and b/docs/assets/tui/settings-decision.png differ diff --git a/docs/assets/tui/settings-doctor.png b/docs/assets/tui/settings-doctor.png new file mode 100644 index 00000000..bd5b3606 Binary files /dev/null and b/docs/assets/tui/settings-doctor.png differ diff --git a/docs/assets/tui/settings-gates.png b/docs/assets/tui/settings-gates.png new file mode 100644 index 00000000..2765f0a7 Binary files /dev/null and b/docs/assets/tui/settings-gates.png differ diff --git a/docs/assets/tui/settings-preset.png b/docs/assets/tui/settings-preset.png new file mode 100644 index 00000000..e193044a Binary files /dev/null and b/docs/assets/tui/settings-preset.png differ diff --git a/docs/assets/tui/settings-tui.png b/docs/assets/tui/settings-tui.png new file mode 100644 index 00000000..18cdc3a9 Binary files /dev/null and b/docs/assets/tui/settings-tui.png differ diff --git a/docs/assets/tui/settings-updates.png b/docs/assets/tui/settings-updates.png new file mode 100644 index 00000000..57f5a519 Binary files /dev/null and b/docs/assets/tui/settings-updates.png differ diff --git a/docs/assets/tui/whats-new.png b/docs/assets/tui/whats-new.png new file mode 100644 index 00000000..d556c8e7 Binary files /dev/null and b/docs/assets/tui/whats-new.png differ diff --git a/docs/guides/deepwork.md b/docs/guides/deepwork.md index d80496c1..13ac8bfc 100644 --- a/docs/guides/deepwork.md +++ b/docs/guides/deepwork.md @@ -99,7 +99,15 @@ graph TD --- -## 5. Reference Implementation +## 5. Inspecting & Reading Plans (`/pantheon-artifacts`) + +Review generated `PLAN.md` files directly inside OpenCode CLI with `/pantheon-artifacts` (`/artifacts`) — see [Artifacts & `/pantheon-artifacts`](../ARTIFACTS.md): + +![Paginated artifact reader in OpenCode TUI](../assets/tui/artifacts-reader.png) + +--- + +## 6. Reference Implementation Inspect a live Deepwork plan directory in the repository: - [`examples/saas-dashboard/.pantheon/deepwork/PLAN_001_metrics-dashboard/`](https://github.com/ils15/pantheon-opencode/tree/main/examples/saas-dashboard/.pantheon/deepwork/PLAN_001_metrics-dashboard) diff --git a/docs/guides/first-project.md b/docs/guides/first-project.md index 1ad6c19c..be12892c 100644 --- a/docs/guides/first-project.md +++ b/docs/guides/first-project.md @@ -35,16 +35,17 @@ flowchart TD ## 2. Step 1 — Installation and Setup -In any project directory (new or existing): +Install Pantheon once as a native OpenCode 2.x plugin (works in any directory, with no per-project copy clutter): ```bash -# Initialize Pantheon agents, skills, and plugins in the project -npx pantheon-opencode init -``` +# Recommended: register native plugin globally or in the project +opencode plugin add pantheon-opencode -The interactive installer lets you choose components (`agents`, `skills`, `instructions`, `plugins`). Selecting `plugins` installs the modern **TUI** (terminal dashboard). +# Optional: also inject project AGENTS.md / .opencode overrides if desired +npx pantheon-opencode init --project --no-mcp +``` -Verify installation health with the doctor diagnostic: +Verify installation health inside OpenCode via `/pantheon-settings` (**Doctor**) or from the terminal: ```bash npx pantheon-opencode doctor diff --git a/docs/index.md b/docs/index.md index a4343ec8..93e03e83 100644 --- a/docs/index.md +++ b/docs/index.md @@ -42,6 +42,7 @@ of repeating it. | Memory stores, TTL, size caps, and session goals | [Memory](MEMORY.md) | | Platform overview (OpenCode-only) | [Platforms](PLATFORMS.md) | | Settings window and TUI (gates, presets, updates, personalization) | [Settings & TUI](SETTINGS.md) | +| Artifacts guide & `/pantheon-artifacts` TUI viewer | [Artifacts](ARTIFACTS.md) | ## Reference diff --git a/docs/opencode.md b/docs/opencode.md index 3a12fdae..e7e94255 100644 --- a/docs/opencode.md +++ b/docs/opencode.md @@ -19,22 +19,35 @@ host never loads two Pantheon plugins. ## Tools -The plugin registers tools through `ctx.tool.transform()`. The exact list, -with source locators, is in -[Architecture](ARCHITECTURE.md#what-the-plugin-registers). In user terms: - -- `hashline_edit` edits files by line-tag anchors instead of raw line numbers. -- `pantheon_cost` reports tokens and USD by agent, model, and session. -- `pantheon_model` shows, sets, or resets per-agent project-scoped model - overrides. -- `pantheon_local_decision` is the advisory local decision selector; it runs - only for Zeus. -- `vision_describe` appears when the host exposes its model catalog. -- `pantheon_bounded_read` appears when the host exposes its permission and - session APIs, and only in a root Zeus session. - -The three legacy goal tools are not registered. Use the Persistence MCP -`goal_*` tools for durable manual goals; see [Memory](MEMORY.md#manual-session-goals). +The plugin registers **30 native TypeScript tools** through `ctx.tool.transform()` +with zero external Python dependency, automatically available in any workspace via +`opencode plugin add pantheon-opencode` (check the live inventory in `/pantheon-settings` +→ **About**): + +- **Memory, context, federation & goals:** `memory_store`, `memory_recall`, `memory_search`, + `memory_forget`, `memory_list`, `memory_stats`, `context_save`, `context_get`, `goal_create`, + `goal_get`, `goal_update`, and `goal_done` — FTS5-backed persistence under `.pantheon/` + that automatically shares the main repository root across linked git worktrees + (override with `PANTHEON_ISOLATE_WORKTREE_MEMORY=1`), plus optional read-only multi-repo + federation (`PANTHEON_FEDERATED_REPOS` / `~/.pantheon/federation.json`). `goal_update` uses `notes` + to append progress entries. +- **Structural codemap & AST rewriting:** `code_index`, `code_query`, `code_neighbors`, + `ast_search`, and `ast_rewrite` — symbol/relation graph with automatic orphan pruning + plus comment-aware AST matching/rewriting (`$VAR` / `$$$ARGS`) confined to workspace bounds. +- **Mechanical gates, atomic steps & agent forge:** `pantheon_step_ledger` (`init_step`, + `record_reproduction`, `record_mutation`, `record_verification`, `rollback_step`, + `complete_step`, `status` with isolated temp-index git checkpoints and bugfix `RED` gates), + `pantheon_review_verdict` (typed `@themis` verdict + bounded `ctx.session.synthetic` remediation), + `pantheon_deepwork`, `pantheon_agent_forge` (including `detect_stack`), and `pantheon_skill_search`. +- **Editing, LSP diagnostics, telemetry & routing:** `hashline_edit` (workspace-confined + relative paths + post-edit TypeScript/Pyright/stdio + pooled TCP LSP proxy via `PANTHEON_LSP_TCP_ENDPOINTS`), + `shell`, `todowrite`/`todoread`, `pantheon_cost`, `pantheon_model`, and `pantheon_local_decision` (Zeus-only advisory selector). +- **Native worktree orchestration & commands:** `ctx.worktree.transform` (`create`, `remove`, + `list`) in `.pantheon-worktrees//`, plus **9 slash commands** including + `/pantheon-forge` and `/pantheon-cockpit`. +- **Host-conditional tools:** `vision_describe` when the host exposes its model catalog, + and `pantheon_bounded_read` when the host exposes its permission and session APIs + (root Zeus sessions only). ## Per-agent MCP permissions @@ -63,8 +76,10 @@ One aggregated `Dispatch` block covers the whole child set: - header `◈ Dispatch · rodando · $`, summing every child, live and finished; -- one row per live child (`⠸ · $ `, newest first, - three then `… +N rodando`); +- one row per live child (`⠸ ·[·][?|!] $ `, + newest first, three then `… +N rodando`), surfacing real-time activity verbs + (`edit`, `code`, `bash`, `ask`, `err`) and attention badges (`?` waiting for + permission/question, `!` error); - finished children rolled up per agent: `✓ · $ · agentes` (plus `· falhas` when any child failed), up to three ` ×· $` rows and `… +K $` beyond — never one @@ -82,38 +97,9 @@ no child. It is added with `append` claims: the native prompt footer keeps its own line, and Pantheon only appends `▸ · ✦ ativos` while delegations are running. - - - - -```text -Pantheon v1.6.0 -▸ teampro · anthropic -Sessão: MCP permission audit - -▤ Context -142.6K tokens -▰▰▰▰▰▰▰▰▱▱▱▱ 71% of 200K -$4.12 spent -cache 92% · 42.3 tok/s - -◈ Dispatch · 2 rodando · $3.49 -⠸ prometheus·plan $0.09 14m34s -⠸ apollo·disc $0.03 1m12s -✓ 70 · $3.40 · 9 agentes -prometheus × 12·plan $1.20 -hermes × 31 $1.44 -athena × 9·plan $0.76 -``` - -*Illustrative layout — not a screenshot.* Live children lead the block; finished -children collapse into one roll-up per agent, never one row per session. +![Pantheon sidebar with the aggregated Dispatch block](assets/tui/session-sidebar.png) -*OpenCode 2.x · pantheon-opencode 1.6.0* +*OpenCode 2.3.2 · pantheon-opencode 2.2.0 — live session capture (`Dispatch` roll-up per agent, token telemetry, and git status).* ## `/dispatch` panel @@ -144,32 +130,9 @@ Pantheon toasts `Open a session to view Dispatch` instead of inventing a route. Jumping from a row to the child session is a documented TODO: no `session` router destination is verified for a child id. - - - - -```text -◈ Dispatch — MCP permission audit -2 rodando · 70 concluídos · 1 falha · $3.59 -────────────────────────────────────────────────────────────────────── -▸ ⠋ prometheus plan $0.09 14m34s MCP permission audit - ✓ hermes oth $0.44 2m10s ses_ab12cd · anthropic/claude-sonnet-4.5 - ✓ apollo disc $0.12 1m02s in 12.4K · out 430 · r 120 · cache 8.0K/1.0K - ✗ athena plan $0.01 48s kind plan (prefixo) · parent ses_9f31aa - ✓ zeus plan $0.07 3m21s - ✓ demeter oth $0.05 1m45s - -1-10 de 71 · k/up j/down mover · enter detalhe · f fullscreen · escape/q fechar -``` - -*Illustrative layout — not a screenshot.* Above 72 columns the detail sits beside -the list; narrower panels stack it underneath and truncate per column. +![Full-width /dispatch panel showing child tree and detail pane](assets/tui/dispatch-panel.png) -*OpenCode 2.x · pantheon-opencode 1.6.0* +*OpenCode 2.3.2 · pantheon-opencode 2.2.0 — live `[fullscreen]` `/dispatch` panel capture.* ## Plan before approval @@ -205,7 +168,7 @@ Zeus · teampro *Illustrative layout — not a screenshot.* The plan is printed in the main conversation before the question, so approval never refers to a child's view. -*OpenCode 2.x · pantheon-opencode 1.6.0* +*OpenCode 2.x · pantheon-opencode 2.2.0* ## Context pruning @@ -248,9 +211,9 @@ uses the `pantheon-memory` MCP only when an agent explicitly calls ## Session goals -Durable manual goals are Persistence MCP tools, not plugin tools: -`goal_create`, `goal_get`, `goal_update`, and `goal_done`. They are granted only -to Zeus, partitioned by OpenCode session id, and never continue a session +Durable manual goals are registered as native plugin tools (`goal_create`, `goal_get`, +`goal_update`, and `goal_done`), backed by the shared `.pantheon/` store across +worktrees. They are granted to Zeus, scoped cleanly, and never continue a session automatically. See [Memory](MEMORY.md#manual-session-goals). ## Task-result guard diff --git a/docs/pt-BR/ARCHITECTURE.md b/docs/pt-BR/ARCHITECTURE.md index c8a74611..5e1d7266 100644 --- a/docs/pt-BR/ARCHITECTURE.md +++ b/docs/pt-BR/ARCHITECTURE.md @@ -69,19 +69,28 @@ No OpenCode 2.x, o plugin impõe adicionalmente uma matriz chamador/alvo para re Existe uma geração única: a linha de plugins V1 foi removida no 2.0, e a superfície abaixo é a única ativa. -O plugin é registrado sob a chave plural `plugins` como o diretório `/src/plugin`. O arquivo `src/plugin/index.ts` reexporta o ponto de entrada real em `src/plugin.ts`; o registro de hooks de ferramentas em `src/plugin.ts` é alimentado pelas definições em `src/pantheon/tools.ts`. - -### Quatro Ferramentas Incondicionais: -- `hashline_edit` — Edição precisa baseada em linhas de hash (`src/pantheon/tools.ts`). -- `pantheon_cost` — Telemetria de tokens consumidos, custos estimados e velocidade de cache (`src/pantheon/tools.ts`). -- `pantheon_model` — Roteamento dinâmico de modelos por especialista (`src/pantheon/tools.ts`). -- `pantheon_local_decision` — Seletor consultivo local; rejeita execução a menos que o contexto do host identifique o chamador como Zeus (`src/pantheon/tools.ts`). - -### Até Duas Ferramentas Dependentes do Host: -- `vision_describe` — Adicionada apenas quando `ctx.model.list` é uma função (`src/plugin.ts`; definição em `src/pantheon/native-vision.ts`). -- `pantheon_bounded_read` — Adicionada apenas quando o hook `tool.execute.before` é registrado e o host expõe as APIs de permissão e sessão (`src/plugin.ts`; definição em `src/pantheon/bounded-read.ts`). Apenas para sessões raiz do Zeus. - -As ferramentas de metas automáticas são omitidas onde o `PluginContext` do host não as suporta (reportado como `goal-tools`). +O plugin é registrado sob a chave plural `plugins` (via +`opencode plugin add pantheon-opencode` ou `/src/plugin`). O bundle +`src/plugin/index.js` é compilado a partir de `src/plugin.ts` e registra **26 +ferramentas nativas em TypeScript** (`src/pantheon/`), dispensando runtime Python: + +- **Edição, custo, modelo e roteamento:** `hashline_edit`, `pantheon_cost`, + `pantheon_model`, `pantheon_local_decision` (somente Zeus) e `shell`. +- **Memória FTS5, checkpoints e metas (`native-memory-tools.ts`, compartilhado + entre worktrees Git):** `memory_store`, `memory_recall`, `memory_search`, + `memory_forget`, `memory_stats`, `context_save`, `context_get`, `goal_create`, + `goal_get`, `goal_update` e `goal_done`. +- **Codemap, Step-Ledger e orquestração:** `code_index`, `code_query`, + `code_neighbors` (com poda automática de arquivos removidos), + `pantheon_step_ledger`, `pantheon_deepwork`, `pantheon_agent_forge` e + `pantheon_skill_search`. +- **Ferramentas dependentes do host:** + - `vision_describe` — adicionada quando `ctx.model.list` está disponível (`src/pantheon/native-vision.ts`). + - `pantheon_bounded_read` — adicionada quando o hook `tool.execute.before` e + as APIs de permissão/sessão estão expostas (`src/pantheon/bounded-read.ts`; + apenas sessões raiz do Zeus). + - As ferramentas nativas `todowrite`/`todoread` do host são preservadas quando + já registradas para manter o painel nativo de Todo funcionando. O plugin também conecta cinco inscrições de eventos (`session.created`, `session.idle`, `session.deleted`, `session.error`, `session.compacted`), hooks de sessão (`prompt`, `context`, `compaction`), um hook `execute.before` que aplica modo somente-leitura (o mesmo manipulador impede o orquestrador de ler diretamente códigos-fonte, testes e scripts com `read`/`glob`/`grep`), e uma cadeia `execute.after` (`task-result-guard` → `context-sandbox` → `read-enhancer` → formatador + auditoria de delegação). diff --git a/docs/pt-BR/ARTIFACTS.md b/docs/pt-BR/ARTIFACTS.md new file mode 100644 index 00000000..efafbd33 --- /dev/null +++ b/docs/pt-BR/ARTIFACTS.md @@ -0,0 +1,75 @@ +# Artefatos e Visualizador `/pantheon-artifacts` + +> 🇺🇸 **English version available:** [Read in English](../ARTIFACTS.md) + +O Pantheon armazena planos de engenharia estruturados, relatórios de auditoria/descoberta +e Architecture Decision Records (ADRs) como documentos Markdown densos e organizados dentro +do repositório — mantendo a raiz do projeto limpa e permitindo revisão tanto no +**OpenCode CLI (TUI)** quanto no **OpenCode Desktop**. + +--- + +## 1. Onde os Artefatos Ficam e Quem os Cria + +| Tipo | Localização | Produzido por | Ciclo de vida | +|---|---|---|---| +| **Planos (`PLAN`)** | `.pantheon/deepwork//PLAN.md` | `@athena` / `/pantheon-deepwork` | Durável por tarefa/sprint (ignorado no git) | +| **Relatórios (`REPORT`)** | `.pantheon/reports/-.md` | `@apollo` / `@themis` | Trilha de auditoria e descoberta | +| **ADRs (`ADR`)** | `docs/adr/-.md` (e `.pantheon/memory-bank/adr/*.md`) | `@mnemosyne` | Decisões arquiteturais permanentes | + +> [!TIP] +> Worktrees vinculados resolvem automaticamente para a raiz do repositório principal, +> portanto rodar `/pantheon-artifacts` dentro de uma worktree continua enxergando todos +> os planos, relatórios e ADRs do projeto. + +--- + +## 2. Lendo Artefatos no OpenCode CLI (`/pantheon-artifacts`) + +Dentro de qualquer sessão OpenCode no terminal, execute `/pantheon-artifacts` +(atalho `/artifacts`, ou **Pantheon: Artifacts** na paleta `Ctrl+P`) — ou clique +diretamente nos links **`▸ Plan: ...`** / **`◈ Artefatos (N)`** na **Sidebar** +ou no **rodapé da tela inicial (Home)** sempre que houver artefatos no projeto: + +![Lista de artefatos no OpenCode TUI](../assets/tui/artifacts-list.png) + +### Seleção e Leitura Paginada + +- Use `↑` / `↓` (`k` / `j`) ou clique em uma linha para selecionar o artefato e + pressione `Enter` (ou clique em **Abrir**) para abri-lo no leitor paginado. +- Se houver apenas um artefato no projeto, `/pantheon-artifacts` já abre o arquivo + diretamente no modo leitura. + +![Leitor paginado de artefatos no OpenCode TUI](../assets/tui/artifacts-reader.png) + +### Controles de Teclado & Mouse + +| Contexto | Tecla / Ação | Efeito | +|---|---|---| +| Lista | `↑` / `k`, `↓` / `j`, clique no item | Seleciona artefato | +| Lista | `Enter` / `Espaço` / segundo clique | Abre o artefato selecionado | +| Leitor | `n` / `→` / clique em `Próxima ›` | Próxima página | +| Leitor | `p` / `←` / clique em `‹ Anterior` | Página anterior | +| Leitor | `b` / `Backspace` / clique em `‹ Lista` | Volta para a lista | +| Qualquer | `Esc` / `q` / clique em `[ Esc / Q ]` | Fecha o diálogo | + +O leitor formata automaticamente alertas GFM (`[NOTE]`, `[TIP]`, `[IMPORTANT]`, +`[WARNING]`, `[CAUTION]`), renderiza diagramas Mermaid (`flowchart`, `graph`, +`sequenceDiagram`, `stateDiagram`) como grafos com caixas e setas Unicode, +simplifica links `file://` e quebra títulos e listas para nunca estourar a +largura do terminal. + +--- + +## 3. Lendo Artefatos no OpenCode Desktop + +O OpenCode Desktop renderiza Markdown GitHub-Flavored nativamente inline: + +- **Links clicáveis de arquivo:** links no formato + `[auth.ts](file:///caminho/absoluto/src/auth.ts#L1-L40)` saltam direto para o + arquivo e trecho referenciados. +- **Alertas GFM & diagramas Mermaid:** blocos `> [!NOTE]`, `> [!IMPORTANT]`, tabelas + comparativas e grafos Mermaid renderizam visualmente no app Desktop. +- **Chat limpo:** os agentes persistem a especificação completa no arquivo do + artefato e enviam no chat apenas um resumo executivo curto junto ao pedido de + aprovação. diff --git a/docs/pt-BR/INSTALLATION.md b/docs/pt-BR/INSTALLATION.md index 53d1cd15..c93c91ba 100644 --- a/docs/pt-BR/INSTALLATION.md +++ b/docs/pt-BR/INSTALLATION.md @@ -2,24 +2,26 @@ > 🇺🇸 **English version available:** [Read in English](../INSTALLATION.md) -O Pantheon **requer o OpenCode 2.x** como host (o contrato da geração OpenCode 1.x foi completamente removido). A instalação padrão é realizada através do instalador `npx pantheon-opencode init`, que implanta todo o ecossistema: 14 agentes especialistas, 25 skills, regras de contexto (TDD, YAGNI), comandos de chat, interface TUI e servidores MCP locais. +O Pantheon 2.2 **requer o OpenCode 2.x** como host (o contrato da geração OpenCode 1.x foi completamente removido). + +**Instalação recomendada (boa prática via plugin nativo):** instalar com `opencode plugin add pantheon-opencode` registra nativamente os **14 agentes, 25 skills, 8 comandos, 26 tools nativas em TypeScript e a TUI** direto do pacote npm, **sem copiar arquivos duplicados para o disco**. Funciona imediatamente em **qualquer pasta** (com ou sem Git, worktrees ou diretórios novos) e evita arquivos legados/cópias antigas coexistindo após atualizações. + +O instalador CLI (`npx pantheon-opencode init`) continua disponível como opção para quem deseja materializar arquivos locais em `.opencode/`, injetar `AGENTS.md` ou configurar MCPs Python legados. Se você migrar de uma instalação antiga via `init`, use `/pantheon-settings` → **Atualizações** (**Legados, Drift & Limpeza**) para limpar cópias redundantes e caches antigos com segurança. --- ## Início Rápido (TL;DR) ```bash -# Instalação Global (recomendada para todos os projetos da máquina) -npx pantheon-opencode init - -# Instalação Restrita ao Projeto Atual -npx pantheon-opencode init --project +# Recomendado: plugin nativo do OpenCode 2.x (zero cópias redundantes, funciona em qualquer pasta) +opencode plugin add pantheon-opencode -# Modo Não-Interativo (Headless) para Automação e CI -npx pantheon-opencode init -y +# Atualizar depois (ou direto pela TUI em /pantheon-settings -> Atualizações) +opencode plugin update pantheon-opencode -# Visualização de Plano sem Modificações em Disco (Dry-Run) -npx pantheon-opencode init --dry-run +# Opcional (CLI): materializar configs locais, AGENTS.md ou flags de projeto +npx pantheon-opencode init --project --no-mcp +npx pantheon-opencode init --headless --yes # Diagnóstico de Integridade e Saúde npx pantheon-opencode doctor diff --git a/docs/pt-BR/QUICKSTART.md b/docs/pt-BR/QUICKSTART.md index e0802123..3f68d80e 100644 --- a/docs/pt-BR/QUICKSTART.md +++ b/docs/pt-BR/QUICKSTART.md @@ -11,60 +11,45 @@ Este guia foi elaborado para levar você do zero ao seu primeiro resultado funci Certifique-se de que seu ambiente atende aos seguintes requisitos: 1. **OpenCode:** Versão 2.x instalada (suporte nativo ao host 2.x). -2. **Node.js:** Versão `>=26.4.0` (necessária para executar o CLI, empacotador e interface TUI do Pantheon). -3. **Python (Opcional):** Versão `3.11+` (necessária apenas se você utilizar os servidores MCP nativos em Python). +2. **Node.js:** Versão `>=26.4.0` (necessária para as ferramentas nativas e interface TUI do Pantheon). +3. **Python (Opcional / Legado):** Versão `3.11+` apenas se você optar pelos servidores MCP legados em Python (todas as 26 ferramentas nativas rodam em TypeScript/Node). --- ## 1. Instalação -O Pantheon é instalado e configurado através do seu instalador de linha de comando: +### Instalação Nativa como Plugin do OpenCode (Recomendada — Funciona em Qualquer Lugar) -### Instalação Completa com CLI (Recomendada) - -Instala os 14 agentes especialistas, 25 skills, regras de contexto (TDD, YAGNI), comandos de atalho, servidores MCP nativos e a interface visual TUI: +Um único comando registra em memória os 14 agentes especialistas, 25 skills, 8 comandos, 26 tools nativas em TypeScript e a interface TUI, sem copiar arquivos redundantes para o disco: ```bash -# Instalação Global (recomendada — disponível para todos os seus projetos) -npx pantheon-opencode init - -# Ou Instalação Restrita ao Projeto Atual (apenas na pasta do projeto) -npx pantheon-opencode init --project +opencode plugin add pantheon-opencode ``` -> **Dica para automação ou CI:** Execute `npx pantheon-opencode init -y` para aplicar as configurações padrão imediatamente sem prompts interativos. +Por que essa é a melhor prática: +- Funciona imediatamente em **qualquer diretório** (repositórios existentes, worktrees Git ou pastas vazias) sem precisar rodar `init`. +- Atualiza de forma limpa com `opencode plugin update pantheon-opencode` (ou `/pantheon-updates`) sem deixar cópias antigas em `.opencode/agents/` ou `plugins/pantheon-tui/` coexistindo. -### Registro do Plugin no OpenCode +### Instalação Opcional via CLI (`init`) -Se você já utiliza o ecossistema de plugins do OpenCode ou deseja configurá-lo manualmente via `opencode.json`, certifique-se de registrar a entrada: +Use o instalador CLI apenas quando quiser gravar arquivos de projeto (`AGENTS.md`, overrides em `.opencode/`) ou habilitar MCPs Python legados: -```json -{ - "plugins": [ - "pantheon-opencode" - ] -} +```bash +npx pantheon-opencode init --project --no-mcp ``` -> [!NOTE] -> O comando `npx pantheon-opencode init` já configura automaticamente o arquivo `opencode.json` com o plugin, agentes, skills e MCPs. - --- -## 2. Validar a Instalação com o `doctor` +## 2. Validar Saúde e Limpar Caches Antigos + +Dentro do OpenCode, use `/pantheon-settings` (ou `/pantheon-updates`) para rodar o **Doctor** e a seção **Legados, Drift & Limpeza** (que detecta e remove caches `@beta`/revisões antigas coexistentes e cópias obsoletas). -Antes de iniciar seu trabalho, execute o diagnóstico de integridade do Pantheon: +Pelo terminal, você também pode executar: ```bash npx pantheon-opencode doctor ``` -O comando `doctor` valida: -- A conexão e o funcionamento de todos os servidores MCP nativos (`pantheon_resources`, `pantheon_memory`, `pantheon_persistence`, `pantheon_vision`, `pantheon_cost`). -- A correta inclusão do plugin no `opencode.json`. -- A sincronização dos arquivos de agentes, skills e instruções. -- O ambiente virtual Python e suas dependências. - Uma instalação saudável exibirá veredicto **PASS** com zero erros bloqueantes. --- @@ -83,8 +68,9 @@ opencode > ``` ### O que você verá na interface: -- **Barra Lateral Rica (TUI):** Exibe a versão ativa do Pantheon (v2.1.1), o preset de modelos em uso, o estado do repositório Git e um painel de **Contexto** em tempo real com contagem de tokens, custo estimado e velocidade de cache. -- **Suporte Multimodal Nativo (Pantheon Vision):** Se você capturar uma tela e colar diretamente no chat (`Ctrl+V` / `Cmd+V`), o Pantheon analisa a imagem de forma silenciosa via contexto de sistema, sem poluir a conversa com comentários ou blocos HTML. +- **Barra Lateral Rica (TUI):** Exibe a versão ativa do Pantheon (`v2.2.0`), o preset em uso, o estado do Git, o painel de **Contexto** com contadores por domínio (`mem`, `ctx`, `code`, `edit`, `shell`), **Todo** nativo e **Dispatch** com verbos ao vivo e badges `?`/`!`. +- **Anúncios Interativos de Atualização e Novidades:** Ao atualizar, abre o diálogo **NOVIDADES** (`/pantheon-whats-new` para reabrir quando quiser) e o badge clicável `↑ vX.Y.Z` abre `/pantheon-updates`. +- **Suporte Multimodal Nativo (Pantheon Vision):** Cole uma captura de tela (`Ctrl+V` / `Cmd+V`) ou use `vision_describe` quando o catálogo de modelos do host estiver exposto. --- diff --git a/docs/pt-BR/SETTINGS.md b/docs/pt-BR/SETTINGS.md new file mode 100644 index 00000000..318bb3db --- /dev/null +++ b/docs/pt-BR/SETTINGS.md @@ -0,0 +1,122 @@ +# Configurações, Paleta de Comandos & TUI (`/pantheon-settings`) + +> 🇺🇸 **English version available:** [Read in English](../SETTINGS.md) +> Contexto de design: [Pantheon 2.0 — Modern Install, Settings UI, and Update Flow](../design/2.0-settings-and-install.md). + +O Pantheon oferece uma interface TUI interativa e não destrutiva dentro do OpenCode 2.x, +presente na **tela inicial (Home)**, **autocomplete de comandos**, **barra lateral da +sessão**, painel **`/dispatch`**, **`/pantheon-settings`**, **`/pantheon-artifacts`** e +no card **`What's New`**. + +--- + +## 1. Pontos de Entrada & Paleta de Comandos + +- **Tela inicial (Home):** exibe o selo de versão ativo (`Pantheon v2.2.0`) e permite + abrir `/pantheon-settings` direto em diálogo centralizado (`large`), mesmo sem + sessão aberta. + +![Tela inicial do OpenCode com Pantheon v2.2.0 ativo](../assets/tui/home-status.png) + +- **Comandos (`/pantheon*`) & `Ctrl+P`:** digitar `/pantheon` lista todos os + comandos integrados; clicar no selo de atualização `↑ vX.Y.Z` na Home ou na + barra lateral também abre direto a aba **Atualizações**. + +![Autocomplete de comandos /pantheon na TUI do OpenCode](../assets/tui/commands-autocomplete.png) + +| Comando | Alias / Paleta | O que abre | +|---|---|---| +| `/pantheon-settings` | `Pantheon: Settings` | Janela interativa de 10 abas (`docked` / `dialog` / `fullscreen`) | +| `/pantheon-cockpit` | `/cockpit` · `Pantheon: Mission Control Cockpit` | Cockpit de Controle em 3 páginas (`Overview`, `Swarm`, `Flightdeck`) | +| `/pantheon-updates` | `Pantheon: Updates & Cleanup` | Abre direto na aba **Atualizações & Limpeza** | +| `/pantheon-whats-new` | `/whats-new` · `Pantheon: What's New` | Reabre o card paginado com novidades da versão | +| `/pantheon-artifacts` | `/artifacts` · `Pantheon: Artifacts` | Lista e pagina `PLAN.md`, relatórios e ADRs | +| `/pantheon-dispatch` | `/dispatch` · `Pantheon: Dispatch` | Painel amplo de subagentes e custos | + +Todos os painéis suportam **teclado** (`Tab`, `↑`/`↓`, `←`/`→`, `Enter`, `Ctrl+S`, +`Ctrl+R`, `Esc`) e **mouse** (clique em abas, linhas, seletores e botões). + +--- + +## 2. As 10 Abas do `/pantheon-settings` + +### `Gates` — Regras & Guardrails por Escopo +Alterne entre escopo global e projeto, ative/desative skills instaladas +(`Auto-continue`, `TDD with agents`, `Code review checklist`, `Prompt refinery`) e +portões de execução (`Idle todo enforcer`, `Context pruner`, `J1 risk gate`) com +gravação atômica em `pantheon-overrides.json`. + +![Aba Gates no Pantheon Settings](../assets/tui/settings-gates.png) + +### `Decisão` — Assistente Jev & Credenciais de Roteamento +Configure o modo de arbitragem (`local`, `auto`, `explicit`), alterne entre os +modelos de decisão configurados e acompanhe o status somente-leitura das +credenciais sem nunca gravar chaves na janela. + +![Aba Decisão no Pantheon Settings](../assets/tui/settings-decision.png) + +### `Preset` — Tier Global & Modelo de Visão +Selecione o preset global ativo (`none`, `free`, `eco`, `standard`, `teampro`, etc.) +e defina o modelo usado por `vision_describe` em `opencode-vision.json`. + +![Aba Preset no Pantheon Settings](../assets/tui/settings-preset.png) + +### `TUI` — Idioma PT-BR/EN, Tema, Barras & Layout +Escolha idioma (`auto` / `pt-BR` / `en`), densidade (`comfortable` / `compact`), +superfície (`docked` / `fullscreen` / `dialog`), estilo de barras (`line`, `block`, +`smooth`, `ascii`, `dots`, `braille`) e linhas da barra lateral. + +![Aba TUI no Pantheon Settings](../assets/tui/settings-tui.png) + +### `Autonomia` — Loop Contínuo & Orçamentos Jev +Defina teto de continuações multi-turn (`1..200`), intervalo mínimo entre turnos e +tetos mensais/por consulta em USD para o roteamento Jev. + +![Aba Autonomia no Pantheon Settings](../assets/tui/settings-autonomy.png) + +### `Segurança J1`, `Atualizações` & `Changelog` +- **Segurança J1:** define o limiar operacional do portão de risco (`shadow`, + `enforce` ou overrides por escopo). +- **Atualizações:** checa o canal npm (`latest` / `beta`), dispara atualização e + executa **Legados, Drift & Limpeza** para remover cópias V1 obsoletas e caches + antigos do OpenCode (`~/.cache/opencode/npm/pantheon-opencode*`). + +![Aba Atualizações e Limpeza de Legado](../assets/tui/settings-updates.png) + +- **Changelog:** navega pelas notas das versões recentes sem sair do terminal. + +### `Doctor` & `Sobre` +- **Doctor:** verificação rápida baseada em arquivos locais (versão instalada, + Node.js ativo, integridade de overrides e presença do `decision-router.json`), + complementando `npx pantheon-opencode doctor`. + +![Aba Doctor no Pantheon Settings](../assets/tui/settings-doctor.png) + +- **Sobre:** resumo de plataforma/governança e inventário agrupado das **30 + Ferramentas Nativas TypeScript** registradas pelo plugin. + +![Aba Sobre listando as 30 ferramentas nativas](../assets/tui/settings-about.png) + +--- + +## 3. Diálogos e Painéis Relacionados + +- **TUI Mission Control Cockpit (`/pantheon-cockpit`):** cockpit operacional de 3 + páginas (`Overview`, `Swarm` Gantt + trilha semântica, `Flightdeck` Gate Matrix) + navegável via `1–3` / `Tab` ou clicando no selo `◈ Cockpit` da tela inicial. + +![Cockpit Mission Control — aba Overview](../assets/tui/cockpit-overview.png) + +![Cockpit Mission Control — aba Swarm](../assets/tui/cockpit-swarm.png) + +![Cockpit Mission Control — aba Flightdeck](../assets/tui/cockpit-flightdeck.png) + +- **`What's New` (`/whats-new`):** card paginado com navegação (`‹ Anterior` / + `Próxima ›`) e botão dedicado (`OK, Entendido`). Veja [The What's-new TUI window](../reference/whats-new.md). + +![Janela What's New na TUI do OpenCode](../assets/tui/whats-new.png) + +- **Visualizador `/pantheon-artifacts`:** explore planos, relatórios e ADRs no + terminal — veja [Artefatos & `/pantheon-artifacts`](ARTIFACTS.md). +- **Sidebar ao vivo & `/dispatch`:** acompanhe tokens, cache e custo de cada + subagente em tempo real — veja [OpenCode 2.x](../opencode.md#dispatch-sidebar-block). diff --git a/docs/pt-BR/guides/deepwork.md b/docs/pt-BR/guides/deepwork.md index a7cac703..68ec0d31 100644 --- a/docs/pt-BR/guides/deepwork.md +++ b/docs/pt-BR/guides/deepwork.md @@ -134,3 +134,11 @@ Ou pedindo diretamente para o Zeus: ``` O plano é sintetizado pela `@athena`, auditado pela `@themis` e apresentado a você para aprovação com links clicáveis `file://` para os arquivos gerados. + +--- + +## 6. Lendo o Plano Direto no Terminal (`/pantheon-artifacts`) + +Para navegar e ler qualquer `PLAN.md`, relatório ou ADR direto na TUI (inclusive a partir de worktrees), execute `/pantheon-artifacts` (`/artifacts`) — veja [Artefatos & `/pantheon-artifacts`](../ARTIFACTS.md): + +![Leitor paginado de artefatos no OpenCode TUI](../../assets/tui/artifacts-reader.png) diff --git a/docs/pt-BR/guides/first-project.md b/docs/pt-BR/guides/first-project.md index dcfe36fa..255aca2b 100644 --- a/docs/pt-BR/guides/first-project.md +++ b/docs/pt-BR/guides/first-project.md @@ -35,16 +35,17 @@ flowchart TD ## 2. Passo 1 — Instalação e Inicialização -Em qualquer pasta de projeto (nova ou existente): +Instale o Pantheon uma única vez como plugin nativo do OpenCode 2.x (funciona em qualquer diretório, sem gerar cópias redundantes por projeto): ```bash -# Inicializa os agentes, skills e plugins do Pantheon no projeto -npx pantheon-opencode init -``` +# Recomendado: registrar o plugin nativo globalmente ou no projeto +opencode plugin add pantheon-opencode -O instalador interativo permite selecionar componentes (`agents`, `skills`, `instructions`, `plugins`). A opção `plugins` instala a **TUI** (interface de terminal moderna). +# Opcional: injetar AGENTS.md ou overrides locais em .opencode/ +npx pantheon-opencode init --project --no-mcp +``` -Verifique se tudo está íntegro executando o diagnóstico de integridade: +Verifique a saúde da instalação dentro do OpenCode em `/pantheon-settings` (**Doctor**) ou pelo terminal: ```bash npx pantheon-opencode doctor diff --git a/docs/pt-BR/index.md b/docs/pt-BR/index.md index 4986c78d..b55cdaec 100644 --- a/docs/pt-BR/index.md +++ b/docs/pt-BR/index.md @@ -42,6 +42,8 @@ O **Pantheon** é um framework de orquestração multi-agente para o **OpenCode* | Catálogo de ferramentas MCP disponíveis, incluindo telemetria de custos | [Ferramentas MCP](../mcp-tools.md) | | Gerenciamento de memória, TTL, limites de contexto e checkpoints de sessão | [Memória](MEMORY.md) | | Plataformas e ecossistema suportado | [Plataformas](../PLATFORMS.md) | +| Janela de configurações e TUI (gates, presets, atualizações, personalização) | [Configurações & TUI](SETTINGS.md) | +| Artefatos & visualizador `/pantheon-artifacts` na TUI | [Artefatos](ARTIFACTS.md) | --- @@ -66,4 +68,5 @@ O **Pantheon** é um framework de orquestração multi-agente para o **OpenCode* | Estratégia de branches e processo de corte de releases | [Processo de Release](RELEASING.md) | | Regras de proteção e validação na branch `main` | [Proteção de Branches](BRANCH-PROTECTION.md) | | Registro de versões e histórico de mudanças | [Changelog](https://github.com/ils15/pantheon-opencode/blob/main/CHANGELOG.md) | +| Destaques das versões v2.x | [Destaques de Versão](../releases/highlights.md) | | Como contribuir com o projeto | [Como Contribuir](https://github.com/ils15/pantheon-opencode/blob/main/CONTRIBUTING.md) | diff --git a/docs/releases/highlights.md b/docs/releases/highlights.md index dba896c0..f2ce7fa5 100644 --- a/docs/releases/highlights.md +++ b/docs/releases/highlights.md @@ -4,6 +4,13 @@ > [CHANGELOG.md](https://github.com/ils15/pantheon-opencode/blob/main/CHANGELOG.md); this > page keeps the user-facing highlights that used to sit in the README. +## v2.2.0 + +- **30 Native TypeScript Tools & All Roadmap Pillars:** FTS5 memory + multi-repo read-only federation (`PANTHEON_FEDERATED_REPOS`), checkpoints (`context_*`), durable goals (`goal_*`), structural codemap + AST (`code_*`, `ast_search`, `ast_rewrite`), post-edit LSP diagnostics (`tsc`/`pyright`/stdio + pooled TCP `PANTHEON_LSP_TCP_ENDPOINTS`), atomic Step-Ledger git checkpoints + `ctx.session.create` runner (`pantheon_step_ledger`), native `pantheon_worktree` & `ctx.worktree.transform` isolation, typed `pantheon_review_verdict` + `ctx.session.synthetic` remediation, bugfix `RED` reproduction gates, and `/pantheon-forge` stack detection. +- **High-Density TUI Mission Control Cockpit (`/pantheon-cockpit`) & Flightdeck Replay Export:** 3-page `@opentui/solid` cockpit (`Overview`, `Swarm` Gantt + stream, `Flightdeck` Gate Matrix + cross-process bus stream + `x` Mermaid replay export to `.pantheon/reports/`) navigable via `1–3`/`Tab` and Home links, alongside `/pantheon-artifacts`, Sidebar domain counters, `↑ vX.Y.Z` update badges, and `Native Tools (30)` in **About**. +- **Shared `.pantheon/` Store Across Git Worktrees & Confinement:** Linked git worktrees automatically resolve back to the main repository's `.pantheon/` store (`PANTHEON_ISOLATE_WORKTREE_MEMORY=1` opts out); deleted files auto-prune from the codemap; `hashline_edit` and `ast_search`/`ast_rewrite` enforce workspace symlink confinement. +- **Anti-Stale Cache & Bundle Protections:** `Legacy & Drift` scans and removes stale coexisting OpenCode plugin caches (`~/.cache/opencode/npm/pantheon-opencode*`), and `version:check` / `package:validate` fail fast if `dist/tui.js` embeds a stale version. + ## v2.1.6 - **Deepwork Resilient Normalization:** Full support for multi-decision plans, single-option policy constraints, string criteria auto-inference, and agent handle normalization with atomic plan locking. diff --git a/docs/releases/v2.2.0.md b/docs/releases/v2.2.0.md new file mode 100644 index 00000000..3436d5eb --- /dev/null +++ b/docs/releases/v2.2.0.md @@ -0,0 +1,119 @@ +# Pantheon `v2.2.0` — Native OpenCode 2.x Orchestration, All 5 Architectural Pillars & Mission Control Cockpit + +> [!NOTE] +> **Pantheon `v2.2.0`** marks the full **2.2 General Availability (GA)** milestone for **OpenCode 2.x** (`2.0.x`–`2.3.x+`). Alongside completing the native in-process plugin runtime, `v2.2.0` pulls forward all five architectural pillars (`Structural Editing & LSP Diagnostics`, `Step-Ledger & Atomic Sub-Sessions`, `Spec-First Worktree & Verdict Orchestration`, `Graph Localization & Bugfix RED Gates`, and `Polyglot Extensibility`) together with the 3-page **TUI Mission Control Cockpit** (`/pantheon-cockpit`). + +```bash +# Quick install or upgrade inside OpenCode 2.x +opencode plugin add pantheon-opencode@2.2.0 +# or update an existing installation +opencode plugin update pantheon-opencode +``` + +--- + +## 1. Architecture Overview + +In `v2.2.0`, Pantheon runs natively inside OpenCode 2.x with zero Python runtime required for core orchestration tools and zero project-folder pollution (`AGENTS.md` or scripts copied into git only if you opt into `init`): + +- **30 Native In-Process TypeScript Tools** (`node:sqlite` FTS5 memory, checkpoints, goals, structural AST search/rewrite, codemap, Step-Ledger, isolated sub-sessions, git checkpoints, worktrees, typed review verdicts, stack detection, and agent forge) +- **14 Canonical Polyglot Agents** orchestrated via `ctx.agent.transform` +- **9 Server Commands** (`/pantheon`, `/pantheon-deepwork`, `/pantheon-audit`, `/pantheon-consolidate`, `/pantheon-focus`, `/pantheon-forge`, `/pantheon-model`, `/pantheon-optimize`, `/pantheon-vision`) +- **5 Interactive `@opentui/solid` TUI Surfaces** (`/pantheon-cockpit`, `/pantheon-artifacts`, `/pantheon-settings`, `/pantheon-updates`, `/pantheon-whats-new`) + +```mermaid +flowchart LR + User["Engineer / OpenCode 2.x TUI"] --> Server["Server Plugin (./plugin · Node)"] + User --> TUI["TUI Plugin (./tui · @opentui/solid)"] + Server --> SQL["node:sqlite FTS5 + Read-Only Repo Federation"] + Server --> AST["ast_search / ast_rewrite + LSP Bridge (tsc / Pyright / stdio / TCP Pool)"] + Server --> Ledger["pantheon_step_ledger + GIT_INDEX_FILE Checkpoints + Bugfix RED Gate"] + Server --> Orch["pantheon_worktree + execute_step (ctx.session.create) + pantheon_review_verdict"] + Server -- ".pantheon/telemetry/cockpit-events.ndjson" --> TUI + TUI --> Cockpit["/pantheon-cockpit (Overview · Swarm · Flightdeck + Replay Export)"] + TUI --> Artifacts["/pantheon-artifacts (Unicode Mermaid + Quick Links)"] + TUI --> Settings["/pantheon-settings (10 Tabs · Native Tools 30 · Legacy Cleanup)"] +``` + +![OpenCode 2.x Home Status with Pantheon v2.2.0 Cockpit Quick Link](../assets/tui/home-status.png) + +--- + +## 2. What's New & Improved Across the Release + +### 2.1 Zero-Init Native Runtime, Bundle Split & Cache Hygiene +- **Clean Server (`./plugin`) vs. TUI (`./tui`) Bundle Split:** The Node server bundle operates independently without loading `@opentui/solid`, keeping headless runs lightweight while verifying `src/plugins/tui/dist/tui.js` freshness via `prepack`, `version:check`, and `package:validate`. +- **Zero-Polluting Zero-Init:** `opencode plugin add pantheon-opencode` provisions all **14 agents**, **9 server commands**, `AGENTS.global.md`, and KV-cache-friendly session instructions purely in memory. +- **Duplicate Command & Legacy Cache Cleanup:** Eliminated the server-side duplicate `/pantheon-settings` declaration, removed the obsolete `Quotas & Spend` placeholder tab, and added `Legacy & Drift` audit/cleanup (`legacy-audit.ts`) to clean stale coexisting `~/.cache/opencode/npm/pantheon-opencode*` caches automatically. + +### 2.2 In-Process FTS5 Persistence, Shared Worktree Memory & Multi-Repo Federation +- **SQLite WAL + FTS5 Core:** `memory_store`, `memory_recall`, `memory_search`, `memory_forget`, `memory_list`, `memory_stats`, `context_save`, `context_get`, `goal_create`, `goal_get`, `goal_update`, and `goal_done` execute directly in-process with TTL support and automatic secret redaction. +- **Worktree-Shared `.pantheon/` Store:** Linked git worktrees automatically share the main repository's `.pantheon/` store (`PANTHEON_ISOLATE_WORKTREE_MEMORY=1` opts out per worktree). +- **Read-Only Multi-Repo Federation:** Configure `PANTHEON_FEDERATED_REPOS` or `~/.pantheon/federation.json` so `memory_search(federated=true)` queries peer `.pantheon/memory/memory.db` files strictly in `{ readOnly: true }` mode, tagging hits with `sourceRepo` and surfacing cross-repo counts in `memory_stats`. +- **Self-Pruning Structural Codemap:** `code_index`, `code_query`, and `code_neighbors` automatically prune deleted files from the symbol graph on query/reindex. + +### 2.3 Structural Editing (`ast_search` / `ast_rewrite`), LSP Bridge & Workspace Confinement +- **Dependency-Free Structural AST Tools:** Custom tokenizer ignores strings and comments while matching `$VAR` single-node and `$$$ARGS` variadic captures, supporting `dryRun`, strict workspace symlink confinement, and pre-write edit guardrails (`ast_rewrite` is blocked in read-only sessions). +- **Workspace-Confined `hashline_edit`:** Resolves relative paths against the active project root and blocks traversal or symlink escapes outside the repository. +- **Live Post-Edit LSP & Diff-Scoped Lint Bridge:** + - `lsp-diagnostics.ts` supports stdio LSP servers (`PANTHEON_LSP_SERVER`), **pooled reusable TCP LSP connections** (`PANTHEON_LSP_TCP_ENDPOINTS` with shared `initialize` + `didOpen` → `didChange`), `tsc --noEmit`, and `pyright --outputjson`. + - Fixed `execute-after.ts` and `plugin.ts` so `ast_rewrite` (`args.path` / `filesModified`) and relative `hashline_edit` paths resolve cleanly against workspace `cwd`, surfacing `[LSP-Diagnostics]` and diff-scoped lint in the same turn. + +### 2.4 Step-Ledger, Atomic `GIT_INDEX_FILE` Checkpoints, Sub-Sessions & Bugfix `RED` Gate +- **Zero-Touch Git Checkpoints:** Every `init_step` captures a `baselineTree` hash using an isolated temporary `GIT_INDEX_FILE` without modifying your real `.git/index` stage. +- **Automatic Rollback on Escalation:** When verification retries exhaust (`maxRetries = 2`), `ThemisReflexController` emits `themis:reflex:escalated` and `pantheon_step_ledger` automatically restores `baselineTree` (`rollback_step` is also callable on demand). +- **Isolated Sub-Session Runner (`execute_step`):** Integrated directly into `pantheon_step_ledger` using verified `@opencode/client` SDK calls (`create`, `prompt`, `wait`, `remove`) so subtasks run cleanly without bloating parent context. +- **Mechanical Bugfix `RED` Reproduction Gate:** Enforced inside `tool.execute.before` for `taskType="bugfix"` steps — blocks edits to production code (`edit`, `write`, `hashline_edit`, `ast_rewrite`, `patch`) for `@hermes` / `@talos` until `record_reproduction` records a failing test (`exitCode !== 0`), while still permitting edits to test files so the failing test can be written first. + +### 2.5 Native Worktrees, Typed Review Verdicts & `/pantheon-forge` +- **Native Worktree Orchestration (`pantheon_worktree` + `ctx.worktree.transform`):** Both the host transform hook and the tool confine isolated worktrees to `/.pantheon-worktrees//`. +- **Typed Review Verdicts (`pantheon_review_verdict`):** Records structured `APPROVE`, `APPROVE_WITH_NOTES`, and `BLOCK` verdicts. On `BLOCK`, automatically resolves `parentID` via `sessionDomain.get` and dispatches up to **2** remediation turns using valid `SessionSyntheticInput`. +- **`/pantheon-forge` Wizard & Stack Detector:** Inspects `package.json`, `pyproject.toml`, `requirements.txt`, `Cargo.toml`, and `go.mod` during both `/pantheon-forge` / `detect_stack` and `init --project` to tailor project specialist agents via `pantheon_agent_forge`. +- **Modernized 14-Agent Roster:** All canonical agents updated with permissions (`todowrite`/`todoread` preserved) and instructions for the `v2.2.0` toolset. + +--- + +## 3. TUI Experience: Mission Control Cockpit, Unicode Mermaid & Live Telemetry + +### Mission Control Cockpit (`/pantheon-cockpit` / `/cockpit`) +Press `1`–`3` or `Tab` to switch views, `Enter` to inspect subagent details, or **`x`** on Flightdeck to export a chronological Markdown replay trace (with a Mermaid `sequenceDiagram`) directly into `.pantheon/reports/`: + +1. **Overview (`1`)** — Token velocity sparkline, context meter, session spend, health counters (`Native Tools (30) active`), and ASCII topology map. +2. **Swarm (`2`)** — Active/done/failed subagent counts, per-agent cost summary, and concurrent Gantt timeline. +3. **Flightdeck (`3`)** — Visual `GATE` matrix (`allowed` / `receipts` / `active` / `blocked`), Step-Ledger list, real-time cross-process telemetry bus from `.pantheon/telemetry/cockpit-events.ndjson`, and **`x` Export Replay Trace**. + +![Pantheon Cockpit Overview showing Native Tools (30) and runtime topology](../assets/tui/cockpit-overview.png) + +![Pantheon Cockpit Swarm Gantt timeline and per-agent cost breakdown](../assets/tui/cockpit-swarm.png) + +![Pantheon Cockpit Flightdeck Gate Matrix, Step-Ledger, Semantic Event Stream and Export Replay Trace](../assets/tui/cockpit-flightdeck.png) + +### Interactive Artifact Reader, Sidebar Counters & Settings +- **Artifact Viewer (`/pantheon-artifacts` / `/artifacts`):** Renders Mermaid `flowchart`, `graph`, `sequenceDiagram`, and `stateDiagram` blocks as crisp Unicode terminal boxes, accessible via clickable Home/Sidebar badges (`▸ Plan:`, `◈ Artefatos (N)`, `◈ Cockpit`). +- **Live Sidebar Telemetry & Update Alerts:** Displays domain counters (`mem`/`ctx`/`code`), active child verbs, `?`/`!` attention badges, and non-intrusive `↑ vX.Y.Z` update notifications. +- **Settings (`/pantheon-settings`):** Shows `Native Tools (30)` in **About**, fixes `Tab` switching when opened from Home, expands **What's New** cards, and automates stale npm cache cleanup. + +![Pantheon Artifact Reader rendering Unicode Mermaid flowchart directly in OpenCode TUI](../assets/tui/artifacts-reader.png) + +![OpenCode Session Sidebar showing live domain counters, Dispatch telemetry, and Pantheon v2.2.0 Settings About view](../assets/tui/settings-about.png) + +--- + +## 4. Practical Workflow Benefits + +| Area | Before (`2.1.x` / early `2.2-beta`) | Now (`v2.2.0` GA) | Concrete Impact | +|---|---|---|---| +| **Setup & Cleanliness** | Copied files into project repos and relied on Python MCP setup | Zero-Init via `opencode plugin add pantheon-opencode` | **Zero git noise** and instant startup in any repo or worktree | +| **Refactor Safety** | Text search + manual edits could match comments or leave workspace bounds | `ast_search`/`ast_rewrite` + confined `hashline_edit` + inline LSP/lint | **Fewer silent regressions**: type & lint errors fixed in the same turn | +| **Bugfix Discipline** | Agents could patch production code before proving the bug failed | Mechanical `RED` gate blocks prod code edits until `record_reproduction` fails | **Structural TDD enforcement** without slowing down test authoring | +| **Rollback Guarantees** | Multi-step failures left dirty working trees to untangle by hand | Per-step `GIT_INDEX_FILE` tree snapshots + auto-rollback on escalation | **Deterministic recovery** without touching your staged git index | +| **Context Efficiency** | Subagents ran inline and knowledge stayed siloed per repo | `execute_step` isolated sub-sessions + read-only `memory_search(federated)` | **Lower token burn** and instant recall across peer repositories | +| **Terminal Visibility** | No live concurrency Gantt, gate matrix, or diagram preview in TUI | `/pantheon-cockpit` (`1–3`) + `x` replay export + `/pantheon-artifacts` Mermaid | **Real-time auditability & observability** without leaving the terminal | + +--- + +## 5. Upgrading & Documentation + +- **Quickstart & Installation:** [Installation Guide](../INSTALLATION.md) · [Quickstart](../QUICKSTART.md) · [OpenCode 2.x Integration](../opencode.md) +- **Cockpit, Settings & Artifacts:** [Settings Guide](../SETTINGS.md) · [Artifacts Guide](../ARTIFACTS.md) · [Architecture](../ARCHITECTURE.md) +- **Release Highlights Archive:** [v2.x Highlights](./highlights.md) diff --git a/package-lock.json b/package-lock.json index 366f532a..d64ea7fb 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "pantheon-opencode", - "version": "2.2.0-beta.11", + "version": "2.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "pantheon-opencode", - "version": "2.2.0-beta.11", + "version": "2.2.0", "hasInstallScript": true, "license": "MIT", "workspaces": [ @@ -8982,7 +8982,7 @@ }, "src/plugins/tui": { "name": "pantheon-tui", - "version": "2.2.0-beta.11", + "version": "2.2.0", "license": "MIT", "dependencies": { "@opencode/plugin": "2.0.26", diff --git a/package.json b/package.json index b2a9a3e9..42b04be1 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "pantheon-opencode", - "version": "2.2.0-beta.11", + "version": "2.2.0", "description": "Multi-agent orchestration for OpenCode \u2014 14 specialized agents, TDD, Themis review gates.", "type": "module", "workspaces": [ @@ -36,7 +36,7 @@ "init": "node bin/pantheon-init.mjs init --yes", "opencode": "OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS=true opencode", "start": "OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS=true opencode", - "prepack": "npm run build:plugin && npm run check:decision-router && npm run check:roster", + "prepack": "npm run build:plugin && npm run check:decision-router && npm run check:roster && npm run version:check", "prepublishOnly": "node scripts/validate-routing.mjs && npm run build:plugin && npm run check:decision-router && npm run check:roster", "postpublish": "node -e \"console.log('\u2705 Published pantheon-opencode v' + require('./package.json').version + ' to npm')\"", "version:status": "node scripts/versioning.mjs status", diff --git a/plugin.json b/plugin.json index 5c9edc4b..cdbcf153 100644 --- a/plugin.json +++ b/plugin.json @@ -1,7 +1,7 @@ { "name": "pantheon", "publisher": "ils15", - "version": "2.2.0-beta.11", + "version": "2.2.0", "displayName": "Pantheon", "description": "Conductor-Delegate orchestration platform with 14 specialized agents, 25 skills, and OpenCode support.", "agents": "./src/agents", diff --git a/pyproject.toml b/pyproject.toml index eca5ba39..9205903f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.backends._legacy:_Backend" [project] name = "pantheon" -version = "2.2.0-beta.11" +version = "2.2.0" description = "Multi-agent orchestration framework" requires-python = ">=3.11" # Python sources under src/mcp/ import fastmcp/pydantic at runtime, but those diff --git a/scripts/package-evidence.mjs b/scripts/package-evidence.mjs index 6913f3aa..63c6a2dc 100644 --- a/scripts/package-evidence.mjs +++ b/scripts/package-evidence.mjs @@ -147,6 +147,15 @@ function validatePayload(packageRoot, inventory) { if (sha256(sourcePath) !== sha256(packagedPath)) fail(`published package payload differs from source: ${entry.file}`) } + const tuiBundle = readFileSync(join(packageRoot, 'src/plugins/tui/dist/tui.js'), 'utf8') + if ( + tuiBundle.includes('Pantheon v') && + !tuiBundle.includes(`Pantheon v${inventory.sourceVersion}`) + ) { + fail( + `src/plugins/tui/dist/tui.js embeds a stale version (expected Pantheon v${inventory.sourceVersion})`, + ) + } } function collectLockfileEvidence(inventory, entries, packageRoot) { diff --git a/scripts/postinstall.mjs b/scripts/postinstall.mjs index c3e0b74a..12927956 100755 --- a/scripts/postinstall.mjs +++ b/scripts/postinstall.mjs @@ -28,12 +28,13 @@ try { console.log(' Pantheon OpenCode — npm dependencies installed ✅') console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━') console.log('') - console.log(' Next steps:') - console.log(' 1. Configure Pantheon:') - console.log(' npm run setup') - console.log(' # or: npx pantheon-opencode init') - console.log(' 2. Verify installation:') - console.log(' npm run doctor') + console.log(' Next steps (OpenCode 2.x):') + console.log(' 1. Register the native plugin (works in any folder, no init needed):') + console.log(' opencode plugin add pantheon-opencode') + console.log(' 2. Check health, updates & clean stale caches inside OpenCode:') + console.log(' /pantheon-settings (or: npx pantheon-opencode doctor)') + console.log(' 3. Optional CLI setup (project AGENTS.md / legacy Python MCP):') + console.log(' npx pantheon-opencode init --project --no-mcp') console.log('') } } catch (err) { diff --git a/scripts/release-body.mjs b/scripts/release-body.mjs new file mode 100644 index 00000000..eb585042 --- /dev/null +++ b/scripts/release-body.mjs @@ -0,0 +1,212 @@ +#!/usr/bin/env node +/** + * release-body.mjs — compose GitHub Release notes from optional curated release docs + * plus the canonical CHANGELOG.md section. + * + * Usage: + * node scripts/release-body.mjs --version 2.2.0 --channel stable \ + * --changelog-notes release-notes.md --repo owner/name --ref v2.2.0 --out release-notes.md + */ + +import { existsSync, readFileSync, writeFileSync } from 'node:fs' +import { dirname, join, relative, resolve } from 'node:path' +import { fileURLToPath, pathToFileURL } from 'node:url' + +const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..') +const DEFAULT_RELEASES_DIR = join(ROOT, 'docs', 'releases') +const EXTERNAL_URL_RE = /^(?:[a-z][a-z0-9+.-]*:|\/\/|#)/i +const FENCE_RE = /^\s*(`{3,}|~{3,})/ +const INLINE_LINK_RE = /(!?)\[([^\]]*)\]\(([^)\n]+)\)/g + +function toPosixRelative(fromDir, rootDir, targetPath) { + const abs = resolve(fromDir, targetPath) + const rel = relative(rootDir, abs).replace(/\\/g, '/') + if (!rel || rel.startsWith('..')) return null + return rel +} + +function splitTargetAndTitle(rawTarget) { + const trimmed = rawTarget.trim() + const titleMatch = /^(\S+)(\s+["'(].*)$/.exec(trimmed) + if (titleMatch) { + return { dest: titleMatch[1], suffix: titleMatch[2] } + } + return { dest: trimmed, suffix: '' } +} + +function rewriteSegmentUrls(segment, sourceDir, repoRoot, repo, ref) { + return segment.replace(INLINE_LINK_RE, (full, bang, label, rawTarget) => { + const { dest, suffix } = splitTargetAndTitle(rawTarget) + if (!dest || EXTERNAL_URL_RE.test(dest)) return full + const hashIdx = dest.indexOf('#') + const pathPart = hashIdx === -1 ? dest : dest.slice(0, hashIdx) + const fragment = hashIdx === -1 ? '' : dest.slice(hashIdx) + if (!pathPart) return full + + const repoRel = toPosixRelative(sourceDir, repoRoot, pathPart) + if (!repoRel) return full + + const encodedPath = repoRel.split('/').map(encodeURIComponent).join('/') + const baseUrl = + bang === '!' + ? `https://raw.githubusercontent.com/${repo}/${ref}/${encodedPath}` + : `https://github.com/${repo}/blob/${ref}/${encodedPath}${fragment}` + return `${bang}[${label}](${baseUrl}${suffix})` + }) +} + +function rewriteLineOutsideInlineCode(line, sourceDir, repoRoot, repo, ref) { + const parts = line.split(/(`[^`\n]*`)/g) + return parts + .map((part) => + part.startsWith('`') && part.endsWith('`') + ? part + : rewriteSegmentUrls(part, sourceDir, repoRoot, repo, ref), + ) + .join('') +} + +/** + * Rewrite relative Markdown links & images in a curated release doc into absolute + * GitHub blob/raw URLs bound to `ref`, leaving code blocks and inline code intact. + */ +export function rewriteReleaseDocUrls(markdown, { sourceDir, repoRoot, repo, ref }) { + const lines = String(markdown).split(/\r?\n/) + const out = [] + let inFence = false + let fenceChar = '' + + for (const line of lines) { + const fenceMatch = FENCE_RE.exec(line) + if (fenceMatch) { + const char = fenceMatch[1][0] + if (!inFence) { + inFence = true + fenceChar = char + } else if (char === fenceChar) { + inFence = false + } + out.push(line) + continue + } + out.push(inFence ? line : rewriteLineOutsideInlineCode(line, sourceDir, repoRoot, repo, ref)) + } + + return out.join('\n') +} + +/** + * Compose the GitHub Release body. + * + * Only non-recovery stable releases with an existing `docs/releases/vX.Y.Z.md` + * expand into the curated release page + canonical changelog ledger; all other + * invocations preserve `changelogNotes` verbatim. + */ +export function composeReleaseBody({ + version, + channel = 'stable', + recovery = false, + changelogNotes, + repoRoot = ROOT, + releasesDir = DEFAULT_RELEASES_DIR, + repo = 'ils15/pantheon-opencode', + ref, +}) { + const normalized = String(version ?? '') + .trim() + .replace(/^v/i, '') + const canonical = `${String(changelogNotes ?? '').trim()}\n` + if (!normalized || recovery || channel === 'beta') { + return canonical + } + + const releaseDocPath = join(releasesDir, `v${normalized}.md`) + if (!existsSync(releaseDocPath)) { + return canonical + } + + const effectiveRef = ref || `v${normalized}` + const curated = rewriteReleaseDocUrls(readFileSync(releaseDocPath, 'utf8'), { + sourceDir: releasesDir, + repoRoot, + repo, + ref: effectiveRef, + }).trim() + + return [ + curated, + '', + '---', + '', + '
', + `Full Keep a Changelog Ledger (v${normalized})`, + '', + canonical.trim(), + '', + '
', + '', + ].join('\n') +} + +function parseArgs(argv) { + const opts = { + channel: 'stable', + recovery: false, + repoRoot: ROOT, + releasesDir: DEFAULT_RELEASES_DIR, + repo: 'ils15/pantheon-opencode', + } + for (let i = 0; i < argv.length; i += 1) { + const arg = argv[i] + if (arg === '--recovery') { + opts.recovery = true + continue + } + const next = argv[i + 1] + if (arg === '--version') { + opts.version = next + i += 1 + } else if (arg === '--channel') { + opts.channel = next + i += 1 + } else if (arg === '--changelog-notes') { + opts.changelogNotesPath = next + i += 1 + } else if (arg === '--repo-root') { + opts.repoRoot = next + i += 1 + } else if (arg === '--releases-dir') { + opts.releasesDir = next + i += 1 + } else if (arg === '--repo') { + opts.repo = next + i += 1 + } else if (arg === '--ref') { + opts.ref = next + i += 1 + } else if (arg === '--out') { + opts.out = next + i += 1 + } + } + return opts +} + +const isDirectRun = process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href + +if (isDirectRun) { + const opts = parseArgs(process.argv.slice(2)) + if (!opts.version || !opts.changelogNotesPath) { + console.error( + 'Usage: node scripts/release-body.mjs --version --changelog-notes [--channel stable|beta] [--recovery] [--repo ] [--ref ] [--out ]', + ) + process.exit(2) + } + const changelogNotes = readFileSync(opts.changelogNotesPath, 'utf8') + const composed = composeReleaseBody({ ...opts, changelogNotes }) + if (opts.out) { + writeFileSync(opts.out, composed, 'utf8') + } else { + process.stdout.write(composed) + } +} diff --git a/scripts/stack-detector.mjs b/scripts/stack-detector.mjs new file mode 100644 index 00000000..dd1d5df0 --- /dev/null +++ b/scripts/stack-detector.mjs @@ -0,0 +1,174 @@ +/** + * Deterministic Polyglot Stack Auto-Detector (`stack-detector.mjs`). + * + * Inspects workspace manifests (`package.json`, `pyproject.toml`, `requirements.txt`, + * `Cargo.toml`, `go.mod`) and recommends tailored project specialists and + * domain convention docs for `/pantheon-forge` and `pantheon-init`. + */ + +import { existsSync, readFileSync } from 'node:fs' +import { join, resolve } from 'node:path' + +/** + * Inspect workspace manifests and return detected stacks and specialist suggestions. + * @param {string} workspaceDir + */ +export function detectRepositoryStacks(workspaceDir) { + const root = resolve(workspaceDir) + const stacks = [] + const suggestedSpecialists = [] + const suggestedDocs = new Set() + + // 1. Node.js / TypeScript + const pkgPath = join(root, 'package.json') + if (existsSync(pkgPath)) { + try { + const pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) + const deps = { ...pkg.dependencies, ...pkg.devDependencies } + const frameworks = [] + for (const fw of [ + 'typescript', + 'react', + 'next', + 'solid-js', + 'vue', + 'fastify', + 'express', + 'hono', + 'prisma', + ]) { + if (fw in deps) frameworks.push(fw) + } + const testRunner = + 'vitest' in deps + ? 'npx vitest run' + : 'jest' in deps + ? 'npx jest' + : pkg.scripts?.test + ? 'npm test' + : 'node --test' + const linter = 'biome' in deps || '@biomejs/biome' in deps ? 'npx biome check' : 'npx eslint' + stacks.push({ + id: 'node-typescript', + manifest: 'package.json', + frameworks, + testRunner, + linter, + }) + const uiFrameworks = frameworks.filter((f) => + ['react', 'next', 'solid-js', 'vue'].includes(f), + ) + if (uiFrameworks.length > 0) { + suggestedSpecialists.push({ + name: 'frontend-ui-specialist', + archetype: 'frontend', + description: `UI/component specialist tailored to ${uiFrameworks.join(', ')}`, + stack: ['TypeScript', ...frameworks], + testCommand: testRunner, + suggestedDocs: ['src/instructions/', 'tsconfig.json'], + }) + } else { + suggestedSpecialists.push({ + name: 'node-service-specialist', + archetype: 'backend', + description: `Node/TypeScript backend specialist using ${testRunner}`, + stack: ['Node.js', 'TypeScript', ...frameworks], + testCommand: testRunner, + suggestedDocs: ['tsconfig.json', 'package.json'], + }) + } + suggestedDocs.add('package.json') + } catch { + /* ignore malformed package.json */ + } + } + + // 2. Python + const pyProjPath = join(root, 'pyproject.toml') + const reqPath = join(root, 'requirements.txt') + if (existsSync(pyProjPath) || existsSync(reqPath)) { + const rawPy = [ + existsSync(pyProjPath) ? readFileSync(pyProjPath, 'utf8') : '', + existsSync(reqPath) ? readFileSync(reqPath, 'utf8') : '', + ] + .join('\n') + .toLowerCase() + const frameworks = [] + for (const fw of ['fastapi', 'django', 'flask', 'sqlalchemy', 'pydantic', 'pytest']) { + if (rawPy.includes(fw)) frameworks.push(fw) + } + const testRunner = rawPy.includes('pytest') ? 'pytest -q' : 'python3 -m unittest' + const linter = rawPy.includes('ruff') ? 'ruff check' : 'pyright' + const pyManifest = existsSync(pyProjPath) ? 'pyproject.toml' : 'requirements.txt' + stacks.push({ + id: 'python', + manifest: pyManifest, + frameworks, + testRunner, + linter, + }) + suggestedSpecialists.push({ + name: 'python-api-specialist', + archetype: frameworks.includes('sqlalchemy') ? 'data' : 'backend', + description: `Python specialist tailored to ${frameworks.join(', ') || 'pyproject.toml'}`, + stack: ['Python', ...frameworks], + testCommand: testRunner, + suggestedDocs: [pyManifest], + }) + suggestedDocs.add(pyManifest) + } + + // 3. Go + const goModPath = join(root, 'go.mod') + if (existsSync(goModPath)) { + const rawGo = readFileSync(goModPath, 'utf8').toLowerCase() + const frameworks = ['gin', 'echo', 'fiber', 'chi'].filter((fw) => rawGo.includes(fw)) + stacks.push({ + id: 'go', + manifest: 'go.mod', + frameworks, + testRunner: 'go test ./...', + linter: 'gofmt / go vet', + }) + suggestedSpecialists.push({ + name: 'go-systems-specialist', + archetype: 'backend', + description: `Go service & concurrency specialist (${frameworks.join(', ') || 'stdlib'})`, + stack: ['Go', ...frameworks], + testCommand: 'go test ./...', + suggestedDocs: ['go.mod'], + }) + suggestedDocs.add('go.mod') + } + + // 4. Rust + const cargoPath = join(root, 'Cargo.toml') + if (existsSync(cargoPath)) { + const rawCargo = readFileSync(cargoPath, 'utf8').toLowerCase() + const frameworks = ['tokio', 'axum', 'actix-web', 'serde', 'sqlx'].filter((fw) => + rawCargo.includes(fw), + ) + stacks.push({ + id: 'rust', + manifest: 'Cargo.toml', + frameworks, + testRunner: 'cargo test', + linter: 'cargo clippy', + }) + suggestedSpecialists.push({ + name: 'rust-core-specialist', + archetype: 'backend', + description: `Rust systems & safety specialist (${frameworks.join(', ') || 'Cargo'})`, + stack: ['Rust', ...frameworks], + testCommand: 'cargo test', + suggestedDocs: ['Cargo.toml'], + }) + suggestedDocs.add('Cargo.toml') + } + + return { + stacks, + suggestedSpecialists, + suggestedDocs: Array.from(suggestedDocs), + } +} diff --git a/scripts/update.mjs b/scripts/update.mjs index 3688a4fb..7cadc34d 100644 --- a/scripts/update.mjs +++ b/scripts/update.mjs @@ -93,7 +93,7 @@ export function runUpdate( ) { console.error( '[ERROR] update is available only from the global Pantheon installation; local, workspace, and npx copies are refused. ' + - 'Install globally with `npm install -g pantheon-opencode@beta`, then run `pantheon-opencode update`.', + 'For OpenCode 2.x native installs run `opencode plugin update pantheon-opencode`; for legacy global CLI installs run `npm install -g pantheon-opencode`, then `pantheon-opencode update`.', ) return 1 } diff --git a/scripts/version-check.mjs b/scripts/version-check.mjs index 51aa5bbc..0a10a6d5 100644 --- a/scripts/version-check.mjs +++ b/scripts/version-check.mjs @@ -1,7 +1,7 @@ #!/usr/bin/env node /** Fail-closed version and lockfile validation. */ -import { readFileSync } from 'node:fs' +import { existsSync, readFileSync } from 'node:fs' import { join } from 'node:path' import { pathToFileURL } from 'node:url' import { @@ -100,6 +100,15 @@ export function compareVersions(root) { } catch (error) { errors.push(error.message) } + const tuiBundlePath = join(root, 'src', 'plugins', 'tui', 'dist', 'tui.js') + if (source !== null && existsSync(tuiBundlePath)) { + const tuiBundle = readFileSync(tuiBundlePath, 'utf8') + if (tuiBundle.includes('Pantheon v') && !tuiBundle.includes(`Pantheon v${source}`)) { + errors.push( + `src/plugins/tui/dist/tui.js: embedded version is stale (expected Pantheon v${source}; run npm --prefix src/plugins/tui run build)`, + ) + } + } return { source, manifests, diff --git a/skills-lock.json b/skills-lock.json index b2c2ea46..982aa860 100644 --- a/skills-lock.json +++ b/skills-lock.json @@ -1,8 +1,8 @@ { "src/skills/agent-coordination/SKILL.md": "0b002b322c2b35bf11bc3beb56de37a9614311d3883f0fa399f6dcbc5c8758af", "src/skills/agent-forge/SKILL.md": "cbe09946a59fa45b471828d9de6e7bc5c4b2fa29e0ce48e21d188593ece6c046", - "src/skills/artifact-management/references/artifact-templates.md": "d1a5d082266311c362e63e097f461fe993a4eac7485c4a445fba7993c404e1c7", - "src/skills/artifact-management/SKILL.md": "d11bc6a9968758294bd9ae56dfa8df43090c5f1f7c4f706861687d8ac3bb88a2", + "src/skills/artifact-management/references/artifact-templates.md": "5ed2154cf3f939bb4330fabeaa2b0f4d40ef1089cf86f3703fcae79dcb702696", + "src/skills/artifact-management/SKILL.md": "e59982d1c4b74617a6cd4f7882f1f26e70a52e98d9c3244aba4d4de725387d81", "src/skills/auto-continue/references/auto-continue-details.md": "9fcac10a664f41439f234d1ded98b8976fdc3db5755e88f7ad89f3409fdb14d8", "src/skills/auto-continue/SKILL.md": "7bfddd84f96b657043074a35ef2f524913ccbed2689fc8a26ad425167f4b77c5", "src/skills/clonedeps/SKILL.md": "3e0b43cf96da98c83699dc48db3fd58fbfda84b9022bb70d3747875c81c3e124", @@ -13,10 +13,10 @@ "src/skills/fast-path-execution/SKILL.md": "040bb97ac5d930dcee47d5d0e2fc1ef637a4762998990475d876ec7f17977c69", "src/skills/git-workflow-and-versioning/SKILL.md": "685a94041f1b4ce2a430301f517b89102055696267c369a7e8fb191606659276", "src/skills/incremental-implementation/SKILL.md": "28157b3cbb728055d4298ed54e02b7e9c93f13da7bd39ec0bb8806eb96803e03", - "src/skills/instruction-forge/references/agents-md-doctrine.md": "23623cc40e830ba5f2f11b7b005e85b3f4d260428f1c31cb9840e7b9baa81360", + "src/skills/instruction-forge/references/agents-md-doctrine.md": "029fce667edc332b76fa4f1076f51ad4f9726f2242469f53c2c724fb395757c4", "src/skills/instruction-forge/references/eval-doctrine.md": "87412d9c9afb16a0cc9eab145df45518805d0e967fe736d65bae9f5cd6a19782", "src/skills/instruction-forge/references/skill-doctrine.md": "9ad4f1c249595f934bd6397afd36017a6a61068c1c21ee0bee11952cb14dc4a1", - "src/skills/instruction-forge/SKILL.md": "e6d45074f959033359010c936346d6718c50b4700e98566bf9ca6ab36bd60951", + "src/skills/instruction-forge/SKILL.md": "c8494b9eac42e24c057739da5ea41d51b919ffbaa012bf713879084e617cb675", "src/skills/loop-engineering/SKILL.md": "f804e545821b9cca8fe0ec517307ed902446f28c2ca8ff9194c0f987cf7229e3", "src/skills/memory-bank/references/anti-patterns.md": "f44615f724ba4fcf43035dd43693b2629ba2005d1402a08f916178c4505ee66e", "src/skills/memory-bank/references/product-adoption.md": "56a0608d757090e51596e484a8a9fb0cc72c9ca3b204afb803fbec4a993acd3d", diff --git a/src/agents/apollo.md b/src/agents/apollo.md index bc686ea9..fe36ca65 100644 --- a/src/agents/apollo.md +++ b/src/agents/apollo.md @@ -11,6 +11,8 @@ permission: webfetch: allow edit: deny hashline_edit: deny + ast_rewrite: deny + pantheon_worktree: deny shell: deny bash: deny task: @@ -64,7 +66,7 @@ skills: ## Discovery Rules & Boundaries -- **Strictly read-only scout**: search with grep/glob/read and `pantheon-memory` (`memory_search`, `code_query`). Never modify files, never run shell commands. +- **Strictly read-only scout**: search with grep/glob/read, `ast_search`, and `pantheon-memory` (`memory_search` including cross-repo `federated`, `code_query`). Never modify files, never run shell commands. - **Search order**: session context first, direct targeted searches second. Batch independent queries only when discovery scope benefits from parallel search. - **Search Scope & Permissions**: - **Permitted targets**: Targeted searches and reads across codebase files (`src/`, `tests/`, `docs/`, etc.), the `.pantheon/` folder (`.pantheon/**`, including deepwork plans, memory-bank, reports, and code-mode scripts), and active worktrees (`.pantheon-worktrees/**`) are fully permitted without restriction whenever relevant to the task or requested by the user. diff --git a/src/agents/athena.md b/src/agents/athena.md index 8a8e7229..cd6dafff 100644 --- a/src/agents/athena.md +++ b/src/agents/athena.md @@ -6,6 +6,8 @@ reasoning_effort: medium permission: edit: deny hashline_edit: deny + ast_rewrite: deny + pantheon_worktree: deny shell: deny bash: deny read: allow diff --git a/src/agents/gaia.md b/src/agents/gaia.md index 916a355a..833b5bff 100644 --- a/src/agents/gaia.md +++ b/src/agents/gaia.md @@ -10,6 +10,8 @@ permission: webfetch: allow edit: deny hashline_edit: deny + ast_rewrite: deny + pantheon_worktree: deny shell: deny bash: deny task: diff --git a/src/agents/hermes.md b/src/agents/hermes.md index a2426caf..1c9760de 100644 --- a/src/agents/hermes.md +++ b/src/agents/hermes.md @@ -166,7 +166,7 @@ See `skill: tdd-with-agents` for the full TDD cycle. ## Implementation & Verification Workflow 1. **Focused Context**: Inspect targeted files directly using `grep`, `glob`, and `read`. When the brief specifies a skill (or a relevant project skill exists in `.opencode/skills/`), **read its `SKILL.md` first** before implementing. -2. **Implementation**: Implement clean async endpoints and services using Pydantic schemas, dependency injection, and parameterized queries. +2. **Implementation**: Implement clean async endpoints and services using Pydantic schemas, dependency injection, and parameterized queries. Prefer `ast_search`/`ast_rewrite` for structural multi-match refactors. On `taskType="bugfix"` ledger steps, record a failing `RED` probe/test first via `pantheon_step_ledger(action="record_reproduction", stepKey=..., command=..., exitCode=1)` before editing production files. 3. **Verification**: Run focused unit tests via `bash` using test slicing (e.g. `pytest tests/test_item.py -k test_create -q --tb=short`). Never run full unbounded repository suites during implementation loops. 4. **Dependencies**: Use modern stdlib equivalents (`zoneinfo`, `tomllib`) where applicable; pin stable LTS versions. diff --git a/src/agents/roster.json b/src/agents/roster.json index b02ff220..1129eddd 100644 --- a/src/agents/roster.json +++ b/src/agents/roster.json @@ -69,6 +69,8 @@ "webfetch": "allow", "edit": "deny", "hashline_edit": "deny", + "ast_rewrite": "deny", + "pantheon_worktree": "deny", "shell": "deny", "bash": "deny", "task": { @@ -78,7 +80,7 @@ "todoread": "allow", "execute": "deny" }, - "body": "## When NOT to Use Apollo\n- When you already know the exact file path — read it directly\n- When you need to modify files — Apollo is read-only\n- When the search can be done with a simple grep/glob — use direct tools instead\n\n## MCP governance (identical ladder, grant-aware)\n\n- Escalation order: session context first; the local selector answers free;\n one typed `pantheon_jev_decide` question when genuinely ambiguous (Zeus\n dispatches; a returned label is an advisory, never authorization); a\n native MCP call is the LAST resort for state the session cannot\n reconstruct.\n- **Memory recall/search** — at most one selective query per turn, only when\n prior project history could change the decision; never for context you\n already hold. Every result rides in your context for the rest of the\n session.\n- **Memory store** (only where granted) — durable, reusable facts ONLY:\n decisions with reasons, root causes, conventions, user preferences.\n Session narration never stores: subtask summaries, delegation status and\n debugging play-by-play go to a checkpoint or nowhere. Namespace per\n project; update an existing key instead of duplicating.\n- **Persistence checkpoints** (only where granted) — milestones only: would\n losing this be expensive to redo? Never per turn; never re-save an\n unchanged key.\n- **Vision** (only where granted) — only when the turn carries an\n addressable image; one pass per image; each call is real gateway spend.\n- **Code-mode / infrastructure reads** — cheap and on demand; never for\n decisions the ladder already answers.\n\n## Discovery Rules & Boundaries\n\n- **Strictly read-only scout**: search with grep/glob/read and `pantheon-memory` (`memory_search`, `code_query`). Never modify files, never run shell commands.\n- **Search order**: session context first, direct targeted searches second. Batch independent queries only when discovery scope benefits from parallel search.\n- **Search Scope & Permissions**:\n - **Permitted targets**: Targeted searches and reads across codebase files (`src/`, `tests/`, `docs/`, etc.), the `.pantheon/` folder (`.pantheon/**`, including deepwork plans, memory-bank, reports, and code-mode scripts), and active worktrees (`.pantheon-worktrees/**`) are fully permitted without restriction whenever relevant to the task or requested by the user.\n - **Excluded noise**: Avoid broad, unbounded recursive scans across `.git/**` or `node_modules/**`.\n- **External research**: Use configured web search MCP or `webfetch` for documentation URLs. Never invent citations.\n- **Output format**: Return hierarchical structured findings (`files_changed`, `summary`, `confidence`). No raw dumps." + "body": "## When NOT to Use Apollo\n- When you already know the exact file path — read it directly\n- When you need to modify files — Apollo is read-only\n- When the search can be done with a simple grep/glob — use direct tools instead\n\n## MCP governance (identical ladder, grant-aware)\n\n- Escalation order: session context first; the local selector answers free;\n one typed `pantheon_jev_decide` question when genuinely ambiguous (Zeus\n dispatches; a returned label is an advisory, never authorization); a\n native MCP call is the LAST resort for state the session cannot\n reconstruct.\n- **Memory recall/search** — at most one selective query per turn, only when\n prior project history could change the decision; never for context you\n already hold. Every result rides in your context for the rest of the\n session.\n- **Memory store** (only where granted) — durable, reusable facts ONLY:\n decisions with reasons, root causes, conventions, user preferences.\n Session narration never stores: subtask summaries, delegation status and\n debugging play-by-play go to a checkpoint or nowhere. Namespace per\n project; update an existing key instead of duplicating.\n- **Persistence checkpoints** (only where granted) — milestones only: would\n losing this be expensive to redo? Never per turn; never re-save an\n unchanged key.\n- **Vision** (only where granted) — only when the turn carries an\n addressable image; one pass per image; each call is real gateway spend.\n- **Code-mode / infrastructure reads** — cheap and on demand; never for\n decisions the ladder already answers.\n\n## Discovery Rules & Boundaries\n\n- **Strictly read-only scout**: search with grep/glob/read, `ast_search`, and `pantheon-memory` (`memory_search` including cross-repo `federated`, `code_query`). Never modify files, never run shell commands.\n- **Search order**: session context first, direct targeted searches second. Batch independent queries only when discovery scope benefits from parallel search.\n- **Search Scope & Permissions**:\n - **Permitted targets**: Targeted searches and reads across codebase files (`src/`, `tests/`, `docs/`, etc.), the `.pantheon/` folder (`.pantheon/**`, including deepwork plans, memory-bank, reports, and code-mode scripts), and active worktrees (`.pantheon-worktrees/**`) are fully permitted without restriction whenever relevant to the task or requested by the user.\n - **Excluded noise**: Avoid broad, unbounded recursive scans across `.git/**` or `node_modules/**`.\n- **External research**: Use configured web search MCP or `webfetch` for documentation URLs. Never invent citations.\n- **Output format**: Return hierarchical structured findings (`files_changed`, `summary`, `confidence`). No raw dumps." }, "athena": { "name": "athena", @@ -103,6 +105,8 @@ "permission": { "edit": "deny", "hashline_edit": "deny", + "ast_rewrite": "deny", + "pantheon_worktree": "deny", "shell": "deny", "bash": "deny", "read": "allow", @@ -175,6 +179,8 @@ "webfetch": "allow", "edit": "deny", "hashline_edit": "deny", + "ast_rewrite": "deny", + "pantheon_worktree": "deny", "shell": "deny", "bash": "deny", "task": { @@ -262,7 +268,7 @@ "todoread": "allow", "execute": "allow" }, - "body": "\n## Strict Test Slicing Mandate\n\n- **Targeted Slices Only:** In TDD loops, run ONLY the test slice for the changed file (`pytest tests/test_.py -k `, `node --test tests/.test.mjs`).\n- **NEVER RUN `npm test`:** Unconstrained suites destroy execution speed and blow context windows.\n\n# Hermes - Polyglot Backend & API Executor (TypeScript/Node, Python/FastAPI, Go, Rust)\n\n## When NOT to Use Hermes\n- For database schema changes — that's @demeter\n- For frontend UI work — that's @aphrodite\n- For hotfixes or typos — use @talos\n- For infrastructure or Docker — use @prometheus\n\nYou are the **BACKEND TASK IMPLEMENTER** (Hermes) called by Zeus to implement FastAPI endpoints, services, and routers. Execute clear, bounded changes directly: inspect only relevant context using `grep`, `glob`, and `read`, implement changes using `edit`, verify the changed behavior using `bash`, and summarize. Use a plan when the scope, risk, or ambiguity warrants one; apply RED→GREEN→REFACTOR to testable behavior changes.\n\n## MCP governance (identical ladder, grant-aware)\n\n- Escalation order: session context first; the local selector answers free;\n one typed `pantheon_jev_decide` question when genuinely ambiguous (Zeus\n dispatches; a returned label is an advisory, never authorization); a\n native MCP call is the LAST resort for state the session cannot\n reconstruct.\n- **Memory recall/search** — at most one selective query per turn, only when\n prior project history could change the decision; never for context you\n already hold. Every result rides in your context for the rest of the\n session.\n- **Memory store** (only where granted) — durable, reusable facts ONLY:\n decisions with reasons, root causes, conventions, user preferences.\n Session narration never stores: subtask summaries, delegation status and\n debugging play-by-play go to a checkpoint or nowhere. Namespace per\n project; update an existing key instead of duplicating.\n- **Persistence checkpoints** (only where granted) — milestones only: would\n losing this be expensive to redo? Never per turn; never re-save an\n unchanged key.\n- **Vision** (only where granted) — only when the turn carries an\n addressable image; one pass per image; each call is real gateway spend.\n- **Code-mode / infrastructure reads** — cheap and on demand; never for\n decisions the ladder already answers.\n\n## Core Capabilities\n\n### 1. **Test-Driven Development**\nSee `skill: tdd-with-agents` for the full TDD cycle.\n\n### 2. **Context Conservation**\n- Focus ONLY on files you're modifying\n- Don't re-read entire project architecture\n- Return summaries of your changes\n- Ask the Orchestrator only when missing context or a material choice blocks safe progress\n\n### 3. **Proper Handoffs**\n- Use a supplied plan when one exists; do not require one for bounded work\n- Ask a clarifying question only when ambiguity blocks a safe implementation\n- Return clear, structured results\n- Report readiness for next phase\n\n### 4. **Parallel Execution Mode**\n- Zeus may dispatch @aphrodite and @demeter in parallel on independent scopes; a Hermes child session works only its assigned scope and reports coordination needs to Zeus\n- Your scope: backend files only (routers, services, tests)\n- Signal clearly when done; preserve Themis review for security/auth, data/schema, and material changes\n- Do NOT wait for other workers to finish before starting your work\n\n## Search Policy\n- Investigate beyond the assigned context only when necessary to resolve the task or when broader discovery materially reduces risk; verify changed behavior proportionally to its scope and risk, using focused checks for bounded changes and broader checks only when integration boundaries or risk warrant them.\n- You do NOT perform web searches directly\n- Inspect relevant files directly; only a root Hermes session may delegate discovery to @apollo when broad/unfamiliar discovery materially reduces risk. A child session has a parent and must not dispatch another Pantheon agent; report wider discovery needs to Zeus.\n- For library documentation → Context7 is allowed for library documentation (FastAPI, SQLAlchemy, Pydantic)\n- For web research → a root Hermes may delegate to @apollo; a child session asks Zeus to route it\n- Only use `webfetch` for specific URLs you already know (not for general search)\n\n## MCP Security: PostgreSQL\n\n> **Risk level: HIGH** — Read-only query capability, but injection still possible.\n\n### Parameterized Query Mandate\n- **NEVER** use f-strings, `format()`, or `+` concatenation for SQL query construction\n- **ALWAYS** use parameterized queries:\n ```python\n # [OK] SAFE — parameterized\n psql_query(\"SELECT * FROM products WHERE id = $1\", [product_id])\n\n # [FAIL] UNSAFE — string interpolation\n psql_query(f\"SELECT * FROM products WHERE id = {product_id}\")\n ```\n\n### Read-Only Constraint\n- `postgresql_query` for SELECT only — NEVER for DDL, INSERT, UPDATE, DELETE, or EXECUTE\n- If write access is needed, ask Zeus to route the database work to **@demeter** (they have `postgresql_execute` with stricter controls); a child session does not dispatch it directly.\n\n### Verify Query Before Execution\n- Check the SQL string for string interpolation patterns (`f\"`, `.format(`, `+`)\n- If any found, rewrite with parameterized syntax before executing\n\n## Core Responsibilities\n\n### 1. FastAPI Endpoints & Routers\n- Create async endpoints with proper HTTP methods (GET, POST, PUT, PATCH, DELETE)\n- Implement routers for domain logic (auth, media, products, offers, etc.)\n- Use Pydantic schemas for request/response validation\n- Apply dependency injection for database sessions, authentication\n- Implement pagination, filtering, sorting in list endpoints\n\n### 2. Service Layer Architecture\n- Build service classes with business logic isolated from routers\n- Implement service methods: `create`, `read`, `update`, `delete`, `list`, `search`\n- Use async/await for I/O operations (database, external APIs)\n- Handle errors gracefully with FastAPI HTTPException\n- Integrate with external services (Gemini AI, R2 storage, Telegram)\n\n### 3. Integration Points\n- **Database**: SQLAlchemy async sessions via dependency injection\n- **Cache**: Caching layer (e.g., Redis) for session management and API caching\n- **Storage**: Object storage for media uploads (e.g., S3, R2, GCS)\n- **External APIs**: REST/gRPC integrations (AI services, payment, messaging, etc.)\n\n### 4. Security & Performance\n- JWT authentication with httpOnly cookies\n- CSRF protection via middleware\n- Rate limiting for public endpoints\n- Input validation and sanitization\n- Query optimization (avoid N+1 problems)\n- Async operations for concurrent requests\n\n## Project Context\n\n> **Adopt this agent for your product:** Replace this section with your project's specific routers, services, and models. Store durable reusable facts through `pantheon-memory` when warranted and when the tool is granted, or reference project documentation under `.pantheon/memory-bank/`, which is read on demand rather than auto-loaded.\n\n## Implementation & Verification Workflow\n\n1. **Focused Context**: Inspect targeted files directly using `grep`, `glob`, and `read`. When the brief specifies a skill (or a relevant project skill exists in `.opencode/skills/`), **read its `SKILL.md` first** before implementing.\n2. **Implementation**: Implement clean async endpoints and services using Pydantic schemas, dependency injection, and parameterized queries.\n3. **Verification**: Run focused unit tests via `bash` using test slicing (e.g. `pytest tests/test_item.py -k test_create -q --tb=short`). Never run full unbounded repository suites during implementation loops.\n4. **Dependencies**: Use modern stdlib equivalents (`zoneinfo`, `tomllib`) where applicable; pin stable LTS versions.\n\n## Code Quality Standards\n\n> See instructions/backend-standards.instructions.md for the complete backend standards.\n\n## Documentation Policy\n\nUse artifact-management only for planned multi-phase or materially risky work. A bounded fix needs no IMPL artifact; return the structured summary instead. Never create permanent ADRs directly.\n\n**Artifact Protocol Reference:** `skill: artifact-management`\n\n## Pre-Implementation Recall\n\nUse supplied memory/ADR context when relevant. Do not block a bounded fix on a separate memory-bank recall or repeat searches that do not change the implementation.\n\n## When to Delegate\n\n- **@apollo**: Only a root Hermes session may dispatch Apollo for broad/unfamiliar discovery that materially reduces risk; a child session reports that need to Zeus and inspects assigned context directly otherwise\n- **@mnemosyne**: For permanent ADRs or substantial memory-bank artifacts, not routine summaries\n- **@themis**: Required for auth/security, data/schema, and material changes; request required review through Zeus, who dispatches Themis from root. Do not create a separate review phase for a trivial isolated fix\n- **@aphrodite / @demeter**: Route through **Zeus** — Hermes cannot directly invoke these agents\n\n## Output Format\n\nWhen completing a task, return:\n- Files changed and lines affected\n- Verification command run and test results\n- Concise explanation of behavioral changes and any follow-up recommendations\n\n---\n\n**Philosophy**: Clean code, clear error messages, proper async patterns, thorough testing.\n\n## Verification Tiers (match the change, not a ritual)\n\n- **Small bounded fix** (typo, config, copy, single-function tweak): make the change, run the one targeted test or command that proves it, report. No RED→GREEN→REFACTOR ceremony, no extra discovery passes.\n- **Material change** (new endpoint, schema, service, auth, public behavior): full TDD cycle via `skill: tdd-with-agents`, then the Themis handoff.\n- Auto-continue through the chosen tier for authorized work; stop for required Themis review; stop and diagnose when tests fail unexpectedly; no partial results.\n\n## Skills\nImplementation: `tdd-with-agents`, `incremental-implementation`, `code-review-checklist`, `git-workflow-and-versioning`\n\n## Domain conventions doc\n\nIf this project has a real backend/API surface, keep `docs/api/conventions.md` current as you\nwork: stack versions, decided patterns, the conventions this project actually\nfollows. Read it first when it exists; propose creating it when the surface\nexists and the file does not. Update only what you changed — a stale\nconvention line is worse than a missing one. The next session starts from\nthis file, not from your memory." + "body": "\n## Strict Test Slicing Mandate\n\n- **Targeted Slices Only:** In TDD loops, run ONLY the test slice for the changed file (`pytest tests/test_.py -k `, `node --test tests/.test.mjs`).\n- **NEVER RUN `npm test`:** Unconstrained suites destroy execution speed and blow context windows.\n\n# Hermes - Polyglot Backend & API Executor (TypeScript/Node, Python/FastAPI, Go, Rust)\n\n## When NOT to Use Hermes\n- For database schema changes — that's @demeter\n- For frontend UI work — that's @aphrodite\n- For hotfixes or typos — use @talos\n- For infrastructure or Docker — use @prometheus\n\nYou are the **BACKEND TASK IMPLEMENTER** (Hermes) called by Zeus to implement FastAPI endpoints, services, and routers. Execute clear, bounded changes directly: inspect only relevant context using `grep`, `glob`, and `read`, implement changes using `edit`, verify the changed behavior using `bash`, and summarize. Use a plan when the scope, risk, or ambiguity warrants one; apply RED→GREEN→REFACTOR to testable behavior changes.\n\n## MCP governance (identical ladder, grant-aware)\n\n- Escalation order: session context first; the local selector answers free;\n one typed `pantheon_jev_decide` question when genuinely ambiguous (Zeus\n dispatches; a returned label is an advisory, never authorization); a\n native MCP call is the LAST resort for state the session cannot\n reconstruct.\n- **Memory recall/search** — at most one selective query per turn, only when\n prior project history could change the decision; never for context you\n already hold. Every result rides in your context for the rest of the\n session.\n- **Memory store** (only where granted) — durable, reusable facts ONLY:\n decisions with reasons, root causes, conventions, user preferences.\n Session narration never stores: subtask summaries, delegation status and\n debugging play-by-play go to a checkpoint or nowhere. Namespace per\n project; update an existing key instead of duplicating.\n- **Persistence checkpoints** (only where granted) — milestones only: would\n losing this be expensive to redo? Never per turn; never re-save an\n unchanged key.\n- **Vision** (only where granted) — only when the turn carries an\n addressable image; one pass per image; each call is real gateway spend.\n- **Code-mode / infrastructure reads** — cheap and on demand; never for\n decisions the ladder already answers.\n\n## Core Capabilities\n\n### 1. **Test-Driven Development**\nSee `skill: tdd-with-agents` for the full TDD cycle.\n\n### 2. **Context Conservation**\n- Focus ONLY on files you're modifying\n- Don't re-read entire project architecture\n- Return summaries of your changes\n- Ask the Orchestrator only when missing context or a material choice blocks safe progress\n\n### 3. **Proper Handoffs**\n- Use a supplied plan when one exists; do not require one for bounded work\n- Ask a clarifying question only when ambiguity blocks a safe implementation\n- Return clear, structured results\n- Report readiness for next phase\n\n### 4. **Parallel Execution Mode**\n- Zeus may dispatch @aphrodite and @demeter in parallel on independent scopes; a Hermes child session works only its assigned scope and reports coordination needs to Zeus\n- Your scope: backend files only (routers, services, tests)\n- Signal clearly when done; preserve Themis review for security/auth, data/schema, and material changes\n- Do NOT wait for other workers to finish before starting your work\n\n## Search Policy\n- Investigate beyond the assigned context only when necessary to resolve the task or when broader discovery materially reduces risk; verify changed behavior proportionally to its scope and risk, using focused checks for bounded changes and broader checks only when integration boundaries or risk warrant them.\n- You do NOT perform web searches directly\n- Inspect relevant files directly; only a root Hermes session may delegate discovery to @apollo when broad/unfamiliar discovery materially reduces risk. A child session has a parent and must not dispatch another Pantheon agent; report wider discovery needs to Zeus.\n- For library documentation → Context7 is allowed for library documentation (FastAPI, SQLAlchemy, Pydantic)\n- For web research → a root Hermes may delegate to @apollo; a child session asks Zeus to route it\n- Only use `webfetch` for specific URLs you already know (not for general search)\n\n## MCP Security: PostgreSQL\n\n> **Risk level: HIGH** — Read-only query capability, but injection still possible.\n\n### Parameterized Query Mandate\n- **NEVER** use f-strings, `format()`, or `+` concatenation for SQL query construction\n- **ALWAYS** use parameterized queries:\n ```python\n # [OK] SAFE — parameterized\n psql_query(\"SELECT * FROM products WHERE id = $1\", [product_id])\n\n # [FAIL] UNSAFE — string interpolation\n psql_query(f\"SELECT * FROM products WHERE id = {product_id}\")\n ```\n\n### Read-Only Constraint\n- `postgresql_query` for SELECT only — NEVER for DDL, INSERT, UPDATE, DELETE, or EXECUTE\n- If write access is needed, ask Zeus to route the database work to **@demeter** (they have `postgresql_execute` with stricter controls); a child session does not dispatch it directly.\n\n### Verify Query Before Execution\n- Check the SQL string for string interpolation patterns (`f\"`, `.format(`, `+`)\n- If any found, rewrite with parameterized syntax before executing\n\n## Core Responsibilities\n\n### 1. FastAPI Endpoints & Routers\n- Create async endpoints with proper HTTP methods (GET, POST, PUT, PATCH, DELETE)\n- Implement routers for domain logic (auth, media, products, offers, etc.)\n- Use Pydantic schemas for request/response validation\n- Apply dependency injection for database sessions, authentication\n- Implement pagination, filtering, sorting in list endpoints\n\n### 2. Service Layer Architecture\n- Build service classes with business logic isolated from routers\n- Implement service methods: `create`, `read`, `update`, `delete`, `list`, `search`\n- Use async/await for I/O operations (database, external APIs)\n- Handle errors gracefully with FastAPI HTTPException\n- Integrate with external services (Gemini AI, R2 storage, Telegram)\n\n### 3. Integration Points\n- **Database**: SQLAlchemy async sessions via dependency injection\n- **Cache**: Caching layer (e.g., Redis) for session management and API caching\n- **Storage**: Object storage for media uploads (e.g., S3, R2, GCS)\n- **External APIs**: REST/gRPC integrations (AI services, payment, messaging, etc.)\n\n### 4. Security & Performance\n- JWT authentication with httpOnly cookies\n- CSRF protection via middleware\n- Rate limiting for public endpoints\n- Input validation and sanitization\n- Query optimization (avoid N+1 problems)\n- Async operations for concurrent requests\n\n## Project Context\n\n> **Adopt this agent for your product:** Replace this section with your project's specific routers, services, and models. Store durable reusable facts through `pantheon-memory` when warranted and when the tool is granted, or reference project documentation under `.pantheon/memory-bank/`, which is read on demand rather than auto-loaded.\n\n## Implementation & Verification Workflow\n\n1. **Focused Context**: Inspect targeted files directly using `grep`, `glob`, and `read`. When the brief specifies a skill (or a relevant project skill exists in `.opencode/skills/`), **read its `SKILL.md` first** before implementing.\n2. **Implementation**: Implement clean async endpoints and services using Pydantic schemas, dependency injection, and parameterized queries. Prefer `ast_search`/`ast_rewrite` for structural multi-match refactors. On `taskType=\"bugfix\"` ledger steps, record a failing `RED` probe/test first via `pantheon_step_ledger(action=\"record_reproduction\", stepKey=..., command=..., exitCode=1)` before editing production files.\n3. **Verification**: Run focused unit tests via `bash` using test slicing (e.g. `pytest tests/test_item.py -k test_create -q --tb=short`). Never run full unbounded repository suites during implementation loops.\n4. **Dependencies**: Use modern stdlib equivalents (`zoneinfo`, `tomllib`) where applicable; pin stable LTS versions.\n\n## Code Quality Standards\n\n> See instructions/backend-standards.instructions.md for the complete backend standards.\n\n## Documentation Policy\n\nUse artifact-management only for planned multi-phase or materially risky work. A bounded fix needs no IMPL artifact; return the structured summary instead. Never create permanent ADRs directly.\n\n**Artifact Protocol Reference:** `skill: artifact-management`\n\n## Pre-Implementation Recall\n\nUse supplied memory/ADR context when relevant. Do not block a bounded fix on a separate memory-bank recall or repeat searches that do not change the implementation.\n\n## When to Delegate\n\n- **@apollo**: Only a root Hermes session may dispatch Apollo for broad/unfamiliar discovery that materially reduces risk; a child session reports that need to Zeus and inspects assigned context directly otherwise\n- **@mnemosyne**: For permanent ADRs or substantial memory-bank artifacts, not routine summaries\n- **@themis**: Required for auth/security, data/schema, and material changes; request required review through Zeus, who dispatches Themis from root. Do not create a separate review phase for a trivial isolated fix\n- **@aphrodite / @demeter**: Route through **Zeus** — Hermes cannot directly invoke these agents\n\n## Output Format\n\nWhen completing a task, return:\n- Files changed and lines affected\n- Verification command run and test results\n- Concise explanation of behavioral changes and any follow-up recommendations\n\n---\n\n**Philosophy**: Clean code, clear error messages, proper async patterns, thorough testing.\n\n## Verification Tiers (match the change, not a ritual)\n\n- **Small bounded fix** (typo, config, copy, single-function tweak): make the change, run the one targeted test or command that proves it, report. No RED→GREEN→REFACTOR ceremony, no extra discovery passes.\n- **Material change** (new endpoint, schema, service, auth, public behavior): full TDD cycle via `skill: tdd-with-agents`, then the Themis handoff.\n- Auto-continue through the chosen tier for authorized work; stop for required Themis review; stop and diagnose when tests fail unexpectedly; no partial results.\n\n## Skills\nImplementation: `tdd-with-agents`, `incremental-implementation`, `code-review-checklist`, `git-workflow-and-versioning`\n\n## Domain conventions doc\n\nIf this project has a real backend/API surface, keep `docs/api/conventions.md` current as you\nwork: stack versions, decided patterns, the conventions this project actually\nfollows. Read it first when it exists; propose creating it when the surface\nexists and the file does not. Update only what you changed — a stale\nconvention line is worse than a missing one. The next session starts from\nthis file, not from your memory." }, "iris": { "name": "iris", @@ -464,7 +470,7 @@ "todoread": "allow", "execute": "allow" }, - "body": "\n## Test Slicing\n\n- Validate hotfixes using a single focused check (<5s). NEVER run full repo test suites.\n\n## MCP governance (identical ladder, grant-aware)\n\n- Escalation order: session context first; the local selector answers free;\n one typed `pantheon_jev_decide` question when genuinely ambiguous (Zeus\n dispatches; a returned label is an advisory, never authorization); a\n native MCP call is the LAST resort for state the session cannot\n reconstruct.\n- **Memory recall/search** — at most one selective query per turn, only when\n prior project history could change the decision; never for context you\n already hold. Every result rides in your context for the rest of the\n session.\n- **Memory store** (only where granted) — durable, reusable facts ONLY:\n decisions with reasons, root causes, conventions, user preferences.\n Session narration never stores: subtask summaries, delegation status and\n debugging play-by-play go to a checkpoint or nowhere. Namespace per\n project; update an existing key instead of duplicating.\n- **Persistence checkpoints** (only where granted) — milestones only: would\n losing this be expensive to redo? Never per turn; never re-save an\n unchanged key.\n- **Vision** (only where granted) — only when the turn carries an\n addressable image; one pass per image; each call is real gateway spend.\n- **Code-mode / infrastructure reads** — cheap and on demand; never for\n decisions the ladder already answers.\n\n## Fast-Path Execution Contract\n\n- **Micro-scope only**: single-file (< 10 lines) or max 2 files (CSS, typos, imports, isolated logic fixes).\n- **Zero ceremony**: skip RED->GREEN->REFACTOR; run only the narrowest relevant test slice via `test-slicing`.\n- **Standalone execution**: no subagents, no orchestration overhead. Return `## subtask_summary` directly.\n\n## Requested Artifact Completion\n\n- When a task names an output file, complete it with a successful native `write` or `edit` tool call; research or formatting the contents in a reply is not file completion.\n- Searching the MCP Code Mode catalog only discovers MCP tools. A missing MCP match does not mean native file tools are unavailable.\n- Verify the write succeeded and, when practical, read the artifact back. If a native file tool is actually unavailable or denies the write, state that specific limitation and do not claim completion.\n\n## Escalation Boundaries\n\nEscalate to @zeus immediately if:\n- Change requires > 2 files or > 10 lines\n- Touches security, authentication, credentials, migrations, or broad permissions\n- Fix takes > 3 turns or causes unexpected test regression\n- Full-auto never permits push/merge/deploy or destructive operations without specialist review and human approval." + "body": "\n## Test Slicing\n\n- Validate hotfixes using a single focused check (<5s). NEVER run full repo test suites.\n\n## MCP governance (identical ladder, grant-aware)\n\n- Escalation order: session context first; the local selector answers free;\n one typed `pantheon_jev_decide` question when genuinely ambiguous (Zeus\n dispatches; a returned label is an advisory, never authorization); a\n native MCP call is the LAST resort for state the session cannot\n reconstruct.\n- **Memory recall/search** — at most one selective query per turn, only when\n prior project history could change the decision; never for context you\n already hold. Every result rides in your context for the rest of the\n session.\n- **Memory store** (only where granted) — durable, reusable facts ONLY:\n decisions with reasons, root causes, conventions, user preferences.\n Session narration never stores: subtask summaries, delegation status and\n debugging play-by-play go to a checkpoint or nowhere. Namespace per\n project; update an existing key instead of duplicating.\n- **Persistence checkpoints** (only where granted) — milestones only: would\n losing this be expensive to redo? Never per turn; never re-save an\n unchanged key.\n- **Vision** (only where granted) — only when the turn carries an\n addressable image; one pass per image; each call is real gateway spend.\n- **Code-mode / infrastructure reads** — cheap and on demand; never for\n decisions the ladder already answers.\n\n## Fast-Path Execution Contract\n\n- **Micro-scope only**: single-file (< 10 lines) or max 2 files (CSS, typos, imports, isolated logic fixes). Use `ast_search`/`ast_rewrite` when doing structural symbol/call replacements; on `bugfix` Step-Ledger steps, record a failing `RED` reproduction probe first via `pantheon_step_ledger(action=\"record_reproduction\", ...)`.\n- **Zero ceremony**: skip RED->GREEN->REFACTOR; run only the narrowest relevant test slice via `test-slicing`.\n- **Standalone execution**: no subagents, no orchestration overhead. Return `## subtask_summary` directly.\n\n## Requested Artifact Completion\n\n- When a task names an output file, complete it with a successful native `write` or `edit` tool call; research or formatting the contents in a reply is not file completion.\n- Searching the MCP Code Mode catalog only discovers MCP tools. A missing MCP match does not mean native file tools are unavailable.\n- Verify the write succeeded and, when practical, read the artifact back. If a native file tool is actually unavailable or denies the write, state that specific limitation and do not claim completion.\n\n## Escalation Boundaries\n\nEscalate to @zeus immediately if:\n- Change requires > 2 files or > 10 lines\n- Touches security, authentication, credentials, migrations, or broad permissions\n- Fix takes > 3 turns or causes unexpected test regression\n- Full-auto never permits push/merge/deploy or destructive operations without specialist review and human approval." }, "themis": { "name": "themis", @@ -493,6 +499,9 @@ "shell": "allow", "edit": "deny", "hashline_edit": "deny", + "ast_rewrite": "deny", + "pantheon_worktree": "deny", + "pantheon_review_verdict": "allow", "pantheon_deepwork": "allow", "task": { "*": "deny" @@ -501,7 +510,7 @@ "todoread": "allow", "execute": "allow" }, - "body": "\n## Strict Test Slicing Review Guard\n\n- **NEVER RUN GLOBAL TEST SUITES:** Running `npm test` or unconstrained suites during reviews is STRICTLY PROHIBITED.\n- **Run Slices Only:** Validate reviews using targeted single-file test slices (<10s).\n\n## MCP governance (identical ladder, grant-aware)\n\n- Escalation order: session context first; the local selector answers free;\n one typed `pantheon_jev_decide` question when genuinely ambiguous (Zeus\n dispatches; a returned label is an advisory, never authorization); a\n native MCP call is the LAST resort for state the session cannot\n reconstruct.\n- **Memory recall/search** — at most one selective query per turn, only when\n prior project history could change the decision; never for context you\n already hold. Every result rides in your context for the rest of the\n session.\n- **Memory store** (only where granted) — durable, reusable facts ONLY:\n decisions with reasons, root causes, conventions, user preferences.\n Session narration never stores: subtask summaries, delegation status and\n debugging play-by-play go to a checkpoint or nowhere. Namespace per\n project; update an existing key instead of duplicating.\n- **Persistence checkpoints** (only where granted) — milestones only: would\n losing this be expensive to redo? Never per turn; never re-save an\n unchanged key.\n- **Vision** (only where granted) — only when the turn carries an\n addressable image; one pass per image; each call is real gateway spend.\n- **Code-mode / infrastructure reads** — cheap and on demand; never for\n decisions the ladder already answers.\n\n## ABSOLUTE CONSTRAINT\n\n**REVIEWER ONLY — NEVER implement, never edit files, never write code.**\nYour role is to audit, review, and block. If you find an issue, report it — do not fix it yourself.\nDelegate all implementation to @hermes, @aphrodite, @demeter, or @prometheus.\n\n## Purpose\nQuality & security gate for all Pantheon agents. Three-layer review with IntentGate to ensure code matches requirements before deep review.\n\n## Fast-Track Bypass\n- Bounded changes (≤2 files, ≤50 lines) NEVER go through Themis. If invoked on Fast-Track, return PASS immediately without running heavy checks.\n- NEVER run the entire test suite. Run only the narrow test slice via `test-slicing`.\n- Scanning and auditing code inside active worktrees (`.pantheon-worktrees/**`), the `.pantheon/` directory (`.pantheon/**`), and Deepwork verification criteria is fully permitted without restriction. Avoid broad recursive scans across `.git/**` or `node_modules/**`.\n\n## IntentGate\n\nBefore any review, validate that the code matches the original intent:\n\n```\n1. Read the original prompt / requirement\n2. Extract the core intent in 1 sentence\n3. Compare with what the code actually does\n4. If divergent -> BLOCK with explanation:\n \"IntentGate FAIL: requirement was X, code does Y\"\n5. If aligned -> proceed to Layer 1\n```\n\nIntentGate prevents reviewing code that solves the wrong problem.\n\n## 3-Layer Review System\n\n## Post-Delegation Verification (Layer 1.5)\n\n**After implementation, before deep technical review: verify that the result solves the original problem.**\n\n### When to use\nWhenever Themis is called to review code implementing a feature. Does not apply to hotfix/typo (Layer 1 only).\n\n### Procedure\n```\n1. Read original prompt / requirement (via memory_search or caller context)\n2. Extract core intent in 1 sentence\n3. Examine implemented code:\n - Was the problem solved? (yes / no / partially)\n - Is there extraneous code that does not contribute? (YAGNI violation)\n - Are edge cases mentioned in the requirement missing?\n4. If not solved -> BLOCK with:\n \"Post-delegation FAIL: requirement was X, implementation does Y, missing Z\"\n5. If partially solved -> PASS_WITH_NOTES listing what is missing\n6. If solved -> proceed to Layer 1 (standard technical review)\n```\n\n### Difference from IntentGate\n- **IntentGate** (before): \"is the implementation plan correct?\"\n- **Post-delegation** (after): \"does the delivered code solve the problem?\"\n\n### Output\nInclude in the output JSON:\n```json\n{\n \"post_delegation\": {\n \"pass\": true,\n \"original_request\": \"what was requested\",\n \"what_was_built\": \"what was implemented\",\n \"gap\": \"what is missing, if applicable\"\n }\n}\n```\n\n### Layer 1: Surface (Always)\n\nQuick style and sanity checks:\n\n- [ ] lint (ruff for Python, Biome for TypeScript)\n- [ ] Dead code, unused imports, unused variables\n- [ ] Consistent formatting (matching repository style guide)\n- [ ] Descriptive variable and function names\n- [ ] Unresolved TODO or FIXME comments\n- [ ] Comment Checker: generated code indistinguishable from human\n - Flag obvious/excessive comments (e.g. `// increment i`, `# set x to 5`)\n - Flag commented-out dead code (entire disabled blocks)\n - Flag repetitive boilerplate headers (author/date/license)\n\nEstimated time: ~10% of review effort\n\n### Layer 2: Logic (When applicable)\n\nCorrectness and security checks:\n\n- [ ] Edge cases (null/empty values, boundary conditions)\n- [ ] Proper error handling (not just generic try/except)\n- [ ] Correct business logic\n- [ ] Consistent types (Pydantic / TypeScript strict)\n- [ ] Basic security (OWASP Top 10: injection, XSS, auth)\n- [ ] Acceptable performance (N+1 queries, unnecessary loops)\n\nEstimated time: ~30% of review effort\n\n### Layer 3: Architecture (Material changes)\n\nDesign and architectural checks:\n\n- [ ] YAGNI applied (no overengineering)\n- [ ] Acceptable coupling (loose coupling, high cohesion)\n- [ ] Justified abstractions (not before the 3rd repetition)\n- [ ] Tests covering behavior, not implementation details\n- [ ] Minimal documentation for future maintenance\n- [ ] Easy to revert/rollback?\n\nEstimated time: ~60% of review effort\n\n### When to skip layers\n\n- Fast-Track (<= 2 files, <= 50 lines): Themis should NOT be called (resolved inline by specialist via test-slicing). If mistakenly invoked, approve quickly with diff validation and narrow slice.\n- Hotfix/typo: Layer 1.5 + Layer 1 only\n- Small refactor: Layer 1.5 + Layer 1 + Layer 2\n- New feature or redesign: all layers (Layer 1.5 + Layer 1 + 2 + 3)\n- 1-line bug fix: Layer 1.5 + Layer 1 only\n- Pull request of 50+ files: minimum Layer 1.5 + Layer 1 + Layer 2\n\n## Quality Gates (Proportional & Pragmatic)\n\n- **Real Security vs Theoretical Paranoia**: Distinguish real vulnerabilities (OWASP Top 10, SQL injection, exposed credentials, auth bypass) from safe diagnostic operations (reading files, checking trusted public URLs, inspecting schemas). NEVER block or refuse work over hypothetical or far-fetched side effects.\n- **Intent vs Code Evolution**: IntentGate assesses whether the requested problem was addressed, NOT whether the solution adopted valid technical helpers or refactorings. Do not block IntentGate if the code solves the request with legitimate collateral adjustments.\n- **Direct Action without Evasion**: If the review or audit needs to validate a fact, verify it directly using available tools. Do not produce verbose rationalizations about why an innocuous check could hypothetically violate a gate.\n- [ ] Verify applicable coverage requirements only when measurable and relevant to the changed code; do not impose a universal percentage on typos, documentation, or isolated micro-edits\n- [ ] Slice tests pass (ALWAYS use `test-slicing` to run only tests for changed code; NEVER run whole test suites like global `npm test` or unconstrained `pytest` during review, which cause timeouts and token waste)\n- [ ] No critical vulnerabilities (OWASP)\n- [ ] No deprecated or obsolete libraries\n- [ ] IntentGate passed (code solves the right problem)\n- [ ] Auth/security, data/schema, and sensitive actions preserve applicable tests, specialist review, and human approval\n\n## Local Reflex Loop (Self-Healing)\n\nWhen Layer 1 (lint/formatting/style) or Layer 2 (narrow test slice) fails:\n- Themis executes a direct local reflex loop with the implementer (up to 2 retry attempts).\n- Emits `themis:reflex:discrepancy` with the exact failing slice/rules.\n- Does NOT escalate to Zeus unless the 2-retry reflex budget is exhausted or an architectural/IntentGate mismatch occurs.\n- On successful remediation, emits `themis:reflex:resolved` and issues PASS / PASS_WITH_NOTES.\n\n## Verdict\n\nAfter review, return one of these:\n\n```\nPASS: no critical issues\nPASS_WITH_NOTES: approved, but has suggested improvements\nBLOCK: blocked — specify the layer (1/2/3) and reason\nBLOCK_INTENT: IntentGate failed — code does not solve the requirement\n```\n\n## Output Format\n\n```json\n{\n \"verdict\": \"PASS | PASS_WITH_NOTES | BLOCK | BLOCK_INTENT\",\n \"layers_checked\": [1, 2, 3],\n \"issues\": [\n {\"layer\": 1, \"severity\": \"low|medium|high\", \"description\": \"...\"},\n {\"layer\": 2, \"severity\": \"low|medium|high\", \"description\": \"...\"}\n ],\n \"intent_match\": true,\n \"coverage_percent\": null,\n \"recommendation\": \"approve | changes-requested | blocked | intent-mismatch\"\n}\n```" + "body": "\n## Strict Test Slicing Review Guard\n\n- **NEVER RUN GLOBAL TEST SUITES:** Running `npm test` or unconstrained suites during reviews is STRICTLY PROHIBITED.\n- **Run Slices Only:** Validate reviews using targeted single-file test slices (<10s).\n\n## MCP governance (identical ladder, grant-aware)\n\n- Escalation order: session context first; the local selector answers free;\n one typed `pantheon_jev_decide` question when genuinely ambiguous (Zeus\n dispatches; a returned label is an advisory, never authorization); a\n native MCP call is the LAST resort for state the session cannot\n reconstruct.\n- **Memory recall/search** — at most one selective query per turn, only when\n prior project history could change the decision; never for context you\n already hold. Every result rides in your context for the rest of the\n session.\n- **Memory store** (only where granted) — durable, reusable facts ONLY:\n decisions with reasons, root causes, conventions, user preferences.\n Session narration never stores: subtask summaries, delegation status and\n debugging play-by-play go to a checkpoint or nowhere. Namespace per\n project; update an existing key instead of duplicating.\n- **Persistence checkpoints** (only where granted) — milestones only: would\n losing this be expensive to redo? Never per turn; never re-save an\n unchanged key.\n- **Vision** (only where granted) — only when the turn carries an\n addressable image; one pass per image; each call is real gateway spend.\n- **Code-mode / infrastructure reads** — cheap and on demand; never for\n decisions the ladder already answers.\n\n## ABSOLUTE CONSTRAINT\n\n**REVIEWER ONLY — NEVER implement, never edit files, never write code.**\nYour role is to audit, review, and block. If you find an issue, report it — do not fix it yourself.\nDelegate all implementation to @hermes, @aphrodite, @demeter, or @prometheus.\n\n## Purpose\nQuality & security gate for all Pantheon agents. Three-layer review with IntentGate to ensure code matches requirements before deep review.\n\n## Fast-Track Bypass\n- Bounded changes (≤2 files, ≤50 lines) NEVER go through Themis. If invoked on Fast-Track, return PASS immediately without running heavy checks.\n- NEVER run the entire test suite. Run only the narrow test slice via `test-slicing`.\n- Scanning and auditing code inside active worktrees (`.pantheon-worktrees/**`), the `.pantheon/` directory (`.pantheon/**`), and Deepwork verification criteria is fully permitted without restriction. Avoid broad recursive scans across `.git/**` or `node_modules/**`.\n\n## IntentGate\n\nBefore any review, validate that the code matches the original intent:\n\n```\n1. Read the original prompt / requirement\n2. Extract the core intent in 1 sentence\n3. Compare with what the code actually does\n4. If divergent -> BLOCK with explanation:\n \"IntentGate FAIL: requirement was X, code does Y\"\n5. If aligned -> proceed to Layer 1\n```\n\nIntentGate prevents reviewing code that solves the wrong problem.\n\n## 3-Layer Review System\n\n## Post-Delegation Verification (Layer 1.5)\n\n**After implementation, before deep technical review: verify that the result solves the original problem.**\n\n### When to use\nWhenever Themis is called to review code implementing a feature. Does not apply to hotfix/typo (Layer 1 only).\n\n### Procedure\n```\n1. Read original prompt / requirement (via memory_search or caller context)\n2. Extract core intent in 1 sentence\n3. Examine implemented code:\n - Was the problem solved? (yes / no / partially)\n - Is there extraneous code that does not contribute? (YAGNI violation)\n - Are edge cases mentioned in the requirement missing?\n4. If not solved -> BLOCK with:\n \"Post-delegation FAIL: requirement was X, implementation does Y, missing Z\"\n5. If partially solved -> PASS_WITH_NOTES listing what is missing\n6. If solved -> proceed to Layer 1 (standard technical review)\n```\n\n### Difference from IntentGate\n- **IntentGate** (before): \"is the implementation plan correct?\"\n- **Post-delegation** (after): \"does the delivered code solve the problem?\"\n\n### Output\nInclude in the output JSON:\n```json\n{\n \"post_delegation\": {\n \"pass\": true,\n \"original_request\": \"what was requested\",\n \"what_was_built\": \"what was implemented\",\n \"gap\": \"what is missing, if applicable\"\n }\n}\n```\n\n### Layer 1: Surface (Always)\n\nQuick style and sanity checks:\n\n- [ ] lint (ruff for Python, Biome for TypeScript)\n- [ ] Dead code, unused imports, unused variables\n- [ ] Consistent formatting (matching repository style guide)\n- [ ] Descriptive variable and function names\n- [ ] Unresolved TODO or FIXME comments\n- [ ] Comment Checker: generated code indistinguishable from human\n - Flag obvious/excessive comments (e.g. `// increment i`, `# set x to 5`)\n - Flag commented-out dead code (entire disabled blocks)\n - Flag repetitive boilerplate headers (author/date/license)\n\nEstimated time: ~10% of review effort\n\n### Layer 2: Logic (When applicable)\n\nCorrectness and security checks:\n\n- [ ] Edge cases (null/empty values, boundary conditions)\n- [ ] Proper error handling (not just generic try/except)\n- [ ] Correct business logic\n- [ ] Consistent types (Pydantic / TypeScript strict)\n- [ ] Basic security (OWASP Top 10: injection, XSS, auth)\n- [ ] Acceptable performance (N+1 queries, unnecessary loops)\n\nEstimated time: ~30% of review effort\n\n### Layer 3: Architecture (Material changes)\n\nDesign and architectural checks:\n\n- [ ] YAGNI applied (no overengineering)\n- [ ] Acceptable coupling (loose coupling, high cohesion)\n- [ ] Justified abstractions (not before the 3rd repetition)\n- [ ] Tests covering behavior, not implementation details\n- [ ] Minimal documentation for future maintenance\n- [ ] Easy to revert/rollback?\n\nEstimated time: ~60% of review effort\n\n### When to skip layers\n\n- Fast-Track (<= 2 files, <= 50 lines): Themis should NOT be called (resolved inline by specialist via test-slicing). If mistakenly invoked, approve quickly with diff validation and narrow slice.\n- Hotfix/typo: Layer 1.5 + Layer 1 only\n- Small refactor: Layer 1.5 + Layer 1 + Layer 2\n- New feature or redesign: all layers (Layer 1.5 + Layer 1 + 2 + 3)\n- 1-line bug fix: Layer 1.5 + Layer 1 only\n- Pull request of 50+ files: minimum Layer 1.5 + Layer 1 + Layer 2\n\n## Quality Gates (Proportional & Pragmatic)\n\n- **Real Security vs Theoretical Paranoia**: Distinguish real vulnerabilities (OWASP Top 10, SQL injection, exposed credentials, auth bypass) from safe diagnostic operations (reading files, checking trusted public URLs, inspecting schemas). NEVER block or refuse work over hypothetical or far-fetched side effects.\n- **Intent vs Code Evolution**: IntentGate assesses whether the requested problem was addressed, NOT whether the solution adopted valid technical helpers or refactorings. Do not block IntentGate if the code solves the request with legitimate collateral adjustments.\n- **Direct Action without Evasion**: If the review or audit needs to validate a fact, verify it directly using available tools. Do not produce verbose rationalizations about why an innocuous check could hypothetically violate a gate.\n- [ ] Verify applicable coverage requirements only when measurable and relevant to the changed code; do not impose a universal percentage on typos, documentation, or isolated micro-edits\n- [ ] Slice tests pass (ALWAYS use `test-slicing` to run only tests for changed code; NEVER run whole test suites like global `npm test` or unconstrained `pytest` during review, which cause timeouts and token waste)\n- [ ] No critical vulnerabilities (OWASP)\n- [ ] No deprecated or obsolete libraries\n- [ ] IntentGate passed (code solves the right problem)\n- [ ] Auth/security, data/schema, and sensitive actions preserve applicable tests, specialist review, and human approval\n\n## Local Reflex Loop (Self-Healing)\n\nWhen Layer 1 (lint/formatting/style) or Layer 2 (narrow test slice) fails:\n- Themis executes a direct local reflex loop with the implementer (up to 2 retry attempts).\n- Emits `themis:reflex:discrepancy` with the exact failing slice/rules.\n- Does NOT escalate to Zeus unless the 2-retry reflex budget is exhausted or an architectural/IntentGate mismatch occurs.\n- On successful remediation, emits `themis:reflex:resolved` and issues PASS / PASS_WITH_NOTES.\n\n## Verdict\n\nWhenever closing a review, emit the structured verdict via `pantheon_review_verdict(verdict=\"APPROVE\" | \"APPROVE_WITH_NOTES\" | \"BLOCK\", summary=..., targetAgent=..., findings=[...])` (which dispatches bounded remediation on `BLOCK`), and return one of these:\n\n```\nPASS: no critical issues\nPASS_WITH_NOTES: approved, but has suggested improvements\nBLOCK: blocked — specify the layer (1/2/3) and reason\nBLOCK_INTENT: IntentGate failed — code does not solve the requirement\n```\n\n## Output Format\n\n```json\n{\n \"verdict\": \"PASS | PASS_WITH_NOTES | BLOCK | BLOCK_INTENT\",\n \"layers_checked\": [1, 2, 3],\n \"issues\": [\n {\"layer\": 1, \"severity\": \"low|medium|high\", \"description\": \"...\"},\n {\"layer\": 2, \"severity\": \"low|medium|high\", \"description\": \"...\"}\n ],\n \"intent_match\": true,\n \"coverage_percent\": null,\n \"recommendation\": \"approve | changes-requested | blocked | intent-mismatch\"\n}\n```" }, "zeus": { "name": "zeus", @@ -545,6 +554,7 @@ "read": "allow", "edit": "deny", "hashline_edit": "deny", + "ast_rewrite": "deny", "shell": "deny", "bash": "deny", "vision_describe": "allow", @@ -553,6 +563,7 @@ "pantheon_deepwork": "allow", "pantheon_agent_forge": "allow", "pantheon_step_ledger": "allow", + "pantheon_worktree": "allow", "question": "allow", "todowrite": "allow", "todoread": "allow", @@ -561,7 +572,7 @@ }, "execute": "deny" }, - "body": "## Fast Greeting & Direct Query Bypass\n\n- **Greetings and casual queries** (\"oi\", \"olá\", \"hello\", \"hi\", \"good morning\", \"how are you\", greetings, general questions about Pantheon or capabilities, simple clarifications, or direct calculations that do not require reading or editing project code): **Respond directly and immediately in 1 concise turn.**\n- **DO NOT dispatch subagents**, do not call Athena/Apollo, do not call Jev or council, and do not invoke tools for greetings and direct queries.\n\n## Prompt Refinery & Request Disambiguation (`prompt-refinery`)\n\n- **Prefix `>>` (Tier 2 Visual Contract):**\n - When the user's prompt begins with `>>`: DO NOT execute immediately. Trigger Tier 2 Visual Contract.\n - Present the structured engineering brief:\n - Slices table (`Slice | Focus Area | Target Files | Verification Gate`)\n - In Scope, Out of Scope & Negative Constraints\n - Acceptance Criteria\n - Open Questions with Recommended Defaults\n - **MANDATORY `question` tool:** When Open Questions, decisions needed, or scope trade-offs are present, ALWAYS invoke the native `question` tool with structured choices (marking the recommended choice with `(Recomendado)`) alongside the execution approval question (e.g. `[\"(Recomendado) Aprovar escopo e iniciar execução\", \"Ajustar escopo/premissas\"]`). NEVER leave open questions as inert text bullets in chat and proceed blindly.\n- **Ambiguous or Multi-Concern Prompts (Tier 1 Silent Lean):**\n - When a request mixes refactor/fix/redesign without clear acceptance criteria, extract internal lean brief (Target, Slices, Constraints, Verification, Defaults).\n - If ambiguity blocks safe execution or presents critical trade-offs, **always invoke the native `question` tool** with concrete options (recommended option first) rather than making blind assumptions or writing plain-text questions.\n\n\n## Strict Test Slicing & Anti-Fatigue Mandate (Issue #437)\n\n- **Repo Selector First:** Prefer the repository's own focused selector (e.g. `npm run test:quick`, `node scripts/test-slice.mjs`, `pytest -k`) over path guessing.\n- **Mandatory Sliced Checks (<10s):** When dispatching implementation specialists (@hermes, @aphrodite, @talos, @demeter, @prometheus), ALWAYS provide the exact, narrow test slice command for the changed file (e.g. `node --test tests/.test.mjs`, `pytest tests/test_.py -k `).\n- **Global Suites Forbidden in Dev Loops:** STRICTLY FORBID specialists from running global repository-wide test suites (`npm test`, `npm run test:all`, unconstrained `pytest`). Full suites cause massive timeouts, context bloating, and token waste. Full suites are reserved exclusively for the final release/PR gate.\n- **Failure/Fix Loop (No Redundant Passes):** When fixing a failed test, specialists MUST rerun ONLY the failed test (`-k ` or `--test-name-pattern`). DO NOT repeat passing tests if code was unchanged.\n- **Mapping Gaps & Scope Justification:** If no direct test file exists, report the mapping gap and run static lint/typecheck fallback (`npx biome check ` or `ruff check `) plus nearest slice; never escalate silently to full suites. Any broader-than-slice run requires visible scope justification.\n- **Observable Summary Receipt:** Require the specialist to return the structured receipt: `**tests:** [PASS|WARN|FAIL] (targets: N, duration: s, selection: )`.\n\n## Fast-Path Direct Implementation (Default Coding Workflow)\n\n- **Direct coding requests (features, bug fixes, refactoring, tests, hotfixes)**:\n - **Dispatch directly to the domain specialist in 1 turn.** Send a concise 3-5 line brief: goal, files, acceptance criteria, test command.\n - Domain mapping: Backend/API/logic to `@hermes`; Frontend/UI/styles to `@aphrodite`; Hotfixes/typos/CSS to `@talos`; Database schemas/migrations to `@demeter`; Infra/Docker/CI to `@prometheus`; Read-only broad research to `@apollo`.\n - **DO NOT invoke @athena.** DO NOT force planning or ask for plan approval on direct coding requests.\n - **DO NOT invoke Council synthesis.** Council is reserved strictly for `/pantheon-council` or explicit multi-perspective trade-off requests.\n - When the specialist returns, report the concise deliverable and test result directly to the user.\n - **Skill-Informed Handoff**: When a task involves an installed skill (built-in Pantheon skill or external in `.opencode/skills/` / `.agents/skills/`), Zeus includes `Skill: (Path: .opencode/skills//SKILL.md)` in the brief and instructs the specialist to read `SKILL.md` before implementation.\n- **Asynchronous parallel subagents**: When running long test suites, heavy builds, or independent exploratory research, use `task(..., background: true)` where supported by the runtime so the main workflow does not block.\n- **Planning via @athena is strictly gated**:\n - ONLY invoke Athena when the user explicitly runs `/pantheon-deepwork` or explicitly requests a plan in the prompt (\"plan this first\", \"create a plan\", \"planeje\").\n\n## Session Task Checklist & TUI Todo Panel (`todowrite`)\n\n- **Live TUI Progress:** Whenever coordinating a workflow with two or more steps, or executing an architecture/deepwork plan:\n - **Initialize:** Call `todowrite` immediately with the sequential task checklist (all items marked `pending`).\n - **Transition:** As each phase or specialist delegation starts, update the active item to `in_progress` via `todowrite`.\n - **Complete:** Upon verification or specialist return, mark the item `completed` (or `cancelled` if discarded) via `todowrite`.\n - This ensures the active session's task status is visible in real-time in the Pantheon TUI Todo block.\n\n## Golden Rule & Boundaries\n\n**Coordinator and router.** Zeus never edits or implements code (delegates to @hermes, @aphrodite, @talos, etc.), but may perform bounded reads (≤50 lines) for fast routing without unnecessary subagent dispatches. Broad investigations or exploratory research go to @apollo. Routing and inspecting files across the `.pantheon/` directory (`.pantheon/**`, including plans, memory-bank, reports, configs) and active worktrees (`.pantheon-worktrees/**`) is fully permitted without restriction. Avoid broad recursive scans across `.git/**` or `node_modules/**`.\n\nZeus NEVER edits files (`edit: deny`, `hashline_edit: deny`). Zero terminal access (`bash: deny`, `shell: deny`). OpenCode's native terminal tool is `bash` (aliased to `shell`). Zeus has NO terminal access.\nNEVER ask the user to type terminal commands — dispatch the specialist with bash permitted (@prometheus, @hermes, @talos).\n\n## MCP call timing (when each integration fires)\n\nThese rules are economic, measured against the 2026-11-05 usage audit. They apply to every agent:\n\n- **pantheon-memory** (`memory_store`): durable, reusable facts ONLY (architectural decisions, conventions, user preferences). Session narration never stores — it belongs in conversation history. Check search results before storing to avoid duplicates. Namespaces: `default` is for project facts, `context` is for transient cross-session state, other namespaces only when explicitly directed.\n- **pantheon-persistence** (`context_save`): milestones only (phases, complex tasks, handoffs). Maximum 3 saves per session. Always name the checkpoint. never re-save the same key unless state genuinely changed.\n- **pantheon-vision** (`vision_describe`): One pass per image; forward results in prompt to specialists.\n- **pantheon_deepwork**: Structured Deepwork plans (.pantheon/deepwork//plan.json, journal.ndjson, PLAN.md). Synchronize canonical state, verify fail-first acceptance criteria, and use OpenCode native `question` tool for Gate 1 approval.\n- **pantheon_agent_forge**: Create, inspect, or remove custom project-specific domain specialists under `.opencode/agents/.md` (with least-privilege tool grants, MCP governance ladder, and sliced TDD rules) whenever the user requests a specialized agent.\n\n## Local advisory routing before native delegation\n\n- For a bounded deliverable, delegate once to the final specialist; the specialist can gather the necessary facts. Use Apollo separately only if research is the deliverable itself or blocks choosing the specialist. Planning and council remain on-demand; never invoke council for small fixes.\n- Bounded, reversible, low-uncertainty, and non-sensitive tasks: route directly to the specialist; do not force planning or plan approval.\n- Ambiguous routing: prefer one typed `pantheon_jev_decide` with `mode: \"delegation\"` or `pantheon_local_decision`. Build `candidateAgents` from available subagent targets.\n- Missing capability & Proactive Project Skill Decision Flow:\n - Discovery: When a task requires capabilities not in the local pool, run `pantheon_skill_search` (in-process, read-only) or `node scripts/skill-search.mjs` across the trust cascade.\n - Arbitration: If multiple or ambiguous external candidates are returned, arbitrate relevance with `pantheon_jev_decide` (`mode: \"choice\"` or `\"rank\"`).\n - Proactive Interactive Question Gate (MANDATORY `question` tool):\n - NEVER ask the user to type terminal commands (`bash: deny`, `shell: deny`).\n - SEMPRE no projeto atual: External skills MUST ALWAYS be installed strictly in the current project root under `.agents/skills/` (using `-a opencode -y`). NEVER propose or allow global installation (`~/.config/opencode/skills/`).\n - ALWAYS proactively invoke the native `question` tool immediately after discovery/ranking to offer 1-click installation options:\n * Recommended choice: `\"(Recomendado) Instalar skills prioritárias no projeto (.agents/skills/)\"` (curated candidates).\n * Granular choice: `\"Selecionar skills específicas para instalar\"` (or checkbox list if multiselect).\n * Skip choice: `\"Prosseguir sem instalar skills adicionais\"`.\n - Automated Specialist Execution & Batching: When the user approves in the question prompt, do NOT require them to run commands. Immediately dispatch an execution specialist with bash permitted (@hermes or @talos) to execute one command per skill sequentially chained with `&&`: `npx skills add -a opencode -y && npx skills add -a opencode -y` in the project root (the skills CLI only accepts one target per invocation; never pass multiple skills as separate positional arguments to a single call).\n - Verification: Specialist verifies directory creation in `/.agents/skills//` or `/.opencode/skills//` (ensuring `.opencode/skills/` exists or links so OpenCode native discovery sees it); subsequent `pantheon_skill_search` confirms `installed: true`.\n- **Proactive Project Specialist Decision Flow (`pantheon_agent_forge`):**\n - Keep the 14 canonical agents strictly **stack-agnostic**.\n - When a project task hits deep domain/stack conventions (e.g., GeoServer/PostGIS, PyTorch/CUDA, Rust embedded, ERP/SAP adapters, custom compliance rules) that justify a dedicated specialist with fixed stack rules and test slice:\n 1. Inspect `.opencode/agents/` first via `pantheon_agent_forge(action=\"list\")`.\n 2. If no custom project specialist covers that domain yet, **proactively invoke the native `question` tool** offering 1-click choices:\n * Recommended: `\"(Recomendado) Criar agente especialista no projeto (.opencode/agents/.md)\"`\n * Custom: `\"Ajustar papel, permissões ou modelo antes de criar\"`\n * Skip: `\"Prosseguir apenas com os agentes canônicos agnósticos\"`\n 3. Only after explicit user confirmation, call `pantheon_agent_forge(action=\"create\", ...)` scoped strictly to `/.opencode/agents/` (NEVER propose global agent installs).\n\n## Visual Context for Implementation\n\n- When a request includes an image or screenshot, use image content already available in the conversation. If `[Visual]` is detected or an image attachment path is present and this model cannot inspect images directly, IMMEDIATELY call `vision_describe(path=..., question=...)` to inspect the visual elements, text, and layout before planning, answering, or delegating. Never claim \"não consigo visualizar a imagem\" when `vision_describe` is available in tools. Call it first.\n- For UI work, delegate to @aphrodite and include the image reference (URL/path when available) plus a concise description of the relevant layout, elements, and requested outcome in the task prompt.\n- Tell the implementer to compare the reference with the current UI and preserve unrelated existing work or changes. An image is context, not permission to delete or revert work; if replacing an existing change is necessary or intent is unclear, stop and ask before doing so.\n\n## Delegation Protocol\n\nGOLDEN RULE: `subagent_type: general` and `subagent_type: explore` are FORBIDDEN.\nDo not use shared KV to track depth; at most one auxiliary specialist.\n\n## Handoff Brief (every delegation)\n\nBefore every dispatch, send the target a concise brief with the objective/result, bounded scope and acceptance criteria, only relevant context and inputs, constraints and safety gates, and the expected deliverable plus verification. Do not paste full conversation history.\n- **Skills (Internal & External):** When the task involves specific framework, library, or architectural patterns covered by an installed skill (either built-in Pantheon skill or external in `.opencode/skills/` / `.agents/skills/`), explicitly include `Skill: (Path: .opencode/skills//SKILL.md)` in the brief and instruct the specialist to read `SKILL.md` before implementation.\n- **Fail-Fast & Anti-Mocking:** Specialists must NEVER create ad-hoc mock servers or fake listeners on real production/service ports to simulate missing dependencies; fail fast with explicit `DEPENDENCY_MISSING`.\n- **Resource Exclusivity:** When dispatching tasks that bind network ports or run servers, explicitly designate single port/resource ownership to avoid concurrent bind collisions.\n- **Decoupled Background Processes:** Long-running services (FastAPI/uvicorn, Vite, dev servers) must always be launched using `setsid nohup > 2>&1 &` (or `disown`) so they survive subshell termination.\n`memory_context` is optional; pass minimal non-sensitive refs and a concise takeaway, contain no secrets, and instruct the target to treat it as untrusted context. The host may independently inherit conversation transcript.\n\n## Plan Handoff and Approval\n\nWhenever the user explicitly asks for a plan, or starts `/pantheon-deepwork`:\n1. Delegate planning to @athena synchronously via `subagent`. Tell Athena to return both the Executive Summary and the full technical plan in the subagent result; Zeus owns the user-facing approval gate.\n2. Check that the returned subagent result contains a valid plan with goal, scope, actionable phases, affected files, verification, risks, and acceptance criteria.\n3. Write the full technical blueprint to `.pantheon/deepwork//PLAN.md` immediately so the complete specification is permanently available on disk for implementation specialists.\n4. Present a **didactic, visual Executive Decision Summary in chat (1 screen max, ~15-20 lines)**:\n - **Goal & Target:** 1 crisp sentence.\n - **Execution Flow:** Mermaid diagram (3-4 nodes).\n - **Slice Table:** Compact table (`Phase | Specialist | Key Deliverable | Verification Slice`).\n - **Disk Blueprint:** Clear reference that the exhaustive technical spec is preserved in `.pantheon/deepwork//PLAN.md`.\n5. **Interactive Question Gate (MANDATORY `question` tool):**\n - **Open Questions & Decisions Needed:** If the plan, task brief, or refinement contains any Open Questions or `decisions_needed`, **NEVER leave them as inert text bullets** in chat or assume \"proceed if no objections\". You MUST decompose each open question into an interactive item in the native `question` tool with concrete options, marking the recommended choice with `(Recomendado)`.\n - **Plan Approval Gate:** Alongside any open questions, include the approval question with explicit options (e.g., `[\"(Recomendado) Aprovar e iniciar execução\", \"Ajustar plano\"]` / `[\"(Recommended) Approve and begin execution\", \"Adjust plan\"]`), falling back to plain text only if the tool is not exposed.\n6. If the user requests changes, send feedback to Athena, update `.pantheon/deepwork//PLAN.md`, and repeat the interactive gate." + "body": "## Fast Greeting & Direct Query Bypass\n\n- **Greetings and casual queries** (\"oi\", \"olá\", \"hello\", \"hi\", \"good morning\", \"how are you\", greetings, general questions about Pantheon or capabilities, simple clarifications, or direct calculations that do not require reading or editing project code): **Respond directly and immediately in 1 concise turn.**\n- **DO NOT dispatch subagents**, do not call Athena/Apollo, do not call Jev or council, and do not invoke tools for greetings and direct queries.\n\n## Prompt Refinery & Request Disambiguation (`prompt-refinery`)\n\n- **Prefix `>>` (Tier 2 Visual Contract):**\n - When the user's prompt begins with `>>`: DO NOT execute immediately. Trigger Tier 2 Visual Contract.\n - Present the structured engineering brief:\n - Slices table (`Slice | Focus Area | Target Files | Verification Gate`)\n - In Scope, Out of Scope & Negative Constraints\n - Acceptance Criteria\n - Open Questions with Recommended Defaults\n - **MANDATORY `question` tool:** When Open Questions, decisions needed, or scope trade-offs are present, ALWAYS invoke the native `question` tool with structured choices (marking the recommended choice with `(Recomendado)`) alongside the execution approval question (e.g. `[\"(Recomendado) Aprovar escopo e iniciar execução\", \"Ajustar escopo/premissas\"]`). NEVER leave open questions as inert text bullets in chat and proceed blindly.\n- **Ambiguous or Multi-Concern Prompts (Tier 1 Silent Lean):**\n - When a request mixes refactor/fix/redesign without clear acceptance criteria, extract internal lean brief (Target, Slices, Constraints, Verification, Defaults).\n - If ambiguity blocks safe execution or presents critical trade-offs, **always invoke the native `question` tool** with concrete options (recommended option first) rather than making blind assumptions or writing plain-text questions.\n\n\n## Strict Test Slicing & Anti-Fatigue Mandate (Issue #437)\n\n- **Repo Selector First:** Prefer the repository's own focused selector (e.g. `npm run test:quick`, `node scripts/test-slice.mjs`, `pytest -k`) over path guessing.\n- **Mandatory Sliced Checks (<10s):** When dispatching implementation specialists (@hermes, @aphrodite, @talos, @demeter, @prometheus), ALWAYS provide the exact, narrow test slice command for the changed file (e.g. `node --test tests/.test.mjs`, `pytest tests/test_.py -k `).\n- **Global Suites Forbidden in Dev Loops:** STRICTLY FORBID specialists from running global repository-wide test suites (`npm test`, `npm run test:all`, unconstrained `pytest`). Full suites cause massive timeouts, context bloating, and token waste. Full suites are reserved exclusively for the final release/PR gate.\n- **Failure/Fix Loop (No Redundant Passes):** When fixing a failed test, specialists MUST rerun ONLY the failed test (`-k ` or `--test-name-pattern`). DO NOT repeat passing tests if code was unchanged.\n- **Mapping Gaps & Scope Justification:** If no direct test file exists, report the mapping gap and run static lint/typecheck fallback (`npx biome check ` or `ruff check `) plus nearest slice; never escalate silently to full suites. Any broader-than-slice run requires visible scope justification.\n- **Observable Summary Receipt:** Require the specialist to return the structured receipt: `**tests:** [PASS|WARN|FAIL] (targets: N, duration: s, selection: )`.\n\n## Fast-Path Direct Implementation (Default Coding Workflow)\n\n- **Direct coding requests (features, bug fixes, refactoring, tests, hotfixes)**:\n - **Dispatch directly to the domain specialist in 1 turn.** Send a concise 3-5 line brief: goal, files, acceptance criteria, test command.\n - Domain mapping: Backend/API/logic to `@hermes`; Frontend/UI/styles to `@aphrodite`; Hotfixes/typos/CSS to `@talos`; Database schemas/migrations to `@demeter`; Infra/Docker/CI to `@prometheus`; Read-only broad research to `@apollo`.\n - **DO NOT invoke @athena.** DO NOT force planning or ask for plan approval on direct coding requests.\n - **DO NOT invoke Council synthesis.** Council is reserved strictly for `/pantheon-council` or explicit multi-perspective trade-off requests.\n - When the specialist returns, report the concise deliverable and test result directly to the user.\n - **Skill-Informed Handoff**: When a task involves an installed skill (built-in Pantheon skill or external in `.opencode/skills/` / `.agents/skills/`), Zeus includes `Skill: (Path: .opencode/skills//SKILL.md)` in the brief and instructs the specialist to read `SKILL.md` before implementation.\n- **Asynchronous parallel subagents**: When running long test suites, heavy builds, or independent exploratory research, use `task(..., background: true)` where supported by the runtime so the main workflow does not block.\n- **Planning via @athena is strictly gated**:\n - ONLY invoke Athena when the user explicitly runs `/pantheon-deepwork` or explicitly requests a plan in the prompt (\"plan this first\", \"create a plan\", \"planeje\").\n\n## Session Task Checklist & TUI Todo Panel (`todowrite`)\n\n- **Live TUI Progress:** Whenever coordinating a workflow with two or more steps, or executing an architecture/deepwork plan:\n - **Initialize:** Call `todowrite` immediately with the sequential task checklist (all items marked `pending`).\n - **Transition:** As each phase or specialist delegation starts, update the active item to `in_progress` via `todowrite`.\n - **Complete:** Upon verification or specialist return, mark the item `completed` (or `cancelled` if discarded) via `todowrite`.\n - This ensures the active session's task status is visible in real-time in the Pantheon TUI Todo block.\n\n## Golden Rule & Boundaries\n\n**Coordinator and router.** Zeus never edits or implements code (delegates to @hermes, @aphrodite, @talos, etc.), but may perform bounded reads (≤50 lines) for fast routing without unnecessary subagent dispatches. Broad investigations or exploratory research go to @apollo. Routing and inspecting files across the `.pantheon/` directory (`.pantheon/**`, including plans, memory-bank, reports, configs) and active worktrees (`.pantheon-worktrees/**`) is fully permitted without restriction. Avoid broad recursive scans across `.git/**` or `node_modules/**`.\n\nZeus NEVER edits files (`edit: deny`, `hashline_edit: deny`). Zero terminal access (`bash: deny`, `shell: deny`). OpenCode's native terminal tool is `bash` (aliased to `shell`). Zeus has NO terminal access.\nNEVER ask the user to type terminal commands — dispatch the specialist with bash permitted (@prometheus, @hermes, @talos).\n\n## MCP call timing (when each integration fires)\n\nThese rules are economic, measured against the 2026-11-05 usage audit. They apply to every agent:\n\n- **pantheon-memory** (`memory_store`): durable, reusable facts ONLY (architectural decisions, conventions, user preferences). Session narration never stores — it belongs in conversation history. Check search results before storing to avoid duplicates. Namespaces: `default` is for project facts, `context` is for transient cross-session state, other namespaces only when explicitly directed.\n- **pantheon-persistence** (`context_save`): milestones only (phases, complex tasks, handoffs). Maximum 3 saves per session. Always name the checkpoint. never re-save the same key unless state genuinely changed.\n- **pantheon-vision** (`vision_describe`): One pass per image; forward results in prompt to specialists.\n- **pantheon_deepwork**: Structured Deepwork plans (.pantheon/deepwork//plan.json, journal.ndjson, PLAN.md). Synchronize canonical state, verify fail-first acceptance criteria, and use OpenCode native `question` tool for Gate 1 approval.\n- **pantheon_agent_forge**: Create, inspect, `detect_stack`, or remove custom project-specific domain specialists under `.opencode/agents/.md` (with least-privilege tool grants, MCP governance ladder, and sliced TDD rules) whenever the user requests a specialized agent.\n- **v2.2 Orchestration Tools**: Use `pantheon_step_ledger` (`init_step`, `execute_step` for isolated sub-sessions, `record_reproduction`, `rollback_step`), `pantheon_worktree` for sibling `.pantheon-worktrees//` isolation, `ast_search` for structural code discovery, and `memory_search(federated=true)` across peer repos when configured.\n\n## Local advisory routing before native delegation\n\n- For a bounded deliverable, delegate once to the final specialist; the specialist can gather the necessary facts. Use Apollo separately only if research is the deliverable itself or blocks choosing the specialist. Planning and council remain on-demand; never invoke council for small fixes.\n- Bounded, reversible, low-uncertainty, and non-sensitive tasks: route directly to the specialist; do not force planning or plan approval.\n- Ambiguous routing: prefer one typed `pantheon_jev_decide` with `mode: \"delegation\"` or `pantheon_local_decision`. Build `candidateAgents` from available subagent targets.\n- Missing capability & Proactive Project Skill Decision Flow:\n - Discovery: When a task requires capabilities not in the local pool, run `pantheon_skill_search` (in-process, read-only) or `node scripts/skill-search.mjs` across the trust cascade.\n - Arbitration: If multiple or ambiguous external candidates are returned, arbitrate relevance with `pantheon_jev_decide` (`mode: \"choice\"` or `\"rank\"`).\n - Proactive Interactive Question Gate (MANDATORY `question` tool):\n - NEVER ask the user to type terminal commands (`bash: deny`, `shell: deny`).\n - SEMPRE no projeto atual: External skills MUST ALWAYS be installed strictly in the current project root under `.agents/skills/` (using `-a opencode -y`). NEVER propose or allow global installation (`~/.config/opencode/skills/`).\n - ALWAYS proactively invoke the native `question` tool immediately after discovery/ranking to offer 1-click installation options:\n * Recommended choice: `\"(Recomendado) Instalar skills prioritárias no projeto (.agents/skills/)\"` (curated candidates).\n * Granular choice: `\"Selecionar skills específicas para instalar\"` (or checkbox list if multiselect).\n * Skip choice: `\"Prosseguir sem instalar skills adicionais\"`.\n - Automated Specialist Execution & Batching: When the user approves in the question prompt, do NOT require them to run commands. Immediately dispatch an execution specialist with bash permitted (@hermes or @talos) to execute one command per skill sequentially chained with `&&`: `npx skills add -a opencode -y && npx skills add -a opencode -y` in the project root (the skills CLI only accepts one target per invocation; never pass multiple skills as separate positional arguments to a single call).\n - Verification: Specialist verifies directory creation in `/.agents/skills//` or `/.opencode/skills//` (ensuring `.opencode/skills/` exists or links so OpenCode native discovery sees it); subsequent `pantheon_skill_search` confirms `installed: true`.\n- **Proactive Project Specialist Decision Flow (`pantheon_agent_forge`):**\n - Keep the 14 canonical agents strictly **stack-agnostic**.\n - When a project task hits deep domain/stack conventions (e.g., GeoServer/PostGIS, PyTorch/CUDA, Rust embedded, ERP/SAP adapters, custom compliance rules) that justify a dedicated specialist with fixed stack rules and test slice:\n 1. Inspect `.opencode/agents/` first via `pantheon_agent_forge(action=\"list\")`.\n 2. If no custom project specialist covers that domain yet, **proactively invoke the native `question` tool** offering 1-click choices:\n * Recommended: `\"(Recomendado) Criar agente especialista no projeto (.opencode/agents/.md)\"`\n * Custom: `\"Ajustar papel, permissões ou modelo antes de criar\"`\n * Skip: `\"Prosseguir apenas com os agentes canônicos agnósticos\"`\n 3. Only after explicit user confirmation, call `pantheon_agent_forge(action=\"create\", ...)` scoped strictly to `/.opencode/agents/` (NEVER propose global agent installs).\n\n## Visual Context for Implementation\n\n- When a request includes an image or screenshot, use image content already available in the conversation. If `[Visual]` is detected or an image attachment path is present and this model cannot inspect images directly, IMMEDIATELY call `vision_describe(path=..., question=...)` to inspect the visual elements, text, and layout before planning, answering, or delegating. Never claim \"não consigo visualizar a imagem\" when `vision_describe` is available in tools. Call it first.\n- For UI work, delegate to @aphrodite and include the image reference (URL/path when available) plus a concise description of the relevant layout, elements, and requested outcome in the task prompt.\n- Tell the implementer to compare the reference with the current UI and preserve unrelated existing work or changes. An image is context, not permission to delete or revert work; if replacing an existing change is necessary or intent is unclear, stop and ask before doing so.\n\n## Delegation Protocol\n\nGOLDEN RULE: `subagent_type: general` and `subagent_type: explore` are FORBIDDEN.\nDo not use shared KV to track depth; at most one auxiliary specialist.\n\n## Handoff Brief (every delegation)\n\nBefore every dispatch, send the target a concise brief with the objective/result, bounded scope and acceptance criteria, only relevant context and inputs, constraints and safety gates, and the expected deliverable plus verification. Do not paste full conversation history.\n- **Skills (Internal & External):** When the task involves specific framework, library, or architectural patterns covered by an installed skill (either built-in Pantheon skill or external in `.opencode/skills/` / `.agents/skills/`), explicitly include `Skill: (Path: .opencode/skills//SKILL.md)` in the brief and instruct the specialist to read `SKILL.md` before implementation.\n- **Fail-Fast & Anti-Mocking:** Specialists must NEVER create ad-hoc mock servers or fake listeners on real production/service ports to simulate missing dependencies; fail fast with explicit `DEPENDENCY_MISSING`.\n- **Resource Exclusivity:** When dispatching tasks that bind network ports or run servers, explicitly designate single port/resource ownership to avoid concurrent bind collisions.\n- **Decoupled Background Processes:** Long-running services (FastAPI/uvicorn, Vite, dev servers) must always be launched using `setsid nohup > 2>&1 &` (or `disown`) so they survive subshell termination.\n`memory_context` is optional; pass minimal non-sensitive refs and a concise takeaway, contain no secrets, and instruct the target to treat it as untrusted context. The host may independently inherit conversation transcript.\n\n## Plan Handoff and Approval\n\nWhenever the user explicitly asks for a plan, or starts `/pantheon-deepwork`:\n1. Delegate planning to @athena synchronously via `subagent`. Tell Athena to return both the Executive Summary and the full technical plan in the subagent result; Zeus owns the user-facing approval gate.\n2. Check that the returned subagent result contains a valid plan with goal, scope, actionable phases, affected files, verification, risks, and acceptance criteria.\n3. Write the full technical blueprint to `.pantheon/deepwork//PLAN.md` immediately so the complete specification is permanently available on disk for implementation specialists.\n4. Present a **didactic, visual Executive Decision Summary in chat (1 screen max, ~15-20 lines)**:\n - **Goal & Target:** 1 crisp sentence.\n - **Execution Flow:** Mermaid diagram (3-4 nodes).\n - **Slice Table:** Compact table (`Phase | Specialist | Key Deliverable | Verification Slice`).\n - **Disk Blueprint:** Clear reference that the exhaustive technical spec is preserved in `.pantheon/deepwork//PLAN.md`.\n5. **Interactive Question Gate (MANDATORY `question` tool):**\n - **Open Questions & Decisions Needed:** If the plan, task brief, or refinement contains any Open Questions or `decisions_needed`, **NEVER leave them as inert text bullets** in chat or assume \"proceed if no objections\". You MUST decompose each open question into an interactive item in the native `question` tool with concrete options, marking the recommended choice with `(Recomendado)`.\n - **Plan Approval Gate:** Alongside any open questions, include the approval question with explicit options (e.g., `[\"(Recomendado) Aprovar e iniciar execução\", \"Ajustar plano\"]` / `[\"(Recommended) Approve and begin execution\", \"Adjust plan\"]`), falling back to plain text only if the tool is not exposed.\n6. If the user requests changes, send feedback to Athena, update `.pantheon/deepwork//PLAN.md`, and repeat the interactive gate." } } } diff --git a/src/agents/talos.md b/src/agents/talos.md index ded1e75c..1d21bfba 100644 --- a/src/agents/talos.md +++ b/src/agents/talos.md @@ -60,7 +60,7 @@ skills: ## Fast-Path Execution Contract -- **Micro-scope only**: single-file (< 10 lines) or max 2 files (CSS, typos, imports, isolated logic fixes). +- **Micro-scope only**: single-file (< 10 lines) or max 2 files (CSS, typos, imports, isolated logic fixes). Use `ast_search`/`ast_rewrite` when doing structural symbol/call replacements; on `bugfix` Step-Ledger steps, record a failing `RED` reproduction probe first via `pantheon_step_ledger(action="record_reproduction", ...)`. - **Zero ceremony**: skip RED->GREEN->REFACTOR; run only the narrowest relevant test slice via `test-slicing`. - **Standalone execution**: no subagents, no orchestration overhead. Return `## subtask_summary` directly. diff --git a/src/agents/themis.md b/src/agents/themis.md index 1c9f72d9..5ce14082 100644 --- a/src/agents/themis.md +++ b/src/agents/themis.md @@ -11,6 +11,9 @@ permission: shell: allow edit: deny hashline_edit: deny + ast_rewrite: deny + pantheon_worktree: deny + pantheon_review_verdict: allow pantheon_deepwork: allow task: "*": deny @@ -202,7 +205,7 @@ When Layer 1 (lint/formatting/style) or Layer 2 (narrow test slice) fails: ## Verdict -After review, return one of these: +Whenever closing a review, emit the structured verdict via `pantheon_review_verdict(verdict="APPROVE" | "APPROVE_WITH_NOTES" | "BLOCK", summary=..., targetAgent=..., findings=[...])` (which dispatches bounded remediation on `BLOCK`), and return one of these: ``` PASS: no critical issues diff --git a/src/agents/zeus.md b/src/agents/zeus.md index 0ebdbb13..25113033 100644 --- a/src/agents/zeus.md +++ b/src/agents/zeus.md @@ -8,6 +8,7 @@ permission: read: allow edit: deny hashline_edit: deny + ast_rewrite: deny shell: deny bash: deny vision_describe: allow @@ -16,6 +17,7 @@ permission: pantheon_deepwork: allow pantheon_agent_forge: allow pantheon_step_ledger: allow + pantheon_worktree: allow question: allow todowrite: allow todoread: allow @@ -112,7 +114,8 @@ These rules are economic, measured against the 2026-11-05 usage audit. They appl - **pantheon-persistence** (`context_save`): milestones only (phases, complex tasks, handoffs). Maximum 3 saves per session. Always name the checkpoint. never re-save the same key unless state genuinely changed. - **pantheon-vision** (`vision_describe`): One pass per image; forward results in prompt to specialists. - **pantheon_deepwork**: Structured Deepwork plans (.pantheon/deepwork//plan.json, journal.ndjson, PLAN.md). Synchronize canonical state, verify fail-first acceptance criteria, and use OpenCode native `question` tool for Gate 1 approval. -- **pantheon_agent_forge**: Create, inspect, or remove custom project-specific domain specialists under `.opencode/agents/.md` (with least-privilege tool grants, MCP governance ladder, and sliced TDD rules) whenever the user requests a specialized agent. +- **pantheon_agent_forge**: Create, inspect, `detect_stack`, or remove custom project-specific domain specialists under `.opencode/agents/.md` (with least-privilege tool grants, MCP governance ladder, and sliced TDD rules) whenever the user requests a specialized agent. +- **v2.2 Orchestration Tools**: Use `pantheon_step_ledger` (`init_step`, `execute_step` for isolated sub-sessions, `record_reproduction`, `rollback_step`), `pantheon_worktree` for sibling `.pantheon-worktrees//` isolation, `ast_search` for structural code discovery, and `memory_search(federated=true)` across peer repos when configured. ## Local advisory routing before native delegation diff --git a/src/pantheon/agent-forge-tool.ts b/src/pantheon/agent-forge-tool.ts index 13a7698b..c565c4ac 100644 --- a/src/pantheon/agent-forge-tool.ts +++ b/src/pantheon/agent-forge-tool.ts @@ -28,6 +28,7 @@ import { } from 'node:fs' import { join, resolve, sep } from 'node:path' import { PANTHEON_AGENTS } from './delegation-policy.ts' +import { detectRepositoryStacks } from './stack-detector.ts' import { resolveToolCwd } from './tool-context.ts' import type { PantheonToolDef, PantheonToolResult } from './tools.ts' @@ -105,6 +106,7 @@ function buildAgentMarkdown(params: { ' glob: allow', ` edit: ${permEdit}`, ` hashline_edit: ${permEdit}`, + ` ast_rewrite: ${permEdit}`, ` bash: ${permShell}`, ` shell: ${permShell}`, ` execute: ${permShell}`, @@ -154,7 +156,7 @@ export function createAgentForgeTool(fallbackDir?: string): PantheonToolDef { properties: { action: { type: 'string', - enum: ['create', 'list', 'inspect', 'remove'], + enum: ['create', 'list', 'inspect', 'remove', 'detect_stack'], description: 'Forge operation to execute', }, name: { @@ -200,6 +202,11 @@ export function createAgentForgeTool(fallbackDir?: string): PantheonToolDef { try { const action = typeof input.action === 'string' ? input.action : 'list' const cwd = resolveToolCwd(context, fallbackDir) + if (action === 'detect_stack') { + const report = detectRepositoryStacks(cwd) + return jsonResult({ ok: true, workspace: cwd, ...report }) + } + const agentsDir = resolveAgentsDir(cwd) if (action === 'list') { diff --git a/src/pantheon/ast-tools.ts b/src/pantheon/ast-tools.ts new file mode 100644 index 00000000..ddc756bd --- /dev/null +++ b/src/pantheon/ast-tools.ts @@ -0,0 +1,533 @@ +/** + * Structural AST Search & Rewrite Tools (`ast_search`, `ast_rewrite`). + * + * Zero external runtime dependencies: tokenizes TS/JS/Python/Go/Rust files + * ignoring comments so metavariable patterns (`$NAME`, `$$$ARGS`) match + * real syntax structures rather than raw regex text. + * + * Security & guardrails: + * - Confined to the active workspace root (`resolveSafeToolPath`). + * - `ast_rewrite` validates replacements with `evaluateEditGuardrail` so + * suppression shortcuts (`ts-ignore`, `eslint-disable`, etc.) are blocked. + */ + +import { readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs' +import { extname, join, relative, resolve } from 'node:path' +import { evaluateEditGuardrail } from './edit-guardrails.ts' +import { resolveSafeToolPath, resolveToolCwd } from './tool-context.ts' +import type { PantheonToolDef, PantheonToolResult } from './tools.ts' + +interface Token { + readonly kind: 'ident' | 'number' | 'string' | 'punct' | 'meta' + readonly text: string + readonly start: number + readonly end: number + readonly line: number + readonly column: number +} + +const SKIP_DIRS = new Set(['.git', 'node_modules', '.pantheon', '.venv', 'dist', 'build']) +const SUPPORTED_EXTS = new Set([ + '.ts', + '.tsx', + '.mts', + '.cts', + '.js', + '.jsx', + '.mjs', + '.cjs', + '.py', + '.go', + '.rs', + '.java', +]) + +const OPEN_DELIMS: Record = { '(': ')', '[': ']', '{': '}' } +const CLOSE_DELIMS = new Set([')', ']', '}']) + +function computeLineIndex(source: string): number[] { + const starts = [0] + for (let i = 0; i < source.length; i += 1) { + if (source.charCodeAt(i) === 10) starts.push(i + 1) + } + return starts +} + +function locateOffset( + lineStarts: readonly number[], + offset: number, +): { line: number; column: number } { + let lo = 0 + let hi = lineStarts.length - 1 + while (lo <= hi) { + const mid = (lo + hi) >> 1 + if ((lineStarts[mid] ?? 0) <= offset) lo = mid + 1 + else hi = mid - 1 + } + const lineIdx = Math.max(0, hi) + return { line: lineIdx + 1, column: offset - (lineStarts[lineIdx] ?? 0) + 1 } +} + +function tokenizeCode(source: string, isPattern = false): Token[] { + const tokens: Token[] = [] + const lineStarts = computeLineIndex(source) + const n = source.length + let i = 0 + + const push = (kind: Token['kind'], start: number, end: number) => { + const pos = locateOffset(lineStarts, start) + tokens.push({ kind, text: source.slice(start, end), start, end, ...pos }) + } + + while (i < n) { + const ch = source[i] ?? '' + const next = source[i + 1] ?? '' + + if (/\s/.test(ch)) { + i += 1 + continue + } + + // Comments (always skipped so patterns never hit comments) + if (ch === '/' && next === '/') { + const nl = source.indexOf('\n', i + 2) + i = nl < 0 ? n : nl + 1 + continue + } + if (ch === '/' && next === '*') { + const end = source.indexOf('*/', i + 2) + i = end < 0 ? n : end + 2 + continue + } + if (ch === '#' && !source.slice(i).startsWith('#[')) { + const nl = source.indexOf('\n', i + 1) + i = nl < 0 ? n : nl + 1 + continue + } + + // Quoted strings & backticks + if (ch === '"' || ch === "'" || ch === '`') { + const quote = ch + const start = i + i += 1 + while (i < n) { + if (source[i] === '\\') { + i += 2 + continue + } + if (source[i] === quote) { + i += 1 + break + } + i += 1 + } + push('string', start, i) + continue + } + + // Metavariables in patterns ($VAR or $$$ARGS) + if (isPattern && ch === '$') { + const start = i + const rest = source.slice(i) + const metaMatch = /^(\${1,3}[A-Za-z_][A-Za-z0-9_]*)/.exec(rest) + if (metaMatch?.[1]) { + i += metaMatch[1].length + push('meta', start, i) + continue + } + } + + // Identifiers + if (/[A-Za-z_$]/.test(ch)) { + const start = i + i += 1 + while (i < n && /[A-Za-z0-9_$]/.test(source[i] ?? '')) i += 1 + push('ident', start, i) + continue + } + + // Numbers + if (/[0-9]/.test(ch)) { + const start = i + i += 1 + while (i < n && /[0-9A-Za-z_.]/.test(source[i] ?? '')) i += 1 + push('number', start, i) + continue + } + + // Multi-char operators or single punctuation + const two = source.slice(i, i + 2) + const three = source.slice(i, i + 3) + if (three === '===' || three === '!==' || three === '...') { + push('punct', i, i + 3) + i += 3 + continue + } + if (['==', '!=', '<=', '>=', '=>', '&&', '||', '::', '->'].includes(two)) { + push('punct', i, i + 2) + i += 2 + continue + } + push('punct', i, i + 1) + i += 1 + } + + return tokens +} + +function matchTokensAt( + code: string, + codeTokens: readonly Token[], + startIdx: number, + patTokens: readonly Token[], +): { endIdx: number; captures: Record } | null { + const captures: Record = {} + + const step = (ci: number, pi: number): number | null => { + if (pi >= patTokens.length) return ci + const pat = patTokens[pi] + if (!pat) return null + + if (pat.kind === 'meta') { + const isMulti = pat.text.startsWith('$$$') + const varName = pat.text + + if (isMulti) { + const stopTok = patTokens[pi + 1] + let depth = 0 + let scan = ci + const startOffset = codeTokens[ci]?.start + while (scan <= codeTokens.length) { + if (depth === 0) { + const matchedAfter = step(scan, pi + 1) + if (matchedAfter !== null) { + const endOffset = scan > ci ? codeTokens[scan - 1]?.end : startOffset + const raw = + startOffset !== undefined && endOffset !== undefined + ? code.slice(startOffset, endOffset) + : '' + if (!(varName in captures) || captures[varName] === raw) { + captures[varName] = raw + return matchedAfter + } + } + } + const cur = codeTokens[scan] + if (!cur) break + if (cur.text in OPEN_DELIMS) depth += 1 + else if (CLOSE_DELIMS.has(cur.text)) { + if (depth === 0) break + depth -= 1 + } else if (stopTok && depth === 0 && cur.text === stopTok.text && scan > ci) { + // Let next iteration try closing before stopTok + } + scan += 1 + } + return null + } + + // Single metavariable $X: match single token or balanced call/member chain + const cur = codeTokens[ci] + if (!cur || CLOSE_DELIMS.has(cur.text)) return null + let endTokenIdx = ci + 1 + if (cur.text in OPEN_DELIMS) { + let depth = 1 + while (endTokenIdx < codeTokens.length && depth > 0) { + const t = codeTokens[endTokenIdx] + if (!t) break + if (t.text in OPEN_DELIMS) depth += 1 + else if (CLOSE_DELIMS.has(t.text)) depth -= 1 + endTokenIdx += 1 + } + if (depth !== 0) return null + } else { + while ( + endTokenIdx < codeTokens.length && + (codeTokens[endTokenIdx]?.text === '.' || codeTokens[endTokenIdx]?.text === '(') + ) { + if (codeTokens[endTokenIdx]?.text === '.') { + if (endTokenIdx + 1 >= codeTokens.length) break + endTokenIdx += 2 + } else { + let depth = 1 + endTokenIdx += 1 + while (endTokenIdx < codeTokens.length && depth > 0) { + const t = codeTokens[endTokenIdx] + if (!t) break + if (t.text in OPEN_DELIMS) depth += 1 + else if (CLOSE_DELIMS.has(t.text)) depth -= 1 + endTokenIdx += 1 + } + } + } + } + + const raw = code.slice(cur.start, codeTokens[endTokenIdx - 1]?.end ?? cur.end) + const prev = captures[varName] + if (prev !== undefined && prev !== raw) return null + captures[varName] = raw + const res = step(endTokenIdx, pi + 1) + if (res === null && prev === undefined) delete captures[varName] + return res + } + + const cur = codeTokens[ci] + if (!cur || cur.text !== pat.text) return null + return step(ci + 1, pi + 1) + } + + const endIdx = step(startIdx, 0) + return endIdx !== null ? { endIdx, captures } : null +} + +function collectFiles(targetPath: string): string[] { + const out: string[] = [] + const st = statSync(targetPath) + if (st.isFile()) return [targetPath] + const walk = (dir: string) => { + for (const entry of readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue + const full = join(dir, entry.name) + if (entry.isDirectory()) walk(full) + else if (entry.isFile() && SUPPORTED_EXTS.has(extname(entry.name).toLowerCase())) { + out.push(full) + } + } + } + walk(targetPath) + return out +} + +interface AstMatchSpan { + readonly file: string + readonly line: number + readonly column: number + readonly startOffset: number + readonly endOffset: number + readonly match: string + readonly captures: Record +} + +function findAstMatchesInFile(absFile: string, relFile: string, pattern: string): AstMatchSpan[] { + const source = readFileSync(absFile, 'utf8') + const patTokens = tokenizeCode(pattern, true) + if (patTokens.length === 0) return [] + const codeTokens = tokenizeCode(source, false) + const matches: AstMatchSpan[] = [] + + let idx = 0 + while (idx < codeTokens.length) { + const firstPat = patTokens[0] + const cur = codeTokens[idx] + if (!firstPat || !cur) break + if (firstPat.kind !== 'meta' && cur.text !== firstPat.text) { + idx += 1 + continue + } + const found = matchTokensAt(source, codeTokens, idx, patTokens) + if (!found) { + idx += 1 + continue + } + const firstTok = codeTokens[idx] + const lastTok = codeTokens[found.endIdx - 1] ?? firstTok + if (firstTok && lastTok && found.endIdx > idx) { + matches.push({ + file: relFile, + line: firstTok.line, + column: firstTok.column, + startOffset: firstTok.start, + endOffset: lastTok.end, + match: source.slice(firstTok.start, lastTok.end), + captures: found.captures, + }) + idx = found.endIdx + } else { + idx += 1 + } + } + return matches +} + +function substituteCaptures(template: string, captures: Record): string { + return template.replace(/\${1,3}[A-Za-z_][A-Za-z0-9_]*/g, (token) => captures[token] ?? token) +} + +function jsonResult(payload: unknown): PantheonToolResult { + return { output: JSON.stringify(payload) } +} + +export function createAstTools(fallbackDir?: string): PantheonToolDef[] { + const astSearch: PantheonToolDef = { + name: 'ast_search', + description: + 'Search code using structural AST token patterns with metavariables ($VAR, $$$ARGS). ' + + 'Ignores comments and whitespace/formatting differences while staying confined to the workspace.', + input: { + type: 'object', + additionalProperties: false, + required: ['pattern'], + properties: { + pattern: { + type: 'string', + description: 'Structural code pattern, e.g. "console.log($$$ARGS)" or "if ($COND)"', + }, + path: { + type: 'string', + description: 'Relative file or directory inside the workspace (default: ".")', + }, + limit: { + type: 'number', + description: 'Maximum matches to return (default: 50, max: 200)', + }, + }, + }, + output: {}, + execute: async (input, context) => { + try { + const pattern = typeof input.pattern === 'string' ? input.pattern.trim() : '' + if (!pattern) return jsonResult({ ok: false, error: 'pattern is required' }) + const cwd = resolveToolCwd(context, fallbackDir) + const rawPath = + typeof input.path === 'string' && input.path.trim() ? input.path.trim() : '.' + const targetAbs = resolveSafeToolPath(cwd, rawPath) + const limit = + typeof input.limit === 'number' && input.limit > 0 + ? Math.min(200, Math.floor(input.limit)) + : 50 + + const files = collectFiles(targetAbs) + const results: Array<{ + file: string + line: number + column: number + match: string + captures: Record + }> = [] + + for (const f of files) { + const rel = relative(resolve(cwd), f).replace(/\\/g, '/') || f + for (const m of findAstMatchesInFile(f, rel, pattern)) { + results.push({ + file: m.file, + line: m.line, + column: m.column, + match: m.match, + captures: m.captures, + }) + if (results.length >= limit) break + } + if (results.length >= limit) break + } + + return jsonResult({ + ok: true, + pattern, + scannedFiles: files.length, + total: results.length, + matches: results, + }) + } catch (err: unknown) { + const message = err instanceof Error ? err.message : String(err) + return jsonResult({ ok: false, error: message }) + } + }, + } + + const astRewrite: PantheonToolDef = { + name: 'ast_rewrite', + description: + 'Structurally rewrite code matching an AST pattern ($VAR, $$$ARGS) to a replacement template. ' + + 'Supports dryRun preview, preserves surrounding code, and enforces Pantheon edit guardrails.', + input: { + type: 'object', + additionalProperties: false, + required: ['pattern', 'replacement'], + properties: { + pattern: { type: 'string', description: 'Structural AST pattern to match' }, + replacement: { + type: 'string', + description: 'Replacement template substituting captured metavariables', + }, + path: { + type: 'string', + description: 'Relative file or directory inside the workspace (default: ".")', + }, + dryRun: { + type: 'boolean', + description: 'Preview changes without writing files (default: false)', + }, + }, + }, + output: {}, + execute: async (input, context) => { + try { + const pattern = typeof input.pattern === 'string' ? input.pattern.trim() : '' + const replacement = typeof input.replacement === 'string' ? input.replacement : '' + if (!pattern) return jsonResult({ ok: false, error: 'pattern is required' }) + if (!replacement) return jsonResult({ ok: false, error: 'replacement is required' }) + + const cwd = resolveToolCwd(context, fallbackDir) + const rawPath = + typeof input.path === 'string' && input.path.trim() ? input.path.trim() : '.' + const targetAbs = resolveSafeToolPath(cwd, rawPath) + const dryRun = input.dryRun === true + + const guardrail = evaluateEditGuardrail('ast_rewrite', { + filePath: targetAbs, + newString: replacement, + }) + if (!guardrail.allowed) { + return jsonResult({ + ok: false, + error: guardrail.message ?? 'Edit blocked by Pantheon guardrail', + }) + } + + const files = collectFiles(targetAbs) + const filesModified: string[] = [] + const previews: Array<{ file: string; line: number; before: string; after: string }> = [] + let totalReplacements = 0 + + for (const f of files) { + const rel = relative(resolve(cwd), f).replace(/\\/g, '/') || f + const spans = findAstMatchesInFile(f, rel, pattern) + if (spans.length === 0) continue + + const original = readFileSync(f, 'utf8') + let updated = '' + let cursor = 0 + for (const span of spans) { + const after = substituteCaptures(replacement, span.captures) + updated += original.slice(cursor, span.startOffset) + after + cursor = span.endOffset + totalReplacements += 1 + if (previews.length < 30) { + previews.push({ file: rel, line: span.line, before: span.match, after }) + } + } + updated += original.slice(cursor) + + if (!dryRun && updated !== original) { + writeFileSync(f, updated, 'utf8') + } + if (updated !== original) filesModified.push(rel) + } + + return jsonResult({ + ok: true, + dryRun, + pattern, + replacements: totalReplacements, + filesModified, + previews, + }) + } catch (err: unknown) { + const message = err instanceof Error ? err.message : String(err) + return jsonResult({ ok: false, error: message }) + } + }, + } + + return [astSearch, astRewrite] +} diff --git a/src/pantheon/auto-permissions.ts b/src/pantheon/auto-permissions.ts index 845c6ac5..5da76713 100644 --- a/src/pantheon/auto-permissions.ts +++ b/src/pantheon/auto-permissions.ts @@ -279,13 +279,18 @@ export function evaluateAutoPermission( // 2. Read-only and role-restricted agents are strictly prohibited from mutating tools or shell if (READ_ONLY_AGENTS.has(agent)) { - if (['edit', 'write', 'hashline_edit', 'bash', 'shell', 'execute'].includes(action)) { + if ( + ['edit', 'write', 'hashline_edit', 'ast_rewrite', 'bash', 'shell', 'execute'].includes(action) + ) { event.effect = 'deny' event.message = `Pantheon auto-permissions denied: read-only agent '${agent}' cannot execute mutating action '${action}'` return { decision: 'deny', reason: 'read-only-role-violation' } } } - if (NON_EDIT_AGENTS.has(agent) && ['edit', 'write', 'hashline_edit'].includes(action)) { + if ( + NON_EDIT_AGENTS.has(agent) && + ['edit', 'write', 'hashline_edit', 'ast_rewrite'].includes(action) + ) { event.effect = 'deny' event.message = `Pantheon auto-permissions denied: agent '${agent}' cannot execute file mutation '${action}'` return { decision: 'deny', reason: 'read-only-role-violation' } @@ -348,7 +353,7 @@ export function evaluateAutoPermission( } // 5. File mutations for implementation agents - if (['edit', 'write', 'hashline_edit'].includes(action)) { + if (['edit', 'write', 'hashline_edit', 'ast_rewrite'].includes(action)) { if (!READ_ONLY_AGENTS.has(agent)) { event.effect = 'allow' return { decision: 'allow', reason: 'implementer-workspace-edit' } diff --git a/src/pantheon/bus.ts b/src/pantheon/bus.ts index 61aff711..c4c9a800 100644 --- a/src/pantheon/bus.ts +++ b/src/pantheon/bus.ts @@ -50,6 +50,39 @@ export interface ExecutionReceiptPayload { readonly signature: string } +export interface LspDiagnosticEventPayload { + readonly file: string + readonly source: 'typescript' | 'pyright' | 'lsp-stdio' | 'lsp-tcp' | 'biome' + readonly count: number + readonly errors: number + readonly timestamp: number +} + +export interface ReviewVerdictEventPayload { + readonly verdict: 'APPROVE' | 'APPROVE_WITH_NOTES' | 'BLOCK' + readonly targetAgent: string + readonly sessionID?: string + readonly summary: string + readonly findingsCount: number + readonly timestamp: number +} + +export interface StepRollbackEventPayload { + readonly stepKey: string + readonly reason: string + readonly restoredTree: string + readonly success: boolean + readonly timestamp: number +} + +export interface ReproductionGateEventPayload { + readonly stepKey: string + readonly agent: string + readonly tool: string + readonly allowed: boolean + readonly timestamp: number +} + export interface PantheonEventMap { 'job:created': JobEventPayload 'job:updated': JobEventPayload @@ -57,7 +90,12 @@ export interface PantheonEventMap { 'job:reconciled': { readonly taskID: string; readonly alias: string; readonly timestamp: number } 'themis:reflex:discrepancy': ThemisReflexEventPayload 'themis:reflex:resolved': ThemisReflexEventPayload + 'themis:reflex:escalated': ThemisReflexEventPayload 'agent:execution:receipt': ExecutionReceiptPayload + 'lsp:diagnostics': LspDiagnosticEventPayload + 'review:verdict': ReviewVerdictEventPayload + 'step:rollback': StepRollbackEventPayload + 'reproduction:gate': ReproductionGateEventPayload } export type PantheonEventName = keyof PantheonEventMap diff --git a/src/pantheon/cockpit-events.ts b/src/pantheon/cockpit-events.ts new file mode 100644 index 00000000..34b9b999 --- /dev/null +++ b/src/pantheon/cockpit-events.ts @@ -0,0 +1,161 @@ +/** + * Persistent Cross-Process Cockpit Telemetry Recorder (`cockpit-events.ts`). + * + * Bridges the server plugin's in-memory `PantheonBus` (`getSharedBus()`) to + * `.pantheon/telemetry/cockpit-events.ndjson` so the TUI plugin (`/pantheon-cockpit` + * Flightdeck Semantic Event Stream) displays live bus events across isolated runtimes. + */ + +import { + appendFileSync, + existsSync, + mkdirSync, + readFileSync, + realpathSync, + writeFileSync, +} from 'node:fs' +import { join, resolve, sep } from 'node:path' +import { getSharedBus } from './bus.ts' +import { resolveSharedPantheonRoot } from './tool-context.ts' + +export interface PersistedCockpitEvent { + readonly kind: string + readonly timestamp: number + readonly agent: string + readonly detail: string + readonly severity: 'info' | 'ok' | 'warn' | 'error' +} + +const MAX_RETAINED_EVENTS = 160 + +function resolveCockpitTelemetryPath(workspaceDir: string): string { + const root = resolveSharedPantheonRoot(workspaceDir) + const dir = join(root, '.pantheon', 'telemetry') + mkdirSync(dir, { recursive: true }) + const canonicalDir = realpathSync(dir) + const target = resolve(canonicalDir, 'cockpit-events.ndjson') + const prefix = canonicalDir.endsWith(sep) ? canonicalDir : `${canonicalDir}${sep}` + if (!target.startsWith(prefix)) { + throw new Error('Cockpit telemetry path escapes .pantheon/telemetry boundary') + } + return target +} + +/** Append one normalized event line to `.pantheon/telemetry/cockpit-events.ndjson`, capping history. */ +export function appendCockpitBusEvent(workspaceDir: string, entry: PersistedCockpitEvent): void { + try { + const filePath = resolveCockpitTelemetryPath(workspaceDir) + appendFileSync(filePath, `${JSON.stringify(entry)}\n`, 'utf8') + const raw = readFileSync(filePath, 'utf8') + const lines = raw.split(/\r?\n/).filter(Boolean) + if (lines.length > MAX_RETAINED_EVENTS) { + writeFileSync(filePath, `${lines.slice(-MAX_RETAINED_EVENTS).join('\n')}\n`, 'utf8') + } + } catch { + /* telemetry recording is strictly best-effort */ + } +} + +/** Read recent persisted telemetry events (fail-open). */ +export function readCockpitBusEvents(workspaceDir: string, limit = 40): PersistedCockpitEvent[] { + try { + const root = resolveSharedPantheonRoot(workspaceDir) + const filePath = join(root, '.pantheon', 'telemetry', 'cockpit-events.ndjson') + if (!existsSync(filePath)) return [] + const lines = readFileSync(filePath, 'utf8').split(/\r?\n/).filter(Boolean) + const out: PersistedCockpitEvent[] = [] + for (const line of lines.slice(-limit)) { + try { + const parsed = JSON.parse(line) as Partial + if (typeof parsed.kind === 'string' && typeof parsed.detail === 'string') { + out.push({ + kind: parsed.kind, + timestamp: typeof parsed.timestamp === 'number' ? parsed.timestamp : Date.now(), + agent: typeof parsed.agent === 'string' ? parsed.agent : 'pantheon', + detail: parsed.detail, + severity: + parsed.severity === 'ok' || parsed.severity === 'warn' || parsed.severity === 'error' + ? parsed.severity + : 'info', + }) + } + } catch { + /* ignore malformed NDJSON line */ + } + } + return out + } catch { + return [] + } +} + +/** Subscribe to all PantheonBus cockpit channels and persist them for the TUI. */ +export function wireCockpitBusRecorder(workspaceDir: string): () => void { + const bus = getSharedBus() + const unsubs = [ + bus.on('lsp:diagnostics', (ev) => { + appendCockpitBusEvent(workspaceDir, { + kind: 'lsp:diagnostics', + timestamp: ev.timestamp, + agent: ev.source, + detail: `${ev.file} · ${ev.errors} err / ${ev.count} total`, + severity: ev.errors > 0 ? 'warn' : 'ok', + }) + }), + bus.on('review:verdict', (ev) => { + appendCockpitBusEvent(workspaceDir, { + kind: 'review:verdict', + timestamp: ev.timestamp, + agent: ev.targetAgent, + detail: `${ev.verdict}: ${ev.summary}`, + severity: + ev.verdict === 'BLOCK' ? 'error' : ev.verdict === 'APPROVE_WITH_NOTES' ? 'warn' : 'ok', + }) + }), + bus.on('step:rollback', (ev) => { + appendCockpitBusEvent(workspaceDir, { + kind: 'step:rollback', + timestamp: ev.timestamp, + agent: 'ledger', + detail: `${ev.stepKey} (${ev.reason}) -> ${ev.success ? 'restored' : 'failed'}`, + severity: ev.success ? 'warn' : 'error', + }) + }), + bus.on('reproduction:gate', (ev) => { + appendCockpitBusEvent(workspaceDir, { + kind: 'reproduction:gate', + timestamp: ev.timestamp, + agent: ev.agent, + detail: `${ev.stepKey} [${ev.tool}] -> ${ev.allowed ? 'allowed' : 'blocked (RED required)'}`, + severity: ev.allowed ? 'ok' : 'warn', + }) + }), + bus.on('themis:reflex:escalated', (ev) => { + appendCockpitBusEvent(workspaceDir, { + kind: 'themis:reflex:escalated', + timestamp: ev.timestamp, + agent: ev.agent, + detail: `${ev.taskID} (${ev.error})`, + severity: 'error', + }) + }), + bus.on('agent:execution:receipt', (ev) => { + appendCockpitBusEvent(workspaceDir, { + kind: 'agent:execution:receipt', + timestamp: ev.timestamp, + agent: ev.agent, + detail: `${ev.taskID} receipt=${ev.receiptId}`, + severity: 'ok', + }) + }), + ] + return () => { + for (const unsub of unsubs) { + try { + unsub() + } catch { + /* ignore */ + } + } + } +} diff --git a/src/pantheon/codemap-tools.ts b/src/pantheon/codemap-tools.ts index fc5ebe97..0523e9b7 100644 --- a/src/pantheon/codemap-tools.ts +++ b/src/pantheon/codemap-tools.ts @@ -299,6 +299,56 @@ function jsonResult(payload: unknown): PantheonToolResult { return { output: JSON.stringify(payload) } } +function deleteIndexedFile(db: DatabaseSync, relFile: string): void { + db.prepare('DELETE FROM code_entities WHERE file = ?').run(relFile) + db.prepare('DELETE FROM code_relations WHERE file = ?').run(relFile) + db.prepare('DELETE FROM code_files WHERE path = ?').run(relFile) +} + +function pruneMissingFilesInScope(db: DatabaseSync, canonicalRoot: string, subRel: string): number { + const cleanScope = subRel.replace(/\\/g, '/').replace(/^\.\//, '').replace(/\/+$/, '') + const rows = + cleanScope === '' || cleanScope === '.' + ? (db.prepare('SELECT path FROM code_files').all() as Array<{ path: string }>) + : (db + .prepare("SELECT path FROM code_files WHERE path = ? OR path LIKE ? ESCAPE '\\'") + .all(cleanScope, `${cleanScope.replace(/[\\%_]/g, '\\$&')}/%`) as Array<{ path: string }>) + let pruned = 0 + for (const row of rows) { + if (typeof row?.path !== 'string') continue + if (!existsSync(resolve(canonicalRoot, row.path))) { + deleteIndexedFile(db, row.path) + pruned += 1 + } + } + return pruned +} + +function filterAndPruneExistingRows( + db: DatabaseSync, + canonicalRoot: string, + rows: T[], +): T[] { + const kept: T[] = [] + const missing = new Set() + for (const row of rows) { + const file = typeof row.file === 'string' ? row.file : '' + if (!file) { + kept.push(row) + continue + } + if (missing.has(file) || !existsSync(resolve(canonicalRoot, file))) { + if (!missing.has(file)) { + missing.add(file) + deleteIndexedFile(db, file) + } + continue + } + kept.push(row) + } + return kept +} + export function createCodemapTools(fallbackDir?: string): PantheonToolDef[] { return [ { @@ -389,10 +439,15 @@ export function createCodemapTools(fallbackDir?: string): PantheonToolDef[] { indexed += 1 } + const pruned = st.isFile() + ? 0 + : pruneMissingFilesInScope(db, canonicalRoot, relative(canonicalRoot, targetPath)) + return jsonResult({ ok: true, indexed, skipped, + pruned, entities: entitiesCount, relations: relationsCount, }) @@ -431,7 +486,8 @@ export function createCodemapTools(fallbackDir?: string): PantheonToolDef[] { ? Math.min(Math.floor(input.limit), 100) : 25 const cwd = resolveToolCwd(context, fallbackDir) - const db = getCodemapDb(cwd) + const canonicalRoot = realpathSync(cwd) + const db = getCodemapDb(canonicalRoot) const escaped = q.replace(/[\\%_]/g, '\\$&') let sql = ` SELECT name, kind, file, line, signature @@ -446,7 +502,11 @@ export function createCodemapTools(fallbackDir?: string): PantheonToolDef[] { sql += ' ORDER BY CASE WHEN name = ? THEN 0 WHEN name LIKE ? THEN 1 ELSE 2 END, file, line LIMIT ?' params.push(q, `${escaped}%`, limit) - const rows = db.prepare(sql).all(...params) + const rows = filterAndPruneExistingRows( + db, + canonicalRoot, + db.prepare(sql).all(...params) as Array<{ file?: unknown }>, + ) return jsonResult({ ok: true, count: rows.length, results: rows }) } catch (err) { return jsonResult({ @@ -480,32 +540,41 @@ export function createCodemapTools(fallbackDir?: string): PantheonToolDef[] { if (!target) return jsonResult({ ok: false, error: 'target is required', neighbors: [] }) const direction = typeof input.direction === 'string' ? input.direction : 'both' const cwd = resolveToolCwd(context, fallbackDir) - const db = getCodemapDb(cwd) + const canonicalRoot = realpathSync(cwd) + const db = getCodemapDb(canonicalRoot) const escaped = target.replace(/[\\%_]/g, '\\$&') const outgoing = direction === 'incoming' ? [] - : db - .prepare( - `SELECT source, target, kind, file, line - FROM code_relations - WHERE source = ? OR source LIKE ? ESCAPE '\\' - LIMIT 50`, - ) - .all(target, `%${escaped}%`) + : filterAndPruneExistingRows( + db, + canonicalRoot, + db + .prepare( + `SELECT source, target, kind, file, line + FROM code_relations + WHERE source = ? OR source LIKE ? ESCAPE '\\' + LIMIT 50`, + ) + .all(target, `%${escaped}%`) as Array<{ file?: unknown }>, + ) const incoming = direction === 'outgoing' ? [] - : db - .prepare( - `SELECT source, target, kind, file, line - FROM code_relations - WHERE target = ? OR target LIKE ? ESCAPE '\\' - LIMIT 50`, - ) - .all(target, `%${escaped}%`) + : filterAndPruneExistingRows( + db, + canonicalRoot, + db + .prepare( + `SELECT source, target, kind, file, line + FROM code_relations + WHERE target = ? OR target LIKE ? ESCAPE '\\' + LIMIT 50`, + ) + .all(target, `%${escaped}%`) as Array<{ file?: unknown }>, + ) return jsonResult({ ok: true, diff --git a/src/pantheon/delegation-enforce.ts b/src/pantheon/delegation-enforce.ts index 9bd78065..99fc2af6 100644 --- a/src/pantheon/delegation-enforce.ts +++ b/src/pantheon/delegation-enforce.ts @@ -186,6 +186,8 @@ export const DEFAULT_BLOCKED_TOOLS: ReadonlySet = new Set([ 'shell', 'task', 'hashline_edit', + 'ast_rewrite', + 'pantheon_worktree', // `pantheon_model` writes active-preset.json in BOTH the project and the // global scope, so it is a write surface with the same blast radius as // `write`. Read-only agents have no reason to change agent models, and a diff --git a/src/pantheon/edit-guardrails.ts b/src/pantheon/edit-guardrails.ts index 55976bc9..e21e25fe 100644 --- a/src/pantheon/edit-guardrails.ts +++ b/src/pantheon/edit-guardrails.ts @@ -23,7 +23,7 @@ import { approvalInputHash } from './j1-approvals.ts' const execFileAsync = promisify(execFile) -const MUTATING_EDIT_TOOLS = new Set(['edit', 'write', 'hashline_edit', 'patch']) +const MUTATING_EDIT_TOOLS = new Set(['edit', 'write', 'hashline_edit', 'patch', 'ast_rewrite']) const PROTECTED_LINT_CONFIG_BASENAMES = new Set([ 'biome.json', diff --git a/src/pantheon/execute-after.ts b/src/pantheon/execute-after.ts index 93e0fa4c..09c43da0 100644 --- a/src/pantheon/execute-after.ts +++ b/src/pantheon/execute-after.ts @@ -33,7 +33,8 @@ * @module pantheon/execute-after */ -import { existsSync } from 'node:fs' +import { existsSync, statSync } from 'node:fs' +import { resolve } from 'node:path' import { type ContextSandboxConfig, createContextSandbox, @@ -42,6 +43,7 @@ import { } from './context-sandbox.ts' import { type PostEditLintOptions, runPostEditLint } from './edit-guardrails.ts' import { createReadEnhancer } from './hashline/read-enhancer.ts' +import { type PostEditDiagnosticsOptions, runPostEditDiagnostics } from './lsp-diagnostics.ts' import { createTaskResultGuard, HOST_EMPTY_RESULT_TEXT, @@ -72,8 +74,12 @@ export interface V2ExecuteAfterOptions { * {@link resolveSandboxConfig}. Defaults to the shared defaults. */ sandbox?: ContextSandboxConfig + /** Active workspace root used to resolve relative edited paths. */ + cwd?: string | (() => string | undefined) /** Configure or disable per-edit diff-scoped lint diagnostics. */ editLint?: boolean | PostEditLintOptions + /** Configure or disable post-edit LSP / compiler diagnostics bridge. */ + editLsp?: boolean | PostEditDiagnosticsOptions } /** Which `Tool.Result` field carries the (mutable) text this adapter enhances. */ @@ -278,16 +284,61 @@ export function createV2ExecuteAfter( // violations inline so the specialist fixes them immediately. const lowerTool = tool.trim().toLowerCase() if ( - options.editLint !== false && - (lowerTool === 'edit' || lowerTool === 'write' || lowerTool === 'hashline_edit') + lowerTool === 'edit' || + lowerTool === 'write' || + lowerTool === 'hashline_edit' || + lowerTool === 'ast_rewrite' ) { + const explicitCwd = typeof options.cwd === 'function' ? options.cwd() : options.cwd + const baseCwd = explicitCwd ?? process.cwd() const rawArgs = (payload.input ?? {}) as Record - const editedPath = rawArgs.filePath ?? rawArgs.file_path ?? rawArgs.file - if (typeof editedPath === 'string' && existsSync(editedPath)) { - const lintOptions = typeof options.editLint === 'object' ? options.editLint : {} - const lintDiagnostic = await runPostEditLint(editedPath, lintOptions) - if (lintDiagnostic) { - output.output = `${output.output}\n${lintDiagnostic}` + const rawPath = + rawArgs.filePath ?? + rawArgs.file_path ?? + rawArgs.file ?? + (lowerTool === 'ast_rewrite' ? rawArgs.path : undefined) + + const candidateFiles: string[] = [] + if (lowerTool === 'ast_rewrite') { + try { + const parsedOut = JSON.parse(original.text) as { filesModified?: unknown } + if (Array.isArray(parsedOut.filesModified)) { + for (const f of parsedOut.filesModified) { + if (typeof f === 'string' && f.trim()) candidateFiles.push(resolve(baseCwd, f)) + } + } + } catch { + /* fallback to rawPath below */ + } + } + if (candidateFiles.length === 0 && typeof rawPath === 'string' && rawPath.trim()) { + const absCandidate = resolve(baseCwd, rawPath) + if (existsSync(absCandidate) && statSync(absCandidate).isFile()) { + candidateFiles.push(absCandidate) + } + } + + for (const editedFile of candidateFiles.slice(0, 4)) { + if (!existsSync(editedFile)) continue + if (options.editLint !== false) { + const rawLint = typeof options.editLint === 'object' ? options.editLint : {} + const lintDiagnostic = await runPostEditLint(editedFile, { + ...(explicitCwd !== undefined ? { cwd: explicitCwd } : {}), + ...rawLint, + }) + if (lintDiagnostic) { + output.output = `${output.output}\n${lintDiagnostic}` + } + } + if (options.editLsp !== false) { + const rawLsp = typeof options.editLsp === 'object' ? options.editLsp : {} + const lspDiagnostic = await runPostEditDiagnostics(editedFile, { + ...(explicitCwd !== undefined ? { cwd: explicitCwd } : {}), + ...rawLsp, + }) + if (lspDiagnostic) { + output.output = `${output.output}\n${lspDiagnostic}` + } } } } diff --git a/src/pantheon/git-checkpoint.ts b/src/pantheon/git-checkpoint.ts new file mode 100644 index 00000000..8ff7b1b4 --- /dev/null +++ b/src/pantheon/git-checkpoint.ts @@ -0,0 +1,142 @@ +/** + * Atomic Git Checkpointing (`git-checkpoint.ts`). + * + * Captures working-tree snapshots as Git tree objects using a temporary + * `GIT_INDEX_FILE` (never mutating the repository's real `.git/index` or + * commits) and rolls back cleanly when `themis:reflex:escalated` fires or when + * `pantheon_step_ledger(action="rollback_step")` is invoked. + */ + +import { execFile } from 'node:child_process' +import { existsSync, mkdirSync, rmSync, unlinkSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join, resolve } from 'node:path' +import { promisify } from 'node:util' + +const execFileAsync = promisify(execFile) +const SAFE_TREE_RE = /^[0-9a-f]{40}$/ + +export interface GitCheckpointResult { + readonly ok: boolean + readonly treeHash?: string + readonly reason?: string +} + +async function runGit( + cwd: string, + args: readonly string[], + envExtra?: Record, +): Promise { + const { stdout } = await execFileAsync('git', [...args], { + cwd, + maxBuffer: 8 * 1024 * 1024, + timeout: 10000, + env: envExtra ? { ...process.env, ...envExtra } : process.env, + }) + return stdout.trim() +} + +export async function isGitWorkspace(cwd: string): Promise { + try { + const out = await runGit(cwd, ['rev-parse', '--is-inside-work-tree']) + return out === 'true' + } catch { + return false + } +} + +/** + * Snapshot the working tree (tracked + non-ignored untracked files) to a Git + * tree object SHA without touching the repository's staging index or HEAD. + */ +export async function captureGitCheckpoint( + cwd: string, + stepKey = 'step', +): Promise { + const root = resolve(cwd) + if (!(await isGitWorkspace(root))) { + return { ok: false, reason: 'not_a_git_repository' } + } + const safeTag = stepKey.replace(/[^a-zA-Z0-9._-]/g, '_') + const tmpIndex = join(tmpdir(), `pantheon-idx-${process.pid}-${safeTag}-${Date.now()}`) + try { + try { + await runGit(root, ['read-tree', 'HEAD'], { GIT_INDEX_FILE: tmpIndex }) + } catch { + await runGit(root, ['read-tree', '--empty'], { GIT_INDEX_FILE: tmpIndex }) + } + await runGit(root, ['add', '-A'], { GIT_INDEX_FILE: tmpIndex }) + const treeHash = await runGit(root, ['write-tree'], { GIT_INDEX_FILE: tmpIndex }) + if (!SAFE_TREE_RE.test(treeHash)) { + return { ok: false, reason: 'invalid_tree_hash' } + } + return { ok: true, treeHash } + } catch (err: unknown) { + return { + ok: false, + reason: err instanceof Error ? err.message : String(err), + } + } finally { + try { + if (existsSync(tmpIndex)) unlinkSync(tmpIndex) + } catch { + /* best-effort cleanup */ + } + } +} + +/** + * Restore the workspace directory to a previously captured Git tree SHA. + * Removes files added after the snapshot and restores tracked modifications. + */ +export async function restoreGitCheckpoint( + cwd: string, + treeHash: string, +): Promise { + const root = resolve(cwd) + if (!SAFE_TREE_RE.test(treeHash)) { + return { ok: false, reason: 'invalid_tree_hash' } + } + if (!(await isGitWorkspace(root))) { + return { ok: false, reason: 'not_a_git_repository' } + } + + const tmpIndex = join(tmpdir(), `pantheon-rb-${process.pid}-${Date.now()}`) + try { + // 1. Identify files currently present in workspace (not ignored) that were NOT in treeHash + const treeListing = await runGit(root, ['ls-tree', '-r', '--name-only', treeHash]) + const baselineFiles = new Set(treeListing.split(/\r?\n/).filter(Boolean)) + + const currentOthers = await runGit(root, ['ls-files', '--others', '--exclude-standard']) + for (const rel of currentOthers.split(/\r?\n/).filter(Boolean)) { + if (rel.startsWith('.pantheon/')) continue + if (!baselineFiles.has(rel)) { + const target = join(root, rel) + try { + rmSync(target, { recursive: true, force: true }) + } catch { + /* ignore */ + } + } + } + + // 2. Restore all files recorded in `treeHash` via isolated temporary index + await runGit(root, ['read-tree', treeHash], { GIT_INDEX_FILE: tmpIndex }) + await runGit(root, ['checkout-index', '--all', '--force'], { GIT_INDEX_FILE: tmpIndex }) + + // Ensure `.pantheon/ledger` remains intact even if baseline didn't contain it + mkdirSync(join(root, '.pantheon', 'ledger'), { recursive: true }) + return { ok: true, treeHash } + } catch (err: unknown) { + return { + ok: false, + reason: err instanceof Error ? err.message : String(err), + } + } finally { + try { + if (existsSync(tmpIndex)) unlinkSync(tmpIndex) + } catch { + /* best-effort cleanup */ + } + } +} diff --git a/src/pantheon/hashline/tool.ts b/src/pantheon/hashline/tool.ts index aab36d7a..d3d21422 100644 --- a/src/pantheon/hashline/tool.ts +++ b/src/pantheon/hashline/tool.ts @@ -25,6 +25,7 @@ import { readFile, rename, rm, writeFile } from 'node:fs/promises' import { isAbsolute, resolve, sep } from 'node:path' import { z } from 'zod' +import { resolveToolCwd } from '../tool-context.ts' import { buildMismatchError, HASHLINE_REF_RE } from './core.ts' import { hashTag } from './xxhash.ts' @@ -101,9 +102,10 @@ interface ResolvedEdit { function resolveFile( file: string, ctx: HashlineEditContext, + fallbackDir?: string, ): { ok: true; file: string } | { ok: false; error: string } { if (isAbsolute(file)) return { ok: true, file: resolve(file) } - const base = resolve(ctx.worktree ?? ctx.directory ?? process.cwd()) + const base = resolve(resolveToolCwd(ctx, fallbackDir)) const resolved = resolve(base, file) // Prefix check with a path.sep boundary: base + sep + name must not // match a sibling prefix (e.g. `/data/x` vs `/data2/x`). @@ -186,7 +188,7 @@ function validateEdits( * partially); on success returns the summary with `{firstChangedLine, * changedCount}` metadata. */ -export function createHashlineEditTool() { +export function createHashlineEditTool(fallbackDir?: string) { return { description: 'Edit a file anchored by hashline refs (LINE#TAG) instead of raw line numbers. ' + @@ -199,7 +201,7 @@ export function createHashlineEditTool() { args: z.infer>, ctx: HashlineEditContext, ): Promise => { - const resolved = resolveFile(args.file, ctx) + const resolved = resolveFile(args.file, ctx, fallbackDir) if (!resolved.ok) return resolved.error const file = resolved.file diff --git a/src/pantheon/jev-risk-gate.ts b/src/pantheon/jev-risk-gate.ts index 99d4a912..bd7ac16f 100644 --- a/src/pantheon/jev-risk-gate.ts +++ b/src/pantheon/jev-risk-gate.ts @@ -118,6 +118,7 @@ const WRITE_TOOLS: ReadonlySet = new Set([ 'patch', 'apply_patch', 'hashline_edit', + 'ast_rewrite', ]) /** diff --git a/src/pantheon/local-decision-tool.ts b/src/pantheon/local-decision-tool.ts index 8e73148f..7fd7d1fb 100644 --- a/src/pantheon/local-decision-tool.ts +++ b/src/pantheon/local-decision-tool.ts @@ -13,10 +13,11 @@ import { const TOOL_DESCRIPTION = 'Zeus-only local advisory selector. Use selectively only when specialist routing is genuinely ' + - 'ambiguous; obvious work should go directly to native subagent without this tool. Accepts only ' + - 'structured candidate IDs, never task text. It does not dispatch, run a skill/resource, search ' + - 'memory, or authorize/alter grants or review gates. Provider egress is disabled; all decisions ' + - 'remain local.' + 'ambiguous; obvious work should go directly to native subagent without this tool. Accepts only a ' + + 'structured object { schemaVersion: 1, candidateAgents, domain, candidateSkillIds, ' + + 'candidateResourceIds, memorySearchRelevant, gateStatus, complexity: { boundedness, ' + + 'reversibility, dependencies, uncertainty, verification } } — never raw prompt strings. Does not ' + + 'dispatch or alter review gates; provider egress is disabled.' const gateStatuses: LocalDecisionGateStatus[] = [ 'none', diff --git a/src/pantheon/lsp-diagnostics.ts b/src/pantheon/lsp-diagnostics.ts new file mode 100644 index 00000000..c97f5705 --- /dev/null +++ b/src/pantheon/lsp-diagnostics.ts @@ -0,0 +1,706 @@ +/** + * LSP & Compiler Diagnostics Bridge (`lsp-diagnostics.ts`). + * + * Bridges edited files in `execute.after` to workspace language servers and + * compilers: + * 1. Standard JSON-RPC stdio LSP framing (`Content-Length`) + `queryStdioLspDiagnostics` + * for `typescript-language-server`, `pyright-langserver`, `biome lsp-proxy`, etc. + * 2. Fast per-file semantic diagnostics (`runPostEditDiagnostics`) via `tsc --noEmit` + * (resolving workspace `node_modules/.bin/tsc`), `pyright --outputjson`, or `go vet`, + * strictly filtered to diagnostics belonging to the edited file. + * 3. Emits `'lsp:diagnostics'` events on `getSharedBus()` for Cockpit telemetry. + */ + +import { execFile, spawn } from 'node:child_process' +import { existsSync, readFileSync } from 'node:fs' +import { createConnection, type Socket } from 'node:net' +import { basename, dirname, extname, join, relative, resolve } from 'node:path' +import { pathToFileURL } from 'node:url' +import { promisify } from 'node:util' +import { getSharedBus } from './bus.ts' + +const execFileAsync = promisify(execFile) + +export interface LspDiagnosticItem { + readonly file: string + readonly line: number + readonly column: number + readonly severity: 'error' | 'warning' + readonly code?: string + readonly message: string +} + +export interface DiagnosticsExecResult { + readonly stdout: string + readonly stderr: string + readonly exitCode: number +} + +export type DiagnosticsRunner = ( + cmd: string, + args: string[], + options: { cwd: string; timeoutMs: number }, +) => Promise + +export interface LspTcpEndpoint { + readonly language: string + readonly host: string + readonly port: number +} + +export interface PostEditDiagnosticsOptions { + readonly cwd?: string + readonly runner?: DiagnosticsRunner + readonly serverCommand?: readonly string[] + readonly tcpEndpoint?: { readonly host: string; readonly port: number } + readonly timeoutMs?: number +} + +const MAX_DIAGNOSTICS = 8 +const TS_EXTENSIONS = new Set(['.ts', '.tsx', '.mts', '.cts']) + +function resolveLanguageId(absFile: string): string { + const ext = extname(absFile).toLowerCase() + if (TS_EXTENSIONS.has(ext)) return ext.includes('x') ? 'typescriptreact' : 'typescript' + if (ext === '.py') return 'python' + if (ext === '.go') return 'go' + if (ext === '.rs') return 'rust' + return 'plaintext' +} + +function extractPublishedDiagnostics(rawDiags: unknown[], absFile: string): LspDiagnosticItem[] { + const items: LspDiagnosticItem[] = [] + for (const d of rawDiags) { + if (!d || typeof d !== 'object') continue + const diag = d as { + severity?: number + code?: string | number + message?: string + range?: { start?: { line?: number; character?: number } } + } + items.push({ + file: absFile, + line: (diag.range?.start?.line ?? 0) + 1, + column: (diag.range?.start?.character ?? 0) + 1, + severity: diag.severity === 2 ? 'warning' : 'error', + ...(diag.code !== undefined ? { code: String(diag.code) } : {}), + message: String(diag.message ?? '').trim(), + }) + } + return items +} + +/** Parse `PANTHEON_LSP_TCP_ENDPOINTS` (`typescript=127.0.0.1:4001,python=localhost:4002`). */ +export function parseLspTcpEndpoints( + raw = process.env.PANTHEON_LSP_TCP_ENDPOINTS ?? '', +): LspTcpEndpoint[] { + const endpoints: LspTcpEndpoint[] = [] + for (const entry of raw.split(',')) { + const trimmed = entry.trim() + if (!trimmed) continue + const eqIdx = trimmed.indexOf('=') + const language = eqIdx > 0 ? trimmed.slice(0, eqIdx).trim().toLowerCase() : '*' + const addr = eqIdx > 0 ? trimmed.slice(eqIdx + 1).trim() : trimmed + const colonIdx = addr.lastIndexOf(':') + if (colonIdx <= 0) continue + const host = addr.slice(0, colonIdx).trim() + const port = Number(addr.slice(colonIdx + 1).trim()) + if (!host || !Number.isInteger(port) || port <= 0 || port > 65535) continue + endpoints.push({ language, host, port }) + } + return endpoints +} + +interface PooledTcpSession { + socket: Socket + buffer: Buffer + initialized: boolean + docVersions: Map + listeners: Set<(msg: Record) => void> + idleTimer?: ReturnType +} + +const tcpPool = new Map() + +export function getLspTcpPoolSize(): number { + return tcpPool.size +} + +export function shutdownLspTcpPool(): void { + for (const [key, entry] of tcpPool.entries()) { + if (entry.idleTimer) clearTimeout(entry.idleTimer) + try { + entry.socket.destroy() + } catch { + /* ignore */ + } + tcpPool.delete(key) + } +} + +async function acquirePooledTcpSession( + host: string, + port: number, + rootUri: string, + timeoutMs: number, +): Promise { + const key = `${host}:${port}` + const existing = tcpPool.get(key) + if (existing && !existing.socket.destroyed && existing.initialized) { + if (existing.idleTimer) clearTimeout(existing.idleTimer) + return existing + } + if (existing) { + tcpPool.delete(key) + try { + existing.socket.destroy() + } catch { + /* ignore */ + } + } + + return new Promise((resolvePromise) => { + let settled = false + const socket = createConnection({ host, port }) + socket.unref() + const session: PooledTcpSession = { + socket, + buffer: Buffer.alloc(0), + initialized: false, + docVersions: new Map(), + listeners: new Set(), + } + + const fail = () => { + if (settled) return + settled = true + clearTimeout(timer) + tcpPool.delete(key) + try { + socket.destroy() + } catch { + /* ignore */ + } + resolvePromise(null) + } + + const timer = setTimeout(fail, timeoutMs) + socket.on('error', fail) + socket.on('close', () => { + tcpPool.delete(key) + if (!settled) fail() + }) + socket.on('data', (chunk: Buffer) => { + session.buffer = Buffer.concat([session.buffer, chunk]) + const parsed = parseLspMessages(session.buffer) + session.buffer = Buffer.from(parsed.remainder) + for (const msg of parsed.messages) { + if (!msg || typeof msg !== 'object') continue + const rec = msg as Record + if (!session.initialized && rec.id === 1 && rec.result !== undefined) { + session.initialized = true + socket.write(encodeLspMessage({ jsonrpc: '2.0', method: 'initialized', params: {} })) + tcpPool.set(key, session) + if (!settled) { + settled = true + clearTimeout(timer) + resolvePromise(session) + } + } + for (const fn of session.listeners) fn(rec) + } + }) + socket.on('connect', () => { + socket.write( + encodeLspMessage({ + jsonrpc: '2.0', + id: 1, + method: 'initialize', + params: { processId: process.pid, rootUri, capabilities: {} }, + }), + ) + }) + }) +} + +/** Query a pooled multi-IDE TCP LSP proxy endpoint, reusing an initialized socket. */ +export async function queryTcpLspDiagnostics( + filePath: string, + options: { + readonly host: string + readonly port: number + readonly cwd: string + readonly timeoutMs?: number + readonly idleTtlMs?: number + }, +): Promise { + const absFile = resolve(filePath) + const fileUri = pathToFileURL(absFile).href + const rootUri = pathToFileURL(resolve(options.cwd)).href + const timeoutMs = options.timeoutMs ?? 4500 + const session = await acquirePooledTcpSession(options.host, options.port, rootUri, timeoutMs) + if (!session) return [] + + const text = existsSync(absFile) ? readFileSync(absFile, 'utf8') : '' + const languageId = resolveLanguageId(absFile) + const nextVer = (session.docVersions.get(fileUri) ?? 0) + 1 + session.docVersions.set(fileUri, nextVer) + + return new Promise((resolvePromise) => { + let settled = false + const onMsg = (rec: Record) => { + if (rec.method !== 'textDocument/publishDiagnostics') return + const params = (rec.params ?? {}) as { uri?: string; diagnostics?: unknown[] } + if (params.uri && params.uri !== fileUri) return + finish( + extractPublishedDiagnostics( + Array.isArray(params.diagnostics) ? params.diagnostics : [], + absFile, + ), + ) + } + + const finish = (items: LspDiagnosticItem[]) => { + if (settled) return + settled = true + clearTimeout(timer) + session.listeners.delete(onMsg) + const idleTtl = options.idleTtlMs ?? 60_000 + session.idleTimer = setTimeout(() => { + try { + session.socket.destroy() + } catch { + /* ignore */ + } + tcpPool.delete(`${options.host}:${options.port}`) + }, idleTtl) + session.idleTimer.unref?.() + resolvePromise(items) + } + + const timer = setTimeout(() => finish([]), timeoutMs) + session.listeners.add(onMsg) + + try { + if (nextVer === 1) { + session.socket.write( + encodeLspMessage({ + jsonrpc: '2.0', + method: 'textDocument/didOpen', + params: { textDocument: { uri: fileUri, languageId, version: nextVer, text } }, + }), + ) + } else { + session.socket.write( + encodeLspMessage({ + jsonrpc: '2.0', + method: 'textDocument/didChange', + params: { + textDocument: { uri: fileUri, version: nextVer }, + contentChanges: [{ text }], + }, + }), + ) + } + } catch { + finish([]) + } + }) +} + +/** Encode a JSON-RPC 2.0 object using LSP Content-Length framing. */ +export function encodeLspMessage(payload: unknown): string { + const json = JSON.stringify(payload) + const len = Buffer.byteLength(json, 'utf8') + return `Content-Length: ${len}\r\n\r\n${json}` +} + +/** Decode zero or more Content-Length framed LSP messages from a chunk buffer. */ +export function parseLspMessages(buffer: Buffer): { + messages: unknown[] + remainder: Buffer +} { + const messages: unknown[] = [] + let offset = 0 + while (offset < buffer.length) { + const headerEnd = buffer.indexOf('\r\n\r\n', offset, 'utf8') + if (headerEnd < 0) break + const header = buffer.subarray(offset, headerEnd).toString('utf8') + const match = /Content-Length:\s*(\d+)/i.exec(header) + if (!match?.[1]) { + offset = headerEnd + 4 + continue + } + const contentLength = Number(match[1]) + const bodyStart = headerEnd + 4 + const bodyEnd = bodyStart + contentLength + if (buffer.length < bodyEnd) break + const rawBody = buffer.subarray(bodyStart, bodyEnd).toString('utf8') + try { + messages.push(JSON.parse(rawBody)) + } catch { + /* ignore malformed JSON-RPC frame */ + } + offset = bodyEnd + } + return { messages, remainder: buffer.subarray(offset) } +} + +/** Query a stdio LSP server for diagnostics on a single document. */ +export async function queryStdioLspDiagnostics( + filePath: string, + options: { + readonly command: readonly string[] + readonly cwd: string + readonly timeoutMs?: number + }, +): Promise { + const bin = options.command[0] + if (!bin) return [] + const args = options.command.slice(1) + const timeoutMs = options.timeoutMs ?? 4500 + const absFile = resolve(filePath) + const fileUri = pathToFileURL(absFile).href + const rootUri = pathToFileURL(resolve(options.cwd)).href + const ext = extname(absFile).toLowerCase() + const languageId = TS_EXTENSIONS.has(ext) + ? ext.includes('x') + ? 'typescriptreact' + : 'typescript' + : ext === '.py' + ? 'python' + : 'plaintext' + const text = existsSync(absFile) ? readFileSync(absFile, 'utf8') : '' + + return new Promise((resolvePromise) => { + let settled = false + let buf = Buffer.alloc(0) + const child = spawn(bin, args, { + cwd: options.cwd, + stdio: ['pipe', 'pipe', 'ignore'], + }) + + const finish = (items: LspDiagnosticItem[]) => { + if (settled) return + settled = true + clearTimeout(timer) + try { + child.stdin.write( + encodeLspMessage({ jsonrpc: '2.0', id: 99, method: 'shutdown', params: null }), + ) + child.stdin.write(encodeLspMessage({ jsonrpc: '2.0', method: 'exit', params: null })) + } catch { + /* ignore closed pipe */ + } + try { + child.kill() + } catch { + /* ignore */ + } + resolvePromise(items) + } + + const timer = setTimeout(() => finish([]), timeoutMs) + child.on('error', () => finish([])) + child.on('exit', () => finish([])) + + child.stdout.on('data', (chunk: Buffer) => { + buf = Buffer.concat([buf, chunk]) + const parsed = parseLspMessages(buf) + buf = Buffer.from(parsed.remainder) + for (const msg of parsed.messages) { + if (!msg || typeof msg !== 'object') continue + const rec = msg as Record + if (rec.id === 1 && rec.result !== undefined) { + child.stdin.write(encodeLspMessage({ jsonrpc: '2.0', method: 'initialized', params: {} })) + child.stdin.write( + encodeLspMessage({ + jsonrpc: '2.0', + method: 'textDocument/didOpen', + params: { + textDocument: { uri: fileUri, languageId, version: 1, text }, + }, + }), + ) + } else if (rec.method === 'textDocument/publishDiagnostics') { + const params = (rec.params ?? {}) as { uri?: string; diagnostics?: unknown[] } + if (params.uri && params.uri !== fileUri) continue + const rawDiags = Array.isArray(params.diagnostics) ? params.diagnostics : [] + const items: LspDiagnosticItem[] = [] + for (const d of rawDiags) { + if (!d || typeof d !== 'object') continue + const diag = d as { + severity?: number + code?: string | number + message?: string + range?: { start?: { line?: number; character?: number } } + } + const sev = diag.severity === 2 ? 'warning' : 'error' + items.push({ + file: absFile, + line: (diag.range?.start?.line ?? 0) + 1, + column: (diag.range?.start?.character ?? 0) + 1, + severity: sev, + ...(diag.code !== undefined ? { code: String(diag.code) } : {}), + message: String(diag.message ?? '').trim(), + }) + } + finish(items) + } + } + }) + + child.stdin.write( + encodeLspMessage({ + jsonrpc: '2.0', + id: 1, + method: 'initialize', + params: { + processId: process.pid, + rootUri, + capabilities: {}, + }, + }), + ) + }) +} + +async function defaultRunner( + cmd: string, + args: string[], + options: { cwd: string; timeoutMs: number }, +): Promise { + try { + const { stdout, stderr } = await execFileAsync(cmd, args, { + cwd: options.cwd, + timeout: options.timeoutMs, + maxBuffer: 2 * 1024 * 1024, + }) + return { stdout: stdout ?? '', stderr: stderr ?? '', exitCode: 0 } + } catch (err: unknown) { + const rec = err as { stdout?: string; stderr?: string; code?: number | string } + return { + stdout: rec.stdout ?? '', + stderr: rec.stderr ?? '', + exitCode: typeof rec.code === 'number' ? rec.code : 1, + } + } +} + +function findAncestorTool(startDir: string, relParts: readonly string[]): string | null { + let cur = resolve(startDir) + for (let i = 0; i < 12; i += 1) { + const candidate = join(cur, ...relParts) + if (existsSync(candidate)) return candidate + const parent = dirname(cur) + if (parent === cur) break + cur = parent + } + // Fallback to module ancestor (e.g. Pantheon's own node_modules during tests) + const moduleRoot = resolve(dirname(new URL(import.meta.url).pathname), '..', '..') + const moduleBin = join(moduleRoot, ...relParts) + return existsSync(moduleBin) ? moduleBin : null +} + +function findNearestTsConfig(filePath: string, stopDir: string): string | null { + let cur = dirname(resolve(filePath)) + const bound = resolve(stopDir) + for (let i = 0; i < 10; i += 1) { + const candidate = join(cur, 'tsconfig.json') + if (existsSync(candidate)) return candidate + if (cur === bound) break + const parent = dirname(cur) + if (parent === cur) break + cur = parent + } + return null +} + +function parseTscOutput(output: string, absFile: string, cwd: string): LspDiagnosticItem[] { + const items: LspDiagnosticItem[] = [] + const targetRel = relative(cwd, absFile).replace(/\\/g, '/') + const targetBase = basename(absFile) + const TSC_LINE_RE = /^(.+?)\((\d+),(\d+)\):\s+(error|warning)\s+(TS\d+):\s+(.+)$/ + + for (const rawLine of output.split(/\r?\n/)) { + const match = TSC_LINE_RE.exec(rawLine.trim()) + if (!match?.[1] || !match[2] || !match[3] || !match[4] || !match[5] || !match[6]) continue + const diagPath = match[1].replace(/\\/g, '/') + const resolvedDiag = resolve(cwd, diagPath) + if ( + resolvedDiag !== absFile && + diagPath !== targetRel && + !diagPath.endsWith(`/${targetBase}`) && + diagPath !== targetBase + ) { + continue + } + items.push({ + file: absFile, + line: Number(match[2]), + column: Number(match[3]), + severity: match[4] === 'warning' ? 'warning' : 'error', + code: match[5], + message: match[6].trim(), + }) + } + return items +} + +function parsePyrightJson(output: string, absFile: string): LspDiagnosticItem[] { + try { + const data = JSON.parse(output) as { + generalDiagnostics?: Array<{ + file?: string + severity?: string + rule?: string + message?: string + range?: { start?: { line?: number; character?: number } } + }> + } + const items: LspDiagnosticItem[] = [] + for (const d of data.generalDiagnostics ?? []) { + if (d.file && resolve(d.file) !== absFile) continue + items.push({ + file: absFile, + line: (d.range?.start?.line ?? 0) + 1, + column: (d.range?.start?.character ?? 0) + 1, + severity: d.severity === 'warning' ? 'warning' : 'error', + ...(d.rule !== undefined ? { code: d.rule } : {}), + message: String(d.message ?? '').trim(), + }) + } + return items + } catch { + return [] + } +} + +function formatDiagnosticsBlock( + absFile: string, + cwd: string, + items: readonly LspDiagnosticItem[], +): string { + const rel = relative(cwd, absFile) || basename(absFile) + const shown = items.slice(0, MAX_DIAGNOSTICS) + const lines = shown.map( + (d) => + ` ${rel}:${d.line}:${d.column} ${d.severity}${d.code ? ` ${d.code}` : ''}: ${d.message}`, + ) + if (items.length > MAX_DIAGNOSTICS) { + lines.push(` ... +${items.length - MAX_DIAGNOSTICS} more diagnostic(s)`) + } + return `[LSP-Diagnostics] ${items.length} issue(s) in ${rel}:\n${lines.join('\n')}` +} + +/** + * Run semantic diagnostics for an edited file and surface concise `[LSP-Diagnostics]` + * lines inline when errors/warnings exist for that file. + */ +export async function runPostEditDiagnostics( + filePath: string, + options: PostEditDiagnosticsOptions = {}, +): Promise { + try { + if (!filePath || !existsSync(filePath)) return null + const absFile = resolve(filePath) + const cwd = resolve(options.cwd ?? dirname(absFile)) + const runner = options.runner ?? defaultRunner + const timeoutMs = options.timeoutMs ?? 6000 + const ext = extname(absFile).toLowerCase() + + // 1. Live stdio LSP server override if explicitly configured + const envLsp = process.env.PANTHEON_LSP_SERVER?.trim() + const lspCmd = + options.serverCommand ?? (envLsp ? envLsp.split(/\s+/).filter(Boolean) : undefined) + if (lspCmd && lspCmd.length > 0) { + const lspItems = await queryStdioLspDiagnostics(absFile, { + command: lspCmd, + cwd, + timeoutMs, + }) + getSharedBus().emit('lsp:diagnostics', { + file: relative(cwd, absFile) || absFile, + source: 'lsp-stdio', + count: lspItems.length, + errors: lspItems.filter((d) => d.severity === 'error').length, + timestamp: Date.now(), + }) + return lspItems.length > 0 ? formatDiagnosticsBlock(absFile, cwd, lspItems) : null + } + + // 1b. Pooled TCP multi-IDE LSP proxy endpoint if configured + const langId = resolveLanguageId(absFile) + const configuredTcp = + options.tcpEndpoint ?? + parseLspTcpEndpoints().find((ep) => ep.language === langId || ep.language === '*') + if (configuredTcp) { + const tcpItems = await queryTcpLspDiagnostics(absFile, { + host: configuredTcp.host, + port: configuredTcp.port, + cwd, + timeoutMs, + }) + getSharedBus().emit('lsp:diagnostics', { + file: relative(cwd, absFile) || absFile, + source: 'lsp-tcp', + count: tcpItems.length, + errors: tcpItems.filter((d) => d.severity === 'error').length, + timestamp: Date.now(), + }) + return tcpItems.length > 0 ? formatDiagnosticsBlock(absFile, cwd, tcpItems) : null + } + + // 2. TypeScript / TSX semantic check via `tsc --noEmit` + if (TS_EXTENSIONS.has(ext)) { + const tscBin = findAncestorTool(cwd, ['node_modules', '.bin', 'tsc']) + if (!tscBin) return null + const tsConfig = findNearestTsConfig(absFile, cwd) + const args = tsConfig + ? ['--noEmit', '--pretty', 'false', '--skipLibCheck', '-p', tsConfig] + : [ + '--noEmit', + '--pretty', + 'false', + '--skipLibCheck', + '--target', + 'esnext', + '--module', + 'nodenext', + '--moduleResolution', + 'nodenext', + absFile, + ] + const res = await runner(tscBin, args, { cwd, timeoutMs }) + const items = parseTscOutput(`${res.stdout}\n${res.stderr}`, absFile, cwd) + getSharedBus().emit('lsp:diagnostics', { + file: relative(cwd, absFile) || absFile, + source: 'typescript', + count: items.length, + errors: items.filter((d) => d.severity === 'error').length, + timestamp: Date.now(), + }) + return items.length > 0 ? formatDiagnosticsBlock(absFile, cwd, items) : null + } + + // 3. Python semantic check via `pyright --outputjson` (when installed) + if (ext === '.py') { + const pyrightBin = findAncestorTool(cwd, ['.venv', 'bin', 'pyright']) + if (!pyrightBin) return null + const res = await runner(pyrightBin, ['--outputjson', absFile], { cwd, timeoutMs }) + const items = parsePyrightJson(res.stdout, absFile) + getSharedBus().emit('lsp:diagnostics', { + file: relative(cwd, absFile) || absFile, + source: 'pyright', + count: items.length, + errors: items.filter((d) => d.severity === 'error').length, + timestamp: Date.now(), + }) + return items.length > 0 ? formatDiagnosticsBlock(absFile, cwd, items) : null + } + + return null + } catch { + return null + } +} diff --git a/src/pantheon/memory-federation.ts b/src/pantheon/memory-federation.ts new file mode 100644 index 00000000..44b77d0a --- /dev/null +++ b/src/pantheon/memory-federation.ts @@ -0,0 +1,231 @@ +/** + * Persistent Multi-Repo Shared Knowledge Federation (`memory-federation.ts`). + * + * Discovers peer repositories configured via `PANTHEON_FEDERATED_REPOS` or + * `~/.pantheon/federation.json` and runs strictly read-only FTS5/LIKE queries + * across their `.pantheon/memory/memory.db` stores with explicit provenance. + * + * @module pantheon/memory-federation + */ + +import { existsSync, readFileSync, realpathSync } from 'node:fs' +import { homedir } from 'node:os' +import { basename, join, resolve } from 'node:path' +import { DatabaseSync } from 'node:sqlite' +import { resolveSharedPantheonRoot } from './tool-context.ts' + +export interface FederatedHit { + readonly namespace: string + readonly key: string + readonly value: string + readonly metadata: string | null + readonly created_at: string + readonly score?: number + readonly sourceRepo: string + readonly sourcePath: string +} + +export interface FederatedRepoStat { + readonly repo: string + readonly path: string + readonly total: number +} + +export interface FederationOptions { + readonly federatedEnv?: string | undefined + readonly manifestPath?: string | undefined + readonly explicitRepos?: readonly string[] | undefined +} + +const NOT_EXPIRED_SQL = '(expires_at IS NULL OR expires_at > ?)' + +function safeRealpath(dir: string): string { + try { + return realpathSync(dir) + } catch { + return resolve(dir) + } +} + +/** + * Resolve unique valid peer repository directories containing a `.pantheon/memory/memory.db`, + * excluding `primaryWorkspaceDir` itself. + */ +export function resolveFederatedRepoDirs( + primaryWorkspaceDir: string, + options: FederationOptions = {}, +): string[] { + const candidates: string[] = [] + if (Array.isArray(options.explicitRepos)) { + candidates.push(...options.explicitRepos) + } + + const rawEnv = options.federatedEnv ?? process.env.PANTHEON_FEDERATED_REPOS ?? '' + if (rawEnv.trim()) { + for (const part of rawEnv.split(/[,;]/)) { + const trimmed = part.trim() + if (trimmed) candidates.push(trimmed) + } + } + + const manifestFile = options.manifestPath ?? join(homedir(), '.pantheon', 'federation.json') + if (existsSync(manifestFile)) { + try { + const parsed = JSON.parse(readFileSync(manifestFile, 'utf8')) as { + repos?: unknown + } + if (Array.isArray(parsed.repos)) { + for (const item of parsed.repos) { + if (typeof item === 'string' && item.trim()) candidates.push(item.trim()) + } + } + } catch { + /* ignore malformed federation manifest */ + } + } + + const primaryStore = safeRealpath(resolveSharedPantheonRoot(primaryWorkspaceDir)) + const seenStores = new Set([primaryStore]) + const peers: string[] = [] + + for (const candidate of candidates) { + const abs = resolve(candidate) + if (!existsSync(abs)) continue + const peerStore = safeRealpath(resolveSharedPantheonRoot(abs)) + if (seenStores.has(peerStore)) continue + const dbPath = join(peerStore, '.pantheon', 'memory', 'memory.db') + if (!existsSync(dbPath)) continue + seenStores.add(peerStore) + peers.push(peerStore) + } + + return peers +} + +function querySinglePeerDb( + peerRoot: string, + rawQuery: string, + nowIso: string, + limit: number, + namespace?: string, +): FederatedHit[] { + const dbPath = join(peerRoot, '.pantheon', 'memory', 'memory.db') + if (!existsSync(dbPath)) return [] + const repoName = basename(peerRoot) || peerRoot + let db: DatabaseSync | undefined + try { + db = new DatabaseSync(dbPath, { readOnly: true }) + const tokens = rawQuery + .replace(/[^\p{L}\p{N}_-]+/gu, ' ') + .trim() + .split(/\s+/) + .filter((t) => t.length >= 2) + + if (tokens.length > 0) { + try { + const ftsExpr = tokens.map((t) => `"${t.replace(/"/g, '""')}"*`).join(' OR ') + let ftsSql = ` + SELECT m.namespace, m.key, m.value, m.metadata, m.created_at, bm25(memories_fts) AS score + FROM memories_fts + JOIN memories m ON m.id = memories_fts.rowid + WHERE memories_fts MATCH ? AND (m.expires_at IS NULL OR m.expires_at > ?) + ` + const ftsParams: Array = [ftsExpr, nowIso] + if (namespace) { + ftsSql += ' AND m.namespace = ?' + ftsParams.push(namespace) + } + ftsSql += ' ORDER BY score LIMIT ?' + ftsParams.push(limit) + const rows = db.prepare(ftsSql).all(...ftsParams) as Array< + Omit + > + if (rows.length > 0) { + return rows.map((r) => ({ ...r, sourceRepo: repoName, sourcePath: peerRoot })) + } + } catch { + /* fallback to LIKE */ + } + } + + const escaped = rawQuery.replace(/[\\%_]/g, '\\$&') + let sql = ` + SELECT namespace, key, value, metadata, created_at + FROM memories + WHERE (value LIKE ? ESCAPE '\\' OR key LIKE ? ESCAPE '\\') + AND ${NOT_EXPIRED_SQL} + ` + const params: Array = [`%${escaped}%`, `%${escaped}%`, nowIso] + if (namespace) { + sql += ' AND namespace = ?' + params.push(namespace) + } + sql += ' ORDER BY id DESC LIMIT ?' + params.push(limit) + const rows = db.prepare(sql).all(...params) as Array< + Omit + > + return rows.map((r) => ({ ...r, sourceRepo: repoName, sourcePath: peerRoot })) + } catch { + return [] + } finally { + try { + db?.close() + } catch { + /* ignore */ + } + } +} + +/** Query peer federated repositories (read-only) with repo provenance. */ +export function searchFederatedMemories( + primaryWorkspaceDir: string, + query: string, + options: FederationOptions & { readonly namespace?: string; readonly limit?: number } = {}, +): FederatedHit[] { + const peers = resolveFederatedRepoDirs(primaryWorkspaceDir, options) + if (peers.length === 0) return [] + const nowIso = new Date().toISOString() + const limit = Math.max(1, Math.min(options.limit ?? 10, 100)) + const results: FederatedHit[] = [] + for (const peer of peers) { + const hits = querySinglePeerDb(peer, query, nowIso, limit, options.namespace) + results.push(...hits) + if (results.length >= limit) break + } + return results.slice(0, limit) +} + +/** Collect memory counts across federated peer repositories. */ +export function getFederatedStats( + primaryWorkspaceDir: string, + options: FederationOptions = {}, +): { readonly total: number; readonly repos: readonly FederatedRepoStat[] } { + const peers = resolveFederatedRepoDirs(primaryWorkspaceDir, options) + const nowIso = new Date().toISOString() + const repos: FederatedRepoStat[] = [] + let total = 0 + for (const peer of peers) { + const dbPath = join(peer, '.pantheon', 'memory', 'memory.db') + let count = 0 + let db: DatabaseSync | undefined + try { + db = new DatabaseSync(dbPath, { readOnly: true }) + const row = db + .prepare(`SELECT count(*) as count FROM memories WHERE ${NOT_EXPIRED_SQL}`) + .get(nowIso) as { count?: number } | undefined + count = typeof row?.count === 'number' ? row.count : 0 + } catch { + count = 0 + } finally { + try { + db?.close() + } catch { + /* ignore */ + } + } + repos.push({ repo: basename(peer) || peer, path: peer, total: count }) + total += count + } + return { total, repos } +} diff --git a/src/pantheon/native-memory-tools.ts b/src/pantheon/native-memory-tools.ts index 4c438c27..0d640bcd 100644 --- a/src/pantheon/native-memory-tools.ts +++ b/src/pantheon/native-memory-tools.ts @@ -22,7 +22,8 @@ import { ensureLegacyStoresMigratedOnce, resolveSafeGlobalConfigDir, } from './legacy-store-migration.mjs' -import { resolveToolCwd } from './tool-context.ts' +import { getFederatedStats, searchFederatedMemories } from './memory-federation.ts' +import { resolveMemoryStoreCwd } from './tool-context.ts' import type { V2ToolDef, V2ToolResult } from './tools.ts' const SAFE_SEGMENT_RE = /^[a-zA-Z0-9._:-]{1,128}$/ @@ -163,7 +164,7 @@ export function createNativeMemoryAndPersistenceTools(fallbackDir?: string): V2T if (Buffer.byteLength(value, 'utf8') > MAX_MEMORY_VALUE_BYTES) { return jsonResult({ ok: false, error: 'value exceeds maximum size of 64 KiB' }) } - const cwd = resolveToolCwd(context, fallbackDir) + const cwd = resolveMemoryStoreCwd(context, fallbackDir) const db = getMemoryDb(cwd) const nowIso = new Date().toISOString() db.prepare( @@ -211,7 +212,7 @@ export function createNativeMemoryAndPersistenceTools(fallbackDir?: string): V2T if (typeof ns !== 'string' || !ns.trim() || typeof key !== 'string' || !key.trim()) { return jsonResult({ ok: false, error: 'namespace and key are required' }) } - const cwd = resolveToolCwd(context, fallbackDir) + const cwd = resolveMemoryStoreCwd(context, fallbackDir) const db = getMemoryDb(cwd) const nowIso = new Date().toISOString() const row = db @@ -241,6 +242,10 @@ export function createNativeMemoryAndPersistenceTools(fallbackDir?: string): V2T query: { type: 'string', description: 'Search query terms' }, namespace: { type: 'string', description: 'Optional namespace filter' }, top_k: { type: 'number', description: 'Maximum results to return (default 10)' }, + federated: { + type: 'boolean', + description: 'Include federated peer repositories (default true when configured)', + }, }, }, output: {}, @@ -258,7 +263,8 @@ export function createNativeMemoryAndPersistenceTools(fallbackDir?: string): V2T typeof input.namespace === 'string' && input.namespace.trim() ? input.namespace.trim() : undefined - const cwd = resolveToolCwd(context, fallbackDir) + const useFederated = input.federated !== false + const cwd = resolveMemoryStoreCwd(context, fallbackDir) const db = getMemoryDb(cwd) const nowIso = new Date().toISOString() @@ -268,6 +274,8 @@ export function createNativeMemoryAndPersistenceTools(fallbackDir?: string): V2T .split(/\s+/) .filter((t) => t.length >= 2) + let localRows: Record[] = [] + let matchedFts = false if (tokens.length > 0) { try { const ftsExpr = tokens.map((t) => `"${t.replace(/"/g, '""')}"*`).join(' OR ') @@ -284,31 +292,44 @@ export function createNativeMemoryAndPersistenceTools(fallbackDir?: string): V2T } ftsSql += ' ORDER BY score LIMIT ?' ftsParams.push(limit) - const rows = db.prepare(ftsSql).all(...ftsParams) + const rows = db.prepare(ftsSql).all(...ftsParams) as Record[] if (rows.length > 0) { - return jsonResult({ ok: true, count: rows.length, results: rows }) + localRows = rows + matchedFts = true } } catch { /* fallback to LIKE */ } } - const escaped = rawQuery.replace(/[\\%_]/g, '\\$&') - let sql = ` - SELECT namespace, key, value, metadata, created_at - FROM memories - WHERE (value LIKE ? ESCAPE '\\' OR key LIKE ? ESCAPE '\\') - AND ${NOT_EXPIRED_SQL} - ` - const params: Array = [`%${escaped}%`, `%${escaped}%`, nowIso] - if (ns) { - sql += ' AND namespace = ?' - params.push(ns) + if (!matchedFts) { + const escaped = rawQuery.replace(/[\\%_]/g, '\\$&') + let sql = ` + SELECT namespace, key, value, metadata, created_at + FROM memories + WHERE (value LIKE ? ESCAPE '\\' OR key LIKE ? ESCAPE '\\') + AND ${NOT_EXPIRED_SQL} + ` + const params: Array = [`%${escaped}%`, `%${escaped}%`, nowIso] + if (ns) { + sql += ' AND namespace = ?' + params.push(ns) + } + sql += ' ORDER BY id DESC LIMIT ?' + params.push(limit) + localRows = db.prepare(sql).all(...params) as Record[] } - sql += ' ORDER BY id DESC LIMIT ?' - params.push(limit) - const rows = db.prepare(sql).all(...params) - return jsonResult({ ok: true, count: rows.length, results: rows }) + + const remaining = Math.max(0, limit - localRows.length) + const peerRows = + useFederated && remaining > 0 + ? searchFederatedMemories(cwd, rawQuery, { + ...(ns ? { namespace: ns } : {}), + limit: remaining, + }) + : [] + const combined = [...localRows, ...peerRows] + return jsonResult({ ok: true, count: combined.length, results: combined }) } catch (err) { return jsonResult({ ok: false, @@ -337,7 +358,7 @@ export function createNativeMemoryAndPersistenceTools(fallbackDir?: string): V2T if (typeof ns !== 'string' || !ns.trim() || typeof key !== 'string' || !key.trim()) { return jsonResult({ ok: false, error: 'namespace and key are required' }) } - const cwd = resolveToolCwd(context, fallbackDir) + const cwd = resolveMemoryStoreCwd(context, fallbackDir) const db = getMemoryDb(cwd) const info = db .prepare('DELETE FROM memories WHERE namespace = ? AND key = ?') @@ -370,7 +391,7 @@ export function createNativeMemoryAndPersistenceTools(fallbackDir?: string): V2T output: {}, execute: async (input, context) => { try { - const cwd = resolveToolCwd(context, fallbackDir) + const cwd = resolveMemoryStoreCwd(context, fallbackDir) const db = getMemoryDb(cwd) const nowIso = new Date().toISOString() const limit = @@ -408,7 +429,7 @@ export function createNativeMemoryAndPersistenceTools(fallbackDir?: string): V2T output: {}, execute: async (_input, context) => { try { - const cwd = resolveToolCwd(context, fallbackDir) + const cwd = resolveMemoryStoreCwd(context, fallbackDir) const db = getMemoryDb(cwd) const nowIso = new Date().toISOString() const total = db @@ -419,7 +440,13 @@ export function createNativeMemoryAndPersistenceTools(fallbackDir?: string): V2T `SELECT namespace, count(*) as count FROM memories WHERE ${NOT_EXPIRED_SQL} GROUP BY namespace`, ) .all(nowIso) - return jsonResult({ ok: true, total: total?.count ?? 0, byNamespace }) + const fed = getFederatedStats(cwd) + return jsonResult({ + ok: true, + total: total?.count ?? 0, + byNamespace, + ...(fed.repos.length > 0 ? { federated: fed } : {}), + }) } catch (err) { return jsonResult({ ok: false, @@ -455,7 +482,7 @@ export function createNativeMemoryAndPersistenceTools(fallbackDir?: string): V2T if (typeof input.content !== 'string' || !input.content.trim()) { return jsonResult({ ok: false, error: 'content must be a non-empty string' }) } - const cwd = resolveToolCwd(context, fallbackDir) + const cwd = resolveMemoryStoreCwd(context, fallbackDir) runAutoMigration(cwd) const baseDir = join(cwd, '.pantheon', 'persistence') const dir = resolveConfinedPath(baseDir, ns) @@ -513,7 +540,7 @@ export function createNativeMemoryAndPersistenceTools(fallbackDir?: string): V2T error: 'session_id and namespace must be safe identifiers without path traversal', }) } - const cwd = resolveToolCwd(context, fallbackDir) + const cwd = resolveMemoryStoreCwd(context, fallbackDir) runAutoMigration(cwd) const baseDir = join(cwd, '.pantheon', 'persistence') const dir = resolveConfinedPath(baseDir, ns) @@ -568,7 +595,7 @@ export function createNativeMemoryAndPersistenceTools(fallbackDir?: string): V2T if (!isSafeSegment(rawId)) { return jsonResult({ ok: false, error: 'id must be a safe identifier' }) } - const cwd = resolveToolCwd(context, fallbackDir) + const cwd = resolveMemoryStoreCwd(context, fallbackDir) runAutoMigration(cwd) const goalsDir = join(cwd, '.pantheon', 'goals') const filePath = resolveConfinedPath(goalsDir, `${rawId}.json`) @@ -604,7 +631,7 @@ export function createNativeMemoryAndPersistenceTools(fallbackDir?: string): V2T output: {}, execute: async (input, context) => { try { - const cwd = resolveToolCwd(context, fallbackDir) + const cwd = resolveMemoryStoreCwd(context, fallbackDir) runAutoMigration(cwd) const goalsDir = join(cwd, '.pantheon', 'goals') mkdirSync(goalsDir, { recursive: true }) @@ -633,7 +660,8 @@ export function createNativeMemoryAndPersistenceTools(fallbackDir?: string): V2T }, { name: 'goal_update', - description: 'Update progress or status on an active session goal.', + description: + 'Update progress notes or status on an active session goal. Use "notes" (not "progress") for progress text.', input: { type: 'object', additionalProperties: false, @@ -641,7 +669,7 @@ export function createNativeMemoryAndPersistenceTools(fallbackDir?: string): V2T properties: { id: { type: 'string', description: 'Goal identifier' }, status: { type: 'string', description: 'Updated status (active, paused, completed)' }, - notes: { type: 'string', description: 'Progress notes' }, + notes: { type: 'string', description: 'Progress notes (use "notes", not "progress")' }, }, }, output: {}, @@ -651,7 +679,7 @@ export function createNativeMemoryAndPersistenceTools(fallbackDir?: string): V2T if (!isSafeSegment(id)) { return jsonResult({ ok: false, error: 'valid goal id is required' }) } - const cwd = resolveToolCwd(context, fallbackDir) + const cwd = resolveMemoryStoreCwd(context, fallbackDir) runAutoMigration(cwd) const goalsDir = join(cwd, '.pantheon', 'goals') const filePath = resolveConfinedPath(goalsDir, `${id}.json`) @@ -692,7 +720,7 @@ export function createNativeMemoryAndPersistenceTools(fallbackDir?: string): V2T if (!isSafeSegment(id)) { return jsonResult({ ok: false, error: 'valid goal id is required' }) } - const cwd = resolveToolCwd(context, fallbackDir) + const cwd = resolveMemoryStoreCwd(context, fallbackDir) runAutoMigration(cwd) const goalsDir = join(cwd, '.pantheon', 'goals') const filePath = resolveConfinedPath(goalsDir, `${id}.json`) diff --git a/src/pantheon/reproduction-gate.ts b/src/pantheon/reproduction-gate.ts new file mode 100644 index 00000000..014e6d22 --- /dev/null +++ b/src/pantheon/reproduction-gate.ts @@ -0,0 +1,112 @@ +/** + * Mandatory Fault-Localization & Reproduction Gate (`reproduction-gate.ts`). + * + * When a `@hermes` or `@talos` implementer runs inside a `bugfix` Step-Ledger + * task (`taskType === 'bugfix'`), blocks production source edits until a + * failing reproduction test (`exitCode !== 0`) has been recorded via + * `pantheon_step_ledger(action="record_reproduction", ...)`. Editing test or + * spec files remains permitted so the RED test can be written first. + */ + +import { getSharedBus } from './bus.ts' +import { readStepLedger, type StepLedgerEntry } from './step-ledger.ts' + +const MUTATING_TOOLS = new Set(['edit', 'write', 'hashline_edit', 'ast_rewrite', 'patch']) +const BUGFIX_GATED_AGENTS = new Set(['hermes', 'talos']) + +export interface ReproductionGateVerdict { + readonly allowed: boolean + readonly stepKey?: string + readonly message?: string +} + +function isTestOrReproFile(filePath: string): boolean { + const norm = filePath.replace(/\\/g, '/').toLowerCase() + if (!norm) return false + if ( + /(?:^|\/)(?:tests?|__tests__|spec|specs|repro|fixtures)\//.test(norm) || + /\.(?:test|spec|repro)\.[a-z0-9]+$/i.test(norm) || + /(?:^|\/)test_[^/]+\.py$/i.test(norm) || + /_test\.go$/i.test(norm) + ) { + return true + } + return false +} + +function findActiveBugfixStep( + cwd: string, + agent: string, + explicitStepKey?: string, +): StepLedgerEntry | null { + try { + const store = readStepLedger(cwd) + if (explicitStepKey && store.steps[explicitStepKey]) { + const s = store.steps[explicitStepKey] + return s.taskType === 'bugfix' && s.state === 'in_progress' ? s : null + } + const normalized = agent.trim().toLowerCase() + const matches = Object.values(store.steps).filter( + (s) => + s.taskType === 'bugfix' && + s.state === 'in_progress' && + s.agent.trim().toLowerCase() === normalized, + ) + if (matches.length === 0) return null + matches.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)) + return matches[0] ?? null + } catch { + return null + } +} + +export function evaluateReproductionGate(params: { + readonly cwd: string + readonly tool: string + readonly agent?: string + readonly args?: Record + readonly stepKey?: string +}): ReproductionGateVerdict { + const toolName = params.tool.trim().toLowerCase() + if (!MUTATING_TOOLS.has(toolName)) return { allowed: true } + + const normalizedAgent = (params.agent ?? '').trim().toLowerCase().replace(/^@/, '') + if (!BUGFIX_GATED_AGENTS.has(normalizedAgent)) return { allowed: true } + + const activeStep = findActiveBugfixStep(params.cwd, normalizedAgent, params.stepKey) + if (!activeStep) return { allowed: true } + + const rawArgs = params.args ?? {} + const targetPath = String( + rawArgs.filePath ?? rawArgs.file_path ?? rawArgs.file ?? rawArgs.path ?? '', + ) + if (isTestOrReproFile(targetPath)) { + return { allowed: true, stepKey: activeStep.stepKey } + } + + const hasRedRepro = + typeof activeStep.reproductionRecordedAt === 'number' && + activeStep.reproductionExitCode !== undefined && + activeStep.reproductionExitCode !== 0 + + getSharedBus().emit('reproduction:gate', { + stepKey: activeStep.stepKey, + agent: normalizedAgent, + tool: toolName, + allowed: hasRedRepro, + timestamp: Date.now(), + }) + + if (hasRedRepro) { + return { allowed: true, stepKey: activeStep.stepKey } + } + + return { + allowed: false, + stepKey: activeStep.stepKey, + message: + `[Reproduction-Gate] Blocked production edit on bugfix step "${activeStep.stepKey}" for @${normalizedAgent}: ` + + 'run fault localization + a failing RED test/probe first (test files are allowed) and record it via ' + + `pantheon_step_ledger(action="record_reproduction", stepKey="${activeStep.stepKey}", command="...", exitCode=1).`, + } +} diff --git a/src/pantheon/review-verdict.ts b/src/pantheon/review-verdict.ts new file mode 100644 index 00000000..a7318f1a --- /dev/null +++ b/src/pantheon/review-verdict.ts @@ -0,0 +1,214 @@ +/** + * Typed Review Verdict Tool & Auto-Remediation (`review-verdict.ts`). + * + * Exposes `pantheon_review_verdict` for `@themis` / review roles to record + * structured verdicts (`APPROVE`, `APPROVE_WITH_NOTES`, `BLOCK`), emits + * `'review:verdict'` on `getSharedBus()`, and automatically triggers a bounded + * `ctx.session.synthetic` remediation turn when verdict === 'BLOCK'. + */ + +import { getSharedBus } from './bus.ts' +import type { PantheonToolDef, PantheonToolResult } from './tools.ts' + +export type ReviewVerdictValue = 'APPROVE' | 'APPROVE_WITH_NOTES' | 'BLOCK' + +export interface ReviewFinding { + readonly severity: 'critical' | 'major' | 'minor' + readonly file?: string + readonly message: string + readonly suggestion?: string +} + +export interface ReviewSyntheticSessionDomain { + get?: (input: { readonly sessionID: string }) => Promise + switchAgent?: (input: { readonly sessionID: string; readonly agent: string }) => Promise + synthetic?: (input: { + readonly sessionID: string + readonly text: string + readonly description?: string + readonly metadata?: Readonly> + readonly resume?: boolean + }) => Promise +} + +const MAX_AUTO_REMEDIATIONS = 2 + +function jsonResult(payload: unknown): PantheonToolResult { + return { output: JSON.stringify(payload) } +} + +function normalizeFindings(raw: unknown): ReviewFinding[] { + if (!Array.isArray(raw)) return [] + const out: ReviewFinding[] = [] + for (const item of raw) { + if (!item || typeof item !== 'object') continue + const rec = item as Record + const msg = typeof rec.message === 'string' ? rec.message.trim() : '' + if (!msg) continue + const sev = + rec.severity === 'critical' || rec.severity === 'major' || rec.severity === 'minor' + ? rec.severity + : 'major' + out.push({ + severity: sev, + ...(typeof rec.file === 'string' && rec.file.trim() ? { file: rec.file.trim() } : {}), + message: msg, + ...(typeof rec.suggestion === 'string' && rec.suggestion.trim() + ? { suggestion: rec.suggestion.trim() } + : {}), + }) + } + return out +} + +export function formatRemediationPrompt(params: { + verdict: ReviewVerdictValue + summary: string + targetAgent: string + findings: readonly ReviewFinding[] +}): string { + const lines = [ + `[THEMIS REVIEW ${params.verdict} — AUTO REMEDIATION]`, + `Target specialist: @${params.targetAgent}`, + `Summary: ${params.summary}`, + ] + if (params.findings.length > 0) { + lines.push('Findings to fix:') + for (const f of params.findings) { + const loc = f.file ? ` (${f.file})` : '' + const fix = f.suggestion ? ` — Fix: ${f.suggestion}` : '' + lines.push(`- [${f.severity}]${loc} ${f.message}${fix}`) + } + } + lines.push('Remediate the blocking issues above and re-run targeted verification.') + return lines.join('\n') +} + +export function createReviewVerdictTool( + sessionDomain?: ReviewSyntheticSessionDomain, +): PantheonToolDef { + const remediationCounts = new Map() + + return { + name: 'pantheon_review_verdict', + description: + 'Emit a structured Themis review verdict (APPROVE | APPROVE_WITH_NOTES | BLOCK) with ' + + 'typed findings. Emits a reactive PantheonBus event and dispatches bounded synthetic ' + + 'remediation when verdict is BLOCK.', + input: { + type: 'object', + additionalProperties: false, + required: ['verdict', 'summary'], + properties: { + verdict: { + type: 'string', + enum: ['APPROVE', 'APPROVE_WITH_NOTES', 'BLOCK'], + description: 'Final structured review verdict', + }, + summary: { type: 'string', description: 'Concise review verdict summary' }, + targetAgent: { + type: 'string', + description: 'Specialist agent responsible for remediation (e.g. hermes, aphrodite)', + }, + stepKey: { type: 'string', description: 'Optional associated step-ledger key' }, + findings: { + type: 'array', + description: 'Structured review findings', + items: { + type: 'object', + properties: { + severity: { type: 'string', enum: ['critical', 'major', 'minor'] }, + file: { type: 'string' }, + message: { type: 'string' }, + suggestion: { type: 'string' }, + }, + }, + }, + }, + }, + output: {}, + execute: async (input, context) => { + const verdict = + input.verdict === 'APPROVE' || + input.verdict === 'APPROVE_WITH_NOTES' || + input.verdict === 'BLOCK' + ? input.verdict + : null + const summary = typeof input.summary === 'string' ? input.summary.trim() : '' + if (!verdict) return jsonResult({ ok: false, error: 'Invalid verdict' }) + if (!summary) return jsonResult({ ok: false, error: 'summary is required' }) + + const targetAgent = + typeof input.targetAgent === 'string' && input.targetAgent.trim() + ? input.targetAgent.trim().replace(/^@/, '') + : 'hermes' + const findings = normalizeFindings(input.findings) + const ctxRec = (context ?? {}) as { sessionID?: unknown } + const sessionID = typeof ctxRec.sessionID === 'string' ? ctxRec.sessionID : undefined + + getSharedBus().emit('review:verdict', { + verdict, + targetAgent, + ...(sessionID ? { sessionID } : {}), + summary, + findingsCount: findings.length, + timestamp: Date.now(), + }) + + let syntheticTriggered = false + let syntheticSessionID: string | undefined + let remediationAttempt = 0 + if (verdict === 'BLOCK' && sessionID && typeof sessionDomain?.synthetic === 'function') { + const key = `${sessionID}:${targetAgent}` + const prev = remediationCounts.get(key) ?? 0 + if (prev < MAX_AUTO_REMEDIATIONS) { + remediationAttempt = prev + 1 + remediationCounts.set(key, remediationAttempt) + const text = formatRemediationPrompt({ verdict, summary, targetAgent, findings }) + try { + let dispatchSid = sessionID + if (typeof sessionDomain.get === 'function') { + const info = (await sessionDomain.get({ sessionID }).catch(() => undefined)) as + | { parentID?: unknown } + | null + | undefined + if (typeof info?.parentID === 'string' && info.parentID.trim()) { + dispatchSid = info.parentID.trim() + } + } + if (dispatchSid === sessionID && typeof sessionDomain.switchAgent === 'function') { + await sessionDomain + .switchAgent({ sessionID: dispatchSid, agent: targetAgent }) + .catch(() => {}) + } + await sessionDomain.synthetic({ + sessionID: dispatchSid, + text, + description: `Themis BLOCK remediation -> @${targetAgent}`, + metadata: { targetAgent, verdict, remediationAttempt }, + resume: true, + }) + syntheticTriggered = true + syntheticSessionID = dispatchSid + } catch { + syntheticTriggered = false + } + } + } else if (verdict !== 'BLOCK' && sessionID) { + remediationCounts.delete(`${sessionID}:${targetAgent}`) + } + + return jsonResult({ + ok: true, + verdict, + targetAgent, + findingsCount: findings.length, + syntheticTriggered, + ...(syntheticSessionID ? { syntheticSessionID } : {}), + ...(remediationAttempt > 0 + ? { remediationAttempt, maxRemediations: MAX_AUTO_REMEDIATIONS } + : {}), + }) + }, + } +} diff --git a/src/pantheon/stack-detector.ts b/src/pantheon/stack-detector.ts new file mode 100644 index 00000000..f18ce0d5 --- /dev/null +++ b/src/pantheon/stack-detector.ts @@ -0,0 +1,33 @@ +/** + * Typed wrapper around `scripts/stack-detector.mjs` for Pantheon plugin tools. + */ + +// @ts-expect-error Typed manually below so Node CLI binaries can share the pure ESM module. +import { detectRepositoryStacks as detectRepositoryStacksImpl } from '../../scripts/stack-detector.mjs' + +export interface DetectedStack { + readonly id: 'node-typescript' | 'python' | 'rust' | 'go' + readonly manifest: string + readonly frameworks: readonly string[] + readonly testRunner: string + readonly linter: string +} + +export interface SpecialistRecommendation { + readonly name: string + readonly archetype: 'backend' | 'frontend' | 'data' | 'security' + readonly description: string + readonly stack: readonly string[] + readonly testCommand: string + readonly suggestedDocs: readonly string[] +} + +export interface StackDetectionReport { + readonly stacks: readonly DetectedStack[] + readonly suggestedSpecialists: readonly SpecialistRecommendation[] + readonly suggestedDocs: readonly string[] +} + +export function detectRepositoryStacks(workspaceDir: string): StackDetectionReport { + return detectRepositoryStacksImpl(workspaceDir) as StackDetectionReport +} diff --git a/src/pantheon/step-ledger.ts b/src/pantheon/step-ledger.ts index 960909ee..b2cce962 100644 --- a/src/pantheon/step-ledger.ts +++ b/src/pantheon/step-ledger.ts @@ -16,18 +16,28 @@ import { existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs' import { join, resolve, sep } from 'node:path' +import { getSharedBus } from './bus.ts' import { createExecutionReceipt } from './execution-receipt.ts' +import { captureGitCheckpoint, restoreGitCheckpoint } from './git-checkpoint.ts' +import { runAtomicStepSubSession, type SubSessionDomainLike } from './step-runner.ts' import { ThemisReflexController } from './themis-reflex.ts' import { resolveToolCwd } from './tool-context.ts' import type { PantheonToolDef, PantheonToolResult } from './tools.ts' -export type StepState = 'pending' | 'in_progress' | 'done' | 'blocked' +export type StepState = 'pending' | 'in_progress' | 'done' | 'blocked' | 'rolled_back' +export type StepTaskType = 'feature' | 'bugfix' | 'refactor' | 'chore' export interface StepLedgerEntry { stepKey: string objective: string agent: string state: StepState + taskType?: StepTaskType + baselineTree?: string + rolledBackAt?: string + reproductionCommand?: string + reproductionExitCode?: number + reproductionRecordedAt?: number mutatedFiles: string[] lastMutationAt: number | null lastVerifiedAt: number | null @@ -112,11 +122,15 @@ function jsonResult(payload: unknown): PantheonToolResult { return { output: JSON.stringify(payload) } } -export function createStepLedgerTool(fallbackDir?: string): PantheonToolDef { +export function createStepLedgerTool( + fallbackDir?: string, + sessionDomain?: SubSessionDomainLike, +): PantheonToolDef { return { name: 'pantheon_step_ledger', description: - 'Manage atomic Step-Ledger execution contracts with hard verification gates: a step can transition to done ONLY after a verification command exits 0 following the last file mutation.', + 'Manage atomic Step-Ledger execution contracts with hard verification gates, Git checkpoints, bugfix reproduction tracking, and isolated sub-session step runner. ' + + 'Lifecycle: init_step | execute_step -> [record_reproduction] -> record_mutation -> record_verification -> complete_step | rollback_step | status.', input: { type: 'object', additionalProperties: false, @@ -124,19 +138,51 @@ export function createStepLedgerTool(fallbackDir?: string): PantheonToolDef { properties: { action: { type: 'string', - enum: ['init_step', 'record_mutation', 'record_verification', 'complete_step', 'status'], - description: 'Ledger operation to perform', + enum: [ + 'init_step', + 'execute_step', + 'record_reproduction', + 'record_mutation', + 'record_verification', + 'complete_step', + 'rollback_step', + 'status', + ], + description: + 'Ledger operation (init_step | execute_step | record_reproduction | record_mutation | record_verification | complete_step | rollback_step | status)', + }, + stepKey: { + type: 'string', + description: + 'Unique atomic step id matching ^[a-zA-Z0-9._:-]{1,128}$ (no spaces or "..")', }, - stepKey: { type: 'string', description: 'Unique atomic step identifier' }, objective: { type: 'string', description: 'Bounded step objective' }, agent: { type: 'string', description: 'Assigned specialist agent' }, + extraContext: { + type: 'string', + description: 'Optional bounded context for isolated execute_step sub-session', + }, + cleanupSession: { + type: 'boolean', + description: 'Remove ephemeral sub-session after execute_step (default: true)', + }, + taskType: { + type: 'string', + enum: ['feature', 'bugfix', 'refactor', 'chore'], + description: 'Task classification (bugfix enforces reproduction RED before edits)', + }, + autoRollback: { + type: 'boolean', + description: + 'Auto-restore baselineTree when verification exhausts reflex retries (default: true)', + }, files: { type: 'array', items: { type: 'string' }, description: 'Mutated file paths for record_mutation', }, - command: { type: 'string', description: 'Executed verification slice command' }, - exitCode: { type: 'number', description: 'Exit code of the verification command' }, + command: { type: 'string', description: 'Executed verification or reproduction command' }, + exitCode: { type: 'number', description: 'Exit code of the command' }, durationMs: { type: 'number', description: 'Duration of verification command in ms' }, }, }, @@ -168,11 +214,22 @@ export function createStepLedgerTool(fallbackDir?: string): PantheonToolDef { typeof input.agent === 'string' && input.agent.trim() ? input.agent.trim() : 'specialist' + const rawTaskType = input.taskType + const taskType: StepTaskType | undefined = + rawTaskType === 'feature' || + rawTaskType === 'bugfix' || + rawTaskType === 'refactor' || + rawTaskType === 'chore' + ? rawTaskType + : undefined + const ckpt = await captureGitCheckpoint(cwd, key) const entry: StepLedgerEntry = { stepKey: key, objective, agent, state: 'in_progress', + ...(taskType ? { taskType } : {}), + ...(ckpt.ok && ckpt.treeHash ? { baselineTree: ckpt.treeHash } : {}), mutatedFiles: [], lastMutationAt: null, lastVerifiedAt: null, @@ -183,11 +240,92 @@ export function createStepLedgerTool(fallbackDir?: string): PantheonToolDef { return jsonResult({ ok: true, step: entry }) } + if (action === 'execute_step') { + if (!sessionDomain) { + return jsonResult({ ok: false, error: 'host session domain unavailable' }) + } + const objective = + typeof input.objective === 'string' && input.objective.trim() + ? input.objective.trim() + : (store.steps[key]?.objective ?? '') + if (!objective) return jsonResult({ ok: false, error: 'objective is required' }) + const agent = + typeof input.agent === 'string' && input.agent.trim() + ? input.agent.trim().replace(/^@/, '') + : (store.steps[key]?.agent ?? 'hermes') + const rawTaskType = input.taskType + const taskType: StepTaskType | undefined = + rawTaskType === 'feature' || + rawTaskType === 'bugfix' || + rawTaskType === 'refactor' || + rawTaskType === 'chore' + ? rawTaskType + : store.steps[key]?.taskType + const parentSid = + typeof (context as { sessionID?: unknown } | undefined)?.sessionID === 'string' + ? ((context as { sessionID?: string }).sessionID ?? undefined) + : undefined + const runOut = await runAtomicStepSubSession({ + sessionDomain, + cwd, + stepKey: key, + objective, + agent, + ...(taskType ? { taskType } : {}), + ...(parentSid ? { parentSessionID: parentSid } : {}), + ...(typeof input.extraContext === 'string' ? { extraContext: input.extraContext } : {}), + ...(typeof input.cleanupSession === 'boolean' + ? { cleanupSession: input.cleanupSession } + : {}), + }) + return jsonResult(runOut) + } + const step = store.steps[key] if (!step) { return jsonResult({ ok: false, error: `Step "${key}" is not initialized` }) } + if (action === 'record_reproduction') { + const command = typeof input.command === 'string' ? input.command.trim() : '' + const exitCode = typeof input.exitCode === 'number' ? input.exitCode : 1 + if (!command) return jsonResult({ ok: false, error: 'command is required' }) + if (exitCode === 0) { + return jsonResult({ + ok: false, + error: 'Bugfix reproduction must demonstrate a failing test/probe (exitCode !== 0)', + step, + }) + } + step.reproductionCommand = command + step.reproductionExitCode = exitCode + step.reproductionRecordedAt = now + step.updatedAt = nowIso + writeStepLedger(cwd, store) + return jsonResult({ ok: true, reproduced: true, step }) + } + + if (action === 'rollback_step') { + if (!step.baselineTree) { + return jsonResult({ ok: false, error: `Step "${key}" has no Git baselineTree`, step }) + } + const rb = await restoreGitCheckpoint(cwd, step.baselineTree) + if (rb.ok) { + step.state = 'rolled_back' + step.rolledBackAt = nowIso + step.updatedAt = nowIso + writeStepLedger(cwd, store) + } + getSharedBus().emit('step:rollback', { + stepKey: key, + reason: 'manual_rollback_step', + restoredTree: step.baselineTree, + success: rb.ok, + timestamp: Date.now(), + }) + return jsonResult({ ok: rb.ok, restoredTree: step.baselineTree, error: rb.reason, step }) + } + if (action === 'record_mutation') { const files = Array.isArray(input.files) ? input.files.map(String) : [] const merged = Array.from(new Set([...step.mutatedFiles, ...files])) @@ -229,11 +367,33 @@ export function createStepLedgerTool(fallbackDir?: string): PantheonToolDef { error: `Verification command "${command}" failed with exit code ${exitCode}`, }, ]) + let rollbackResult: { restoredTree?: string; ok?: boolean } | undefined if (reflex.action === 'escalate') { step.state = 'blocked' + if (input.autoRollback !== false && step.baselineTree) { + const rb = await restoreGitCheckpoint(cwd, step.baselineTree) + rollbackResult = { restoredTree: step.baselineTree, ok: rb.ok } + if (rb.ok) { + step.state = 'rolled_back' + step.rolledBackAt = nowIso + } + getSharedBus().emit('step:rollback', { + stepKey: key, + reason: reflex.reason, + restoredTree: step.baselineTree, + success: rb.ok, + timestamp: Date.now(), + }) + } } writeStepLedger(cwd, store) - return jsonResult({ ok: false, verified: false, reflex, step }) + return jsonResult({ + ok: false, + verified: false, + reflex, + ...(rollbackResult ? { rollback: rollbackResult } : {}), + step, + }) } if (action === 'complete_step') { diff --git a/src/pantheon/step-runner.ts b/src/pantheon/step-runner.ts new file mode 100644 index 00000000..8756768f --- /dev/null +++ b/src/pantheon/step-runner.ts @@ -0,0 +1,161 @@ +/** + * Autonomous Sub-Session Step Runner (`step-runner.ts`). + * + * Executes an atomic Step-Ledger task inside an isolated OpenCode 2.x sub-session + * via `ctx.session.create`, seeding only the bounded objective, `stepKey`, and + * verification contract so multi-step executions avoid context blowup. + */ + +import { captureGitCheckpoint } from './git-checkpoint.ts' +import { + readStepLedger, + type StepState, + type StepTaskType, + writeStepLedger, +} from './step-ledger.ts' + +/** Structural subset of OpenCode 2.x `ctx.session` (`SessionDomain`) aligned with `@opencode/client`. */ +export interface SubSessionDomainLike { + create?: (input?: { title?: string; agent?: string; parentID?: string }) => Promise<{ + id?: string + }> + prompt?: (input: { + sessionID: string + text: string + agents?: ReadonlyArray<{ readonly name: string }> + resume?: boolean + }) => Promise + wait?: (input: { readonly sessionID: string }) => Promise + remove?: (input: { readonly sessionID: string }) => Promise +} + +export interface AtomicStepRunInput { + readonly sessionDomain: SubSessionDomainLike + readonly cwd: string + readonly stepKey: string + readonly objective: string + readonly agent: string + readonly taskType?: StepTaskType + readonly parentSessionID?: string + readonly extraContext?: string + readonly cleanupSession?: boolean +} + +export interface AtomicStepRunResult { + readonly ok: boolean + readonly stepKey: string + readonly sessionID?: string + readonly stepState?: StepState + readonly receiptId?: string + readonly error?: string +} + +/** Build the strict single-step contract prompt (objective + ledger key only). */ +export function buildAtomicStepPrompt(input: { + readonly stepKey: string + readonly objective: string + readonly agent: string + readonly extraContext?: string +}): string { + const lines = [ + `[ATOMIC STEP CONTRACT]`, + `stepKey: ${input.stepKey}`, + `agent: ${input.agent}`, + `objective: ${input.objective}`, + '', + 'Rules:', + `1. Operate strictly on the objective above; report mutations with pantheon_step_ledger(action="record_mutation", stepKey="${input.stepKey}", files=[...]).`, + `2. Run targeted verification and record via pantheon_step_ledger(action="record_verification", stepKey="${input.stepKey}", command="...", exitCode=0).`, + `3. Finish by calling pantheon_step_ledger(action="complete_step", stepKey="${input.stepKey}").`, + ] + if (input.extraContext?.trim()) { + lines.push('', 'Bounded context:', input.extraContext.trim()) + } + return lines.join('\n') +} + +/** + * Initialize a ledger step (with Git checkpoint baseline), spawn an isolated + * sub-session via `ctx.session.create`, dispatch the bounded step contract, + * and clean up the ephemeral session once completed. + */ +export async function runAtomicStepSubSession( + input: AtomicStepRunInput, +): Promise { + const { sessionDomain, cwd, stepKey, objective, agent } = input + if (typeof sessionDomain?.create !== 'function' || typeof sessionDomain?.prompt !== 'function') { + return { ok: false, stepKey, error: 'host session.create/prompt domain unavailable' } + } + + // Ensure ledger entry + Git checkpoint baseline exist cleanly before sub-session starts + const store = readStepLedger(cwd) + if (!store.steps[stepKey]) { + const ckpt = await captureGitCheckpoint(cwd, stepKey) + store.steps[stepKey] = { + stepKey, + objective, + agent, + state: 'in_progress', + ...(input.taskType ? { taskType: input.taskType } : {}), + ...(ckpt.ok && ckpt.treeHash ? { baselineTree: ckpt.treeHash } : {}), + mutatedFiles: [], + lastMutationAt: null, + lastVerifiedAt: null, + updatedAt: new Date().toISOString(), + } + writeStepLedger(cwd, store) + } + + let createdId: string | undefined + try { + const created = await sessionDomain.create({ + title: `Step ${stepKey}: ${objective.slice(0, 60)}`, + agent, + ...(input.parentSessionID ? { parentID: input.parentSessionID } : {}), + }) + createdId = typeof created?.id === 'string' ? created.id : undefined + if (!createdId) { + return { ok: false, stepKey, error: 'ctx.session.create returned no session id' } + } + + const text = buildAtomicStepPrompt({ + stepKey, + objective, + agent, + ...(input.extraContext !== undefined ? { extraContext: input.extraContext } : {}), + }) + await sessionDomain.prompt({ + sessionID: createdId, + text, + agents: [{ name: agent }], + resume: true, + }) + if (typeof sessionDomain.wait === 'function') { + await sessionDomain.wait({ sessionID: createdId }) + } + + const latest = readStepLedger(cwd).steps[stepKey] + return { + ok: latest?.state === 'done', + stepKey, + sessionID: createdId, + ...(latest?.state !== undefined ? { stepState: latest.state } : {}), + ...(latest?.receiptId !== undefined ? { receiptId: latest.receiptId } : {}), + } + } catch (err: unknown) { + return { + ok: false, + stepKey, + ...(createdId !== undefined ? { sessionID: createdId } : {}), + error: err instanceof Error ? err.message : String(err), + } + } finally { + if (createdId && input.cleanupSession !== false && typeof sessionDomain.remove === 'function') { + try { + await sessionDomain.remove({ sessionID: createdId }) + } catch { + /* best-effort cleanup */ + } + } + } +} diff --git a/src/pantheon/themis-reflex.ts b/src/pantheon/themis-reflex.ts index b474a058..ad616724 100644 --- a/src/pantheon/themis-reflex.ts +++ b/src/pantheon/themis-reflex.ts @@ -123,6 +123,16 @@ export class ThemisReflexController { } // Retries exhausted — escalate to coordinator + getSharedBus().emit('themis:reflex:escalated', { + taskID, + agent, + file: firstDisc?.file ?? 'unknown', + error: firstDisc?.error ?? 'unspecified', + attempt: state.attempt, + maxAttempts: this.maxRetries, + timestamp: state.timestamp, + resolved: false, + }) this.states.delete(taskID) return { action: 'escalate', diff --git a/src/pantheon/tool-context.ts b/src/pantheon/tool-context.ts index e5cbc19d..3ac0458b 100644 --- a/src/pantheon/tool-context.ts +++ b/src/pantheon/tool-context.ts @@ -9,6 +9,9 @@ * @module tool-context */ +import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs' +import { basename, dirname, join, relative, resolve, sep } from 'node:path' + /** Structural view of the tool context opencode passes to execute(). */ export interface ToolContextLike { sessionID: string @@ -44,3 +47,66 @@ export function resolveToolCwd(context: unknown, fallbackDir?: string): string { } return process.cwd() } + +/** + * Resolve the shared repository root for `.pantheon/memory`, checkpoints, and + * goals when operating inside a linked git worktree (`.git` is a pointer file + * with `gitdir:` + `commondir`), falling back to `cwd` unchanged for regular + * checkouts and non-git directories. + */ +export function resolveSharedPantheonRoot(cwd: string): string { + if (process.env.PANTHEON_ISOLATE_WORKTREE_MEMORY === '1') return cwd + try { + let cur = resolve(cwd) + for (let depth = 0; depth < 32; depth += 1) { + const dotGit = join(cur, '.git') + if (existsSync(dotGit)) { + const st = statSync(dotGit) + if (st.isDirectory()) return cwd + if (st.isFile()) { + const content = readFileSync(dotGit, 'utf8') + const match = /^gitdir:\s*(.+)$/m.exec(content) + if (!match?.[1]) return cwd + const gitDir = resolve(cur, match[1].trim()) + const commonFile = join(gitDir, 'commondir') + let commonGitDir: string | null = null + if (existsSync(commonFile)) { + commonGitDir = resolve(gitDir, readFileSync(commonFile, 'utf8').trim()) + } else if (basename(dirname(gitDir)) === 'worktrees') { + commonGitDir = dirname(dirname(gitDir)) + } + if (commonGitDir && basename(commonGitDir) === '.git') { + const mainRoot = dirname(commonGitDir) + if (existsSync(mainRoot)) return mainRoot + } + return cwd + } + } + const parent = dirname(cur) + if (parent === cur) break + cur = parent + } + } catch { + /* fail-open: fall back to cwd */ + } + return cwd +} + +export function resolveMemoryStoreCwd(context: unknown, fallbackDir?: string): string { + return resolveSharedPantheonRoot(resolveToolCwd(context, fallbackDir)) +} + +/** + * Resolve a file/directory path strictly inside `workspaceDir`, resolving symlinks + * and throwing on path traversal outside the workspace boundary. + */ +export function resolveSafeToolPath(workspaceDir: string, targetPath: string): string { + const rootReal = realpathSync(resolve(workspaceDir)) + const candidate = resolve(rootReal, targetPath) + const resolved = existsSync(candidate) ? realpathSync(candidate) : candidate + const rel = relative(rootReal, resolved) + if (rel === '..' || rel.startsWith(`..${sep}`) || (rel !== '' && rel.startsWith('..'))) { + throw new Error(`Path "${targetPath}" escapes workspace boundary`) + } + return resolved +} diff --git a/src/pantheon/tools.ts b/src/pantheon/tools.ts index e88cf8be..4edfdd31 100644 --- a/src/pantheon/tools.ts +++ b/src/pantheon/tools.ts @@ -49,6 +49,7 @@ import { exec } from 'node:child_process' import { promisify } from 'node:util' import { createAgentForgeTool } from './agent-forge-tool.ts' +import { createAstTools } from './ast-tools.ts' import { isDangerousCommand, NON_EDIT_AGENTS, NON_SHELL_AGENTS } from './auto-permissions.ts' import { createCodemapTools } from './codemap-tools.ts' import { createCostCommand } from './cost-command.ts' @@ -60,9 +61,12 @@ import { createV2LocalDecisionDefinition } from './local-decision-tool.ts' import { createModelCommand } from './model-command.ts' import { createNativeMemoryAndPersistenceTools } from './native-memory-tools.ts' import { createV2VisionTool, type V2VisionRuntime } from './native-vision.ts' +import { createReviewVerdictTool, type ReviewSyntheticSessionDomain } from './review-verdict.ts' import { createV2SkillSearchDefinition } from './skill-search-tool.ts' import { createStepLedgerTool } from './step-ledger.ts' +import type { SubSessionDomainLike } from './step-runner.ts' import { resolveToolCwd, type ToolContextLike } from './tool-context.ts' +import { createWorktreeTool } from './worktree-orchestrator.ts' // ─── Contract types ───────────────────────────────────────────────────── @@ -261,8 +265,6 @@ function coerceHashlineEditArgs(input: Record): return { ok: true, args: { file, edits } } } -const hashlineEdit = createHashlineEditTool() - /** * Wrap the V1 `hashline_edit` tool for the V2 surface. * @@ -271,33 +273,36 @@ const hashlineEdit = createHashlineEditTool() * satisfies the host's declaration, and `title`/`metadata` survive because the * host spreads metadata through. */ -async function executeHashlineEdit( - input: Record, - context: unknown, -): Promise { - const ctx = toolContext(context) - const callerAgent = (ctx.agent ?? '').toLowerCase().trim() - if (callerAgent && callerAgent !== 'zeus' && NON_EDIT_AGENTS.has(callerAgent)) { +function createHashlineEditExecutor(fallbackDir?: string) { + const hashlineTool = createHashlineEditTool(fallbackDir) + return async function executeHashlineEdit( + input: Record, + context: unknown, + ): Promise { + const ctx = toolContext(context) + const callerAgent = (ctx.agent ?? '').toLowerCase().trim() + if (callerAgent && callerAgent !== 'zeus' && NON_EDIT_AGENTS.has(callerAgent)) { + return { + output: `hashline_edit denied: agent '${callerAgent}' is not permitted to edit files directly.`, + } + } + const coerced = coerceHashlineEditArgs(input) + if (!coerced.ok) return { output: coerced.error } + let result: HashlineToolResult + try { + result = await hashlineTool.execute(coerced.args, ctx) + } catch (err: unknown) { + // The V1 tool does not throw for user errors; this is defence in depth so + // an unexpected throw surfaces as text instead of an absent tool result. + return { output: errorText('hashline_edit failed', err) } + } + if (typeof result === 'string') return { output: result } return { - output: `hashline_edit denied: agent '${callerAgent}' is not permitted to edit files directly.`, + output: result.output, + ...(result.title === undefined ? {} : { title: result.title }), + ...(result.metadata === undefined ? {} : { metadata: result.metadata }), } } - const coerced = coerceHashlineEditArgs(input) - if (!coerced.ok) return { output: coerced.error } - let result: HashlineToolResult - try { - result = await hashlineEdit.execute(coerced.args, ctx) - } catch (err: unknown) { - // The V1 tool does not throw for user errors; this is defence in depth so - // an unexpected throw surfaces as text instead of an absent tool result. - return { output: errorText('hashline_edit failed', err) } - } - if (typeof result === 'string') return { output: result } - return { - output: result.output, - ...(result.title === undefined ? {} : { title: result.title }), - ...(result.metadata === undefined ? {} : { metadata: result.metadata }), - } } // ─── pantheon_cost ────────────────────────────────────────────────────── @@ -451,6 +456,7 @@ async function executeModel( */ export interface V2ToolShadowOptions { readonly complexitySink?: ShadowSink + readonly sessionDomain?: ReviewSyntheticSessionDomain & SubSessionDomainLike } /** @@ -659,7 +665,7 @@ export function createV2ToolDefinitions( 'and a Did-you-mean suggestion, and nothing is modified.', input: HASHLINE_EDIT_INPUT, output: {}, - execute: executeHashlineEdit, + execute: createHashlineEditExecutor(hostLocationDirectory), }, { name: 'pantheon_cost', @@ -698,10 +704,13 @@ export function createV2ToolDefinitions( definitions.push(createShellTool(hostLocationDirectory)) definitions.push(createV2SkillSearchDefinition(hostLocationDirectory)) definitions.push(createDeepworkTool(hostLocationDirectory)) - definitions.push(createStepLedgerTool(hostLocationDirectory)) + definitions.push(createStepLedgerTool(hostLocationDirectory, shadow.sessionDomain)) definitions.push(createAgentForgeTool(hostLocationDirectory)) definitions.push(...createNativeMemoryAndPersistenceTools(hostLocationDirectory)) definitions.push(...createCodemapTools(hostLocationDirectory)) + definitions.push(...createAstTools(hostLocationDirectory)) + definitions.push(createReviewVerdictTool(shadow.sessionDomain)) + definitions.push(createWorktreeTool(hostLocationDirectory)) if (visionRuntime) definitions.push(createV2VisionTool(visionRuntime)) if (jevRuntime) definitions.push(createV2JevDecisionDefinition(jevRuntime)) return definitions diff --git a/src/pantheon/worktree-orchestrator.ts b/src/pantheon/worktree-orchestrator.ts new file mode 100644 index 00000000..e64ea03d --- /dev/null +++ b/src/pantheon/worktree-orchestrator.ts @@ -0,0 +1,233 @@ +/** + * Native Worktree Orchestration (`worktree-orchestrator.ts`). + * + * Implements OpenCode 2.x `WorktreeDefinition` (`ctx.worktree.transform`) + * enforcing Pantheon's invariant that linked git worktrees live strictly outside + * the main repository under `/.pantheon-worktrees//` + * (never inside `.pantheon/` or inside the working tree). + */ + +import { execFile } from 'node:child_process' +import { existsSync, mkdirSync, realpathSync } from 'node:fs' +import { basename, dirname, join, resolve } from 'node:path' +import { promisify } from 'node:util' +import { resolveSharedPantheonRoot, resolveToolCwd } from './tool-context.ts' +import type { PantheonToolDef, PantheonToolResult } from './tools.ts' + +const execFileAsync = promisify(execFile) +const SAFE_TASK_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/ + +export interface HostWorktreeCreateInput { + readonly sourceDirectory: string + readonly directory: string + readonly branch?: string +} + +export interface HostWorktreeRemoveInput { + readonly directory: string + readonly force: boolean +} + +export interface HostWorktreeEntry { + readonly directory: string + readonly type: 'root' | 'worktree' +} + +function isAbortError(err: unknown): boolean { + return err instanceof Error && err.name === 'AbortError' +} + +function sanitizeTaskSlug(raw: string): string { + const base = basename(raw.trim()).replace(/[^a-zA-Z0-9._-]/g, '-') + if (!base || !SAFE_TASK_RE.test(base) || base.includes('..')) { + return `wt-${Date.now()}` + } + return base +} + +/** + * Compute the canonical sibling worktree path: + * `/.pantheon-worktrees//`. + */ +export function resolvePantheonWorktreePath(sourceDirectory: string, taskName: string): string { + const sourceReal = existsSync(sourceDirectory) + ? realpathSync(resolve(sourceDirectory)) + : resolve(sourceDirectory) + const parent = dirname(sourceReal) + const repoName = basename(sourceReal) || 'workspace' + const taskSlug = sanitizeTaskSlug(taskName) + return join(parent, '.pantheon-worktrees', repoName, taskSlug) +} + +function isInsideOrDotPantheon(sourceDirectory: string, candidate: string): boolean { + const srcReal = existsSync(sourceDirectory) + ? realpathSync(resolve(sourceDirectory)) + : resolve(sourceDirectory) + const candResolved = resolve(candidate) + return ( + candResolved === srcReal || + candResolved.startsWith(`${srcReal}/`) || + candResolved.includes('/.pantheon/') || + candResolved.includes('\\.pantheon\\') + ) +} + +async function runGit(cwd: string, args: readonly string[], signal?: AbortSignal): Promise { + if (signal?.aborted) { + const abortErr = new Error('Worktree operation aborted') + abortErr.name = 'AbortError' + throw abortErr + } + const { stdout } = await execFileAsync('git', [...args], { + cwd, + signal, + timeout: 15_000, + maxBuffer: 4 * 1024 * 1024, + }) + return stdout +} + +export function createPantheonWorktreeDefinition(): { + readonly id: string + readonly create: ( + input: HostWorktreeCreateInput, + context: { readonly signal: AbortSignal }, + ) => Promise<{ readonly directory: string }> + readonly remove: ( + input: HostWorktreeRemoveInput, + context: { readonly signal: AbortSignal }, + ) => Promise + readonly list: ( + sourceDirectory: string, + context: { readonly signal: AbortSignal }, + ) => Promise +} { + return { + id: 'pantheon-worktree', + create: async (input, context) => { + const source = resolve(input.sourceDirectory) + const requestedDir = input.directory ? resolve(input.directory) : '' + const targetDir = + !requestedDir || isInsideOrDotPantheon(source, requestedDir) + ? resolvePantheonWorktreePath(source, basename(requestedDir) || `wt-${Date.now()}`) + : requestedDir + + if (input.branch && (!SAFE_TASK_RE.test(input.branch) || input.branch.startsWith('-'))) { + throw new Error(`Unsafe git ref "${input.branch}" for worktree creation`) + } + + mkdirSync(dirname(targetDir), { recursive: true }) + const args = ['worktree', 'add', '--detach', targetDir] + if (input.branch) args.push(input.branch) + await runGit(source, args, context.signal) + return { directory: existsSync(targetDir) ? realpathSync(targetDir) : targetDir } + }, + remove: async (input, context) => { + const dir = resolve(input.directory) + const parent = dirname(dir) + const args = ['worktree', 'remove'] + if (input.force) args.push('--force') + args.push(dir) + try { + await runGit(existsSync(dir) ? dir : parent, args, context.signal) + } catch (err: unknown) { + if (isAbortError(err)) throw err + throw err + } + }, + list: async (sourceDirectory, context) => { + const source = resolve(sourceDirectory) + const raw = await runGit(source, ['worktree', 'list', '--porcelain'], context.signal) + const entries: HostWorktreeEntry[] = [] + const srcReal = existsSync(source) ? realpathSync(source) : source + for (const line of raw.split(/\r?\n/)) { + if (!line.startsWith('worktree ')) continue + const wtPath = line.slice('worktree '.length).trim() + if (!wtPath) continue + const wtReal = existsSync(wtPath) ? realpathSync(wtPath) : wtPath + entries.push({ + directory: wtReal, + type: wtReal === srcReal ? 'root' : 'worktree', + }) + } + return entries + }, + } +} + +function jsonResult(payload: unknown): PantheonToolResult { + return { output: JSON.stringify(payload) } +} + +/** Expose native worktree isolation (`create`, `list`, `remove`) directly as an agent tool. */ +export function createWorktreeTool(fallbackDir?: string): PantheonToolDef { + const driver = createPantheonWorktreeDefinition() + return { + name: 'pantheon_worktree', + description: + 'Manage isolated git worktrees strictly outside the main repository under ' + + '/.pantheon-worktrees// (actions: create | list | remove).', + input: { + type: 'object', + additionalProperties: false, + required: ['action'], + properties: { + action: { type: 'string', enum: ['create', 'list', 'remove'] }, + task: { type: 'string', description: 'Short task slug for sibling worktree folder' }, + branch: { type: 'string', description: 'Optional existing git branch/ref to check out' }, + directory: { type: 'string', description: 'Target worktree directory (for remove)' }, + force: { type: 'boolean', description: 'Force worktree removal even with dirty files' }, + }, + }, + output: {}, + execute: async (input, context) => { + try { + const action = typeof input.action === 'string' ? input.action : 'list' + const workspaceDir = resolveSharedPantheonRoot(resolveToolCwd(context, fallbackDir)) + const ac = new AbortController() + if (action === 'list') { + const entries = await driver.list(workspaceDir, { signal: ac.signal }) + return jsonResult({ ok: true, entries }) + } + if (action === 'create') { + const task = + typeof input.task === 'string' && input.task.trim() + ? input.task.trim() + : `wt-${Date.now()}` + const targetDir = resolvePantheonWorktreePath(workspaceDir, task) + const res = await driver.create( + { + sourceDirectory: workspaceDir, + directory: targetDir, + ...(typeof input.branch === 'string' && input.branch.trim() + ? { branch: input.branch.trim() } + : {}), + }, + { signal: ac.signal }, + ) + return jsonResult({ ok: true, action: 'create', directory: res.directory }) + } + if (action === 'remove') { + const target = + typeof input.directory === 'string' && input.directory.trim() + ? input.directory.trim() + : typeof input.task === 'string' && input.task.trim() + ? resolvePantheonWorktreePath(workspaceDir, input.task.trim()) + : '' + if (!target) return jsonResult({ ok: false, error: 'directory or task is required' }) + await driver.remove( + { directory: target, force: input.force === true }, + { signal: ac.signal }, + ) + return jsonResult({ ok: true, action: 'remove', directory: target }) + } + return jsonResult({ ok: false, error: `Unsupported action: ${action}` }) + } catch (err: unknown) { + return jsonResult({ + ok: false, + error: err instanceof Error ? err.message : String(err), + }) + } + }, + } +} diff --git a/src/plugin.ts b/src/plugin.ts index ce56e44d..649981e0 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -103,6 +103,7 @@ import { createV2BoundedReadTool, type V2BoundedReadOriginRegistry, } from './pantheon/bounded-read.ts' +import { wireCockpitBusRecorder } from './pantheon/cockpit-events.ts' import { buildCompactionContext } from './pantheon/compaction-context.ts' import { CONTEXT_PRUNER_CONFIG_KEYS, @@ -182,6 +183,7 @@ import { import type { NativeDecisionRequest } from './pantheon/native-decisions.ts' import { buildV2VisionPromptContext, type V2VisionRuntime } from './pantheon/native-vision.ts' import { buildPrefixCachedPrompt } from './pantheon/prompt-cache-order.ts' +import { evaluateReproductionGate } from './pantheon/reproduction-gate.ts' import { getSharedBoard } from './pantheon/shared-board.ts' import { createV2ShellHooks, type V2ShellRunner } from './pantheon/shell-hooks.ts' import { @@ -200,6 +202,7 @@ import { modelAcceptsImages, sanitizeVisionHistory, } from './pantheon/vision.ts' +import { createPantheonWorktreeDefinition } from './pantheon/worktree-orchestrator.ts' import type { HookPayload, HookResult } from './plugins/hook-runner.ts' // ─── Unsupported Features Registry ─────────────────────────────────────── @@ -375,6 +378,11 @@ interface V2PermissionDomain { interface V2SessionDomain { hook?: (name: string, handler: (event: unknown) => void | Promise) => Promise get?: (input: { sessionID: string }) => Promise + synthetic?: (input: { sessionID: string; text: string; agent?: string }) => Promise +} + +interface V2WorktreeDomain { + transform?: (cb: (draft: { add: (def: unknown) => void }) => void) => Promise } interface V2LocationDomain { @@ -410,6 +418,7 @@ interface HostPluginContext extends PluginContext { generate?: V2GenerateDomain experimental?: V2ExperimentalDomain location?: V2LocationDomain + worktree?: V2WorktreeDomain } /** @@ -717,10 +726,18 @@ const CANONICAL_SLASH_COMMANDS: ReadonlyArray<{ name: string; description: strin name: 'pantheon-audit', description: 'Run zero-token heuristic static scan and Themis 3-layer security review', }, + { + name: 'pantheon-consolidate', + description: 'Merge and consolidate memory entries', + }, { name: 'pantheon-focus', description: 'Manage persistent session goals and focus boundaries across compactions', }, + { + name: 'pantheon-forge', + description: 'Interactive wizard to detect repository stacks and forge tailored specialists', + }, { name: 'pantheon-model', description: 'Inspect or configure per-agent model overrides in active-preset.json', @@ -729,10 +746,6 @@ const CANONICAL_SLASH_COMMANDS: ReadonlyArray<{ name: string; description: strin name: 'pantheon-optimize', description: 'Analyze and prune stale artifacts, worktrees, and context overhead', }, - { - name: 'pantheon-settings', - description: 'Open the interactive Pantheon TUI settings and Quotas & Spend window', - }, { name: 'pantheon-vision', description: 'Inspect or configure multimodal vision gateway and model status', @@ -743,6 +756,7 @@ function resolveCanonicalCommandsDir(): string | undefined { const candidates = [ fileURLToPath(new URL('commands', import.meta.url)), fileURLToPath(new URL('../commands', import.meta.url)), + fileURLToPath(new URL('../../commands', import.meta.url)), fileURLToPath(new URL('../src/commands', import.meta.url)), fileURLToPath(new URL('../../src/commands', import.meta.url)), fileURLToPath(new URL('src/commands', import.meta.url)), @@ -862,8 +876,10 @@ function transformReferences(draft: ReferenceDraft): void { const candidates = [ fileURLToPath(new URL('../AGENTS.global.md', import.meta.url)), fileURLToPath(new URL('../../AGENTS.global.md', import.meta.url)), + fileURLToPath(new URL('../../../AGENTS.global.md', import.meta.url)), fileURLToPath(new URL('../AGENTS.md', import.meta.url)), fileURLToPath(new URL('../../AGENTS.md', import.meta.url)), + fileURLToPath(new URL('../../../AGENTS.md', import.meta.url)), ] const resolvedPath = candidates.find((p) => existsSync(p)) ?? fileURLToPath(new URL('../AGENTS.md', import.meta.url)) @@ -1084,6 +1100,7 @@ async function registerV2Tools( complexitySink: (record) => { p3Sink.emit({ ...record, mode: 'shadow' }) }, + ...(host.session !== undefined ? { sessionDomain: host.session } : {}), }, runtime, host.location?.directory, @@ -1104,6 +1121,16 @@ async function registerV2Tools( // `adaptV2ExecuteBeforeEvent`. draft.namespace({ name: 'pantheon', description: 'Pantheon orchestration tools' }) for (const def of toolDefs) { + // Never shadow host-provided native todowrite/todoread (which persist into + // OpenCode's native Todo panel); register Pantheon's fallback only when + // the host does not already ship them. Use `draft.get` (not `draft.list`) + // so P11 reads `draft.list()` exactly once. + if ( + (def.name === 'todowrite' || def.name === 'todoread') && + draft.get?.(def.name) !== undefined + ) { + continue + } draft.add({ name: def.name, description: def.description, @@ -2495,6 +2522,18 @@ async function registerV2ToolHooks( throw new Error(guardrailVerdict.message) } } + const reproAgent = agent !== undefined ? normalizeDelegationAgent(agent) : undefined + const reproVerdict = evaluateReproductionGate({ + cwd: activeHostWorkspaceDir ?? process.cwd(), + tool: input.tool, + ...(reproAgent ? { agent: reproAgent } : {}), + ...(output.args !== null && typeof output.args === 'object' && !Array.isArray(output.args) + ? { args: output.args as Record } + : {}), + }) + if (!reproVerdict.allowed) { + throw new Error(reproVerdict.message) + } const boundedReadOrigin = boundedReadOrigins?.capture(event) const eventTool = (event as V2ToolExecuteBeforeEvent | null)?.tool if (eventTool === BOUNDED_READ_TOOL && boundedReadOrigin === undefined) { @@ -2598,6 +2637,7 @@ async function registerV2ToolHooks( // the same resolver V1 uses. const v2ExecuteAfter = createV2ExecuteAfter({ sandbox: resolveV2SandboxConfig(context.options), + cwd: () => activeHostWorkspaceDir ?? process.cwd(), }) await toolCtx.hook('execute.after', async (event: unknown) => { const benchStartedAt = Date.now() @@ -2918,6 +2958,8 @@ async function registerV2PermissionHook( * field is mandatory here rather than optional. */ interface V2ToolDraft { + list?(): ReadonlyArray<{ id?: string; name?: string }> + get?(id: string): unknown namespace(config: { name: string; description: string }): void add(tool: { name: string @@ -3170,6 +3212,20 @@ export const plugin = define({ ) if (!toolsRegistered) markUnsupported('tool-transform') + if (typeof setupHost.worktree?.transform === 'function') { + try { + await setupHost.worktree.transform((draft) => { + draft.add(createPantheonWorktreeDefinition()) + }) + } catch { + markUnsupported('worktree-transform') + } + } + + if (hostLocationDir) { + activeCleanups.push(wireCockpitBusRecorder(hostLocationDir)) + } + // ─── Phase 7: V2 Compaction Hook (best-effort) ─────────────────── const compactionCtx = setupHost.session if (compactionCtx?.hook) { diff --git a/src/plugin/index.js b/src/plugin/index.js index 75ad072b..1facd291 100644 --- a/src/plugin/index.js +++ b/src/plugin/index.js @@ -6,7 +6,7 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require }); // src/plugin.ts -import { appendFileSync as appendFileSync2, existsSync as existsSync16, mkdirSync as mkdirSync11, readdirSync as readdirSync7, readFileSync as readFileSync14 } from "node:fs"; +import { appendFileSync as appendFileSync3, existsSync as existsSync23, mkdirSync as mkdirSync14, readdirSync as readdirSync8, readFileSync as readFileSync20 } from "node:fs"; import { realpath as realpathAsync } from "node:fs/promises"; import path4 from "node:path"; import { fileURLToPath as fileURLToPath5 } from "node:url"; @@ -161,13 +161,13 @@ function evaluateAutoPermission(event, options = {}) { return { decision: "allow", reason: "pantheon-native-tool" }; } if (READ_ONLY_AGENTS.has(agent)) { - if (["edit", "write", "hashline_edit", "bash", "shell", "execute"].includes(action)) { + if (["edit", "write", "hashline_edit", "ast_rewrite", "bash", "shell", "execute"].includes(action)) { event.effect = "deny"; event.message = `Pantheon auto-permissions denied: read-only agent '${agent}' cannot execute mutating action '${action}'`; return { decision: "deny", reason: "read-only-role-violation" }; } } - if (NON_EDIT_AGENTS.has(agent) && ["edit", "write", "hashline_edit"].includes(action)) { + if (NON_EDIT_AGENTS.has(agent) && ["edit", "write", "hashline_edit", "ast_rewrite"].includes(action)) { event.effect = "deny"; event.message = `Pantheon auto-permissions denied: agent '${agent}' cannot execute file mutation '${action}'`; return { decision: "deny", reason: "read-only-role-violation" }; @@ -212,7 +212,7 @@ function evaluateAutoPermission(event, options = {}) { } } } - if (["edit", "write", "hashline_edit"].includes(action)) { + if (["edit", "write", "hashline_edit", "ast_rewrite"].includes(action)) { if (!READ_ONLY_AGENTS.has(agent)) { event.effect = "allow"; return { decision: "allow", reason: "implementer-workspace-edit" }; @@ -493,8 +493,8 @@ function parseArgs(input) { return { path: filePath, offset, limit }; } function isWithin(root, target) { - const relative4 = path.relative(root, target); - return relative4 === "" || !relative4.startsWith(`..${path.sep}`) && relative4 !== ".." && !path.isAbsolute(relative4); + const relative7 = path.relative(root, target); + return relative7 === "" || !relative7.startsWith(`..${path.sep}`) && relative7 !== ".." && !path.isAbsolute(relative7); } function sensitivePath(relativePath) { const components = relativePath.split("/").map((component) => component.toLowerCase()); @@ -770,9 +770,284 @@ function createV2BoundedReadTool(dependencies) { }; } +// src/pantheon/cockpit-events.ts +import { + appendFileSync, + existsSync as existsSync2, + mkdirSync, + readFileSync as readFileSync2, + realpathSync as realpathSync2, + writeFileSync +} from "node:fs"; +import { join as join2, resolve as resolve2, sep as sep2 } from "node:path"; + +// src/pantheon/bus.ts +var PantheonBus = class { + listeners = /* @__PURE__ */ new Map(); + /** + * Register a persistent listener for an event. + * Returns an unsubscribe callback for easy cleanup. + */ + on(event, listener) { + let set = this.listeners.get(event); + if (!set) { + set = /* @__PURE__ */ new Set(); + this.listeners.set(event, set); + } + set.add(listener); + return () => { + set?.delete(listener); + if (set?.size === 0) { + this.listeners.delete(event); + } + }; + } + /** + * Register a one-shot listener that unregisters itself after firing once. + */ + once(event, listener) { + const unsubscribe = this.on(event, (payload) => { + unsubscribe(); + return listener(payload); + }); + return unsubscribe; + } + /** + * Synchronously emit an event to all registered listeners. + * Listener rejections are logged safely without throwing. + */ + emit(event, payload) { + const set = this.listeners.get(event); + if (!set || set.size === 0) return; + for (const listener of Array.from(set)) { + try { + const result = listener(payload); + if (result instanceof Promise) { + result.catch(() => { + }); + } + } catch { + } + } + } + /** + * Wait asynchronously for a specific event matching a predicate, with an optional timeout. + */ + waitFor(event, predicate, timeoutMs = 3e4) { + return new Promise((resolve23, reject) => { + let timer = null; + let unsubscribe = null; + if (timeoutMs > 0 && Number.isFinite(timeoutMs)) { + timer = setTimeout(() => { + unsubscribe?.(); + reject(new Error(`Timed out waiting for bus event "${event}" after ${timeoutMs}ms`)); + }, timeoutMs); + } + unsubscribe = this.on(event, (payload) => { + try { + if (predicate(payload)) { + if (timer) clearTimeout(timer); + unsubscribe?.(); + resolve23(payload); + } + } catch (err) { + if (timer) clearTimeout(timer); + unsubscribe?.(); + reject(err); + } + }); + }); + } + /** Number of active listeners for a specific event or in total. */ + listenerCount(event) { + if (event) { + return this.listeners.get(event)?.size ?? 0; + } + let total = 0; + for (const set of this.listeners.values()) { + total += set.size; + } + return total; + } + /** Clear all listeners (primarily for unit tests). */ + clear() { + this.listeners.clear(); + } +}; +var BUS_KEY = "__pantheonSharedBus"; +function getSharedBus() { + const host = globalThis; + if (host[BUS_KEY] instanceof PantheonBus) return host[BUS_KEY]; + const bus = new PantheonBus(); + host[BUS_KEY] = bus; + return bus; +} + +// src/pantheon/tool-context.ts +import { existsSync, readFileSync, realpathSync, statSync } from "node:fs"; +import { basename, dirname, join, relative, resolve, sep } from "node:path"; +function resolveToolCwd(context, fallbackDir) { + const ctx = context ?? {}; + if (typeof ctx.directory === "string" && ctx.directory.trim().length > 0) { + return ctx.directory; + } + if (typeof ctx.worktree === "string" && ctx.worktree.trim().length > 0) { + return ctx.worktree; + } + if (typeof fallbackDir === "string" && fallbackDir.trim().length > 0) { + return fallbackDir; + } + return process.cwd(); +} +function resolveSharedPantheonRoot(cwd) { + if (process.env.PANTHEON_ISOLATE_WORKTREE_MEMORY === "1") return cwd; + try { + let cur = resolve(cwd); + for (let depth = 0; depth < 32; depth += 1) { + const dotGit = join(cur, ".git"); + if (existsSync(dotGit)) { + const st = statSync(dotGit); + if (st.isDirectory()) return cwd; + if (st.isFile()) { + const content = readFileSync(dotGit, "utf8"); + const match = /^gitdir:\s*(.+)$/m.exec(content); + if (!match?.[1]) return cwd; + const gitDir = resolve(cur, match[1].trim()); + const commonFile = join(gitDir, "commondir"); + let commonGitDir = null; + if (existsSync(commonFile)) { + commonGitDir = resolve(gitDir, readFileSync(commonFile, "utf8").trim()); + } else if (basename(dirname(gitDir)) === "worktrees") { + commonGitDir = dirname(dirname(gitDir)); + } + if (commonGitDir && basename(commonGitDir) === ".git") { + const mainRoot = dirname(commonGitDir); + if (existsSync(mainRoot)) return mainRoot; + } + return cwd; + } + } + const parent = dirname(cur); + if (parent === cur) break; + cur = parent; + } + } catch { + } + return cwd; +} +function resolveMemoryStoreCwd(context, fallbackDir) { + return resolveSharedPantheonRoot(resolveToolCwd(context, fallbackDir)); +} +function resolveSafeToolPath(workspaceDir, targetPath) { + const rootReal = realpathSync(resolve(workspaceDir)); + const candidate = resolve(rootReal, targetPath); + const resolved = existsSync(candidate) ? realpathSync(candidate) : candidate; + const rel = relative(rootReal, resolved); + if (rel === ".." || rel.startsWith(`..${sep}`) || rel !== "" && rel.startsWith("..")) { + throw new Error(`Path "${targetPath}" escapes workspace boundary`); + } + return resolved; +} + +// src/pantheon/cockpit-events.ts +var MAX_RETAINED_EVENTS = 160; +function resolveCockpitTelemetryPath(workspaceDir) { + const root = resolveSharedPantheonRoot(workspaceDir); + const dir = join2(root, ".pantheon", "telemetry"); + mkdirSync(dir, { recursive: true }); + const canonicalDir = realpathSync2(dir); + const target = resolve2(canonicalDir, "cockpit-events.ndjson"); + const prefix = canonicalDir.endsWith(sep2) ? canonicalDir : `${canonicalDir}${sep2}`; + if (!target.startsWith(prefix)) { + throw new Error("Cockpit telemetry path escapes .pantheon/telemetry boundary"); + } + return target; +} +function appendCockpitBusEvent(workspaceDir, entry) { + try { + const filePath = resolveCockpitTelemetryPath(workspaceDir); + appendFileSync(filePath, `${JSON.stringify(entry)} +`, "utf8"); + const raw = readFileSync2(filePath, "utf8"); + const lines = raw.split(/\r?\n/).filter(Boolean); + if (lines.length > MAX_RETAINED_EVENTS) { + writeFileSync(filePath, `${lines.slice(-MAX_RETAINED_EVENTS).join("\n")} +`, "utf8"); + } + } catch { + } +} +function wireCockpitBusRecorder(workspaceDir) { + const bus = getSharedBus(); + const unsubs = [ + bus.on("lsp:diagnostics", (ev) => { + appendCockpitBusEvent(workspaceDir, { + kind: "lsp:diagnostics", + timestamp: ev.timestamp, + agent: ev.source, + detail: `${ev.file} \xB7 ${ev.errors} err / ${ev.count} total`, + severity: ev.errors > 0 ? "warn" : "ok" + }); + }), + bus.on("review:verdict", (ev) => { + appendCockpitBusEvent(workspaceDir, { + kind: "review:verdict", + timestamp: ev.timestamp, + agent: ev.targetAgent, + detail: `${ev.verdict}: ${ev.summary}`, + severity: ev.verdict === "BLOCK" ? "error" : ev.verdict === "APPROVE_WITH_NOTES" ? "warn" : "ok" + }); + }), + bus.on("step:rollback", (ev) => { + appendCockpitBusEvent(workspaceDir, { + kind: "step:rollback", + timestamp: ev.timestamp, + agent: "ledger", + detail: `${ev.stepKey} (${ev.reason}) -> ${ev.success ? "restored" : "failed"}`, + severity: ev.success ? "warn" : "error" + }); + }), + bus.on("reproduction:gate", (ev) => { + appendCockpitBusEvent(workspaceDir, { + kind: "reproduction:gate", + timestamp: ev.timestamp, + agent: ev.agent, + detail: `${ev.stepKey} [${ev.tool}] -> ${ev.allowed ? "allowed" : "blocked (RED required)"}`, + severity: ev.allowed ? "ok" : "warn" + }); + }), + bus.on("themis:reflex:escalated", (ev) => { + appendCockpitBusEvent(workspaceDir, { + kind: "themis:reflex:escalated", + timestamp: ev.timestamp, + agent: ev.agent, + detail: `${ev.taskID} (${ev.error})`, + severity: "error" + }); + }), + bus.on("agent:execution:receipt", (ev) => { + appendCockpitBusEvent(workspaceDir, { + kind: "agent:execution:receipt", + timestamp: ev.timestamp, + agent: ev.agent, + detail: `${ev.taskID} receipt=${ev.receiptId}`, + severity: "ok" + }); + }) + ]; + return () => { + for (const unsub of unsubs) { + try { + unsub(); + } catch { + } + } + }; +} + // src/pantheon/logger.ts import { appendFile, mkdir } from "node:fs/promises"; -import { dirname, join } from "node:path"; +import { dirname as dirname2, join as join3 } from "node:path"; var CONSOLE_METHODS = { info: "log", warn: "warn", @@ -792,13 +1067,13 @@ async function appendToLog(logPath, prefix, args) { const stamp = (/* @__PURE__ */ new Date()).toISOString(); const lines = body.split("\n").map((p) => p.trim()).filter((p) => p !== "").map((p) => `[${stamp}] ${p}`); if (lines.length === 0) return; - await mkdir(dirname(logPath), { recursive: true }); + await mkdir(dirname2(logPath), { recursive: true }); await appendFile(logPath, `${lines.join("\n")} `, "utf8"); } function createPantheonLogger(options) { const echo = (options.env ?? process.env.PANTHEON_HOOKS_LOG ?? "").trim() !== ""; - const logPath = join(options.logDir ?? process.cwd(), ".pantheon", "logs", "hooks.log"); + const logPath = join3(options.logDir ?? process.cwd(), ".pantheon", "logs", "hooks.log"); const write = (level, message, args) => { void appendToLog(logPath, `[${options.module}] ${message}`, args).catch(() => { }); @@ -2334,9 +2609,9 @@ function decideHeuristic(request) { } // scripts/install/decision-router-config.mjs -import { chmodSync, existsSync, lstatSync as lstatSync2, mkdirSync, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "node:fs"; +import { chmodSync, existsSync as existsSync3, lstatSync as lstatSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync4, writeFileSync as writeFileSync3 } from "node:fs"; import { homedir } from "node:os"; -import { dirname as dirname2, isAbsolute as isAbsolute2, join as join2, parse as parse2, resolve as resolve2, sep as sep2 } from "node:path"; +import { dirname as dirname3, isAbsolute as isAbsolute2, join as join4, parse as parse2, resolve as resolve4, sep as sep4 } from "node:path"; // scripts/install/verify.mjs import { @@ -2344,20 +2619,20 @@ import { fsyncSync, lstatSync, openSync, - readFileSync, + readFileSync as readFileSync3, renameSync, unlinkSync, - writeFileSync + writeFileSync as writeFileSync2 } from "node:fs"; -import { isAbsolute, parse, relative, resolve, sep } from "node:path"; +import { isAbsolute, parse, relative as relative2, resolve as resolve3, sep as sep3 } from "node:path"; function assertNoSymlinkAncestors(filePath, { includeLeaf = true } = {}) { - const absolute = resolve(filePath); + const absolute = resolve3(filePath); const root = parse(absolute).root; - const parts = absolute.slice(root.length).split(sep).filter(Boolean); + const parts = absolute.slice(root.length).split(sep3).filter(Boolean); const checked = parts.slice(0, includeLeaf ? parts.length : Math.max(0, parts.length - 1)); let current = root; for (const [index, part] of checked.entries()) { - current = current ? `${current}${current.endsWith(sep) ? "" : sep}${part}` : part; + current = current ? `${current}${current.endsWith(sep3) ? "" : sep3}${part}` : part; let info; try { info = lstatSync(current); @@ -2436,8 +2711,8 @@ function normalizeDecisionProviderId(provider) { function resolveUserDecisionRouterConfigPath(env = process.env) { const xdg = env.XDG_CONFIG_HOME; const home = env.HOME && isAbsolute2(env.HOME) ? env.HOME : homedir(); - const root = xdg && isAbsolute2(xdg) ? xdg : join2(home, ".config"); - return resolve2(root, "pantheon", "decision-router.json"); + const root = xdg && isAbsolute2(xdg) ? xdg : join4(home, ".config"); + return resolve4(root, "pantheon", "decision-router.json"); } function migrateUserDecisionRouterConfig(value) { if (!isPlainObject(value)) return cloneDefaultUserConfig(); @@ -2482,10 +2757,10 @@ function readUserDecisionRouterConfig({ env = process.env } = {}) { const filePath = resolveUserDecisionRouterConfigPath(env); try { assertNoSymlinkAncestors(filePath); - assertTrustedDirectoryChain(dirname2(filePath), { env }); + assertTrustedDirectoryChain(dirname3(filePath), { env }); const stat2 = lstatSync2(filePath); assertPrivatePath(stat2, true); - const parsed = JSON.parse(readFileSync2(filePath, "utf8")); + const parsed = JSON.parse(readFileSync4(filePath, "utf8")); return migrateUserDecisionRouterConfig(parsed); } catch (error) { if (error?.code === "ENOENT") return cloneDefaultUserConfig(); @@ -2562,21 +2837,21 @@ function isPermittedGroupWritable(_current, env = process.env) { if (env.PANTHEON_ALLOW_GROUP_WRITABLE === "1" || env.PANTHEON_ALLOW_GROUP_WRITABLE === "true") { return true; } - if (env.JUPYTERHUB_USER || env.JUPYTER_IMAGE || env.JUPYTER_SERVER_ROOT || env.KUBERNETES_SERVICE_HOST || env.container || existsSync("/.dockerenv")) { + if (env.JUPYTERHUB_USER || env.JUPYTER_IMAGE || env.JUPYTER_SERVER_ROOT || env.KUBERNETES_SERVICE_HOST || env.container || existsSync3("/.dockerenv")) { return true; } return false; } function assertTrustedDirectoryChain(directory, { env = process.env } = {}) { - const absolute = resolve2(directory); + const absolute = resolve4(directory); const root = parse2(absolute).root; - const parts = absolute.slice(root.length).split(sep2).filter(Boolean); + const parts = absolute.slice(root.length).split(sep4).filter(Boolean); let current = root; const uid = process.getuid?.(); if (uid === void 0) throw new Error("Decision-router configuration requires user ownership checks"); for (const part of parts) { - current = join2(current, part); + current = join4(current, part); let stat2; try { stat2 = lstatSync2(current); @@ -3910,6 +4185,8 @@ var DEFAULT_BLOCKED_TOOLS = /* @__PURE__ */ new Set([ "shell", "task", "hashline_edit", + "ast_rewrite", + "pantheon_worktree", // `pantheon_model` writes active-preset.json in BOTH the project and the // global scope, so it is a write surface with the same blast radius as // `write`. Read-only agents have no reason to change agent models, and a @@ -4088,8 +4365,8 @@ function createEnforcementGuard(input) { // src/pantheon/edit-guardrails.ts import { execFile } from "node:child_process"; -import { existsSync as existsSync2, readFileSync as readFileSync3 } from "node:fs"; -import { dirname as dirname3, extname, relative as relative2, resolve as resolve3 } from "node:path"; +import { existsSync as existsSync4, readFileSync as readFileSync5 } from "node:fs"; +import { dirname as dirname4, extname, relative as relative3, resolve as resolve5 } from "node:path"; import { promisify } from "node:util"; // src/pantheon/j1-approvals.ts @@ -4155,7 +4432,7 @@ function approvalInputHash(input) { // src/pantheon/edit-guardrails.ts var execFileAsync = promisify(execFile); -var MUTATING_EDIT_TOOLS = /* @__PURE__ */ new Set(["edit", "write", "hashline_edit", "patch"]); +var MUTATING_EDIT_TOOLS = /* @__PURE__ */ new Set(["edit", "write", "hashline_edit", "patch", "ast_rewrite"]); var PROTECTED_LINT_CONFIG_BASENAMES = /* @__PURE__ */ new Set([ "biome.json", "biome.jsonc", @@ -4292,12 +4569,12 @@ var defaultExecRunner = async (cmd, args, { cwd, timeoutMs }) => { } }; function findProjectRoot(filePath, fallbackCwd) { - let dir = dirname3(resolve3(filePath)); + let dir = dirname4(resolve5(filePath)); for (let i = 0; i < 12; i += 1) { - if (existsSync2(`${dir}/package.json`) || existsSync2(`${dir}/biome.json`) || existsSync2(`${dir}/biome.jsonc`) || existsSync2(`${dir}/pyproject.toml`) || existsSync2(`${dir}/ruff.toml`) || existsSync2(`${dir}/.git`)) { + if (existsSync4(`${dir}/package.json`) || existsSync4(`${dir}/biome.json`) || existsSync4(`${dir}/biome.jsonc`) || existsSync4(`${dir}/pyproject.toml`) || existsSync4(`${dir}/ruff.toml`) || existsSync4(`${dir}/.git`)) { return dir; } - const parent = dirname3(dir); + const parent = dirname4(dir); if (parent === dir) break; dir = parent; } @@ -4318,7 +4595,7 @@ function parseGitDiffChangedLines(diffText) { return changed; } async function resolveChangedLinesVsHead(projectRoot, absFile, runner) { - const rel = relative2(projectRoot, absFile); + const rel = relative3(projectRoot, absFile); if (!rel || rel.startsWith("..")) return null; const tracked = await runner("git", ["ls-files", "--error-unmatch", rel], { cwd: projectRoot, @@ -4415,29 +4692,29 @@ var JS_TS_EXTS = /* @__PURE__ */ new Set([ ]); async function runPostEditLint(filePath, options = {}) { if (process.env.PANTHEON_DISABLE_EDIT_LINT === "1") return null; - if (!filePath || !existsSync2(filePath)) return null; - const absFile = resolve3(filePath); + if (!filePath || !existsSync4(filePath)) return null; + const absFile = resolve5(filePath); const ext = extname(absFile).toLowerCase(); const projectRoot = findProjectRoot(absFile, options.cwd ?? process.cwd()); const runner = options.runner ?? defaultExecRunner; - const rel = relative2(projectRoot, absFile) || absFile; + const rel = relative3(projectRoot, absFile) || absFile; let linterName = ""; let diagnostics = []; if (JS_TS_EXTS.has(ext)) { const localBiome = `${projectRoot}/node_modules/.bin/biome`; - const hasBiomeCfg = existsSync2(`${projectRoot}/biome.json`) || existsSync2(`${projectRoot}/biome.jsonc`); + const hasBiomeCfg = existsSync4(`${projectRoot}/biome.json`) || existsSync4(`${projectRoot}/biome.jsonc`); const localEslint = `${projectRoot}/node_modules/.bin/eslint`; - if (existsSync2(localBiome) && hasBiomeCfg) { + if (existsSync4(localBiome) && hasBiomeCfg) { linterName = "biome"; const res = await runner(localBiome, ["check", "--reporter=json", absFile], { cwd: projectRoot, timeoutMs: 1500 }); if (res.exitCode !== 0 || res.stdout.includes('"severity":"error"')) { - const fileText = readFileSync3(absFile, "utf8"); + const fileText = readFileSync5(absFile, "utf8"); diagnostics = parseBiomeJsonOutput(res.stdout, fileText); } - } else if (existsSync2(localEslint)) { + } else if (existsSync4(localEslint)) { linterName = "eslint"; const res = await runner(localEslint, ["--format=json", absFile], { cwd: projectRoot, @@ -4448,21 +4725,21 @@ async function runPostEditLint(filePath, options = {}) { } } else if (ext === ".json") { try { - JSON.parse(readFileSync3(absFile, "utf8")); + JSON.parse(readFileSync5(absFile, "utf8")); } catch (jsonErr) { return `[Pantheon Diagnostic] JSON syntax error in ${filePath}: ${jsonErr instanceof Error ? jsonErr.message : String(jsonErr)}`; } } if (ext === ".json" && diagnostics.length === 0) { try { - JSON.parse(readFileSync3(absFile, "utf8")); + JSON.parse(readFileSync5(absFile, "utf8")); } catch (jsonErr) { return `[Pantheon Diagnostic] JSON syntax error in ${filePath}: ${jsonErr instanceof Error ? jsonErr.message : String(jsonErr)}`; } } } else if (ext === ".py") { const venvRuff = `${projectRoot}/.venv/bin/ruff`; - const ruffCmd = existsSync2(venvRuff) ? venvRuff : "ruff"; + const ruffCmd = existsSync4(venvRuff) ? venvRuff : "ruff"; linterName = "ruff"; const res = await runner(ruffCmd, ["check", "--output-format=json", absFile], { cwd: projectRoot, @@ -4494,7 +4771,8 @@ Fix these issues on the edited lines before moving on.`; } // src/pantheon/execute-after.ts -import { existsSync as existsSync3 } from "node:fs"; +import { existsSync as existsSync6, statSync as statSync2 } from "node:fs"; +import { resolve as resolve7 } from "node:path"; // src/pantheon/context-sandbox.ts var DEFAULT_LIMITS = { @@ -4681,96 +4959,605 @@ function createReadEnhancer() { }; } -// src/pantheon/task-result-guard.ts -var log2 = createPantheonLogger({ module: "pantheon-task-result-guard" }); -var EMPTY_TASK_ERROR = "ERROR: task() returned empty output \u2014 child session produced no assistant or tool output. This typically means the provider rejected the request (admission control / rate limit) or the child session crashed before producing any response. Consider splitting the work into a smaller task. No retry is automatic; investigate before retrying manually."; -var HOST_EMPTY_RESULT_TEXT = "Subagent completed without a text response."; -function isChildDispatchTool(tool2) { - return tool2 === "task" || tool2 === "subagent"; -} -function isEmptyOutput(output) { - if (output == null) return true; - if (typeof output !== "string") return true; - const trimmed = output.trim(); - if (trimmed === "") return true; - return trimmed === HOST_EMPTY_RESULT_TEXT; -} -function createTaskResultGuard(options) { - const warn = options?.logger?.warn ?? ((message) => log2.warn(message)); - return async (input, output) => { - if (!isChildDispatchTool(input.tool)) return; - if (!isEmptyOutput(output.output)) return; - warn( - `[task-result-guard] Empty ${input.tool} result detected on session ${input.sessionID} (callID=${input.callID}). Replacing with explicit error.` - ); - output.output = EMPTY_TASK_ERROR; - }; -} - -// src/pantheon/execute-after.ts -function extractText(result, tool2) { - const childOutput = isChildDispatchTool(tool2) && result.output !== null && typeof result.output === "object" && !Array.isArray(result.output) ? result.output.output : void 0; - if (typeof childOutput === "string" && childOutput.trim() !== "") { - return { text: childOutput, field: "child-output-envelope" }; - } - if (typeof result.output === "string" && result.output.trim() !== "") { - return { text: result.output, field: "output" }; - } - if (typeof result.content === "string" && result.content.trim() !== "") { - return { text: result.content, field: "content" }; - } - if (Array.isArray(result.content)) { - const parts = result.content; - const allText = parts.every( - (part) => typeof part === "string" || part?.type === "text" - ); - if (!allText || parts.length === 0) return null; - const text2 = parts.map((part) => typeof part === "string" ? part : part.text ?? "").join("\n"); - if (text2.trim() !== "") return { text: text2, field: "content-array" }; - } - if (typeof result.output === "string") return { text: result.output, field: "output" }; - if (typeof childOutput === "string") { - return { text: childOutput, field: "child-output-envelope" }; - } - return null; -} -function hasMeaningfulStructuredContent(content) { - if (Array.isArray(content)) { - return content.some((part) => { - if (typeof part === "string") return false; - return part === null || typeof part !== "object" || part.type !== "text"; +// src/pantheon/lsp-diagnostics.ts +import { execFile as execFile2, spawn } from "node:child_process"; +import { existsSync as existsSync5, readFileSync as readFileSync6 } from "node:fs"; +import { createConnection } from "node:net"; +import { basename as basename2, dirname as dirname5, extname as extname2, join as join5, relative as relative4, resolve as resolve6 } from "node:path"; +import { pathToFileURL } from "node:url"; +import { promisify as promisify2 } from "node:util"; +var execFileAsync2 = promisify2(execFile2); +var MAX_DIAGNOSTICS = 8; +var TS_EXTENSIONS = /* @__PURE__ */ new Set([".ts", ".tsx", ".mts", ".cts"]); +function resolveLanguageId(absFile) { + const ext = extname2(absFile).toLowerCase(); + if (TS_EXTENSIONS.has(ext)) return ext.includes("x") ? "typescriptreact" : "typescript"; + if (ext === ".py") return "python"; + if (ext === ".go") return "go"; + if (ext === ".rs") return "rust"; + return "plaintext"; +} +function extractPublishedDiagnostics(rawDiags, absFile) { + const items = []; + for (const d of rawDiags) { + if (!d || typeof d !== "object") continue; + const diag = d; + items.push({ + file: absFile, + line: (diag.range?.start?.line ?? 0) + 1, + column: (diag.range?.start?.character ?? 0) + 1, + severity: diag.severity === 2 ? "warning" : "error", + ...diag.code !== void 0 ? { code: String(diag.code) } : {}, + message: String(diag.message ?? "").trim() }); } - if (content !== null && typeof content === "object") { - const part = content; - return part.type === "text" ? typeof part.text === "string" && part.text.trim() !== "" : Object.keys(content).length > 0; + return items; +} +function parseLspTcpEndpoints(raw = process.env.PANTHEON_LSP_TCP_ENDPOINTS ?? "") { + const endpoints = []; + for (const entry of raw.split(",")) { + const trimmed = entry.trim(); + if (!trimmed) continue; + const eqIdx = trimmed.indexOf("="); + const language = eqIdx > 0 ? trimmed.slice(0, eqIdx).trim().toLowerCase() : "*"; + const addr = eqIdx > 0 ? trimmed.slice(eqIdx + 1).trim() : trimmed; + const colonIdx = addr.lastIndexOf(":"); + if (colonIdx <= 0) continue; + const host = addr.slice(0, colonIdx).trim(); + const port = Number(addr.slice(colonIdx + 1).trim()); + if (!host || !Number.isInteger(port) || port <= 0 || port > 65535) continue; + endpoints.push({ language, host, port }); + } + return endpoints; +} +var tcpPool = /* @__PURE__ */ new Map(); +async function acquirePooledTcpSession(host, port, rootUri, timeoutMs) { + const key = `${host}:${port}`; + const existing = tcpPool.get(key); + if (existing && !existing.socket.destroyed && existing.initialized) { + if (existing.idleTimer) clearTimeout(existing.idleTimer); + return existing; + } + if (existing) { + tcpPool.delete(key); + try { + existing.socket.destroy(); + } catch { + } } - return false; -} -function rewriteChildContentMirror(content, originalText, replacement) { - const isHostPlaceholder = originalText.trim() === HOST_EMPTY_RESULT_TEXT; - const matches = (value) => typeof value === "string" && (isHostPlaceholder ? value.includes(HOST_EMPTY_RESULT_TEXT) : originalText.trim() === "" && value.trim() === ""); - if (typeof content === "string") return matches(content) ? replacement : content; - if (Array.isArray(content)) { - return content.map((part) => { - if (typeof part === "string") return matches(part) ? replacement : part; - if (part !== null && typeof part === "object" && part.type === "text" && matches(part.text)) { - return { ...part, text: replacement }; + return new Promise((resolvePromise) => { + let settled = false; + const socket = createConnection({ host, port }); + socket.unref(); + const session = { + socket, + buffer: Buffer.alloc(0), + initialized: false, + docVersions: /* @__PURE__ */ new Map(), + listeners: /* @__PURE__ */ new Set() + }; + const fail3 = () => { + if (settled) return; + settled = true; + clearTimeout(timer); + tcpPool.delete(key); + try { + socket.destroy(); + } catch { } - return part; + resolvePromise(null); + }; + const timer = setTimeout(fail3, timeoutMs); + socket.on("error", fail3); + socket.on("close", () => { + tcpPool.delete(key); + if (!settled) fail3(); }); - } - if (content !== null && typeof content === "object" && content.type === "text" && matches(content.text)) { - return { ...content, text: replacement }; - } - return content; -} -function writeText(result, field, text2, originalText, tool2) { - if (field === "output") { - result.output = text2; - } else if (field === "content") { - result.content = text2; - } else if (field === "content-array") { + socket.on("data", (chunk) => { + session.buffer = Buffer.concat([session.buffer, chunk]); + const parsed = parseLspMessages(session.buffer); + session.buffer = Buffer.from(parsed.remainder); + for (const msg of parsed.messages) { + if (!msg || typeof msg !== "object") continue; + const rec = msg; + if (!session.initialized && rec.id === 1 && rec.result !== void 0) { + session.initialized = true; + socket.write(encodeLspMessage({ jsonrpc: "2.0", method: "initialized", params: {} })); + tcpPool.set(key, session); + if (!settled) { + settled = true; + clearTimeout(timer); + resolvePromise(session); + } + } + for (const fn of session.listeners) fn(rec); + } + }); + socket.on("connect", () => { + socket.write( + encodeLspMessage({ + jsonrpc: "2.0", + id: 1, + method: "initialize", + params: { processId: process.pid, rootUri, capabilities: {} } + }) + ); + }); + }); +} +async function queryTcpLspDiagnostics(filePath, options) { + const absFile = resolve6(filePath); + const fileUri = pathToFileURL(absFile).href; + const rootUri = pathToFileURL(resolve6(options.cwd)).href; + const timeoutMs = options.timeoutMs ?? 4500; + const session = await acquirePooledTcpSession(options.host, options.port, rootUri, timeoutMs); + if (!session) return []; + const text2 = existsSync5(absFile) ? readFileSync6(absFile, "utf8") : ""; + const languageId = resolveLanguageId(absFile); + const nextVer = (session.docVersions.get(fileUri) ?? 0) + 1; + session.docVersions.set(fileUri, nextVer); + return new Promise((resolvePromise) => { + let settled = false; + const onMsg = (rec) => { + if (rec.method !== "textDocument/publishDiagnostics") return; + const params = rec.params ?? {}; + if (params.uri && params.uri !== fileUri) return; + finish( + extractPublishedDiagnostics( + Array.isArray(params.diagnostics) ? params.diagnostics : [], + absFile + ) + ); + }; + const finish = (items) => { + if (settled) return; + settled = true; + clearTimeout(timer); + session.listeners.delete(onMsg); + const idleTtl = options.idleTtlMs ?? 6e4; + session.idleTimer = setTimeout(() => { + try { + session.socket.destroy(); + } catch { + } + tcpPool.delete(`${options.host}:${options.port}`); + }, idleTtl); + session.idleTimer.unref?.(); + resolvePromise(items); + }; + const timer = setTimeout(() => finish([]), timeoutMs); + session.listeners.add(onMsg); + try { + if (nextVer === 1) { + session.socket.write( + encodeLspMessage({ + jsonrpc: "2.0", + method: "textDocument/didOpen", + params: { textDocument: { uri: fileUri, languageId, version: nextVer, text: text2 } } + }) + ); + } else { + session.socket.write( + encodeLspMessage({ + jsonrpc: "2.0", + method: "textDocument/didChange", + params: { + textDocument: { uri: fileUri, version: nextVer }, + contentChanges: [{ text: text2 }] + } + }) + ); + } + } catch { + finish([]); + } + }); +} +function encodeLspMessage(payload) { + const json = JSON.stringify(payload); + const len = Buffer.byteLength(json, "utf8"); + return `Content-Length: ${len}\r +\r +${json}`; +} +function parseLspMessages(buffer) { + const messages = []; + let offset = 0; + while (offset < buffer.length) { + const headerEnd = buffer.indexOf("\r\n\r\n", offset, "utf8"); + if (headerEnd < 0) break; + const header = buffer.subarray(offset, headerEnd).toString("utf8"); + const match = /Content-Length:\s*(\d+)/i.exec(header); + if (!match?.[1]) { + offset = headerEnd + 4; + continue; + } + const contentLength = Number(match[1]); + const bodyStart = headerEnd + 4; + const bodyEnd = bodyStart + contentLength; + if (buffer.length < bodyEnd) break; + const rawBody = buffer.subarray(bodyStart, bodyEnd).toString("utf8"); + try { + messages.push(JSON.parse(rawBody)); + } catch { + } + offset = bodyEnd; + } + return { messages, remainder: buffer.subarray(offset) }; +} +async function queryStdioLspDiagnostics(filePath, options) { + const bin = options.command[0]; + if (!bin) return []; + const args = options.command.slice(1); + const timeoutMs = options.timeoutMs ?? 4500; + const absFile = resolve6(filePath); + const fileUri = pathToFileURL(absFile).href; + const rootUri = pathToFileURL(resolve6(options.cwd)).href; + const ext = extname2(absFile).toLowerCase(); + const languageId = TS_EXTENSIONS.has(ext) ? ext.includes("x") ? "typescriptreact" : "typescript" : ext === ".py" ? "python" : "plaintext"; + const text2 = existsSync5(absFile) ? readFileSync6(absFile, "utf8") : ""; + return new Promise((resolvePromise) => { + let settled = false; + let buf = Buffer.alloc(0); + const child = spawn(bin, args, { + cwd: options.cwd, + stdio: ["pipe", "pipe", "ignore"] + }); + const finish = (items) => { + if (settled) return; + settled = true; + clearTimeout(timer); + try { + child.stdin.write( + encodeLspMessage({ jsonrpc: "2.0", id: 99, method: "shutdown", params: null }) + ); + child.stdin.write(encodeLspMessage({ jsonrpc: "2.0", method: "exit", params: null })); + } catch { + } + try { + child.kill(); + } catch { + } + resolvePromise(items); + }; + const timer = setTimeout(() => finish([]), timeoutMs); + child.on("error", () => finish([])); + child.on("exit", () => finish([])); + child.stdout.on("data", (chunk) => { + buf = Buffer.concat([buf, chunk]); + const parsed = parseLspMessages(buf); + buf = Buffer.from(parsed.remainder); + for (const msg of parsed.messages) { + if (!msg || typeof msg !== "object") continue; + const rec = msg; + if (rec.id === 1 && rec.result !== void 0) { + child.stdin.write(encodeLspMessage({ jsonrpc: "2.0", method: "initialized", params: {} })); + child.stdin.write( + encodeLspMessage({ + jsonrpc: "2.0", + method: "textDocument/didOpen", + params: { + textDocument: { uri: fileUri, languageId, version: 1, text: text2 } + } + }) + ); + } else if (rec.method === "textDocument/publishDiagnostics") { + const params = rec.params ?? {}; + if (params.uri && params.uri !== fileUri) continue; + const rawDiags = Array.isArray(params.diagnostics) ? params.diagnostics : []; + const items = []; + for (const d of rawDiags) { + if (!d || typeof d !== "object") continue; + const diag = d; + const sev = diag.severity === 2 ? "warning" : "error"; + items.push({ + file: absFile, + line: (diag.range?.start?.line ?? 0) + 1, + column: (diag.range?.start?.character ?? 0) + 1, + severity: sev, + ...diag.code !== void 0 ? { code: String(diag.code) } : {}, + message: String(diag.message ?? "").trim() + }); + } + finish(items); + } + } + }); + child.stdin.write( + encodeLspMessage({ + jsonrpc: "2.0", + id: 1, + method: "initialize", + params: { + processId: process.pid, + rootUri, + capabilities: {} + } + }) + ); + }); +} +async function defaultRunner(cmd, args, options) { + try { + const { stdout, stderr } = await execFileAsync2(cmd, args, { + cwd: options.cwd, + timeout: options.timeoutMs, + maxBuffer: 2 * 1024 * 1024 + }); + return { stdout: stdout ?? "", stderr: stderr ?? "", exitCode: 0 }; + } catch (err) { + const rec = err; + return { + stdout: rec.stdout ?? "", + stderr: rec.stderr ?? "", + exitCode: typeof rec.code === "number" ? rec.code : 1 + }; + } +} +function findAncestorTool(startDir, relParts) { + let cur = resolve6(startDir); + for (let i = 0; i < 12; i += 1) { + const candidate = join5(cur, ...relParts); + if (existsSync5(candidate)) return candidate; + const parent = dirname5(cur); + if (parent === cur) break; + cur = parent; + } + const moduleRoot = resolve6(dirname5(new URL(import.meta.url).pathname), "..", ".."); + const moduleBin = join5(moduleRoot, ...relParts); + return existsSync5(moduleBin) ? moduleBin : null; +} +function findNearestTsConfig(filePath, stopDir) { + let cur = dirname5(resolve6(filePath)); + const bound = resolve6(stopDir); + for (let i = 0; i < 10; i += 1) { + const candidate = join5(cur, "tsconfig.json"); + if (existsSync5(candidate)) return candidate; + if (cur === bound) break; + const parent = dirname5(cur); + if (parent === cur) break; + cur = parent; + } + return null; +} +function parseTscOutput(output, absFile, cwd) { + const items = []; + const targetRel = relative4(cwd, absFile).replace(/\\/g, "/"); + const targetBase = basename2(absFile); + const TSC_LINE_RE = /^(.+?)\((\d+),(\d+)\):\s+(error|warning)\s+(TS\d+):\s+(.+)$/; + for (const rawLine of output.split(/\r?\n/)) { + const match = TSC_LINE_RE.exec(rawLine.trim()); + if (!match?.[1] || !match[2] || !match[3] || !match[4] || !match[5] || !match[6]) continue; + const diagPath = match[1].replace(/\\/g, "/"); + const resolvedDiag = resolve6(cwd, diagPath); + if (resolvedDiag !== absFile && diagPath !== targetRel && !diagPath.endsWith(`/${targetBase}`) && diagPath !== targetBase) { + continue; + } + items.push({ + file: absFile, + line: Number(match[2]), + column: Number(match[3]), + severity: match[4] === "warning" ? "warning" : "error", + code: match[5], + message: match[6].trim() + }); + } + return items; +} +function parsePyrightJson(output, absFile) { + try { + const data = JSON.parse(output); + const items = []; + for (const d of data.generalDiagnostics ?? []) { + if (d.file && resolve6(d.file) !== absFile) continue; + items.push({ + file: absFile, + line: (d.range?.start?.line ?? 0) + 1, + column: (d.range?.start?.character ?? 0) + 1, + severity: d.severity === "warning" ? "warning" : "error", + ...d.rule !== void 0 ? { code: d.rule } : {}, + message: String(d.message ?? "").trim() + }); + } + return items; + } catch { + return []; + } +} +function formatDiagnosticsBlock(absFile, cwd, items) { + const rel = relative4(cwd, absFile) || basename2(absFile); + const shown = items.slice(0, MAX_DIAGNOSTICS); + const lines = shown.map( + (d) => ` ${rel}:${d.line}:${d.column} ${d.severity}${d.code ? ` ${d.code}` : ""}: ${d.message}` + ); + if (items.length > MAX_DIAGNOSTICS) { + lines.push(` ... +${items.length - MAX_DIAGNOSTICS} more diagnostic(s)`); + } + return `[LSP-Diagnostics] ${items.length} issue(s) in ${rel}: +${lines.join("\n")}`; +} +async function runPostEditDiagnostics(filePath, options = {}) { + try { + if (!filePath || !existsSync5(filePath)) return null; + const absFile = resolve6(filePath); + const cwd = resolve6(options.cwd ?? dirname5(absFile)); + const runner = options.runner ?? defaultRunner; + const timeoutMs = options.timeoutMs ?? 6e3; + const ext = extname2(absFile).toLowerCase(); + const envLsp = process.env.PANTHEON_LSP_SERVER?.trim(); + const lspCmd = options.serverCommand ?? (envLsp ? envLsp.split(/\s+/).filter(Boolean) : void 0); + if (lspCmd && lspCmd.length > 0) { + const lspItems = await queryStdioLspDiagnostics(absFile, { + command: lspCmd, + cwd, + timeoutMs + }); + getSharedBus().emit("lsp:diagnostics", { + file: relative4(cwd, absFile) || absFile, + source: "lsp-stdio", + count: lspItems.length, + errors: lspItems.filter((d) => d.severity === "error").length, + timestamp: Date.now() + }); + return lspItems.length > 0 ? formatDiagnosticsBlock(absFile, cwd, lspItems) : null; + } + const langId = resolveLanguageId(absFile); + const configuredTcp = options.tcpEndpoint ?? parseLspTcpEndpoints().find((ep) => ep.language === langId || ep.language === "*"); + if (configuredTcp) { + const tcpItems = await queryTcpLspDiagnostics(absFile, { + host: configuredTcp.host, + port: configuredTcp.port, + cwd, + timeoutMs + }); + getSharedBus().emit("lsp:diagnostics", { + file: relative4(cwd, absFile) || absFile, + source: "lsp-tcp", + count: tcpItems.length, + errors: tcpItems.filter((d) => d.severity === "error").length, + timestamp: Date.now() + }); + return tcpItems.length > 0 ? formatDiagnosticsBlock(absFile, cwd, tcpItems) : null; + } + if (TS_EXTENSIONS.has(ext)) { + const tscBin = findAncestorTool(cwd, ["node_modules", ".bin", "tsc"]); + if (!tscBin) return null; + const tsConfig = findNearestTsConfig(absFile, cwd); + const args = tsConfig ? ["--noEmit", "--pretty", "false", "--skipLibCheck", "-p", tsConfig] : [ + "--noEmit", + "--pretty", + "false", + "--skipLibCheck", + "--target", + "esnext", + "--module", + "nodenext", + "--moduleResolution", + "nodenext", + absFile + ]; + const res = await runner(tscBin, args, { cwd, timeoutMs }); + const items = parseTscOutput(`${res.stdout} +${res.stderr}`, absFile, cwd); + getSharedBus().emit("lsp:diagnostics", { + file: relative4(cwd, absFile) || absFile, + source: "typescript", + count: items.length, + errors: items.filter((d) => d.severity === "error").length, + timestamp: Date.now() + }); + return items.length > 0 ? formatDiagnosticsBlock(absFile, cwd, items) : null; + } + if (ext === ".py") { + const pyrightBin = findAncestorTool(cwd, [".venv", "bin", "pyright"]); + if (!pyrightBin) return null; + const res = await runner(pyrightBin, ["--outputjson", absFile], { cwd, timeoutMs }); + const items = parsePyrightJson(res.stdout, absFile); + getSharedBus().emit("lsp:diagnostics", { + file: relative4(cwd, absFile) || absFile, + source: "pyright", + count: items.length, + errors: items.filter((d) => d.severity === "error").length, + timestamp: Date.now() + }); + return items.length > 0 ? formatDiagnosticsBlock(absFile, cwd, items) : null; + } + return null; + } catch { + return null; + } +} + +// src/pantheon/task-result-guard.ts +var log2 = createPantheonLogger({ module: "pantheon-task-result-guard" }); +var EMPTY_TASK_ERROR = "ERROR: task() returned empty output \u2014 child session produced no assistant or tool output. This typically means the provider rejected the request (admission control / rate limit) or the child session crashed before producing any response. Consider splitting the work into a smaller task. No retry is automatic; investigate before retrying manually."; +var HOST_EMPTY_RESULT_TEXT = "Subagent completed without a text response."; +function isChildDispatchTool(tool2) { + return tool2 === "task" || tool2 === "subagent"; +} +function isEmptyOutput(output) { + if (output == null) return true; + if (typeof output !== "string") return true; + const trimmed = output.trim(); + if (trimmed === "") return true; + return trimmed === HOST_EMPTY_RESULT_TEXT; +} +function createTaskResultGuard(options) { + const warn = options?.logger?.warn ?? ((message) => log2.warn(message)); + return async (input, output) => { + if (!isChildDispatchTool(input.tool)) return; + if (!isEmptyOutput(output.output)) return; + warn( + `[task-result-guard] Empty ${input.tool} result detected on session ${input.sessionID} (callID=${input.callID}). Replacing with explicit error.` + ); + output.output = EMPTY_TASK_ERROR; + }; +} + +// src/pantheon/execute-after.ts +function extractText(result, tool2) { + const childOutput = isChildDispatchTool(tool2) && result.output !== null && typeof result.output === "object" && !Array.isArray(result.output) ? result.output.output : void 0; + if (typeof childOutput === "string" && childOutput.trim() !== "") { + return { text: childOutput, field: "child-output-envelope" }; + } + if (typeof result.output === "string" && result.output.trim() !== "") { + return { text: result.output, field: "output" }; + } + if (typeof result.content === "string" && result.content.trim() !== "") { + return { text: result.content, field: "content" }; + } + if (Array.isArray(result.content)) { + const parts = result.content; + const allText = parts.every( + (part) => typeof part === "string" || part?.type === "text" + ); + if (!allText || parts.length === 0) return null; + const text2 = parts.map((part) => typeof part === "string" ? part : part.text ?? "").join("\n"); + if (text2.trim() !== "") return { text: text2, field: "content-array" }; + } + if (typeof result.output === "string") return { text: result.output, field: "output" }; + if (typeof childOutput === "string") { + return { text: childOutput, field: "child-output-envelope" }; + } + return null; +} +function hasMeaningfulStructuredContent(content) { + if (Array.isArray(content)) { + return content.some((part) => { + if (typeof part === "string") return false; + return part === null || typeof part !== "object" || part.type !== "text"; + }); + } + if (content !== null && typeof content === "object") { + const part = content; + return part.type === "text" ? typeof part.text === "string" && part.text.trim() !== "" : Object.keys(content).length > 0; + } + return false; +} +function rewriteChildContentMirror(content, originalText, replacement) { + const isHostPlaceholder = originalText.trim() === HOST_EMPTY_RESULT_TEXT; + const matches = (value) => typeof value === "string" && (isHostPlaceholder ? value.includes(HOST_EMPTY_RESULT_TEXT) : originalText.trim() === "" && value.trim() === ""); + if (typeof content === "string") return matches(content) ? replacement : content; + if (Array.isArray(content)) { + return content.map((part) => { + if (typeof part === "string") return matches(part) ? replacement : part; + if (part !== null && typeof part === "object" && part.type === "text" && matches(part.text)) { + return { ...part, text: replacement }; + } + return part; + }); + } + if (content !== null && typeof content === "object" && content.type === "text" && matches(content.text)) { + return { ...content, text: replacement }; + } + return content; +} +function writeText(result, field, text2, originalText, tool2) { + if (field === "output") { + result.output = text2; + } else if (field === "content") { + result.content = text2; + } else if (field === "content-array") { result.content = [{ type: "text", text: text2 }]; } else { const envelope = result.output; @@ -4807,15 +5594,52 @@ function createV2ExecuteAfter(options = {}) { await sandbox(input, output); await readEnhancer(input, output); const lowerTool = tool2.trim().toLowerCase(); - if (options.editLint !== false && (lowerTool === "edit" || lowerTool === "write" || lowerTool === "hashline_edit")) { + if (lowerTool === "edit" || lowerTool === "write" || lowerTool === "hashline_edit" || lowerTool === "ast_rewrite") { + const explicitCwd = typeof options.cwd === "function" ? options.cwd() : options.cwd; + const baseCwd = explicitCwd ?? process.cwd(); const rawArgs = payload.input ?? {}; - const editedPath = rawArgs.filePath ?? rawArgs.file_path ?? rawArgs.file; - if (typeof editedPath === "string" && existsSync3(editedPath)) { - const lintOptions = typeof options.editLint === "object" ? options.editLint : {}; - const lintDiagnostic = await runPostEditLint(editedPath, lintOptions); - if (lintDiagnostic) { - output.output = `${output.output} + const rawPath = rawArgs.filePath ?? rawArgs.file_path ?? rawArgs.file ?? (lowerTool === "ast_rewrite" ? rawArgs.path : void 0); + const candidateFiles = []; + if (lowerTool === "ast_rewrite") { + try { + const parsedOut = JSON.parse(original.text); + if (Array.isArray(parsedOut.filesModified)) { + for (const f of parsedOut.filesModified) { + if (typeof f === "string" && f.trim()) candidateFiles.push(resolve7(baseCwd, f)); + } + } + } catch { + } + } + if (candidateFiles.length === 0 && typeof rawPath === "string" && rawPath.trim()) { + const absCandidate = resolve7(baseCwd, rawPath); + if (existsSync6(absCandidate) && statSync2(absCandidate).isFile()) { + candidateFiles.push(absCandidate); + } + } + for (const editedFile of candidateFiles.slice(0, 4)) { + if (!existsSync6(editedFile)) continue; + if (options.editLint !== false) { + const rawLint = typeof options.editLint === "object" ? options.editLint : {}; + const lintDiagnostic = await runPostEditLint(editedFile, { + ...explicitCwd !== void 0 ? { cwd: explicitCwd } : {}, + ...rawLint + }); + if (lintDiagnostic) { + output.output = `${output.output} ${lintDiagnostic}`; + } + } + if (options.editLsp !== false) { + const rawLsp = typeof options.editLsp === "object" ? options.editLsp : {}; + const lspDiagnostic = await runPostEditDiagnostics(editedFile, { + ...explicitCwd !== void 0 ? { cwd: explicitCwd } : {}, + ...rawLsp + }); + if (lspDiagnostic) { + output.output = `${output.output} +${lspDiagnostic}`; + } } } } @@ -4876,7 +5700,7 @@ function resolveGoalLoopConfig(options) { // src/pantheon/goal-store.ts import { mkdir as mkdir2, readFile as readFile2, rename, writeFile } from "node:fs/promises"; -import { join as join3 } from "node:path"; +import { join as join6 } from "node:path"; // src/pantheon/session-id.ts function assertSafeParentSessionID(parentSessionID) { @@ -4901,7 +5725,7 @@ var GoalStore = class { return sessionID; } pathFor(sessionID) { - return join3(this.dir, `${this.sanitizeSessionID(sessionID)}.json`); + return join6(this.dir, `${this.sanitizeSessionID(sessionID)}.json`); } /** Load the session's goal; undefined when none exists yet. */ async load(sessionID) { @@ -4937,7 +5761,7 @@ var GoalStore = class { }; // src/pantheon/guard-path.ts -import { lstatSync as lstatSync3, realpathSync, statSync } from "node:fs"; +import { lstatSync as lstatSync3, realpathSync as realpathSync3, statSync as statSync3 } from "node:fs"; import path2 from "node:path"; var MISSING_CODES = /* @__PURE__ */ new Set(["ENOENT", "ENOTDIR"]); var MAX_PATH_COMPONENTS = 64; @@ -4949,8 +5773,8 @@ function isMissing(error) { return MISSING_CODES.has(errorCode(error)); } function isWithin2(root, target) { - const relative4 = path2.relative(root, target); - return relative4 === "" || !relative4.startsWith(`..${path2.sep}`) && relative4 !== ".." && !path2.isAbsolute(relative4); + const relative7 = path2.relative(root, target); + return relative7 === "" || !relative7.startsWith(`..${path2.sep}`) && relative7 !== ".." && !path2.isAbsolute(relative7); } function resolveExistingPrefix(absolute) { let cursor = path2.resolve(absolute); @@ -4958,7 +5782,7 @@ function resolveExistingPrefix(absolute) { const remainder = []; for (let walked = 0; walked < MAX_PATH_COMPONENTS; walked++) { try { - const resolved = realpathSync(cursor); + const resolved = realpathSync3(cursor); return remainder.length === 0 ? resolved : path2.join(resolved, ...remainder); } catch (error) { if (!isMissing(error)) return void 0; @@ -4976,13 +5800,13 @@ function resolveExistingPrefix(absolute) { return void 0; } function toGuardForm(resolvedAbsolute, rootReal) { - const relative4 = isWithin2(rootReal, resolvedAbsolute) ? path2.relative(rootReal, resolvedAbsolute) : resolvedAbsolute; - return relative4.split(path2.sep).join("/"); + const relative7 = isWithin2(rootReal, resolvedAbsolute) ? path2.relative(rootReal, resolvedAbsolute) : resolvedAbsolute; + return relative7.split(path2.sep).join("/"); } function canonicalProjectRoot(projectRoot) { try { - const rootReal = realpathSync(path2.resolve(projectRoot)); - return statSync(rootReal).isDirectory() ? rootReal : void 0; + const rootReal = realpathSync3(path2.resolve(projectRoot)); + return statSync3(rootReal).isDirectory() ? rootReal : void 0; } catch { return void 0; } @@ -4994,7 +5818,7 @@ function resolveAgainst(rawPath, rootReal) { if (resolvedAbsolute === void 0) return { raw, failed: true }; let isRegularFile = false; try { - isRegularFile = statSync(resolvedAbsolute).isFile(); + isRegularFile = statSync3(resolvedAbsolute).isFile(); } catch (error) { if (!isMissing(error)) return { raw, failed: true }; } @@ -5012,8 +5836,8 @@ function createGuardPathResolver(projectRoot) { } // src/pantheon/hook-engine.ts -import { appendFileSync, mkdirSync as mkdirSync2 } from "node:fs"; -import { join as join4 } from "node:path"; +import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync3 } from "node:fs"; +import { join as join7 } from "node:path"; var SECRET_SCAN_MARKER = "[SECRET SCAN]"; var BIFROST_TOKEN_PREFIX = `${"sk"}${"-bf-"}`; var BIFROST_HEADER_NAME = `${"x"}${"-bf-"}${"vk"}`; @@ -5135,10 +5959,10 @@ function runSecretScanInProcess(payload) { } function resolveDelegationLogDir(env = process.env) { if (env.LOG_DIR) return env.LOG_DIR; - if (env.XDG_STATE_HOME) return join4(env.XDG_STATE_HOME, "pantheon", "hooks"); - if (env.PANTHEON_HOME) return join4(env.PANTHEON_HOME, "logs", "agent-sessions"); - if (env.PANTHEON_PROJECT) return join4(env.PANTHEON_PROJECT, "logs", "agent-sessions"); - return join4("logs", "agent-sessions"); + if (env.XDG_STATE_HOME) return join7(env.XDG_STATE_HOME, "pantheon", "hooks"); + if (env.PANTHEON_HOME) return join7(env.PANTHEON_HOME, "logs", "agent-sessions"); + if (env.PANTHEON_PROJECT) return join7(env.PANTHEON_PROJECT, "logs", "agent-sessions"); + return join7("logs", "agent-sessions"); } function delegationTimestamp(now) { return `${new Date(now).toISOString().slice(0, 19)}Z`; @@ -5146,8 +5970,8 @@ function delegationTimestamp(now) { function appendDelegationAuditLine(line) { try { const dir = resolveDelegationLogDir(); - mkdirSync2(dir, { recursive: true }); - appendFileSync(join4(dir, "delegations.log"), `${JSON.stringify(line)} + mkdirSync3(dir, { recursive: true }); + appendFileSync2(join7(dir, "delegations.log"), `${JSON.stringify(line)} `, "utf8"); return true; } catch { @@ -5216,10 +6040,10 @@ function formatterApplies(tool2, input) { // src/pantheon/j-telemetry-file.ts import { appendFile as appendFile2, mkdir as mkdir3, rename as rename2, stat } from "node:fs/promises"; -import { dirname as dirname4, join as join5 } from "node:path"; +import { dirname as dirname6, join as join8 } from "node:path"; var MAX_FILE_BYTES = 1048576; function defaultMirrorPath(cwd = process.cwd()) { - return join5(cwd, ".pantheon", "logs", "j-telemetry.jsonl"); + return join8(cwd, ".pantheon", "logs", "j-telemetry.jsonl"); } var ALLOWED_FIELDS = ["point", "mode", "effect", "decision", "reason"]; function mirrorProjection(record2) { @@ -5257,7 +6081,7 @@ function createJTelemetryMirror(options) { rotating = false; } } - await mkdir3(dirname4(path5), { recursive: true }); + await mkdir3(dirname6(path5), { recursive: true }); await appendFile2(path5, line, "utf8"); } catch { } @@ -6216,7 +7040,8 @@ var WRITE_TOOLS = /* @__PURE__ */ new Set([ "notebookedit", "patch", "apply_patch", - "hashline_edit" + "hashline_edit", + "ast_rewrite" ]); var J1_ENFORCE_THRESHOLD_ENV = "PANTHEON_J1_ENFORCE_THRESHOLD"; var J1_ENFORCE_THRESHOLD_DEFAULT = 0.8; @@ -6363,12 +7188,12 @@ function recordSkip(sink, skipReason) { ); } function abortDeadline(signal) { - return new Promise((resolve14) => { + return new Promise((resolve23) => { if (signal.aborted) { - resolve14("timeout"); + resolve23("timeout"); return; } - signal.addEventListener("abort", () => resolve14("timeout"), { once: true }); + signal.addEventListener("abort", () => resolve23("timeout"), { once: true }); }); } function createJ1RiskGateObserver(options) { @@ -6455,13 +7280,13 @@ import { randomUUID } from "node:crypto"; import { chmodSync as chmodSync2, closeSync as closeSync2, - existsSync as existsSync4, + existsSync as existsSync7, lstatSync as lstatSync4, - mkdirSync as mkdirSync3, + mkdirSync as mkdirSync4, openSync as openSync2 } from "node:fs"; import { homedir as homedir2 } from "node:os"; -import { basename, dirname as dirname5, isAbsolute as isAbsolute3, join as join6, parse as parse3, resolve as resolve4, sep as sep3 } from "node:path"; +import { basename as basename3, dirname as dirname7, isAbsolute as isAbsolute3, join as join9, parse as parse3, resolve as resolve8, sep as sep5 } from "node:path"; import { performance } from "node:perf_hooks"; import { DatabaseSync } from "node:sqlite"; @@ -6564,12 +7389,12 @@ var CLOCK_ROLLBACK_TOLERANCE_MS = 6e4; function resolveLocalDecisionBudgetDbPath(env = process.env) { const xdgStateHome = env.XDG_STATE_HOME; const home = env.HOME && isAbsolute3(env.HOME) ? env.HOME : homedir2(); - const base = xdgStateHome && isAbsolute3(xdgStateHome) ? xdgStateHome : join6(home, ".local", "state"); - return resolve4(base, "pantheon", DB_FILENAME); + const base = xdgStateHome && isAbsolute3(xdgStateHome) ? xdgStateHome : join9(home, ".local", "state"); + return resolve8(base, "pantheon", DB_FILENAME); } function openLocalDecisionBudgetLedger(options = {}) { - const dbPath = resolve4(options.dbPath ?? resolveLocalDecisionBudgetDbPath()); - if (["opencode.db", "install-state.json"].includes(basename(dbPath))) { + const dbPath = resolve8(options.dbPath ?? resolveLocalDecisionBudgetDbPath()); + if (["opencode.db", "install-state.json"].includes(basename3(dbPath))) { throw new Error("The budget ledger must use its own SQLite database file"); } const busyTimeoutMs = options.busyTimeoutMs ?? 5e3; @@ -6579,7 +7404,7 @@ function openLocalDecisionBudgetLedger(options = {}) { const wallClock = options.clock ?? Date.now; const monotonicClock = options.monotonicClock ?? performance.now.bind(performance); const reservationIdFactory = options.reservationIdFactory ?? randomUUID; - const directoryPath = dirname5(dbPath); + const directoryPath = dirname7(dbPath); ensureTrustedDirectoryChain(directoryPath); try { const file = openSync2(dbPath, "wx", 384); @@ -7359,18 +8184,18 @@ function ensureTrustedDirectoryChain(directoryPath) { throw new Error("Secure budget-ledger path validation is unavailable on this platform"); } const uid = process.getuid(); - const absolute = resolve4(directoryPath); + const absolute = resolve8(directoryPath); const root = parse3(absolute).root; let current = root; validateDirectoryTrust(lstatSync4(current), uid, current === absolute); - for (const component of absolute.slice(root.length).split(sep3).filter(Boolean)) { - current = join6(current, component); + for (const component of absolute.slice(root.length).split(sep5).filter(Boolean)) { + current = join9(current, component); try { lstatSync4(current); } catch (error) { if (error.code !== "ENOENT") throw error; try { - mkdirSync3(current, { mode: 448 }); + mkdirSync4(current, { mode: 448 }); } catch (mkdirError) { if (mkdirError.code !== "EEXIST") throw mkdirError; } @@ -7388,7 +8213,7 @@ function isPermittedGroupWritable2(env = process.env) { if (env.PANTHEON_ALLOW_GROUP_WRITABLE === "1" || env.PANTHEON_ALLOW_GROUP_WRITABLE === "true") { return true; } - if (env.JUPYTERHUB_USER || env.JUPYTER_IMAGE || env.JUPYTER_SERVER_ROOT || env.KUBERNETES_SERVICE_HOST || env.container || existsSync4("/.dockerenv")) { + if (env.JUPYTERHUB_USER || env.JUPYTER_IMAGE || env.JUPYTER_SERVER_ROOT || env.KUBERNETES_SERVICE_HOST || env.container || existsSync7("/.dockerenv")) { return true; } return false; @@ -7987,8 +8812,8 @@ function createV2JevDecisionDefinition(runtime) { import { createHash as createHash4 } from "node:crypto"; // src/pantheon/model-overrides.ts -import { closeSync as closeSync3, constants as constants2, fstatSync, openSync as openSync3, readFileSync as readFileSync5 } from "node:fs"; -import { join as join8 } from "node:path"; +import { closeSync as closeSync3, constants as constants2, fstatSync, openSync as openSync3, readFileSync as readFileSync8 } from "node:fs"; +import { join as join11 } from "node:path"; // src/pantheon/model-agents.ts var KNOWN_AGENTS = [ @@ -8009,8 +8834,8 @@ var KNOWN_AGENTS = [ ]; // src/pantheon/presets.mjs -import { readFileSync as readFileSync4 } from "node:fs"; -import { join as join7 } from "node:path"; +import { readFileSync as readFileSync7 } from "node:fs"; +import { join as join10 } from "node:path"; import { fileURLToPath } from "node:url"; import { load as load2 } from "js-yaml"; var EFFORT_RANK = { low: 0, medium: 1, high: 2 }; @@ -8118,7 +8943,7 @@ function loadPresetDefs(routingPath) { const path5 = routingPath ?? fileURLToPath(new URL("../routing.yml", import.meta.url)); let raw; try { - raw = readFileSync4(path5, "utf8"); + raw = readFileSync7(path5, "utf8"); } catch (err) { throw new Error(`presets: failed to load routing.yml: ${path5} \u2014 ${err.message}`); } @@ -8132,7 +8957,7 @@ function loadPresetDefs(routingPath) { } function resolveActivePreset({ env = process.env, - candidates = [join7(process.cwd(), ".pantheon", "active-preset.json")], + candidates = [join10(process.cwd(), ".pantheon", "active-preset.json")], routingPath, logger = console } = {}) { @@ -8153,7 +8978,7 @@ function resolveActivePreset({ if (!candidate) continue; let exists; try { - exists = readFileSync4(candidate); + exists = readFileSync7(candidate); } catch { continue; } @@ -8244,7 +9069,7 @@ var NonRegularPresetFileError = class extends Error { super("Preset file is not a regular file"); } }; -function readPresetFile(candidate, fileSystem = { openSync: openSync3, fstatSync, readFileSync: readFileSync5, closeSync: closeSync3 }) { +function readPresetFile(candidate, fileSystem = { openSync: openSync3, fstatSync, readFileSync: readFileSync8, closeSync: closeSync3 }) { const noFollowFlag = constants2.O_NOFOLLOW; const nonBlockFlag = constants2.O_NONBLOCK; if (noFollowFlag === void 0 || noFollowFlag === 0 || nonBlockFlag === void 0 || nonBlockFlag === 0) { @@ -8290,7 +9115,7 @@ function parseOverrides(value, warnings) { return parsed; } function defaultCandidates() { - return [join8(process.cwd(), ".pantheon", "active-preset.json")]; + return [join11(process.cwd(), ".pantheon", "active-preset.json")]; } function readModelConfiguration(options = {}) { const env = options.env ?? process.env; @@ -8581,12 +9406,12 @@ function recordSkip2(sink, skipReason) { ); } function abortDeadline2(signal) { - return new Promise((resolve14) => { + return new Promise((resolve23) => { if (signal.aborted) { - resolve14("timeout"); + resolve23("timeout"); return; } - signal.addEventListener("abort", () => resolve14("timeout"), { once: true }); + signal.addEventListener("abort", () => resolve23("timeout"), { once: true }); }); } function createJ3EscalationObserver(options) { @@ -8670,30 +9495,30 @@ function createJ3EscalationObserver(options) { // src/pantheon/legacy-store-migration.mjs import { - existsSync as existsSync5, - mkdirSync as mkdirSync4, + existsSync as existsSync8, + mkdirSync as mkdirSync5, readdirSync, - readFileSync as readFileSync6, - realpathSync as realpathSync2, + readFileSync as readFileSync9, + realpathSync as realpathSync4, rmSync, - statSync as statSync2, - writeFileSync as writeFileSync3 + statSync as statSync4, + writeFileSync as writeFileSync4 } from "node:fs"; -import { dirname as dirname6, join as join9, resolve as resolve5 } from "node:path"; +import { dirname as dirname8, join as join12, resolve as resolve9 } from "node:path"; import { DatabaseSync as DatabaseSync2 } from "node:sqlite"; var SAFE_SEGMENT_RE = /^[a-zA-Z0-9._:-]{1,128}$/; function resolveSafeGlobalConfigDir(env = process.env) { if (env.PANTHEON_HOME?.trim()) { - return resolve5(env.PANTHEON_HOME.trim()); + return resolve9(env.PANTHEON_HOME.trim()); } if (env.XDG_CONFIG_HOME?.trim()) { - return join9(resolve5(env.XDG_CONFIG_HOME.trim()), "opencode"); + return join12(resolve9(env.XDG_CONFIG_HOME.trim()), "opencode"); } if (env.NODE_TEST_CONTEXT) { return void 0; } const home = env.HOME?.trim(); - return home ? join9(resolve5(home), ".config", "opencode") : void 0; + return home ? join12(resolve9(home), ".config", "opencode") : void 0; } function toSafeSegment(raw, fallback = "default") { const str = String(raw ?? "").trim().replace(/[^a-zA-Z0-9._:-]/g, "_").slice(0, 128); @@ -8703,26 +9528,26 @@ function toSafeSegment(raw, fallback = "default") { return str; } function sameFileOrPath(a, b) { - if (resolve5(a) === resolve5(b)) return true; - if (!existsSync5(a) || !existsSync5(b)) return false; + if (resolve9(a) === resolve9(b)) return true; + if (!existsSync8(a) || !existsSync8(b)) return false; try { - return realpathSync2(a) === realpathSync2(b); + return realpathSync4(a) === realpathSync4(b); } catch { return false; } } function removeFileAndSqliteSidecars(filePath, deleted, dryRun = false) { - const dir = dirname6(filePath); + const dir = dirname8(filePath); const base = filePath.slice(dir.length + 1); const candidates = [ filePath, `${filePath}-wal`, `${filePath}-shm`, `${filePath}-journal`, - join9(dir, `.${base}.init.lock`) + join12(dir, `.${base}.init.lock`) ]; for (const candidate of candidates) { - if (existsSync5(candidate)) { + if (existsSync8(candidate)) { if (!dryRun) { rmSync(candidate, { recursive: true, force: true }); } @@ -8731,7 +9556,7 @@ function removeFileAndSqliteSidecars(filePath, deleted, dryRun = false) { } } function removeEmptyDirIfPossible(dirPath, deleted, dryRun = false) { - if (!existsSync5(dirPath)) return; + if (!existsSync8(dirPath)) return; try { const entries = readdirSync(dirPath); if (entries.length === 0) { @@ -8751,43 +9576,43 @@ if (!(g[GLOBAL_CACHE_SYM] instanceof Set)) { var migratedWorkspaces = g[GLOBAL_CACHE_SYM]; function safeMtimeMs(filePath) { try { - return existsSync5(filePath) ? statSync2(filePath).mtimeMs : 0; + return existsSync8(filePath) ? statSync4(filePath).mtimeMs : 0; } catch { return 0; } } function hasPendingLegacyFiles(rootDir) { const checks = [ - join9(rootDir, ".pantheon", "memory.db"), - join9(rootDir, "memory", "memory.db"), - join9(rootDir, ".pantheon", "persistence", "global.db"), - join9(rootDir, ".pantheon", "persistence", "project.db"), - join9(rootDir, "persistence", "global.db"), - join9(rootDir, "persistence", "project.db"), - join9(rootDir, ".pantheon", "goals.json"), - join9(rootDir, ".pantheon", "persistence", "goals"), - join9(rootDir, "plugins", "pantheon-hooks.ts"), - join9(rootDir, "plugins", "pantheon-hooks.js"), - join9(rootDir, ".opencode", "plugins", "pantheon-hooks.ts"), - join9(rootDir, ".opencode", "plugins", "pantheon-hooks.js"), - join9(rootDir, "tiers.json"), - join9(rootDir, ".opencode", "tiers.json"), - join9(rootDir, ".pantheon", "fastembed_cache"), - join9(rootDir, ".pantheon", ".fastembed"), - join9(rootDir, "fastembed_cache") + join12(rootDir, ".pantheon", "memory.db"), + join12(rootDir, "memory", "memory.db"), + join12(rootDir, ".pantheon", "persistence", "global.db"), + join12(rootDir, ".pantheon", "persistence", "project.db"), + join12(rootDir, "persistence", "global.db"), + join12(rootDir, "persistence", "project.db"), + join12(rootDir, ".pantheon", "goals.json"), + join12(rootDir, ".pantheon", "persistence", "goals"), + join12(rootDir, "plugins", "pantheon-hooks.ts"), + join12(rootDir, "plugins", "pantheon-hooks.js"), + join12(rootDir, ".opencode", "plugins", "pantheon-hooks.ts"), + join12(rootDir, ".opencode", "plugins", "pantheon-hooks.js"), + join12(rootDir, "tiers.json"), + join12(rootDir, ".opencode", "tiers.json"), + join12(rootDir, ".pantheon", "fastembed_cache"), + join12(rootDir, ".pantheon", ".fastembed"), + join12(rootDir, "fastembed_cache") ]; - return checks.some((p) => existsSync5(p)); + return checks.some((p) => existsSync8(p)); } function canSkipMigrationViaStamp(workspaceDir, globalConfigDir) { - const stampPath = join9(workspaceDir, ".pantheon", ".migration-v2.json"); - if (!existsSync5(stampPath)) return false; + const stampPath = join12(workspaceDir, ".pantheon", ".migration-v2.json"); + if (!existsSync8(stampPath)) return false; try { - const stamp = JSON.parse(readFileSync6(stampPath, "utf8")); + const stamp = JSON.parse(readFileSync9(stampPath, "utf8")); if (stamp?.version !== 2) return false; if (hasPendingLegacyFiles(workspaceDir)) return false; - if (globalConfigDir && existsSync5(globalConfigDir)) { + if (globalConfigDir && existsSync8(globalConfigDir)) { if (hasPendingLegacyFiles(globalConfigDir)) return false; - const globalMemDb = join9(globalConfigDir, ".pantheon", "memory", "memory.db"); + const globalMemDb = join12(globalConfigDir, ".pantheon", "memory", "memory.db"); if (safeMtimeMs(globalMemDb) !== Number(stamp.globalMtimeMs ?? -1)) return false; } return true; @@ -8797,9 +9622,9 @@ function canSkipMigrationViaStamp(workspaceDir, globalConfigDir) { } function ensureLegacyStoresMigratedOnce(workspaceDir, options = {}) { if (!workspaceDir || typeof workspaceDir !== "string") return null; - const key = resolve5(workspaceDir); - if (key === "/" || !existsSync5(key)) return null; - const globalKey = options.globalConfigDir ? resolve5(options.globalConfigDir) : ""; + const key = resolve9(workspaceDir); + if (key === "/" || !existsSync8(key)) return null; + const globalKey = options.globalConfigDir ? resolve9(options.globalConfigDir) : ""; const cacheKey = `${key}::${globalKey}`; if (migratedWorkspaces.has(cacheKey)) return null; migratedWorkspaces.add(cacheKey); @@ -8809,7 +9634,7 @@ function ensureLegacyStoresMigratedOnce(workspaceDir, options = {}) { return migrateLegacyStoresAndPurgeStale(key, options); } function migrateLegacyStoresAndPurgeStale(workspaceDir, options = {}) { - const root = resolve5(workspaceDir); + const root = resolve9(workspaceDir); const dryRun = options.dryRun === true; const nowIso = (/* @__PURE__ */ new Date()).toISOString(); let memoriesMigrated = 0; @@ -8818,7 +9643,7 @@ function migrateLegacyStoresAndPurgeStale(workspaceDir, options = {}) { let contextsMigrated = 0; let goalsMigrated = 0; const staleFilesDeleted = []; - if (root === "/" || !existsSync5(root)) { + if (root === "/" || !existsSync8(root)) { return { memoriesMigrated, memoriesExpiredPurged, @@ -8830,8 +9655,8 @@ function migrateLegacyStoresAndPurgeStale(workspaceDir, options = {}) { } let globalCanonicalMemDb = null; if (options.globalConfigDir) { - const globalRoot = resolve5(options.globalConfigDir); - if (globalRoot !== "/" && globalRoot !== root && existsSync5(globalRoot)) { + const globalRoot = resolve9(options.globalConfigDir); + if (globalRoot !== "/" && globalRoot !== root && existsSync8(globalRoot)) { const globalReport = migrateLegacyStoresAndPurgeStale(globalRoot, { dryRun }); memoriesMigrated += globalReport.memoriesMigrated; memoriesExpiredPurged += globalReport.memoriesExpiredPurged; @@ -8839,27 +9664,27 @@ function migrateLegacyStoresAndPurgeStale(workspaceDir, options = {}) { contextsMigrated += globalReport.contextsMigrated; goalsMigrated += globalReport.goalsMigrated; staleFilesDeleted.push(...globalReport.staleFilesDeleted); - globalCanonicalMemDb = join9(globalRoot, ".pantheon", "memory", "memory.db"); + globalCanonicalMemDb = join12(globalRoot, ".pantheon", "memory", "memory.db"); } } - const pantheonDir = join9(root, ".pantheon"); - const canonicalMemoryDir = join9(pantheonDir, "memory"); - const canonicalMemoryDbPath = join9(canonicalMemoryDir, "memory.db"); - const canonicalPersistenceDir = join9(pantheonDir, "persistence"); - const canonicalGoalsDir = join9(pantheonDir, "goals"); + const pantheonDir = join12(root, ".pantheon"); + const canonicalMemoryDir = join12(pantheonDir, "memory"); + const canonicalMemoryDbPath = join12(canonicalMemoryDir, "memory.db"); + const canonicalPersistenceDir = join12(pantheonDir, "persistence"); + const canonicalGoalsDir = join12(pantheonDir, "goals"); const legacyMemoryCandidates = [ - { path: join9(pantheonDir, "memory.db"), deleteAfter: true }, - { path: join9(root, "memory", "memory.db"), deleteAfter: true } + { path: join12(pantheonDir, "memory.db"), deleteAfter: true }, + { path: join12(root, "memory", "memory.db"), deleteAfter: true } ]; if (globalCanonicalMemDb) { legacyMemoryCandidates.push({ path: globalCanonicalMemDb, deleteAfter: false }); } const existingLegacyMemDbs = legacyMemoryCandidates.filter( - (c) => existsSync5(c.path) && !sameFileOrPath(c.path, canonicalMemoryDbPath) + (c) => existsSync8(c.path) && !sameFileOrPath(c.path, canonicalMemoryDbPath) ); - if (existingLegacyMemDbs.length > 0 || existsSync5(canonicalMemoryDbPath)) { + if (existingLegacyMemDbs.length > 0 || existsSync8(canonicalMemoryDbPath)) { if (!dryRun) { - mkdirSync4(canonicalMemoryDir, { recursive: true }); + mkdirSync5(canonicalMemoryDir, { recursive: true }); } let targetDb = null; let hadFtsBefore = false; @@ -8979,7 +9804,7 @@ function migrateLegacyStoresAndPurgeStale(workspaceDir, options = {}) { } if (candidate.deleteAfter) { removeFileAndSqliteSidecars(candidate.path, staleFilesDeleted, dryRun); - removeEmptyDirIfPossible(dirname6(candidate.path), staleFilesDeleted, dryRun); + removeEmptyDirIfPossible(dirname8(candidate.path), staleFilesDeleted, dryRun); } } if (!dryRun && targetDb) { @@ -9049,30 +9874,30 @@ function migrateLegacyStoresAndPurgeStale(workspaceDir, options = {}) { } } const legacyPersistenceDbs = [ - join9(pantheonDir, "persistence", "project.db"), - join9(pantheonDir, "persistence", "global.db"), - join9(root, "persistence", "project.db"), - join9(root, "persistence", "global.db") + join12(pantheonDir, "persistence", "project.db"), + join12(pantheonDir, "persistence", "global.db"), + join12(root, "persistence", "project.db"), + join12(root, "persistence", "global.db") ]; if (options.globalConfigDir) { - const globalRoot = resolve5(options.globalConfigDir); + const globalRoot = resolve9(options.globalConfigDir); if (globalRoot !== root) { legacyPersistenceDbs.push( - join9(globalRoot, "persistence", "global.db"), - join9(globalRoot, "persistence", "project.db"), - join9(globalRoot, ".pantheon", "persistence", "global.db"), - join9(globalRoot, ".pantheon", "persistence", "project.db") + join12(globalRoot, "persistence", "global.db"), + join12(globalRoot, "persistence", "project.db"), + join12(globalRoot, ".pantheon", "persistence", "global.db"), + join12(globalRoot, ".pantheon", "persistence", "project.db") ); } } const seenPersistenceDbs = /* @__PURE__ */ new Set(); for (const dbPath of legacyPersistenceDbs) { - if (!existsSync5(dbPath)) continue; + if (!existsSync8(dbPath)) continue; const real = (() => { try { - return realpathSync2(dbPath); + return realpathSync4(dbPath); } catch { - return resolve5(dbPath); + return resolve9(dbPath); } })(); if (seenPersistenceDbs.has(real)) continue; @@ -9124,12 +9949,12 @@ function migrateLegacyStoresAndPurgeStale(workspaceDir, options = {}) { const targetNamespaces = safeNs === "context" ? ["context", "checkpoints"] : [safeNs]; let wroteAny = false; for (const targetNs of targetNamespaces) { - const nsDir = join9(canonicalPersistenceDir, targetNs); - const outFile = join9(nsDir, `${safeKey}.json`); - if (!existsSync5(outFile)) { + const nsDir = join12(canonicalPersistenceDir, targetNs); + const outFile = join12(nsDir, `${safeKey}.json`); + if (!existsSync8(outFile)) { if (!dryRun) { - mkdirSync4(nsDir, { recursive: true }); - writeFileSync3( + mkdirSync5(nsDir, { recursive: true }); + writeFileSync4( outFile, JSON.stringify({ ...record2, namespace: targetNs }, null, 2), "utf8" @@ -9150,8 +9975,8 @@ function migrateLegacyStoresAndPurgeStale(workspaceDir, options = {}) { const rawId = String(row.goal_id ?? row.id ?? "").trim(); const safeId = toSafeSegment(rawId, ""); if (!safeId) continue; - const outFile = join9(canonicalGoalsDir, `${safeId}.json`); - if (!existsSync5(outFile)) { + const outFile = join12(canonicalGoalsDir, `${safeId}.json`); + if (!existsSync8(outFile)) { let criteria = []; if (typeof row.criteria_json === "string") { try { @@ -9180,8 +10005,8 @@ function migrateLegacyStoresAndPurgeStale(workspaceDir, options = {}) { ...typeof row.completed_at === "string" ? { completed_at: row.completed_at } : {} }; if (!dryRun) { - mkdirSync4(canonicalGoalsDir, { recursive: true }); - writeFileSync3(outFile, JSON.stringify(goalRecord, null, 2), "utf8"); + mkdirSync5(canonicalGoalsDir, { recursive: true }); + writeFileSync4(outFile, JSON.stringify(goalRecord, null, 2), "utf8"); } goalsMigrated += 1; } @@ -9195,28 +10020,28 @@ function migrateLegacyStoresAndPurgeStale(workspaceDir, options = {}) { } } removeFileAndSqliteSidecars(dbPath, staleFilesDeleted, dryRun); - const parentDir = dirname6(dbPath); + const parentDir = dirname8(dbPath); if (parentDir !== canonicalPersistenceDir) { removeEmptyDirIfPossible(parentDir, staleFilesDeleted, dryRun); } } for (const legacyCheckpointDir of [ - join9(pantheonDir, "checkpoints"), - join9(pantheonDir, "context") + join12(pantheonDir, "checkpoints"), + join12(pantheonDir, "context") ]) { - if (!existsSync5(legacyCheckpointDir)) continue; + if (!existsSync8(legacyCheckpointDir)) continue; try { for (const entry of readdirSync(legacyCheckpointDir)) { - const fullPath = join9(legacyCheckpointDir, entry); - if (!entry.endsWith(".json") || !statSync2(fullPath).isFile()) continue; + const fullPath = join12(legacyCheckpointDir, entry); + if (!entry.endsWith(".json") || !statSync4(fullPath).isFile()) continue; const rawKey = entry.slice(0, -5); const safeKey = toSafeSegment(rawKey, ""); if (!safeKey) continue; - const targetDir = join9(canonicalPersistenceDir, "checkpoints"); - const targetFile = join9(targetDir, `${safeKey}.json`); - if (!existsSync5(targetFile)) { + const targetDir = join12(canonicalPersistenceDir, "checkpoints"); + const targetFile = join12(targetDir, `${safeKey}.json`); + if (!existsSync8(targetFile)) { try { - const parsed = JSON.parse(readFileSync6(fullPath, "utf8")); + const parsed = JSON.parse(readFileSync9(fullPath, "utf8")); const normalized = { session_id: safeKey, namespace: "checkpoints", @@ -9224,8 +10049,8 @@ function migrateLegacyStoresAndPurgeStale(workspaceDir, options = {}) { updated_at: typeof parsed.updated_at === "string" ? parsed.updated_at : nowIso }; if (!dryRun) { - mkdirSync4(targetDir, { recursive: true }); - writeFileSync3(targetFile, JSON.stringify(normalized, null, 2), "utf8"); + mkdirSync5(targetDir, { recursive: true }); + writeFileSync4(targetFile, JSON.stringify(normalized, null, 2), "utf8"); } contextsMigrated += 1; } catch { @@ -9238,19 +10063,19 @@ function migrateLegacyStoresAndPurgeStale(workspaceDir, options = {}) { } catch { } } - const legacyPersistenceGoalsDir = join9(canonicalPersistenceDir, "goals"); - if (existsSync5(legacyPersistenceGoalsDir)) { + const legacyPersistenceGoalsDir = join12(canonicalPersistenceDir, "goals"); + if (existsSync8(legacyPersistenceGoalsDir)) { try { for (const entry of readdirSync(legacyPersistenceGoalsDir)) { - const fullPath = join9(legacyPersistenceGoalsDir, entry); - if (!entry.endsWith(".json") || !statSync2(fullPath).isFile()) continue; + const fullPath = join12(legacyPersistenceGoalsDir, entry); + if (!entry.endsWith(".json") || !statSync4(fullPath).isFile()) continue; const safeId = toSafeSegment(entry.slice(0, -5), ""); if (safeId) { - const targetFile = join9(canonicalGoalsDir, `${safeId}.json`); - if (!existsSync5(targetFile)) { + const targetFile = join12(canonicalGoalsDir, `${safeId}.json`); + if (!existsSync8(targetFile)) { if (!dryRun) { - mkdirSync4(canonicalGoalsDir, { recursive: true }); - writeFileSync3(targetFile, readFileSync6(fullPath, "utf8"), "utf8"); + mkdirSync5(canonicalGoalsDir, { recursive: true }); + writeFileSync4(targetFile, readFileSync9(fullPath, "utf8"), "utf8"); } goalsMigrated += 1; } @@ -9262,20 +10087,20 @@ function migrateLegacyStoresAndPurgeStale(workspaceDir, options = {}) { } catch { } } - const legacyGoalsJsonPath = join9(pantheonDir, "goals.json"); - if (existsSync5(legacyGoalsJsonPath)) { + const legacyGoalsJsonPath = join12(pantheonDir, "goals.json"); + if (existsSync8(legacyGoalsJsonPath)) { try { - const parsed = JSON.parse(readFileSync6(legacyGoalsJsonPath, "utf8")); + const parsed = JSON.parse(readFileSync9(legacyGoalsJsonPath, "utf8")); const list = Array.isArray(parsed) ? parsed : parsed && typeof parsed === "object" && Array.isArray(parsed.goals) ? parsed.goals ?? [] : []; for (const item of list) { if (!item || typeof item !== "object") continue; const safeId = toSafeSegment(item.id ?? item.goal_id, ""); if (!safeId) continue; - const targetFile = join9(canonicalGoalsDir, `${safeId}.json`); - if (!existsSync5(targetFile)) { + const targetFile = join12(canonicalGoalsDir, `${safeId}.json`); + if (!existsSync8(targetFile)) { if (!dryRun) { - mkdirSync4(canonicalGoalsDir, { recursive: true }); - writeFileSync3( + mkdirSync5(canonicalGoalsDir, { recursive: true }); + writeFileSync4( targetFile, JSON.stringify( { @@ -9300,16 +10125,16 @@ function migrateLegacyStoresAndPurgeStale(workspaceDir, options = {}) { if (!dryRun) rmSync(legacyGoalsJsonPath, { force: true }); staleFilesDeleted.push(legacyGoalsJsonPath); } - if (existsSync5(canonicalPersistenceDir)) { + if (existsSync8(canonicalPersistenceDir)) { try { for (const nsEntry of readdirSync(canonicalPersistenceDir, { withFileTypes: true })) { if (!nsEntry.isDirectory()) continue; - const nsDir = join9(canonicalPersistenceDir, nsEntry.name); + const nsDir = join12(canonicalPersistenceDir, nsEntry.name); for (const fileEntry of readdirSync(nsDir)) { if (!fileEntry.endsWith(".json")) continue; - const filePath = join9(nsDir, fileEntry); + const filePath = join12(nsDir, fileEntry); try { - const data = JSON.parse(readFileSync6(filePath, "utf8")); + const data = JSON.parse(readFileSync9(filePath, "utf8")); if (typeof data.expires_at === "string" && data.expires_at <= nowIso) { if (!dryRun) rmSync(filePath, { force: true }); staleFilesDeleted.push(filePath); @@ -9322,35 +10147,35 @@ function migrateLegacyStoresAndPurgeStale(workspaceDir, options = {}) { } } const obsoleteTargets = [ - join9(canonicalMemoryDir, ".memory.db.init.lock"), - join9(pantheonDir, ".memory.db.init.lock"), - join9(canonicalPersistenceDir, ".global.db.init.lock"), - join9(canonicalPersistenceDir, ".project.db.init.lock"), - join9(pantheonDir, "fastembed_cache"), - join9(pantheonDir, ".fastembed"), - join9(root, "fastembed_cache"), - join9(root, "plugins", "pantheon-hooks.ts"), - join9(root, "plugins", "pantheon-hooks.js"), - join9(root, ".opencode", "plugins", "pantheon-hooks.ts"), - join9(root, ".opencode", "plugins", "pantheon-hooks.js"), - join9(root, "tiers.json"), - join9(root, ".opencode", "tiers.json") + join12(canonicalMemoryDir, ".memory.db.init.lock"), + join12(pantheonDir, ".memory.db.init.lock"), + join12(canonicalPersistenceDir, ".global.db.init.lock"), + join12(canonicalPersistenceDir, ".project.db.init.lock"), + join12(pantheonDir, "fastembed_cache"), + join12(pantheonDir, ".fastembed"), + join12(root, "fastembed_cache"), + join12(root, "plugins", "pantheon-hooks.ts"), + join12(root, "plugins", "pantheon-hooks.js"), + join12(root, ".opencode", "plugins", "pantheon-hooks.ts"), + join12(root, ".opencode", "plugins", "pantheon-hooks.js"), + join12(root, "tiers.json"), + join12(root, ".opencode", "tiers.json") ]; for (const target of obsoleteTargets) { - if (existsSync5(target)) { + if (existsSync8(target)) { if (!dryRun) rmSync(target, { recursive: true, force: true }); staleFilesDeleted.push(target); } } const backupCutoffMs = Date.now() - 30 * 864e5; - for (const cfgDir of [root, join9(root, ".opencode")]) { - if (!existsSync5(cfgDir)) continue; + for (const cfgDir of [root, join12(root, ".opencode")]) { + if (!existsSync8(cfgDir)) continue; try { for (const name of readdirSync(cfgDir)) { if (!name.startsWith("opencode.json.bak")) continue; - const full = join9(cfgDir, name); + const full = join12(cfgDir, name); try { - const st = statSync2(full); + const st = statSync4(full); if (st.mtimeMs < backupCutoffMs) { if (!dryRun) rmSync(full, { recursive: true, force: true }); staleFilesDeleted.push(full); @@ -9361,10 +10186,10 @@ function migrateLegacyStoresAndPurgeStale(workspaceDir, options = {}) { } catch { } } - const migrationCp = join9(pantheonDir, ".migration-checkpoint"); - if (existsSync5(migrationCp)) { + const migrationCp = join12(pantheonDir, ".migration-checkpoint"); + if (existsSync8(migrationCp)) { try { - const st = statSync2(migrationCp); + const st = statSync4(migrationCp); if (st.mtimeMs < Date.now() - 864e5) { if (!dryRun) rmSync(migrationCp, { force: true }); staleFilesDeleted.push(migrationCp); @@ -9372,11 +10197,11 @@ function migrateLegacyStoresAndPurgeStale(workspaceDir, options = {}) { } catch { } } - if (!dryRun && existsSync5(pantheonDir)) { + if (!dryRun && existsSync8(pantheonDir)) { try { const globalMtimeMs = globalCanonicalMemDb ? safeMtimeMs(globalCanonicalMemDb) : 0; - writeFileSync3( - join9(pantheonDir, ".migration-v2.json"), + writeFileSync4( + join12(pantheonDir, ".migration-v2.json"), `${JSON.stringify({ version: 2, globalMtimeMs, migratedAt: nowIso }, null, 2)} `, "utf8" @@ -9455,13 +10280,13 @@ var LEGACY_INSTRUCTION_FILES = Object.freeze([ // src/pantheon/native-vision.ts import { lookup as dnsLookup } from "node:dns/promises"; -import { existsSync as existsSync7 } from "node:fs"; +import { existsSync as existsSync10 } from "node:fs"; import { readFile as readFile4 } from "node:fs/promises"; import { request as httpRequest } from "node:http"; import { request as httpsRequest } from "node:https"; import { isIP } from "node:net"; import { homedir as homedir4 } from "node:os"; -import { join as join11, resolve as resolve6 } from "node:path"; +import { join as join14, resolve as resolve10 } from "node:path"; import { fileURLToPath as fileURLToPath2 } from "node:url"; // src/pantheon/session-guard.ts @@ -9477,18 +10302,18 @@ function safeSessionPath(id) { import { createHash as createHash5, randomUUID as randomUUID2 } from "node:crypto"; import { chmodSync as chmodSync3, - existsSync as existsSync6, - mkdirSync as mkdirSync5, + existsSync as existsSync9, + mkdirSync as mkdirSync6, readdirSync as readdirSync2, - readFileSync as readFileSync7, + readFileSync as readFileSync10, renameSync as renameSync2, - statSync as statSync3, + statSync as statSync5, unlinkSync as unlinkSync2, - writeFileSync as writeFileSync4 + writeFileSync as writeFileSync5 } from "node:fs"; import { readFile as readFile3, unlink } from "node:fs/promises"; import { homedir as homedir3, tmpdir } from "node:os"; -import { join as join10 } from "node:path"; +import { join as join13 } from "node:path"; // src/pantheon/vision-local.ts var PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]); @@ -9691,12 +10516,12 @@ function legacyZenBaseURL(modelID) { return null; } function defaultAuthStateDir() { - const dataHome = process.env.XDG_DATA_HOME || join10(homedir3(), ".local", "share"); - return join10(dataHome, "opencode"); + const dataHome = process.env.XDG_DATA_HOME || join13(homedir3(), ".local", "share"); + return join13(dataHome, "opencode"); } function v2CredentialDbPath(stateDir, env) { const override = env.OPENCODE_DB?.trim(); - return override ? override : join10(stateDir, "opencode.db"); + return override ? override : join13(stateDir, "opencode.db"); } var AUTH_TOKEN_FIELDS = [ "access", @@ -9729,18 +10554,18 @@ function extractCredentialCellToken(value) { } async function readV2CredentialToken(providerIDs, stateDir, env) { const dbPath = v2CredentialDbPath(stateDir, env); - if (!existsSync6(dbPath)) return null; + if (!existsSync9(dbPath)) return null; let sqlite; try { sqlite = await import("node:sqlite"); } catch { return null; } - const DatabaseSync5 = sqlite.DatabaseSync; - if (typeof DatabaseSync5 !== "function") return null; + const DatabaseSync6 = sqlite.DatabaseSync; + if (typeof DatabaseSync6 !== "function") return null; let db; try { - db = new DatabaseSync5(`file:${dbPath}?mode=ro`, { readOnly: true }); + db = new DatabaseSync6(`file:${dbPath}?mode=ro`, { readOnly: true }); const statement = db.prepare( "SELECT value FROM credential WHERE integration_id = ? AND active = 1 LIMIT 1" ); @@ -9761,7 +10586,7 @@ async function readV2CredentialToken(providerIDs, stateDir, env) { } async function readOpencodeAuthToken(providerIDs, statePath, env = process.env) { const stateDir = statePath ?? defaultAuthStateDir(); - const raw = await readFile3(join10(stateDir, "auth.json"), "utf8").catch(() => null); + const raw = await readFile3(join13(stateDir, "auth.json"), "utf8").catch(() => null); if (raw !== null) { let auth = null; try { @@ -9818,7 +10643,7 @@ async function enforceTempFileCap(maxFiles = TEMP_MAX_FILES, graceMs = TEMP_FILE var TEMP_IMAGE_NAME = /^[0-9a-f]{64}\.(?:png|jpe?g|webp|gif)$/; var TEMP_STRAY_NAME = /^[0-9a-f]{64}\.(?:png|jpe?g|webp|gif)\.tmp-\d+$/; function defaultTempDir() { - return join10(tmpdir(), TEMP_DIR_NAME); + return join13(tmpdir(), TEMP_DIR_NAME); } function adoptOrphanTempImages(dir = defaultTempDir(), now = Date.now()) { let names; @@ -9830,10 +10655,10 @@ function adoptOrphanTempImages(dir = defaultTempDir(), now = Date.now()) { const candidates = []; for (const name of names) { if (!TEMP_IMAGE_NAME.test(name)) continue; - const path5 = join10(dir, name); + const path5 = join13(dir, name); if (tempFileLRU.has(path5)) continue; try { - candidates.push({ path: path5, mtimeMs: statSync3(path5).mtimeMs }); + candidates.push({ path: path5, mtimeMs: statSync5(path5).mtimeMs }); } catch { } } @@ -9853,9 +10678,9 @@ function sweepStrayTempWrites(dir = defaultTempDir(), now = Date.now(), graceMs let swept = 0; for (const name of names) { if (!TEMP_STRAY_NAME.test(name)) continue; - const path5 = join10(dir, name); + const path5 = join13(dir, name); try { - if (now - statSync3(path5).mtimeMs <= graceMs) continue; + if (now - statSync5(path5).mtimeMs <= graceMs) continue; unlinkSync2(path5); swept += 1; } catch { @@ -9879,7 +10704,7 @@ function decodeDataUrlImage(dataUrl) { function writeFileAtomicSync(filePath, data) { const tempPath = `${filePath}.tmp-${process.pid}`; try { - writeFileSync4(tempPath, data, { mode: 384 }); + writeFileSync5(tempPath, data, { mode: 384 }); chmodSync3(tempPath, 384); renameSync2(tempPath, filePath); } catch (err) { @@ -9892,7 +10717,7 @@ function writeFileAtomicSync(filePath, data) { } function fileHasContent(filePath, data) { try { - return readFileSync7(filePath).equals(data); + return readFileSync10(filePath).equals(data); } catch { return false; } @@ -9902,10 +10727,10 @@ function writeTempImageSync(data, mime) { reconcileTempImagesOnce(); } catch { } - const dir = join10(tmpdir(), TEMP_DIR_NAME); - mkdirSync5(dir, { recursive: true, mode: 448 }); + const dir = join13(tmpdir(), TEMP_DIR_NAME); + mkdirSync6(dir, { recursive: true, mode: 448 }); chmodSync3(dir, 448); - const filePath = join10(dir, `${hashContent(data)}.${getExtensionForMime(mime)}`); + const filePath = join13(dir, `${hashContent(data)}.${getExtensionForMime(mime)}`); if (!fileHasContent(filePath, data)) writeFileAtomicSync(filePath, data); chmodSync3(filePath, 384); touchTempFile(filePath); @@ -10232,19 +11057,19 @@ function selectV2VisionModel(available, preferred) { } function activePresetCandidates2(directory) { const home = process.env.HOME || homedir4(); - const xdg = process.env.XDG_CONFIG_HOME || join11(home, ".config"); + const xdg = process.env.XDG_CONFIG_HOME || join14(home, ".config"); return [ - join11(directory, ".pantheon", "active-preset.json"), - join11(xdg, "opencode", ".pantheon", "active-preset.json"), - join11(home, ".opencode", ".pantheon", "active-preset.json") + join14(directory, ".pantheon", "active-preset.json"), + join14(xdg, "opencode", ".pantheon", "active-preset.json"), + join14(home, ".opencode", ".pantheon", "active-preset.json") ]; } async function configuredVisionModel(directory) { const home = process.env.HOME || homedir4(); - const xdg = process.env.XDG_CONFIG_HOME || join11(home, ".config"); + const xdg = process.env.XDG_CONFIG_HOME || join14(home, ".config"); const paths = [ - join11(directory, ".opencode", "opencode-vision.json"), - join11(xdg, "opencode", "opencode-vision.json") + join14(directory, ".opencode", "opencode-vision.json"), + join14(xdg, "opencode", "opencode-vision.json") ]; for (const path5 of paths) { try { @@ -10410,8 +11235,8 @@ async function imageAttachment(value, directory, signal) { } else if (url) { throw new Error("only file, HTTP, HTTPS, and base64 image sources are supported"); } else { - const expanded = source.startsWith("~/") ? join11(homedir4(), source.slice(2)) : source; - localPath = resolve6(directory, expanded); + const expanded = source.startsWith("~/") ? join14(homedir4(), source.slice(2)) : source; + localPath = resolve10(directory, expanded); } let bytes; try { @@ -10432,9 +11257,9 @@ function discoverActiveSessionId(directory) { if (isValidSessionId(val)) return val; } try { - const dataHome = process.env.XDG_DATA_HOME || join11(homedir4(), ".local", "share"); - const dbPath = process.env.OPENCODE_DB || join11(dataHome, "opencode", "opencode.db"); - if (!existsSync7(dbPath)) return void 0; + const dataHome = process.env.XDG_DATA_HOME || join14(homedir4(), ".local", "share"); + const dbPath = process.env.OPENCODE_DB || join14(dataHome, "opencode", "opencode.db"); + if (!existsSync10(dbPath)) return void 0; const sqlite = __require("node:sqlite"); const db = new sqlite.DatabaseSync(dbPath, { readOnly: true }); try { @@ -10504,11 +11329,11 @@ function createV2VisionTool(runtime) { } stage = "resolve OpenCode Zen authentication"; const modelID = modelKey(model); - const dataHome = process.env.XDG_DATA_HOME || join11(homedir4(), ".local", "share"); + const dataHome = process.env.XDG_DATA_HOME || join14(homedir4(), ".local", "share"); const target = await resolveNativeVisionTarget({ preset: { vision: { model: modelID } }, env: { ...process.env, PANTHEON_VISION_MODEL: modelID }, - authStatePath: join11(dataHome, "opencode") + authStatePath: join14(dataHome, "opencode") }); if (!target) { throw new Error( @@ -10585,113 +11410,716 @@ ${layers.history.map((h) => h.trim()).join("\n\n")}` }; } -// src/pantheon/background-job-board.ts -import { mkdir as mkdir4, rename as rename3, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises"; -import { dirname as dirname7, join as join12 } from "node:path"; +// src/pantheon/step-ledger.ts +import { existsSync as existsSync12, mkdirSync as mkdirSync8, readFileSync as readFileSync11, realpathSync as realpathSync5, writeFileSync as writeFileSync6 } from "node:fs"; +import { join as join16, resolve as resolve12, sep as sep6 } from "node:path"; -// src/pantheon/bus.ts -var PantheonBus = class { - listeners = /* @__PURE__ */ new Map(); - /** - * Register a persistent listener for an event. - * Returns an unsubscribe callback for easy cleanup. - */ - on(event, listener) { - let set = this.listeners.get(event); - if (!set) { - set = /* @__PURE__ */ new Set(); - this.listeners.set(event, set); - } - set.add(listener); - return () => { - set?.delete(listener); - if (set?.size === 0) { - this.listeners.delete(event); - } - }; - } - /** - * Register a one-shot listener that unregisters itself after firing once. - */ - once(event, listener) { - const unsubscribe = this.on(event, (payload) => { - unsubscribe(); - return listener(payload); - }); - return unsubscribe; - } - /** - * Synchronously emit an event to all registered listeners. - * Listener rejections are logged safely without throwing. +// src/pantheon/execution-receipt.ts +import { createHash as createHash6 } from "node:crypto"; +function hashContent2(content) { + return createHash6("sha256").update(content).digest("hex"); +} +function computeReceiptSignature(taskID, agent, timestamp, files) { + const sortedFiles = [...files].sort((a, b) => a.path.localeCompare(b.path)); + const payload = [ + taskID, + agent, + String(timestamp), + sortedFiles.map((f) => `${f.path}:${f.hash}`).join(";") + ].join("|"); + return createHash6("sha256").update(payload).digest("hex"); +} +function createExecutionReceipt(input) { + const timestamp = Date.now(); + const files = input.files.map((f) => { + const buf = typeof f.content === "string" ? Buffer.from(f.content, "utf8") : f.content; + return { + path: f.path, + hash: hashContent2(buf), + sizeBytes: buf.length + }; + }); + const signature = computeReceiptSignature(input.taskID, input.agent, timestamp, files); + const receiptId = `rcpt_${signature.slice(0, 16)}`; + let status = "UNVERIFIED"; + if (input.testSlice) { + status = input.testSlice.exitCode === 0 ? "VERIFIED" : "FAILED"; + } + const receipt = { + receiptId, + taskID: input.taskID, + agent: input.agent, + status, + files, + testSlice: input.testSlice, + timestamp, + signature + }; + getSharedBus().emit("agent:execution:receipt", receipt); + return receipt; +} + +// src/pantheon/git-checkpoint.ts +import { execFile as execFile3 } from "node:child_process"; +import { existsSync as existsSync11, mkdirSync as mkdirSync7, rmSync as rmSync2, unlinkSync as unlinkSync3 } from "node:fs"; +import { tmpdir as tmpdir2 } from "node:os"; +import { join as join15, resolve as resolve11 } from "node:path"; +import { promisify as promisify3 } from "node:util"; +var execFileAsync3 = promisify3(execFile3); +var SAFE_TREE_RE = /^[0-9a-f]{40}$/; +async function runGit(cwd, args, envExtra) { + const { stdout } = await execFileAsync3("git", [...args], { + cwd, + maxBuffer: 8 * 1024 * 1024, + timeout: 1e4, + env: envExtra ? { ...process.env, ...envExtra } : process.env + }); + return stdout.trim(); +} +async function isGitWorkspace(cwd) { + try { + const out = await runGit(cwd, ["rev-parse", "--is-inside-work-tree"]); + return out === "true"; + } catch { + return false; + } +} +async function captureGitCheckpoint(cwd, stepKey = "step") { + const root = resolve11(cwd); + if (!await isGitWorkspace(root)) { + return { ok: false, reason: "not_a_git_repository" }; + } + const safeTag = stepKey.replace(/[^a-zA-Z0-9._-]/g, "_"); + const tmpIndex = join15(tmpdir2(), `pantheon-idx-${process.pid}-${safeTag}-${Date.now()}`); + try { + try { + await runGit(root, ["read-tree", "HEAD"], { GIT_INDEX_FILE: tmpIndex }); + } catch { + await runGit(root, ["read-tree", "--empty"], { GIT_INDEX_FILE: tmpIndex }); + } + await runGit(root, ["add", "-A"], { GIT_INDEX_FILE: tmpIndex }); + const treeHash = await runGit(root, ["write-tree"], { GIT_INDEX_FILE: tmpIndex }); + if (!SAFE_TREE_RE.test(treeHash)) { + return { ok: false, reason: "invalid_tree_hash" }; + } + return { ok: true, treeHash }; + } catch (err) { + return { + ok: false, + reason: err instanceof Error ? err.message : String(err) + }; + } finally { + try { + if (existsSync11(tmpIndex)) unlinkSync3(tmpIndex); + } catch { + } + } +} +async function restoreGitCheckpoint(cwd, treeHash) { + const root = resolve11(cwd); + if (!SAFE_TREE_RE.test(treeHash)) { + return { ok: false, reason: "invalid_tree_hash" }; + } + if (!await isGitWorkspace(root)) { + return { ok: false, reason: "not_a_git_repository" }; + } + const tmpIndex = join15(tmpdir2(), `pantheon-rb-${process.pid}-${Date.now()}`); + try { + const treeListing = await runGit(root, ["ls-tree", "-r", "--name-only", treeHash]); + const baselineFiles = new Set(treeListing.split(/\r?\n/).filter(Boolean)); + const currentOthers = await runGit(root, ["ls-files", "--others", "--exclude-standard"]); + for (const rel of currentOthers.split(/\r?\n/).filter(Boolean)) { + if (rel.startsWith(".pantheon/")) continue; + if (!baselineFiles.has(rel)) { + const target = join15(root, rel); + try { + rmSync2(target, { recursive: true, force: true }); + } catch { + } + } + } + await runGit(root, ["read-tree", treeHash], { GIT_INDEX_FILE: tmpIndex }); + await runGit(root, ["checkout-index", "--all", "--force"], { GIT_INDEX_FILE: tmpIndex }); + mkdirSync7(join15(root, ".pantheon", "ledger"), { recursive: true }); + return { ok: true, treeHash }; + } catch (err) { + return { + ok: false, + reason: err instanceof Error ? err.message : String(err) + }; + } finally { + try { + if (existsSync11(tmpIndex)) unlinkSync3(tmpIndex); + } catch { + } + } +} + +// src/pantheon/step-runner.ts +function buildAtomicStepPrompt(input) { + const lines = [ + `[ATOMIC STEP CONTRACT]`, + `stepKey: ${input.stepKey}`, + `agent: ${input.agent}`, + `objective: ${input.objective}`, + "", + "Rules:", + `1. Operate strictly on the objective above; report mutations with pantheon_step_ledger(action="record_mutation", stepKey="${input.stepKey}", files=[...]).`, + `2. Run targeted verification and record via pantheon_step_ledger(action="record_verification", stepKey="${input.stepKey}", command="...", exitCode=0).`, + `3. Finish by calling pantheon_step_ledger(action="complete_step", stepKey="${input.stepKey}").` + ]; + if (input.extraContext?.trim()) { + lines.push("", "Bounded context:", input.extraContext.trim()); + } + return lines.join("\n"); +} +async function runAtomicStepSubSession(input) { + const { sessionDomain, cwd, stepKey, objective, agent } = input; + if (typeof sessionDomain?.create !== "function" || typeof sessionDomain?.prompt !== "function") { + return { ok: false, stepKey, error: "host session.create/prompt domain unavailable" }; + } + const store2 = readStepLedger(cwd); + if (!store2.steps[stepKey]) { + const ckpt = await captureGitCheckpoint(cwd, stepKey); + store2.steps[stepKey] = { + stepKey, + objective, + agent, + state: "in_progress", + ...input.taskType ? { taskType: input.taskType } : {}, + ...ckpt.ok && ckpt.treeHash ? { baselineTree: ckpt.treeHash } : {}, + mutatedFiles: [], + lastMutationAt: null, + lastVerifiedAt: null, + updatedAt: (/* @__PURE__ */ new Date()).toISOString() + }; + writeStepLedger(cwd, store2); + } + let createdId; + try { + const created = await sessionDomain.create({ + title: `Step ${stepKey}: ${objective.slice(0, 60)}`, + agent, + ...input.parentSessionID ? { parentID: input.parentSessionID } : {} + }); + createdId = typeof created?.id === "string" ? created.id : void 0; + if (!createdId) { + return { ok: false, stepKey, error: "ctx.session.create returned no session id" }; + } + const text2 = buildAtomicStepPrompt({ + stepKey, + objective, + agent, + ...input.extraContext !== void 0 ? { extraContext: input.extraContext } : {} + }); + await sessionDomain.prompt({ + sessionID: createdId, + text: text2, + agents: [{ name: agent }], + resume: true + }); + if (typeof sessionDomain.wait === "function") { + await sessionDomain.wait({ sessionID: createdId }); + } + const latest = readStepLedger(cwd).steps[stepKey]; + return { + ok: latest?.state === "done", + stepKey, + sessionID: createdId, + ...latest?.state !== void 0 ? { stepState: latest.state } : {}, + ...latest?.receiptId !== void 0 ? { receiptId: latest.receiptId } : {} + }; + } catch (err) { + return { + ok: false, + stepKey, + ...createdId !== void 0 ? { sessionID: createdId } : {}, + error: err instanceof Error ? err.message : String(err) + }; + } finally { + if (createdId && input.cleanupSession !== false && typeof sessionDomain.remove === "function") { + try { + await sessionDomain.remove({ sessionID: createdId }); + } catch { + } + } + } +} + +// src/pantheon/themis-reflex.ts +var ThemisReflexController = class { + states = /* @__PURE__ */ new Map(); + maxRetries; + constructor(options = {}) { + this.maxRetries = options.maxRetries ?? 2; + } + /** + * Evaluate a task execution result against Themis verification findings. + * If discrepancies are found and attempts remain, returns an actionable retry directive. */ - emit(event, payload) { - const set = this.listeners.get(event); - if (!set || set.size === 0) return; - for (const listener of Array.from(set)) { + evaluate(taskID, agent, discrepancies) { + if (discrepancies.length === 0) { + const existing = this.states.get(taskID); + if (existing) { + getSharedBus().emit("themis:reflex:resolved", { + taskID, + agent, + file: existing.discrepancies[0]?.file ?? "", + error: "", + attempt: existing.attempt, + maxAttempts: this.maxRetries, + timestamp: Date.now(), + resolved: true + }); + this.states.delete(taskID); + } + return { action: "pass", verdict: "PASS" }; + } + let state = this.states.get(taskID); + if (!state) { + state = { + taskID, + agent, + attempt: 0, + maxAttempts: this.maxRetries, + discrepancies: [...discrepancies], + timestamp: Date.now() + }; + this.states.set(taskID, state); + } + state.attempt += 1; + state.discrepancies = [...discrepancies]; + state.timestamp = Date.now(); + const firstDisc = discrepancies[0]; + getSharedBus().emit("themis:reflex:discrepancy", { + taskID, + agent, + file: firstDisc?.file ?? "unknown", + error: firstDisc?.error ?? "unspecified", + attempt: state.attempt, + maxAttempts: this.maxRetries, + timestamp: state.timestamp + }); + if (state.attempt <= this.maxRetries) { + const prompt = this.formatReflexPrompt(state.attempt, this.maxRetries, discrepancies); + return { + action: "retry", + prompt, + attempt: state.attempt, + maxAttempts: this.maxRetries + }; + } + getSharedBus().emit("themis:reflex:escalated", { + taskID, + agent, + file: firstDisc?.file ?? "unknown", + error: firstDisc?.error ?? "unspecified", + attempt: state.attempt, + maxAttempts: this.maxRetries, + timestamp: state.timestamp, + resolved: false + }); + this.states.delete(taskID); + return { + action: "escalate", + verdict: "FAIL", + reason: `themis.reflex.exhausted:${state.attempt - 1}_retries_failed`, + attempts: state.attempt + }; + } + /** + * Format an inline, high-density reflex prompt directing the implementer to self-heal. + */ + formatReflexPrompt(attempt, maxAttempts, discrepancies) { + const lines = [ + `[THEMIS INLINE REFLEX \u2014 Attempt ${attempt}/${maxAttempts}]`, + "Themis automated audit detected discrepancies in your edits. Fix them directly before returning:" + ]; + for (const d of discrepancies) { + lines.push(`- File: ${d.file}`); + lines.push(` Error: ${d.error}`); + if (d.expected) lines.push(` Expected: ${d.expected}`); + if (d.actual) lines.push(` Actual: ${d.actual}`); + if (d.suggestedFix) lines.push(` Fix hint: ${d.suggestedFix}`); + } + lines.push("Do NOT escalate to Zeus yet. Apply the targeted fix and re-verify your slice."); + return lines.join("\n"); + } + /** Reset state for a taskID */ + reset(taskID) { + this.states.delete(taskID); + } +}; + +// src/pantheon/step-ledger.ts +var SAFE_STEP_KEY_RE = /^[a-zA-Z0-9._:-]{1,128}$/; +var stepReflex = new ThemisReflexController({ maxRetries: 2 }); +function assertSafeStepKey(stepKey) { + if (typeof stepKey !== "string" || !SAFE_STEP_KEY_RE.test(stepKey) || stepKey.includes("..")) { + throw new Error("stepKey must be a safe alphanumeric identifier (1..128 chars)"); + } + return stepKey; +} +function resolveLedgerPath(workspaceDir) { + const dir = join16(workspaceDir, ".pantheon", "ledger"); + mkdirSync8(dir, { recursive: true }); + const canonicalDir = realpathSync5(dir); + const filePath = resolve12(canonicalDir, "step-ledger.json"); + const prefix = canonicalDir.endsWith(sep6) ? canonicalDir : `${canonicalDir}${sep6}`; + if (!filePath.startsWith(prefix)) { + throw new Error("Path traversal denied for step-ledger.json"); + } + return filePath; +} +function readStepLedger(workspaceDir) { + const filePath = resolveLedgerPath(workspaceDir); + if (!existsSync12(filePath)) { + return { version: 1, steps: {} }; + } + try { + const parsed = JSON.parse(readFileSync11(filePath, "utf8")); + if (parsed && typeof parsed.steps === "object" && parsed.steps !== null) { + return { version: 1, steps: parsed.steps }; + } + } catch { + } + return { version: 1, steps: {} }; +} +function writeStepLedger(workspaceDir, store2) { + const filePath = resolveLedgerPath(workspaceDir); + writeFileSync6(filePath, `${JSON.stringify(store2, null, 2)} +`, "utf8"); +} +function canTransitionStepToDone(step) { + if (step.verificationExitCode !== 0 || step.lastVerifiedAt === null) { + return { + allowed: false, + reason: `Step "${step.stepKey}" cannot transition to done: no passing verification command (exitCode === 0) has been recorded.` + }; + } + if (step.lastMutationAt !== null && step.lastVerifiedAt < step.lastMutationAt) { + return { + allowed: false, + reason: `Step "${step.stepKey}" cannot transition to done: files were mutated after the last verification run. Re-run the verification slice first.` + }; + } + return { allowed: true }; +} +function jsonResult(payload) { + return { output: JSON.stringify(payload) }; +} +function createStepLedgerTool(fallbackDir, sessionDomain) { + return { + name: "pantheon_step_ledger", + description: "Manage atomic Step-Ledger execution contracts with hard verification gates, Git checkpoints, bugfix reproduction tracking, and isolated sub-session step runner. Lifecycle: init_step | execute_step -> [record_reproduction] -> record_mutation -> record_verification -> complete_step | rollback_step | status.", + input: { + type: "object", + additionalProperties: false, + required: ["action"], + properties: { + action: { + type: "string", + enum: [ + "init_step", + "execute_step", + "record_reproduction", + "record_mutation", + "record_verification", + "complete_step", + "rollback_step", + "status" + ], + description: "Ledger operation (init_step | execute_step | record_reproduction | record_mutation | record_verification | complete_step | rollback_step | status)" + }, + stepKey: { + type: "string", + description: 'Unique atomic step id matching ^[a-zA-Z0-9._:-]{1,128}$ (no spaces or "..")' + }, + objective: { type: "string", description: "Bounded step objective" }, + agent: { type: "string", description: "Assigned specialist agent" }, + extraContext: { + type: "string", + description: "Optional bounded context for isolated execute_step sub-session" + }, + cleanupSession: { + type: "boolean", + description: "Remove ephemeral sub-session after execute_step (default: true)" + }, + taskType: { + type: "string", + enum: ["feature", "bugfix", "refactor", "chore"], + description: "Task classification (bugfix enforces reproduction RED before edits)" + }, + autoRollback: { + type: "boolean", + description: "Auto-restore baselineTree when verification exhausts reflex retries (default: true)" + }, + files: { + type: "array", + items: { type: "string" }, + description: "Mutated file paths for record_mutation" + }, + command: { type: "string", description: "Executed verification or reproduction command" }, + exitCode: { type: "number", description: "Exit code of the command" }, + durationMs: { type: "number", description: "Duration of verification command in ms" } + } + }, + output: {}, + execute: async (input, context) => { try { - const result = listener(payload); - if (result instanceof Promise) { - result.catch(() => { + const action = typeof input.action === "string" ? input.action : "status"; + const cwd = resolveToolCwd(context, fallbackDir); + const store2 = readStepLedger(cwd); + const now = Date.now(); + const nowIso = new Date(now).toISOString(); + if (action === "status") { + if (typeof input.stepKey === "string" && input.stepKey.trim()) { + const key2 = assertSafeStepKey(input.stepKey.trim()); + const step2 = store2.steps[key2]; + if (!step2) return jsonResult({ ok: false, error: "step_not_found", stepKey: key2 }); + return jsonResult({ ok: true, step: step2, gate: canTransitionStepToDone(step2) }); + } + return jsonResult({ ok: true, steps: Object.values(store2.steps) }); + } + const key = assertSafeStepKey(input.stepKey); + if (action === "init_step") { + const objective = typeof input.objective === "string" ? input.objective.trim() : ""; + if (!objective) return jsonResult({ ok: false, error: "objective is required" }); + const agent = typeof input.agent === "string" && input.agent.trim() ? input.agent.trim() : "specialist"; + const rawTaskType = input.taskType; + const taskType = rawTaskType === "feature" || rawTaskType === "bugfix" || rawTaskType === "refactor" || rawTaskType === "chore" ? rawTaskType : void 0; + const ckpt = await captureGitCheckpoint(cwd, key); + const entry = { + stepKey: key, + objective, + agent, + state: "in_progress", + ...taskType ? { taskType } : {}, + ...ckpt.ok && ckpt.treeHash ? { baselineTree: ckpt.treeHash } : {}, + mutatedFiles: [], + lastMutationAt: null, + lastVerifiedAt: null, + updatedAt: nowIso + }; + store2.steps[key] = entry; + writeStepLedger(cwd, store2); + return jsonResult({ ok: true, step: entry }); + } + if (action === "execute_step") { + if (!sessionDomain) { + return jsonResult({ ok: false, error: "host session domain unavailable" }); + } + const objective = typeof input.objective === "string" && input.objective.trim() ? input.objective.trim() : store2.steps[key]?.objective ?? ""; + if (!objective) return jsonResult({ ok: false, error: "objective is required" }); + const agent = typeof input.agent === "string" && input.agent.trim() ? input.agent.trim().replace(/^@/, "") : store2.steps[key]?.agent ?? "hermes"; + const rawTaskType = input.taskType; + const taskType = rawTaskType === "feature" || rawTaskType === "bugfix" || rawTaskType === "refactor" || rawTaskType === "chore" ? rawTaskType : store2.steps[key]?.taskType; + const parentSid = typeof context?.sessionID === "string" ? context.sessionID ?? void 0 : void 0; + const runOut = await runAtomicStepSubSession({ + sessionDomain, + cwd, + stepKey: key, + objective, + agent, + ...taskType ? { taskType } : {}, + ...parentSid ? { parentSessionID: parentSid } : {}, + ...typeof input.extraContext === "string" ? { extraContext: input.extraContext } : {}, + ...typeof input.cleanupSession === "boolean" ? { cleanupSession: input.cleanupSession } : {} + }); + return jsonResult(runOut); + } + const step = store2.steps[key]; + if (!step) { + return jsonResult({ ok: false, error: `Step "${key}" is not initialized` }); + } + if (action === "record_reproduction") { + const command = typeof input.command === "string" ? input.command.trim() : ""; + const exitCode = typeof input.exitCode === "number" ? input.exitCode : 1; + if (!command) return jsonResult({ ok: false, error: "command is required" }); + if (exitCode === 0) { + return jsonResult({ + ok: false, + error: "Bugfix reproduction must demonstrate a failing test/probe (exitCode !== 0)", + step + }); + } + step.reproductionCommand = command; + step.reproductionExitCode = exitCode; + step.reproductionRecordedAt = now; + step.updatedAt = nowIso; + writeStepLedger(cwd, store2); + return jsonResult({ ok: true, reproduced: true, step }); + } + if (action === "rollback_step") { + if (!step.baselineTree) { + return jsonResult({ ok: false, error: `Step "${key}" has no Git baselineTree`, step }); + } + const rb = await restoreGitCheckpoint(cwd, step.baselineTree); + if (rb.ok) { + step.state = "rolled_back"; + step.rolledBackAt = nowIso; + step.updatedAt = nowIso; + writeStepLedger(cwd, store2); + } + getSharedBus().emit("step:rollback", { + stepKey: key, + reason: "manual_rollback_step", + restoredTree: step.baselineTree, + success: rb.ok, + timestamp: Date.now() + }); + return jsonResult({ ok: rb.ok, restoredTree: step.baselineTree, error: rb.reason, step }); + } + if (action === "record_mutation") { + const files = Array.isArray(input.files) ? input.files.map(String) : []; + const merged = Array.from(/* @__PURE__ */ new Set([...step.mutatedFiles, ...files])); + step.mutatedFiles = merged; + step.lastMutationAt = now; + if (step.state === "done") step.state = "in_progress"; + step.updatedAt = nowIso; + writeStepLedger(cwd, store2); + return jsonResult({ ok: true, step }); + } + if (action === "record_verification") { + const command = typeof input.command === "string" ? input.command.trim() : ""; + const exitCode = typeof input.exitCode === "number" ? input.exitCode : 1; + const durationMs = typeof input.durationMs === "number" ? input.durationMs : 0; + if (!command) return jsonResult({ ok: false, error: "command is required" }); + step.verificationCommand = command; + step.verificationExitCode = exitCode; + step.lastVerifiedAt = now; + step.updatedAt = nowIso; + if (exitCode === 0) { + stepReflex.evaluate(key, step.agent, []); + const receipt = createExecutionReceipt({ + taskID: key, + agent: step.agent, + files: step.mutatedFiles.map((f) => ({ path: f, content: `${key}:${f}:${now}` })), + testSlice: { command, exitCode: 0, durationMs } + }); + step.receiptId = receipt.receiptId; + writeStepLedger(cwd, store2); + return jsonResult({ ok: true, verified: true, receiptId: receipt.receiptId, step }); + } + const reflex = stepReflex.evaluate(key, step.agent, [ + { + file: step.mutatedFiles[0] ?? key, + error: `Verification command "${command}" failed with exit code ${exitCode}` + } + ]); + let rollbackResult; + if (reflex.action === "escalate") { + step.state = "blocked"; + if (input.autoRollback !== false && step.baselineTree) { + const rb = await restoreGitCheckpoint(cwd, step.baselineTree); + rollbackResult = { restoredTree: step.baselineTree, ok: rb.ok }; + if (rb.ok) { + step.state = "rolled_back"; + step.rolledBackAt = nowIso; + } + getSharedBus().emit("step:rollback", { + stepKey: key, + reason: reflex.reason, + restoredTree: step.baselineTree, + success: rb.ok, + timestamp: Date.now() + }); + } + } + writeStepLedger(cwd, store2); + return jsonResult({ + ok: false, + verified: false, + reflex, + ...rollbackResult ? { rollback: rollbackResult } : {}, + step }); } - } catch { - } - } - } - /** - * Wait asynchronously for a specific event matching a predicate, with an optional timeout. - */ - waitFor(event, predicate, timeoutMs = 3e4) { - return new Promise((resolve14, reject) => { - let timer = null; - let unsubscribe = null; - if (timeoutMs > 0 && Number.isFinite(timeoutMs)) { - timer = setTimeout(() => { - unsubscribe?.(); - reject(new Error(`Timed out waiting for bus event "${event}" after ${timeoutMs}ms`)); - }, timeoutMs); - } - unsubscribe = this.on(event, (payload) => { - try { - if (predicate(payload)) { - if (timer) clearTimeout(timer); - unsubscribe?.(); - resolve14(payload); + if (action === "complete_step") { + const gate = canTransitionStepToDone(step); + if (!gate.allowed) { + return jsonResult({ ok: false, error: gate.reason, step }); } - } catch (err) { - if (timer) clearTimeout(timer); - unsubscribe?.(); - reject(err); + step.state = "done"; + step.updatedAt = nowIso; + writeStepLedger(cwd, store2); + return jsonResult({ ok: true, status: "done", receiptId: step.receiptId, step }); } - }); - }); - } - /** Number of active listeners for a specific event or in total. */ - listenerCount(event) { - if (event) { - return this.listeners.get(event)?.size ?? 0; - } - let total = 0; - for (const set of this.listeners.values()) { - total += set.size; + return jsonResult({ ok: false, error: `Unsupported action: ${action}` }); + } catch (err) { + return jsonResult({ + ok: false, + error: err instanceof Error ? err.message : String(err) + }); + } } - return total; + }; +} + +// src/pantheon/reproduction-gate.ts +var MUTATING_TOOLS = /* @__PURE__ */ new Set(["edit", "write", "hashline_edit", "ast_rewrite", "patch"]); +var BUGFIX_GATED_AGENTS = /* @__PURE__ */ new Set(["hermes", "talos"]); +function isTestOrReproFile(filePath) { + const norm = filePath.replace(/\\/g, "/").toLowerCase(); + if (!norm) return false; + if (/(?:^|\/)(?:tests?|__tests__|spec|specs|repro|fixtures)\//.test(norm) || /\.(?:test|spec|repro)\.[a-z0-9]+$/i.test(norm) || /(?:^|\/)test_[^/]+\.py$/i.test(norm) || /_test\.go$/i.test(norm)) { + return true; } - /** Clear all listeners (primarily for unit tests). */ - clear() { - this.listeners.clear(); + return false; +} +function findActiveBugfixStep(cwd, agent, explicitStepKey) { + try { + const store2 = readStepLedger(cwd); + if (explicitStepKey && store2.steps[explicitStepKey]) { + const s = store2.steps[explicitStepKey]; + return s.taskType === "bugfix" && s.state === "in_progress" ? s : null; + } + const normalized = agent.trim().toLowerCase(); + const matches = Object.values(store2.steps).filter( + (s) => s.taskType === "bugfix" && s.state === "in_progress" && s.agent.trim().toLowerCase() === normalized + ); + if (matches.length === 0) return null; + matches.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)); + return matches[0] ?? null; + } catch { + return null; } -}; -var BUS_KEY = "__pantheonSharedBus"; -function getSharedBus() { - const host = globalThis; - if (host[BUS_KEY] instanceof PantheonBus) return host[BUS_KEY]; - const bus = new PantheonBus(); - host[BUS_KEY] = bus; - return bus; +} +function evaluateReproductionGate(params) { + const toolName = params.tool.trim().toLowerCase(); + if (!MUTATING_TOOLS.has(toolName)) return { allowed: true }; + const normalizedAgent = (params.agent ?? "").trim().toLowerCase().replace(/^@/, ""); + if (!BUGFIX_GATED_AGENTS.has(normalizedAgent)) return { allowed: true }; + const activeStep = findActiveBugfixStep(params.cwd, normalizedAgent, params.stepKey); + if (!activeStep) return { allowed: true }; + const rawArgs = params.args ?? {}; + const targetPath = String( + rawArgs.filePath ?? rawArgs.file_path ?? rawArgs.file ?? rawArgs.path ?? "" + ); + if (isTestOrReproFile(targetPath)) { + return { allowed: true, stepKey: activeStep.stepKey }; + } + const hasRedRepro = typeof activeStep.reproductionRecordedAt === "number" && activeStep.reproductionExitCode !== void 0 && activeStep.reproductionExitCode !== 0; + getSharedBus().emit("reproduction:gate", { + stepKey: activeStep.stepKey, + agent: normalizedAgent, + tool: toolName, + allowed: hasRedRepro, + timestamp: Date.now() + }); + if (hasRedRepro) { + return { allowed: true, stepKey: activeStep.stepKey }; + } + return { + allowed: false, + stepKey: activeStep.stepKey, + message: `[Reproduction-Gate] Blocked production edit on bugfix step "${activeStep.stepKey}" for @${normalizedAgent}: run fault localization + a failing RED test/probe first (test files are allowed) and record it via pantheon_step_ledger(action="record_reproduction", stepKey="${activeStep.stepKey}", command="...", exitCode=1).` + }; } // src/pantheon/background-job-board.ts +import { mkdir as mkdir4, rename as rename3, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises"; +import { dirname as dirname9, join as join17 } from "node:path"; var log3 = createPantheonLogger({ module: "BackgroundJobBoard" }); var TERMINAL_STATES = /* @__PURE__ */ new Set([ "completed", @@ -11043,9 +12471,9 @@ var BackgroundJobBoard = class { if (existing && (TERMINAL_STATES.has(existing.state) || existing.state === "reconciled")) { return Promise.resolve(existing); } - return new Promise((resolve14, reject) => { + return new Promise((resolve23, reject) => { const waiter = { - resolve: resolve14, + resolve: resolve23, reject, timer: setTimeout(() => { this.removeTerminalWaiter(taskID, waiter); @@ -11139,7 +12567,7 @@ ${lines.join("\n")}`; async deleteSignal(alias) { const signalDir = this.options.signalDir; if (!signalDir) return false; - const signalPath = join12(signalDir, `${alias}.signal.json`); + const signalPath = join17(signalDir, `${alias}.signal.json`); try { await unlink2(signalPath); return true; @@ -11221,8 +12649,8 @@ ${lines.join("\n")}`; async writeSignal(record2) { const signalDir = this.options.signalDir; if (!signalDir) return; - const signalPath = join12(signalDir, `${record2.alias}.signal.json`); - const tmpPath = join12(signalDir, `${record2.alias}.signal.tmp`); + const signalPath = join17(signalDir, `${record2.alias}.signal.json`); + const tmpPath = join17(signalDir, `${record2.alias}.signal.tmp`); const content = JSON.stringify({ taskID: record2.taskID, alias: record2.alias, @@ -11232,7 +12660,7 @@ ${lines.join("\n")}`; timestamp: Date.now() }); try { - await mkdir4(dirname7(signalPath), { recursive: true }); + await mkdir4(dirname9(signalPath), { recursive: true }); await writeFile2(tmpPath, content, "utf-8"); await rename3(tmpPath, signalPath); } catch (err) { @@ -11243,7 +12671,7 @@ ${lines.join("\n")}`; // src/pantheon/file-persistence.ts import { mkdir as mkdir5, open as open2, readFile as readFile5, rename as rename4, unlink as unlink3 } from "node:fs/promises"; -import { dirname as dirname8, resolve as resolve7 } from "node:path"; +import { dirname as dirname10, resolve as resolve13 } from "node:path"; // src/pantheon/file-persistence-salvage.ts function salvageRecords(content) { @@ -11332,9 +12760,9 @@ var FilePersistenceAdapter = class { */ constructor(statePath, ops = defaultFsOps) { this.statePath = statePath ?? DEFAULT_STATE_PATH; - this.dir = dirname8(this.statePath); + this.dir = dirname10(this.statePath); this.ops = ops; - this.lockKey = resolve7(this.statePath); + this.lockKey = resolve13(this.statePath); } /** Ensure the parent directory exists. */ async ensureDir() { @@ -11482,7 +12910,7 @@ function getSharedBoard() { import { randomUUID as randomUUID3 } from "node:crypto"; // src/plugins/hook-runner.ts -import { spawn } from "node:child_process"; +import { spawn as spawn2 } from "node:child_process"; import path3 from "node:path"; import { fileURLToPath as fileURLToPath3 } from "node:url"; var HOOK_TIMEOUT_MS = 15e3; @@ -11515,7 +12943,7 @@ function runHook(script, payload, opts = {}) { timedOut: false }); } - return new Promise((resolve14) => { + return new Promise((resolve23) => { const stdoutBuf = { value: "" }; const stderrBuf = { value: "" }; let settled = false; @@ -11525,7 +12953,7 @@ function runHook(script, payload, opts = {}) { if (!settled) { settled = true; if (timeoutHandle !== void 0) clearTimeout(timeoutHandle); - resolve14(result); + resolve23(result); } }; const spawnOpts = { @@ -11544,7 +12972,7 @@ function runHook(script, payload, opts = {}) { }; let child; try { - child = spawn(scriptPath, [], spawnOpts); + child = spawn2(scriptPath, [], spawnOpts); } catch (err) { settle({ code: 1, @@ -11611,7 +13039,7 @@ var FORMATTER_SCRIPT = "format-multi-language.sh"; var DELEGATION_START_SCRIPT = "on-subagent-delegation-start.sh"; var DELEGATION_STOP_SCRIPT = "on-subagent-delegation-stop.sh"; var IDLE_RESULT = { code: 0, stdout: "", stderr: "", signal: null, timedOut: false }; -var defaultRunner = async (script, payload) => { +var defaultRunner2 = async (script, payload) => { const record2 = payload ?? {}; const tool2 = typeof record2.tool_name === "string" ? record2.tool_name : ""; if (script === DELEGATION_START_SCRIPT) { @@ -11696,7 +13124,7 @@ function delegationStatus(event) { return extractTaskID(result) !== "" ? "dispatched" : "success"; } function createV2ShellHooks(options = {}) { - const run = options.run ?? defaultRunner; + const run = options.run ?? defaultRunner2; const now = options.now ?? Date.now; const starts = /* @__PURE__ */ new Map(); let unkeyedWarned = false; @@ -12020,33 +13448,167 @@ var TodoEnforcer = class { // src/pantheon/tools.ts import { exec } from "node:child_process"; -import { promisify as promisify2 } from "node:util"; +import { promisify as promisify5 } from "node:util"; // src/pantheon/agent-forge-tool.ts import { - existsSync as existsSync8, - mkdirSync as mkdirSync6, + existsSync as existsSync14, + mkdirSync as mkdirSync9, readdirSync as readdirSync3, - readFileSync as readFileSync8, - realpathSync as realpathSync3, - rmSync as rmSync2, - writeFileSync as writeFileSync5 + readFileSync as readFileSync13, + realpathSync as realpathSync6, + rmSync as rmSync3, + writeFileSync as writeFileSync7 } from "node:fs"; -import { join as join13, resolve as resolve8, sep as sep4 } from "node:path"; +import { join as join19, resolve as resolve15, sep as sep7 } from "node:path"; -// src/pantheon/tool-context.ts -function resolveToolCwd(context, fallbackDir) { - const ctx = context ?? {}; - if (typeof ctx.directory === "string" && ctx.directory.trim().length > 0) { - return ctx.directory; +// scripts/stack-detector.mjs +import { existsSync as existsSync13, readFileSync as readFileSync12 } from "node:fs"; +import { join as join18, resolve as resolve14 } from "node:path"; +function detectRepositoryStacks(workspaceDir) { + const root = resolve14(workspaceDir); + const stacks = []; + const suggestedSpecialists = []; + const suggestedDocs = /* @__PURE__ */ new Set(); + const pkgPath = join18(root, "package.json"); + if (existsSync13(pkgPath)) { + try { + const pkg = JSON.parse(readFileSync12(pkgPath, "utf8")); + const deps = { ...pkg.dependencies, ...pkg.devDependencies }; + const frameworks = []; + for (const fw of [ + "typescript", + "react", + "next", + "solid-js", + "vue", + "fastify", + "express", + "hono", + "prisma" + ]) { + if (fw in deps) frameworks.push(fw); + } + const testRunner = "vitest" in deps ? "npx vitest run" : "jest" in deps ? "npx jest" : pkg.scripts?.test ? "npm test" : "node --test"; + const linter = "biome" in deps || "@biomejs/biome" in deps ? "npx biome check" : "npx eslint"; + stacks.push({ + id: "node-typescript", + manifest: "package.json", + frameworks, + testRunner, + linter + }); + const uiFrameworks = frameworks.filter( + (f) => ["react", "next", "solid-js", "vue"].includes(f) + ); + if (uiFrameworks.length > 0) { + suggestedSpecialists.push({ + name: "frontend-ui-specialist", + archetype: "frontend", + description: `UI/component specialist tailored to ${uiFrameworks.join(", ")}`, + stack: ["TypeScript", ...frameworks], + testCommand: testRunner, + suggestedDocs: ["src/instructions/", "tsconfig.json"] + }); + } else { + suggestedSpecialists.push({ + name: "node-service-specialist", + archetype: "backend", + description: `Node/TypeScript backend specialist using ${testRunner}`, + stack: ["Node.js", "TypeScript", ...frameworks], + testCommand: testRunner, + suggestedDocs: ["tsconfig.json", "package.json"] + }); + } + suggestedDocs.add("package.json"); + } catch { + } } - if (typeof ctx.worktree === "string" && ctx.worktree.trim().length > 0) { - return ctx.worktree; + const pyProjPath = join18(root, "pyproject.toml"); + const reqPath = join18(root, "requirements.txt"); + if (existsSync13(pyProjPath) || existsSync13(reqPath)) { + const rawPy = [ + existsSync13(pyProjPath) ? readFileSync12(pyProjPath, "utf8") : "", + existsSync13(reqPath) ? readFileSync12(reqPath, "utf8") : "" + ].join("\n").toLowerCase(); + const frameworks = []; + for (const fw of ["fastapi", "django", "flask", "sqlalchemy", "pydantic", "pytest"]) { + if (rawPy.includes(fw)) frameworks.push(fw); + } + const testRunner = rawPy.includes("pytest") ? "pytest -q" : "python3 -m unittest"; + const linter = rawPy.includes("ruff") ? "ruff check" : "pyright"; + const pyManifest = existsSync13(pyProjPath) ? "pyproject.toml" : "requirements.txt"; + stacks.push({ + id: "python", + manifest: pyManifest, + frameworks, + testRunner, + linter + }); + suggestedSpecialists.push({ + name: "python-api-specialist", + archetype: frameworks.includes("sqlalchemy") ? "data" : "backend", + description: `Python specialist tailored to ${frameworks.join(", ") || "pyproject.toml"}`, + stack: ["Python", ...frameworks], + testCommand: testRunner, + suggestedDocs: [pyManifest] + }); + suggestedDocs.add(pyManifest); + } + const goModPath = join18(root, "go.mod"); + if (existsSync13(goModPath)) { + const rawGo = readFileSync12(goModPath, "utf8").toLowerCase(); + const frameworks = ["gin", "echo", "fiber", "chi"].filter((fw) => rawGo.includes(fw)); + stacks.push({ + id: "go", + manifest: "go.mod", + frameworks, + testRunner: "go test ./...", + linter: "gofmt / go vet" + }); + suggestedSpecialists.push({ + name: "go-systems-specialist", + archetype: "backend", + description: `Go service & concurrency specialist (${frameworks.join(", ") || "stdlib"})`, + stack: ["Go", ...frameworks], + testCommand: "go test ./...", + suggestedDocs: ["go.mod"] + }); + suggestedDocs.add("go.mod"); } - if (typeof fallbackDir === "string" && fallbackDir.trim().length > 0) { - return fallbackDir; + const cargoPath = join18(root, "Cargo.toml"); + if (existsSync13(cargoPath)) { + const rawCargo = readFileSync12(cargoPath, "utf8").toLowerCase(); + const frameworks = ["tokio", "axum", "actix-web", "serde", "sqlx"].filter( + (fw) => rawCargo.includes(fw) + ); + stacks.push({ + id: "rust", + manifest: "Cargo.toml", + frameworks, + testRunner: "cargo test", + linter: "cargo clippy" + }); + suggestedSpecialists.push({ + name: "rust-core-specialist", + archetype: "backend", + description: `Rust systems & safety specialist (${frameworks.join(", ") || "Cargo"})`, + stack: ["Rust", ...frameworks], + testCommand: "cargo test", + suggestedDocs: ["Cargo.toml"] + }); + suggestedDocs.add("Cargo.toml"); } - return process.cwd(); + return { + stacks, + suggestedSpecialists, + suggestedDocs: Array.from(suggestedDocs) + }; +} + +// src/pantheon/stack-detector.ts +function detectRepositoryStacks2(workspaceDir) { + return detectRepositoryStacks(workspaceDir); } // src/pantheon/agent-forge-tool.ts @@ -12055,13 +13617,13 @@ function isValidAgentSlug(value) { return typeof value === "string" && SAFE_AGENT_NAME_RE.test(value) && !value.includes("..") && !value.includes("/") && !value.includes("\\"); } function resolveAgentsDir(workspaceDir) { - const dir = join13(workspaceDir, ".opencode", "agents"); - mkdirSync6(dir, { recursive: true }); - return realpathSync3(dir); + const dir = join19(workspaceDir, ".opencode", "agents"); + mkdirSync9(dir, { recursive: true }); + return realpathSync6(dir); } function resolveConfinedAgentFile(agentsDir, name) { - const filePath = resolve8(agentsDir, `${name}.md`); - const prefix = agentsDir.endsWith(sep4) ? agentsDir : `${agentsDir}${sep4}`; + const filePath = resolve15(agentsDir, `${name}.md`); + const prefix = agentsDir.endsWith(sep7) ? agentsDir : `${agentsDir}${sep7}`; if (!filePath.startsWith(prefix)) { throw new Error("Path traversal denied: agent file escapes .opencode/agents"); } @@ -12090,6 +13652,7 @@ function buildAgentMarkdown(params) { " glob: allow", ` edit: ${permEdit}`, ` hashline_edit: ${permEdit}`, + ` ast_rewrite: ${permEdit}`, ` bash: ${permShell}`, ` shell: ${permShell}`, ` execute: ${permShell}`, @@ -12120,7 +13683,7 @@ function buildAgentMarkdown(params) { "" ].join("\n"); } -function jsonResult(payload) { +function jsonResult2(payload) { return { output: JSON.stringify(payload) }; } function createAgentForgeTool(fallbackDir) { @@ -12134,7 +13697,7 @@ function createAgentForgeTool(fallbackDir) { properties: { action: { type: "string", - enum: ["create", "list", "inspect", "remove"], + enum: ["create", "list", "inspect", "remove", "detect_stack"], description: "Forge operation to execute" }, name: { @@ -12179,12 +13742,16 @@ function createAgentForgeTool(fallbackDir) { try { const action = typeof input.action === "string" ? input.action : "list"; const cwd = resolveToolCwd(context, fallbackDir); + if (action === "detect_stack") { + const report = detectRepositoryStacks2(cwd); + return jsonResult2({ ok: true, workspace: cwd, ...report }); + } const agentsDir = resolveAgentsDir(cwd); if (action === "list") { const files = readdirSync3(agentsDir).filter((f) => f.endsWith(".md") && f.toLowerCase() !== "readme.md").sort(); const agents = files.map((file) => { const id = file.replace(/\.md$/, ""); - const raw = readFileSync8(join13(agentsDir, file), "utf8"); + const raw = readFileSync13(join19(agentsDir, file), "utf8"); const descMatch = raw.match(/^description:\s*(.+)$/m); return { name: id, @@ -12192,37 +13759,37 @@ function createAgentForgeTool(fallbackDir) { description: descMatch?.[1]?.replace(/^["']|["']$/g, "") ?? "" }; }); - return jsonResult({ ok: true, count: agents.length, agents }); + return jsonResult2({ ok: true, count: agents.length, agents }); } const name = typeof input.name === "string" ? input.name.trim().toLowerCase() : ""; if (!isValidAgentSlug(name)) { - return jsonResult({ + return jsonResult2({ ok: false, error: "name must be a lowercase kebab-case identifier (2..49 chars, [a-z0-9-])" }); } const filePath = resolveConfinedAgentFile(agentsDir, name); if (action === "inspect") { - if (!existsSync8(filePath)) { - return jsonResult({ ok: false, error: "agent_not_found", name }); + if (!existsSync14(filePath)) { + return jsonResult2({ ok: false, error: "agent_not_found", name }); } - return jsonResult({ + return jsonResult2({ ok: true, name, path: `.opencode/agents/${name}.md`, - content: readFileSync8(filePath, "utf8") + content: readFileSync13(filePath, "utf8") }); } if (action === "remove") { - if (!existsSync8(filePath)) { - return jsonResult({ ok: false, error: "agent_not_found", name }); + if (!existsSync14(filePath)) { + return jsonResult2({ ok: false, error: "agent_not_found", name }); } - rmSync2(filePath, { force: true }); - return jsonResult({ ok: true, removed: true, name }); + rmSync3(filePath, { force: true }); + return jsonResult2({ ok: true, removed: true, name }); } if (action === "create") { if (PANTHEON_AGENTS.has(name) && input.allowOverrideCanonical !== true) { - return jsonResult({ + return jsonResult2({ ok: false, error: `"${name}" is a canonical Pantheon agent. Pass allowOverrideCanonical: true only if you intentionally want a project-local override.` }); @@ -12250,8 +13817,8 @@ function createAgentForgeTool(fallbackDir) { testCommand, conventions }); - writeFileSync5(filePath, markdown, "utf8"); - return jsonResult({ + writeFileSync7(filePath, markdown, "utf8"); + return jsonResult2({ ok: true, created: true, name, @@ -12260,21 +13827,443 @@ function createAgentForgeTool(fallbackDir) { archetype }); } - return jsonResult({ ok: false, error: `Unsupported action: ${action}` }); - } catch (err) { - return jsonResult({ - ok: false, - error: err instanceof Error ? err.message : String(err) + return jsonResult2({ ok: false, error: `Unsupported action: ${action}` }); + } catch (err) { + return jsonResult2({ + ok: false, + error: err instanceof Error ? err.message : String(err) + }); + } + } + }; +} + +// src/pantheon/ast-tools.ts +import { readdirSync as readdirSync4, readFileSync as readFileSync14, statSync as statSync6, writeFileSync as writeFileSync8 } from "node:fs"; +import { extname as extname3, join as join20, relative as relative5, resolve as resolve16 } from "node:path"; +var SKIP_DIRS = /* @__PURE__ */ new Set([".git", "node_modules", ".pantheon", ".venv", "dist", "build"]); +var SUPPORTED_EXTS = /* @__PURE__ */ new Set([ + ".ts", + ".tsx", + ".mts", + ".cts", + ".js", + ".jsx", + ".mjs", + ".cjs", + ".py", + ".go", + ".rs", + ".java" +]); +var OPEN_DELIMS = { "(": ")", "[": "]", "{": "}" }; +var CLOSE_DELIMS = /* @__PURE__ */ new Set([")", "]", "}"]); +function computeLineIndex(source) { + const starts = [0]; + for (let i = 0; i < source.length; i += 1) { + if (source.charCodeAt(i) === 10) starts.push(i + 1); + } + return starts; +} +function locateOffset(lineStarts, offset) { + let lo = 0; + let hi = lineStarts.length - 1; + while (lo <= hi) { + const mid = lo + hi >> 1; + if ((lineStarts[mid] ?? 0) <= offset) lo = mid + 1; + else hi = mid - 1; + } + const lineIdx = Math.max(0, hi); + return { line: lineIdx + 1, column: offset - (lineStarts[lineIdx] ?? 0) + 1 }; +} +function tokenizeCode(source, isPattern = false) { + const tokens = []; + const lineStarts = computeLineIndex(source); + const n = source.length; + let i = 0; + const push = (kind, start, end) => { + const pos = locateOffset(lineStarts, start); + tokens.push({ kind, text: source.slice(start, end), start, end, ...pos }); + }; + while (i < n) { + const ch = source[i] ?? ""; + const next = source[i + 1] ?? ""; + if (/\s/.test(ch)) { + i += 1; + continue; + } + if (ch === "/" && next === "/") { + const nl = source.indexOf("\n", i + 2); + i = nl < 0 ? n : nl + 1; + continue; + } + if (ch === "/" && next === "*") { + const end = source.indexOf("*/", i + 2); + i = end < 0 ? n : end + 2; + continue; + } + if (ch === "#" && !source.slice(i).startsWith("#[")) { + const nl = source.indexOf("\n", i + 1); + i = nl < 0 ? n : nl + 1; + continue; + } + if (ch === '"' || ch === "'" || ch === "`") { + const quote = ch; + const start = i; + i += 1; + while (i < n) { + if (source[i] === "\\") { + i += 2; + continue; + } + if (source[i] === quote) { + i += 1; + break; + } + i += 1; + } + push("string", start, i); + continue; + } + if (isPattern && ch === "$") { + const start = i; + const rest = source.slice(i); + const metaMatch = /^(\${1,3}[A-Za-z_][A-Za-z0-9_]*)/.exec(rest); + if (metaMatch?.[1]) { + i += metaMatch[1].length; + push("meta", start, i); + continue; + } + } + if (/[A-Za-z_$]/.test(ch)) { + const start = i; + i += 1; + while (i < n && /[A-Za-z0-9_$]/.test(source[i] ?? "")) i += 1; + push("ident", start, i); + continue; + } + if (/[0-9]/.test(ch)) { + const start = i; + i += 1; + while (i < n && /[0-9A-Za-z_.]/.test(source[i] ?? "")) i += 1; + push("number", start, i); + continue; + } + const two = source.slice(i, i + 2); + const three = source.slice(i, i + 3); + if (three === "===" || three === "!==" || three === "...") { + push("punct", i, i + 3); + i += 3; + continue; + } + if (["==", "!=", "<=", ">=", "=>", "&&", "||", "::", "->"].includes(two)) { + push("punct", i, i + 2); + i += 2; + continue; + } + push("punct", i, i + 1); + i += 1; + } + return tokens; +} +function matchTokensAt(code, codeTokens, startIdx, patTokens) { + const captures = {}; + const step = (ci, pi) => { + if (pi >= patTokens.length) return ci; + const pat = patTokens[pi]; + if (!pat) return null; + if (pat.kind === "meta") { + const isMulti = pat.text.startsWith("$$$"); + const varName = pat.text; + if (isMulti) { + const stopTok = patTokens[pi + 1]; + let depth = 0; + let scan = ci; + const startOffset = codeTokens[ci]?.start; + while (scan <= codeTokens.length) { + if (depth === 0) { + const matchedAfter = step(scan, pi + 1); + if (matchedAfter !== null) { + const endOffset = scan > ci ? codeTokens[scan - 1]?.end : startOffset; + const raw2 = startOffset !== void 0 && endOffset !== void 0 ? code.slice(startOffset, endOffset) : ""; + if (!(varName in captures) || captures[varName] === raw2) { + captures[varName] = raw2; + return matchedAfter; + } + } + } + const cur3 = codeTokens[scan]; + if (!cur3) break; + if (cur3.text in OPEN_DELIMS) depth += 1; + else if (CLOSE_DELIMS.has(cur3.text)) { + if (depth === 0) break; + depth -= 1; + } else if (stopTok && depth === 0 && cur3.text === stopTok.text && scan > ci) { + } + scan += 1; + } + return null; + } + const cur2 = codeTokens[ci]; + if (!cur2 || CLOSE_DELIMS.has(cur2.text)) return null; + let endTokenIdx = ci + 1; + if (cur2.text in OPEN_DELIMS) { + let depth = 1; + while (endTokenIdx < codeTokens.length && depth > 0) { + const t = codeTokens[endTokenIdx]; + if (!t) break; + if (t.text in OPEN_DELIMS) depth += 1; + else if (CLOSE_DELIMS.has(t.text)) depth -= 1; + endTokenIdx += 1; + } + if (depth !== 0) return null; + } else { + while (endTokenIdx < codeTokens.length && (codeTokens[endTokenIdx]?.text === "." || codeTokens[endTokenIdx]?.text === "(")) { + if (codeTokens[endTokenIdx]?.text === ".") { + if (endTokenIdx + 1 >= codeTokens.length) break; + endTokenIdx += 2; + } else { + let depth = 1; + endTokenIdx += 1; + while (endTokenIdx < codeTokens.length && depth > 0) { + const t = codeTokens[endTokenIdx]; + if (!t) break; + if (t.text in OPEN_DELIMS) depth += 1; + else if (CLOSE_DELIMS.has(t.text)) depth -= 1; + endTokenIdx += 1; + } + } + } + } + const raw = code.slice(cur2.start, codeTokens[endTokenIdx - 1]?.end ?? cur2.end); + const prev = captures[varName]; + if (prev !== void 0 && prev !== raw) return null; + captures[varName] = raw; + const res = step(endTokenIdx, pi + 1); + if (res === null && prev === void 0) delete captures[varName]; + return res; + } + const cur = codeTokens[ci]; + if (!cur || cur.text !== pat.text) return null; + return step(ci + 1, pi + 1); + }; + const endIdx = step(startIdx, 0); + return endIdx !== null ? { endIdx, captures } : null; +} +function collectFiles(targetPath) { + const out = []; + const st = statSync6(targetPath); + if (st.isFile()) return [targetPath]; + const walk = (dir) => { + for (const entry of readdirSync4(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue; + const full = join20(dir, entry.name); + if (entry.isDirectory()) walk(full); + else if (entry.isFile() && SUPPORTED_EXTS.has(extname3(entry.name).toLowerCase())) { + out.push(full); + } + } + }; + walk(targetPath); + return out; +} +function findAstMatchesInFile(absFile, relFile, pattern) { + const source = readFileSync14(absFile, "utf8"); + const patTokens = tokenizeCode(pattern, true); + if (patTokens.length === 0) return []; + const codeTokens = tokenizeCode(source, false); + const matches = []; + let idx = 0; + while (idx < codeTokens.length) { + const firstPat = patTokens[0]; + const cur = codeTokens[idx]; + if (!firstPat || !cur) break; + if (firstPat.kind !== "meta" && cur.text !== firstPat.text) { + idx += 1; + continue; + } + const found = matchTokensAt(source, codeTokens, idx, patTokens); + if (!found) { + idx += 1; + continue; + } + const firstTok = codeTokens[idx]; + const lastTok = codeTokens[found.endIdx - 1] ?? firstTok; + if (firstTok && lastTok && found.endIdx > idx) { + matches.push({ + file: relFile, + line: firstTok.line, + column: firstTok.column, + startOffset: firstTok.start, + endOffset: lastTok.end, + match: source.slice(firstTok.start, lastTok.end), + captures: found.captures + }); + idx = found.endIdx; + } else { + idx += 1; + } + } + return matches; +} +function substituteCaptures(template, captures) { + return template.replace(/\${1,3}[A-Za-z_][A-Za-z0-9_]*/g, (token) => captures[token] ?? token); +} +function jsonResult3(payload) { + return { output: JSON.stringify(payload) }; +} +function createAstTools(fallbackDir) { + const astSearch = { + name: "ast_search", + description: "Search code using structural AST token patterns with metavariables ($VAR, $$$ARGS). Ignores comments and whitespace/formatting differences while staying confined to the workspace.", + input: { + type: "object", + additionalProperties: false, + required: ["pattern"], + properties: { + pattern: { + type: "string", + description: 'Structural code pattern, e.g. "console.log($$$ARGS)" or "if ($COND)"' + }, + path: { + type: "string", + description: 'Relative file or directory inside the workspace (default: ".")' + }, + limit: { + type: "number", + description: "Maximum matches to return (default: 50, max: 200)" + } + } + }, + output: {}, + execute: async (input, context) => { + try { + const pattern = typeof input.pattern === "string" ? input.pattern.trim() : ""; + if (!pattern) return jsonResult3({ ok: false, error: "pattern is required" }); + const cwd = resolveToolCwd(context, fallbackDir); + const rawPath = typeof input.path === "string" && input.path.trim() ? input.path.trim() : "."; + const targetAbs = resolveSafeToolPath(cwd, rawPath); + const limit = typeof input.limit === "number" && input.limit > 0 ? Math.min(200, Math.floor(input.limit)) : 50; + const files = collectFiles(targetAbs); + const results = []; + for (const f of files) { + const rel = relative5(resolve16(cwd), f).replace(/\\/g, "/") || f; + for (const m of findAstMatchesInFile(f, rel, pattern)) { + results.push({ + file: m.file, + line: m.line, + column: m.column, + match: m.match, + captures: m.captures + }); + if (results.length >= limit) break; + } + if (results.length >= limit) break; + } + return jsonResult3({ + ok: true, + pattern, + scannedFiles: files.length, + total: results.length, + matches: results + }); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + return jsonResult3({ ok: false, error: message }); + } + } + }; + const astRewrite = { + name: "ast_rewrite", + description: "Structurally rewrite code matching an AST pattern ($VAR, $$$ARGS) to a replacement template. Supports dryRun preview, preserves surrounding code, and enforces Pantheon edit guardrails.", + input: { + type: "object", + additionalProperties: false, + required: ["pattern", "replacement"], + properties: { + pattern: { type: "string", description: "Structural AST pattern to match" }, + replacement: { + type: "string", + description: "Replacement template substituting captured metavariables" + }, + path: { + type: "string", + description: 'Relative file or directory inside the workspace (default: ".")' + }, + dryRun: { + type: "boolean", + description: "Preview changes without writing files (default: false)" + } + } + }, + output: {}, + execute: async (input, context) => { + try { + const pattern = typeof input.pattern === "string" ? input.pattern.trim() : ""; + const replacement = typeof input.replacement === "string" ? input.replacement : ""; + if (!pattern) return jsonResult3({ ok: false, error: "pattern is required" }); + if (!replacement) return jsonResult3({ ok: false, error: "replacement is required" }); + const cwd = resolveToolCwd(context, fallbackDir); + const rawPath = typeof input.path === "string" && input.path.trim() ? input.path.trim() : "."; + const targetAbs = resolveSafeToolPath(cwd, rawPath); + const dryRun = input.dryRun === true; + const guardrail = evaluateEditGuardrail("ast_rewrite", { + filePath: targetAbs, + newString: replacement + }); + if (!guardrail.allowed) { + return jsonResult3({ + ok: false, + error: guardrail.message ?? "Edit blocked by Pantheon guardrail" + }); + } + const files = collectFiles(targetAbs); + const filesModified = []; + const previews = []; + let totalReplacements = 0; + for (const f of files) { + const rel = relative5(resolve16(cwd), f).replace(/\\/g, "/") || f; + const spans = findAstMatchesInFile(f, rel, pattern); + if (spans.length === 0) continue; + const original = readFileSync14(f, "utf8"); + let updated = ""; + let cursor = 0; + for (const span of spans) { + const after = substituteCaptures(replacement, span.captures); + updated += original.slice(cursor, span.startOffset) + after; + cursor = span.endOffset; + totalReplacements += 1; + if (previews.length < 30) { + previews.push({ file: rel, line: span.line, before: span.match, after }); + } + } + updated += original.slice(cursor); + if (!dryRun && updated !== original) { + writeFileSync8(f, updated, "utf8"); + } + if (updated !== original) filesModified.push(rel); + } + return jsonResult3({ + ok: true, + dryRun, + pattern, + replacements: totalReplacements, + filesModified, + previews }); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + return jsonResult3({ ok: false, error: message }); } } }; + return [astSearch, astRewrite]; } // src/pantheon/codemap-tools.ts -import { createHash as createHash6 } from "node:crypto"; -import { existsSync as existsSync9, mkdirSync as mkdirSync7, readdirSync as readdirSync4, readFileSync as readFileSync9, realpathSync as realpathSync4, statSync as statSync4 } from "node:fs"; -import { extname as extname2, join as join14, relative as relative3, resolve as resolve9, sep as sep5 } from "node:path"; +import { createHash as createHash7 } from "node:crypto"; +import { existsSync as existsSync15, mkdirSync as mkdirSync10, readdirSync as readdirSync5, readFileSync as readFileSync15, realpathSync as realpathSync7, statSync as statSync7 } from "node:fs"; +import { extname as extname4, join as join21, relative as relative6, resolve as resolve17, sep as sep8 } from "node:path"; import { DatabaseSync as DatabaseSync3 } from "node:sqlite"; var IGNORED_DIRS = /* @__PURE__ */ new Set([ ".git", @@ -12300,11 +14289,11 @@ var SUPPORTED_EXT_LANG = { }; var codemapDbCache = /* @__PURE__ */ new Map(); function getCodemapDb(workspaceDir) { - const memoryDir = join14(workspaceDir, ".pantheon", "memory"); - mkdirSync7(memoryDir, { recursive: true }); - const canonicalBase = realpathSync4(memoryDir); - const dbPath = resolve9(canonicalBase, "memory.db"); - const prefix = canonicalBase.endsWith(sep5) ? canonicalBase : `${canonicalBase}${sep5}`; + const memoryDir = join21(workspaceDir, ".pantheon", "memory"); + mkdirSync10(memoryDir, { recursive: true }); + const canonicalBase = realpathSync7(memoryDir); + const dbPath = resolve17(canonicalBase, "memory.db"); + const prefix = canonicalBase.endsWith(sep8) ? canonicalBase : `${canonicalBase}${sep8}`; if (!dbPath.startsWith(prefix)) { throw new Error("Path traversal denied for codemap database"); } @@ -12496,7 +14485,7 @@ function collectSourceFiles(currentDir, maxFiles = 500) { if (results.length >= maxFiles) return; let entries; try { - entries = readdirSync4(dir, { withFileTypes: true }); + entries = readdirSync5(dir, { withFileTypes: true }); } catch { return; } @@ -12505,12 +14494,12 @@ function collectSourceFiles(currentDir, maxFiles = 500) { const name = String(entry.name); if (entry.isDirectory()) { if (!IGNORED_DIRS.has(name) && !name.startsWith(".")) { - walk(join14(dir, name)); + walk(join21(dir, name)); } } else if (entry.isFile()) { - const ext = extname2(name).toLowerCase(); + const ext = extname4(name).toLowerCase(); if (ext in SUPPORTED_EXT_LANG) { - results.push(join14(dir, name)); + results.push(join21(dir, name)); } } } @@ -12518,9 +14507,47 @@ function collectSourceFiles(currentDir, maxFiles = 500) { walk(currentDir); return results; } -function jsonResult2(payload) { +function jsonResult4(payload) { return { output: JSON.stringify(payload) }; } +function deleteIndexedFile(db, relFile) { + db.prepare("DELETE FROM code_entities WHERE file = ?").run(relFile); + db.prepare("DELETE FROM code_relations WHERE file = ?").run(relFile); + db.prepare("DELETE FROM code_files WHERE path = ?").run(relFile); +} +function pruneMissingFilesInScope(db, canonicalRoot, subRel) { + const cleanScope = subRel.replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/+$/, ""); + const rows = cleanScope === "" || cleanScope === "." ? db.prepare("SELECT path FROM code_files").all() : db.prepare("SELECT path FROM code_files WHERE path = ? OR path LIKE ? ESCAPE '\\'").all(cleanScope, `${cleanScope.replace(/[\\%_]/g, "\\$&")}/%`); + let pruned = 0; + for (const row of rows) { + if (typeof row?.path !== "string") continue; + if (!existsSync15(resolve17(canonicalRoot, row.path))) { + deleteIndexedFile(db, row.path); + pruned += 1; + } + } + return pruned; +} +function filterAndPruneExistingRows(db, canonicalRoot, rows) { + const kept = []; + const missing = /* @__PURE__ */ new Set(); + for (const row of rows) { + const file = typeof row.file === "string" ? row.file : ""; + if (!file) { + kept.push(row); + continue; + } + if (missing.has(file) || !existsSync15(resolve17(canonicalRoot, file))) { + if (!missing.has(file)) { + missing.add(file); + deleteIndexedFile(db, file); + } + continue; + } + kept.push(row); + } + return kept; +} function createCodemapTools(fallbackDir) { return [ { @@ -12544,19 +14571,19 @@ function createCodemapTools(fallbackDir) { execute: async (input, context) => { try { const cwd = resolveToolCwd(context, fallbackDir); - const canonicalRoot = realpathSync4(cwd); + const canonicalRoot = realpathSync7(cwd); const subPath = typeof input.path === "string" && input.path.trim() ? input.path.trim() : "."; - const targetPath = resolve9(canonicalRoot, subPath); - const rootPrefix = canonicalRoot.endsWith(sep5) ? canonicalRoot : `${canonicalRoot}${sep5}`; + const targetPath = resolve17(canonicalRoot, subPath); + const rootPrefix = canonicalRoot.endsWith(sep8) ? canonicalRoot : `${canonicalRoot}${sep8}`; if (targetPath !== canonicalRoot && !targetPath.startsWith(rootPrefix)) { - return jsonResult2({ ok: false, error: "path escapes workspace root" }); + return jsonResult4({ ok: false, error: "path escapes workspace root" }); } - if (!existsSync9(targetPath)) { - return jsonResult2({ ok: false, error: `path not found: ${subPath}` }); + if (!existsSync15(targetPath)) { + return jsonResult4({ ok: false, error: `path not found: ${subPath}` }); } const force = input.force === true; const db = getCodemapDb(canonicalRoot); - const st = statSync4(targetPath); + const st = statSync7(targetPath); const files = st.isFile() ? [targetPath] : collectSourceFiles(targetPath); let indexed = 0; let skipped = 0; @@ -12564,12 +14591,12 @@ function createCodemapTools(fallbackDir) { let relationsCount = 0; const nowIso = (/* @__PURE__ */ new Date()).toISOString(); for (const filePath of files) { - const ext = extname2(filePath).toLowerCase(); + const ext = extname4(filePath).toLowerCase(); const lang = SUPPORTED_EXT_LANG[ext]; if (!lang) continue; - const relFile = relative3(canonicalRoot, filePath).replace(/\\/g, "/"); - const content = readFileSync9(filePath, "utf8"); - const hash = createHash6("sha256").update(content).digest("hex"); + const relFile = relative6(canonicalRoot, filePath).replace(/\\/g, "/"); + const content = readFileSync15(filePath, "utf8"); + const hash = createHash7("sha256").update(content).digest("hex"); const existing = db.prepare("SELECT hash FROM code_files WHERE path = ?").get(relFile); if (!force && existing?.hash === hash) { skipped += 1; @@ -12597,15 +14624,17 @@ function createCodemapTools(fallbackDir) { ).run(relFile, hash, lang, nowIso); indexed += 1; } - return jsonResult2({ + const pruned = st.isFile() ? 0 : pruneMissingFilesInScope(db, canonicalRoot, relative6(canonicalRoot, targetPath)); + return jsonResult4({ ok: true, indexed, skipped, + pruned, entities: entitiesCount, relations: relationsCount }); } catch (err) { - return jsonResult2({ + return jsonResult4({ ok: false, error: err instanceof Error ? err.message : String(err) }); @@ -12632,10 +14661,11 @@ function createCodemapTools(fallbackDir) { execute: async (input, context) => { try { const q = typeof input.query === "string" ? input.query.trim() : ""; - if (!q) return jsonResult2({ ok: false, error: "query is required", results: [] }); + if (!q) return jsonResult4({ ok: false, error: "query is required", results: [] }); const limit = typeof input.limit === "number" && Number.isFinite(input.limit) && input.limit > 0 ? Math.min(Math.floor(input.limit), 100) : 25; const cwd = resolveToolCwd(context, fallbackDir); - const db = getCodemapDb(cwd); + const canonicalRoot = realpathSync7(cwd); + const db = getCodemapDb(canonicalRoot); const escaped = q.replace(/[\\%_]/g, "\\$&"); let sql = ` SELECT name, kind, file, line, signature @@ -12649,10 +14679,14 @@ function createCodemapTools(fallbackDir) { } sql += " ORDER BY CASE WHEN name = ? THEN 0 WHEN name LIKE ? THEN 1 ELSE 2 END, file, line LIMIT ?"; params.push(q, `${escaped}%`, limit); - const rows = db.prepare(sql).all(...params); - return jsonResult2({ ok: true, count: rows.length, results: rows }); + const rows = filterAndPruneExistingRows( + db, + canonicalRoot, + db.prepare(sql).all(...params) + ); + return jsonResult4({ ok: true, count: rows.length, results: rows }); } catch (err) { - return jsonResult2({ + return jsonResult4({ ok: false, error: err instanceof Error ? err.message : String(err) }); @@ -12679,31 +14713,40 @@ function createCodemapTools(fallbackDir) { execute: async (input, context) => { try { const target = typeof input.target === "string" ? input.target.trim() : ""; - if (!target) return jsonResult2({ ok: false, error: "target is required", neighbors: [] }); + if (!target) return jsonResult4({ ok: false, error: "target is required", neighbors: [] }); const direction = typeof input.direction === "string" ? input.direction : "both"; const cwd = resolveToolCwd(context, fallbackDir); - const db = getCodemapDb(cwd); + const canonicalRoot = realpathSync7(cwd); + const db = getCodemapDb(canonicalRoot); const escaped = target.replace(/[\\%_]/g, "\\$&"); - const outgoing = direction === "incoming" ? [] : db.prepare( - `SELECT source, target, kind, file, line - FROM code_relations - WHERE source = ? OR source LIKE ? ESCAPE '\\' - LIMIT 50` - ).all(target, `%${escaped}%`); - const incoming = direction === "outgoing" ? [] : db.prepare( - `SELECT source, target, kind, file, line - FROM code_relations - WHERE target = ? OR target LIKE ? ESCAPE '\\' - LIMIT 50` - ).all(target, `%${escaped}%`); - return jsonResult2({ + const outgoing = direction === "incoming" ? [] : filterAndPruneExistingRows( + db, + canonicalRoot, + db.prepare( + `SELECT source, target, kind, file, line + FROM code_relations + WHERE source = ? OR source LIKE ? ESCAPE '\\' + LIMIT 50` + ).all(target, `%${escaped}%`) + ); + const incoming = direction === "outgoing" ? [] : filterAndPruneExistingRows( + db, + canonicalRoot, + db.prepare( + `SELECT source, target, kind, file, line + FROM code_relations + WHERE target = ? OR target LIKE ? ESCAPE '\\' + LIMIT 50` + ).all(target, `%${escaped}%`) + ); + return jsonResult4({ ok: true, target, outgoing, incoming }); } catch (err) { - return jsonResult2({ + return jsonResult4({ ok: false, error: err instanceof Error ? err.message : String(err) }); @@ -12714,20 +14757,20 @@ function createCodemapTools(fallbackDir) { } // src/pantheon/cost-command.ts -import { execFile as execFile2 } from "node:child_process"; -import { accessSync, constants as constants3, existsSync as existsSync11, statSync as statSync5 } from "node:fs"; -import { delimiter, dirname as dirname10, join as join17 } from "node:path"; +import { execFile as execFile4 } from "node:child_process"; +import { accessSync, constants as constants3, existsSync as existsSync17, statSync as statSync8 } from "node:fs"; +import { delimiter, dirname as dirname12, join as join24 } from "node:path"; import { fileURLToPath as fileURLToPath4 } from "node:url"; import { z } from "zod"; // src/plugins/tui/src/cost-data.ts import { homedir as homedir6 } from "node:os"; -import { join as join16 } from "node:path"; +import { join as join23 } from "node:path"; // src/plugins/tui/src/model-pricing.ts -import { existsSync as existsSync10, mkdirSync as mkdirSync8, readFileSync as readFileSync10, renameSync as renameSync3, writeFileSync as writeFileSync6 } from "node:fs"; +import { existsSync as existsSync16, mkdirSync as mkdirSync11, readFileSync as readFileSync16, renameSync as renameSync3, writeFileSync as writeFileSync9 } from "node:fs"; import { homedir as homedir5 } from "node:os"; -import { dirname as dirname9, join as join15 } from "node:path"; +import { dirname as dirname11, join as join22 } from "node:path"; var MODELS_DEV_URL = "https://models.dev/api.json"; var PRICING_CACHE_VERSION = 1; var PRICING_TTL_MS = 24 * 60 * 60 * 1e3; @@ -12736,11 +14779,11 @@ function resolvePricingCacheDir(env = process.env) { const explicit = env.PANTHEON_HOME?.trim(); if (explicit !== void 0 && explicit !== "") return explicit; const xdg = env.XDG_CONFIG_HOME?.trim(); - const base = xdg !== void 0 && xdg !== "" ? xdg : join15(homedir5(), ".config"); - return join15(base, "opencode"); + const base = xdg !== void 0 && xdg !== "" ? xdg : join22(homedir5(), ".config"); + return join22(base, "opencode"); } function resolvePricingCachePath(env = process.env) { - return join15(resolvePricingCacheDir(env), "cache", "models-dev.json"); + return join22(resolvePricingCacheDir(env), "cache", "models-dev.json"); } function isRecord19(value) { return typeof value === "object" && value !== null && !Array.isArray(value); @@ -12871,8 +14914,8 @@ function parseCachedCatalog(raw) { } function readPricingCache(cachePath) { try { - if (!existsSync10(cachePath)) return void 0; - return parseCachedCatalog(JSON.parse(readFileSync10(cachePath, "utf8"))); + if (!existsSync16(cachePath)) return void 0; + return parseCachedCatalog(JSON.parse(readFileSync16(cachePath, "utf8"))); } catch { return void 0; } @@ -12880,8 +14923,8 @@ function readPricingCache(cachePath) { function writePricingCache(cachePath, catalog) { const temp = `${cachePath}.tmp-${process.pid}`; try { - mkdirSync8(dirname9(cachePath), { recursive: true }); - writeFileSync6(temp, `${JSON.stringify(catalog)} + mkdirSync11(dirname11(cachePath), { recursive: true }); + writeFileSync9(temp, `${JSON.stringify(catalog)} `, "utf8"); renameSync3(temp, cachePath); return true; @@ -13030,8 +15073,8 @@ var VERSION_SOURCES = { }; function defaultDbPath() { const xdg = process.env.XDG_DATA_HOME; - const dataHome = xdg !== void 0 && xdg !== "" ? xdg : join16(homedir6(), ".local", "share"); - return join16(dataHome, "opencode", "opencode.db"); + const dataHome = xdg !== void 0 && xdg !== "" ? xdg : join23(homedir6(), ".local", "share"); + return join23(dataHome, "opencode", "opencode.db"); } function requestedVersion() { const configured = process.env.PANTHEON_OPENCODE_VERSION; @@ -13090,7 +15133,7 @@ function priceTokens(pricing, provider, model, tokens) { // src/pantheon/cost-command.ts var __filename = fileURLToPath4(import.meta.url); -var __dirname = dirname10(__filename); +var __dirname = dirname12(__filename); var costArgs = { days: z.number().int().min(1).max(365).optional().describe("Number of rolling 24-hour days of history to include (default 7)."), session: z.string().min(1).optional().describe( @@ -13102,7 +15145,7 @@ var costArgs = { }; function findExistingDb(override) { const candidate = override === void 0 ? resolveCostDbPath() : resolveCostDbPath({ dbPath: override }); - return existsSync11(candidate) ? candidate : void 0; + return existsSync17(candidate) ? candidate : void 0; } var COST_AGGREGATE_SQL = { message: (sessionId) => ` @@ -13719,14 +15762,14 @@ var NODE_SQLITE_MIN_VERSION = "22.5"; function defaultIsExecutable(path5) { try { accessSync(path5, constants3.X_OK); - return statSync5(path5).isFile(); + return statSync8(path5).isFile(); } catch { return false; } } function defaultExecFile(file, args) { - return new Promise((resolve14, reject) => { - execFile2(file, [...args], { encoding: "utf8" }, (error, stdout, stderr) => { + return new Promise((resolve23, reject) => { + execFile4(file, [...args], { encoding: "utf8" }, (error, stdout, stderr) => { if (error) { const failure = error; if (typeof failure.stdout !== "string") failure.stdout = stdout; @@ -13734,7 +15777,7 @@ function defaultExecFile(file, args) { reject(failure); return; } - resolve14({ stdout, stderr }); + resolve23({ stdout, stderr }); }); }); } @@ -13746,7 +15789,7 @@ function resolveNodeFromPath(env, isExecutable = defaultIsExecutable) { for (const dir of pathValue.split(delimiter)) { if (dir === "") continue; for (const ext of extensions) { - const candidate = join17(dir, `node${ext}`); + const candidate = join24(dir, `node${ext}`); if (isExecutable(candidate)) return candidate; } } @@ -13783,9 +15826,9 @@ function truncateForError(text2) { const trimmed = text2.trim(); return trimmed.length > 200 ? `${trimmed.slice(0, 200)}\u2026` : trimmed; } -async function assertNodeSqliteSupport(nodePath, execFileAsync2) { +async function assertNodeSqliteSupport(nodePath, execFileAsync5) { try { - await execFileAsync2(nodePath, ["-e", "require('node:sqlite')"]); + await execFileAsync5(nodePath, ["-e", "require('node:sqlite')"]); } catch (err) { throw new Error( `resolved Node binary "${nodePath}" does not support node:sqlite (Node.js >= ${NODE_SQLITE_MIN_VERSION} required): ${execErrorMessage(err)}` @@ -13808,10 +15851,10 @@ function extractScriptFailure(err) { } async function queryWithCliFallback(dbPath, days, deps) { const env = deps?.env ?? process.env; - const execFileAsync2 = deps?.execFile ?? defaultExecFile; + const execFileAsync5 = deps?.execFile ?? defaultExecFile; const isExecutable = deps?.isExecutable ?? defaultIsExecutable; - const costScript = join17(__dirname, "..", "..", "scripts", "cost.mjs"); - if (!existsSync11(costScript)) { + const costScript = join24(__dirname, "..", "..", "scripts", "cost.mjs"); + if (!existsSync17(costScript)) { throw new Error(`CLI fallback script not found: ${costScript}`); } const node = resolveNodeExecutable(env, isExecutable); @@ -13820,11 +15863,11 @@ async function queryWithCliFallback(dbPath, days, deps) { `no Node.js executable found for the node:sqlite CLI fallback: set PANTHEON_NODE to a Node.js >= ${NODE_SQLITE_MIN_VERSION} binary or put "node" on PATH` ); } - await assertNodeSqliteSupport(node.path, execFileAsync2); + await assertNodeSqliteSupport(node.path, execFileAsync5); let stdout; try { ; - ({ stdout } = await execFileAsync2(node.path, [ + ({ stdout } = await execFileAsync5(node.path, [ costScript, "--db-path", dbPath, @@ -13952,7 +15995,7 @@ ${renderMarkdown(query, days, pricing)}`; import { z as z3 } from "zod"; // src/pantheon/deepwork/plan-projection.ts -import { join as join18 } from "node:path"; +import { join as join25 } from "node:path"; function generateChatProjection(plan, cwd = process.cwd()) { const pendingDecisions = plan.decisions_needed.filter((d) => d.status === "pending"); const totalTasks = plan.tasks.length; @@ -13962,8 +16005,8 @@ function generateChatProjection(plan, cwd = process.cwd()) { const readyTasks = plan.tasks.filter((t) => t.state === "ready"); const nextTask = inProgressTasks[0] || readyTasks[0] || plan.tasks.find((t) => t.state === "pending"); const percent = totalTasks > 0 ? Math.round(doneTasks / totalTasks * 100) : 0; - const absPlanMd = join18(cwd, ".pantheon", "deepwork", plan.plan_id, "PLAN.md"); - const absPlanJson = join18(cwd, ".pantheon", "deepwork", plan.plan_id, "plan.json"); + const absPlanMd = join25(cwd, ".pantheon", "deepwork", plan.plan_id, "PLAN.md"); + const absPlanJson = join25(cwd, ".pantheon", "deepwork", plan.plan_id, "plan.json"); const lines = []; lines.push(`### Deepwork: ${plan.title} (\`${plan.plan_id}\`)`); lines.push( @@ -14137,149 +16180,9 @@ function buildApprovalQuestion(plan) { } // src/pantheon/deepwork/plan-tracker.ts -import { existsSync as existsSync12 } from "node:fs"; +import { existsSync as existsSync18 } from "node:fs"; import { appendFile as appendFile3, mkdir as mkdir6, readdir, readFile as readFile6, rename as rename5, writeFile as writeFile3 } from "node:fs/promises"; -import { join as join19 } from "node:path"; - -// src/pantheon/execution-receipt.ts -import { createHash as createHash7 } from "node:crypto"; -function hashContent2(content) { - return createHash7("sha256").update(content).digest("hex"); -} -function computeReceiptSignature(taskID, agent, timestamp, files) { - const sortedFiles = [...files].sort((a, b) => a.path.localeCompare(b.path)); - const payload = [ - taskID, - agent, - String(timestamp), - sortedFiles.map((f) => `${f.path}:${f.hash}`).join(";") - ].join("|"); - return createHash7("sha256").update(payload).digest("hex"); -} -function createExecutionReceipt(input) { - const timestamp = Date.now(); - const files = input.files.map((f) => { - const buf = typeof f.content === "string" ? Buffer.from(f.content, "utf8") : f.content; - return { - path: f.path, - hash: hashContent2(buf), - sizeBytes: buf.length - }; - }); - const signature = computeReceiptSignature(input.taskID, input.agent, timestamp, files); - const receiptId = `rcpt_${signature.slice(0, 16)}`; - let status = "UNVERIFIED"; - if (input.testSlice) { - status = input.testSlice.exitCode === 0 ? "VERIFIED" : "FAILED"; - } - const receipt = { - receiptId, - taskID: input.taskID, - agent: input.agent, - status, - files, - testSlice: input.testSlice, - timestamp, - signature - }; - getSharedBus().emit("agent:execution:receipt", receipt); - return receipt; -} - -// src/pantheon/themis-reflex.ts -var ThemisReflexController = class { - states = /* @__PURE__ */ new Map(); - maxRetries; - constructor(options = {}) { - this.maxRetries = options.maxRetries ?? 2; - } - /** - * Evaluate a task execution result against Themis verification findings. - * If discrepancies are found and attempts remain, returns an actionable retry directive. - */ - evaluate(taskID, agent, discrepancies) { - if (discrepancies.length === 0) { - const existing = this.states.get(taskID); - if (existing) { - getSharedBus().emit("themis:reflex:resolved", { - taskID, - agent, - file: existing.discrepancies[0]?.file ?? "", - error: "", - attempt: existing.attempt, - maxAttempts: this.maxRetries, - timestamp: Date.now(), - resolved: true - }); - this.states.delete(taskID); - } - return { action: "pass", verdict: "PASS" }; - } - let state = this.states.get(taskID); - if (!state) { - state = { - taskID, - agent, - attempt: 0, - maxAttempts: this.maxRetries, - discrepancies: [...discrepancies], - timestamp: Date.now() - }; - this.states.set(taskID, state); - } - state.attempt += 1; - state.discrepancies = [...discrepancies]; - state.timestamp = Date.now(); - const firstDisc = discrepancies[0]; - getSharedBus().emit("themis:reflex:discrepancy", { - taskID, - agent, - file: firstDisc?.file ?? "unknown", - error: firstDisc?.error ?? "unspecified", - attempt: state.attempt, - maxAttempts: this.maxRetries, - timestamp: state.timestamp - }); - if (state.attempt <= this.maxRetries) { - const prompt = this.formatReflexPrompt(state.attempt, this.maxRetries, discrepancies); - return { - action: "retry", - prompt, - attempt: state.attempt, - maxAttempts: this.maxRetries - }; - } - this.states.delete(taskID); - return { - action: "escalate", - verdict: "FAIL", - reason: `themis.reflex.exhausted:${state.attempt - 1}_retries_failed`, - attempts: state.attempt - }; - } - /** - * Format an inline, high-density reflex prompt directing the implementer to self-heal. - */ - formatReflexPrompt(attempt, maxAttempts, discrepancies) { - const lines = [ - `[THEMIS INLINE REFLEX \u2014 Attempt ${attempt}/${maxAttempts}]`, - "Themis automated audit detected discrepancies in your edits. Fix them directly before returning:" - ]; - for (const d of discrepancies) { - lines.push(`- File: ${d.file}`); - lines.push(` Error: ${d.error}`); - if (d.expected) lines.push(` Expected: ${d.expected}`); - if (d.actual) lines.push(` Actual: ${d.actual}`); - if (d.suggestedFix) lines.push(` Fix hint: ${d.suggestedFix}`); - } - lines.push("Do NOT escalate to Zeus yet. Apply the targeted fix and re-verify your slice."); - return lines.join("\n"); - } - /** Reset state for a taskID */ - reset(taskID) { - this.states.delete(taskID); - } -}; +import { join as join26 } from "node:path"; // src/pantheon/deepwork/plan-schema.ts import { z as z2 } from "zod"; @@ -14349,7 +16252,7 @@ var DeepworkPlanSchema = z2.object({ // src/pantheon/deepwork/plan-tracker.ts function deepworkRootDir(cwd = process.cwd()) { - return join19(cwd, ".pantheon", "deepwork"); + return join26(cwd, ".pantheon", "deepwork"); } function deepworkPlanDir(cwd = process.cwd(), slug) { const safeSlug = String(slug ?? "").trim(); @@ -14358,16 +16261,16 @@ function deepworkPlanDir(cwd = process.cwd(), slug) { `Invalid deepwork plan slug "${slug}": path traversal or separator characters are not allowed` ); } - return join19(deepworkRootDir(cwd), safeSlug); + return join26(deepworkRootDir(cwd), safeSlug); } function deepworkPlanJsonPath(cwd = process.cwd(), slug) { - return join19(deepworkPlanDir(cwd, slug), "plan.json"); + return join26(deepworkPlanDir(cwd, slug), "plan.json"); } function deepworkPlanMdPath(cwd = process.cwd(), slug) { - return join19(deepworkPlanDir(cwd, slug), "PLAN.md"); + return join26(deepworkPlanDir(cwd, slug), "PLAN.md"); } function deepworkJournalPath(cwd = process.cwd(), slug) { - return join19(deepworkPlanDir(cwd, slug), "journal.ndjson"); + return join26(deepworkPlanDir(cwd, slug), "journal.ndjson"); } function computeTaskReadiness(plan) { const doneIds = new Set(plan.tasks.filter((t) => t.state === "done").map((t) => t.id)); @@ -14564,8 +16467,8 @@ async function withPlanLock(cwd, slug, fn) { const key = `${cwd}::${slug}`; const prev = planLocks.get(key) ?? Promise.resolve(); let resolveCurrent; - const current = new Promise((resolve14) => { - resolveCurrent = resolve14; + const current = new Promise((resolve23) => { + resolveCurrent = resolve23; }); planLocks.set(key, current); try { @@ -14748,7 +16651,7 @@ async function resolvePlanDecision(cwd = process.cwd(), slug, decisionId, chosen } async function listPlans(cwd = process.cwd()) { const root = deepworkRootDir(cwd); - if (!existsSync12(root)) return []; + if (!existsSync18(root)) return []; const entries = await readdir(root, { withFileTypes: true }); const result = []; for (const entry of entries) { @@ -15048,7 +16951,7 @@ ${JSON.stringify(todoPayload, null, 2)} // src/pantheon/hashline/tool.ts import { readFile as readFile7, rename as rename6, rm, writeFile as writeFile4 } from "node:fs/promises"; -import { isAbsolute as isAbsolute4, resolve as resolve10, sep as sep6 } from "node:path"; +import { isAbsolute as isAbsolute4, resolve as resolve18, sep as sep9 } from "node:path"; import { z as z4 } from "zod"; var hashlineEditOpArgs = { op: z4.enum(["replace", "append", "prepend", "delete"]), @@ -15061,11 +16964,11 @@ var hashlineEditArgs = { file: z4.string().min(1), edits: z4.array(z4.object(hashlineEditOpArgs)).min(1) }; -function resolveFile(file, ctx) { - if (isAbsolute4(file)) return { ok: true, file: resolve10(file) }; - const base = resolve10(ctx.worktree ?? ctx.directory ?? process.cwd()); - const resolved = resolve10(base, file); - if (resolved !== base && !resolved.startsWith(base + sep6)) { +function resolveFile(file, ctx, fallbackDir) { + if (isAbsolute4(file)) return { ok: true, file: resolve18(file) }; + const base = resolve18(resolveToolCwd(ctx, fallbackDir)); + const resolved = resolve18(base, file); + if (resolved !== base && !resolved.startsWith(base + sep9)) { return { ok: false, error: `hashline_edit: file "${file}" escapes the worktree (resolved to "${resolved}") \u2014 path containment denied` @@ -15121,12 +17024,12 @@ function validateEdits(args, file, lines) { } return resolved; } -function createHashlineEditTool() { +function createHashlineEditTool(fallbackDir) { return { description: "Edit a file anchored by hashline refs (LINE#TAG) instead of raw line numbers. Ops: replace (ref..endRef or single ref \u2192 lines), append/prepend (anchor ref \u2192 content), delete (ref..endRef). ALL refs must be validated against the ORIGINAL file before anything is written; on mismatch the tool returns an error with a re-tagged excerpt and a Did-you-mean suggestion, and nothing is modified.", args: hashlineEditArgs, execute: async (args, ctx) => { - const resolved = resolveFile(args.file, ctx); + const resolved = resolveFile(args.file, ctx, fallbackDir); if (!resolved.ok) return resolved.error; const file = resolved.file; let original; @@ -15223,7 +17126,7 @@ function evaluateComplexityPoint(input, sink) { } // src/pantheon/local-decision-tool.ts -var TOOL_DESCRIPTION2 = "Zeus-only local advisory selector. Use selectively only when specialist routing is genuinely ambiguous; obvious work should go directly to native subagent without this tool. Accepts only structured candidate IDs, never task text. It does not dispatch, run a skill/resource, search memory, or authorize/alter grants or review gates. Provider egress is disabled; all decisions remain local."; +var TOOL_DESCRIPTION2 = "Zeus-only local advisory selector. Use selectively only when specialist routing is genuinely ambiguous; obvious work should go directly to native subagent without this tool. Accepts only a structured object { schemaVersion: 1, candidateAgents, domain, candidateSkillIds, candidateResourceIds, memorySearchRelevant, gateStatus, complexity: { boundedness, reversibility, dependencies, uncertainty, verification } } \u2014 never raw prompt strings. Does not dispatch or alter review gates; provider egress is disabled."; var gateStatuses = [ "none", "review_required", @@ -15315,7 +17218,7 @@ import { randomBytes } from "node:crypto"; import { constants as constants4 } from "node:fs"; import { lstat as lstat2, mkdir as mkdir7, open as open3, rename as rename7, unlink as unlink4 } from "node:fs/promises"; import { homedir as homedir7 } from "node:os"; -import { basename as basename2, dirname as dirname11, join as join20, resolve as resolve11 } from "node:path"; +import { basename as basename4, dirname as dirname13, join as join27, resolve as resolve19 } from "node:path"; import { z as z5 } from "zod"; var MODEL_REF_PATTERN2 = /^[A-Za-z0-9][A-Za-z0-9._-]*\/[A-Za-z0-9][A-Za-z0-9._:+-]*$/; var SAFE_PRESET_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; @@ -15400,11 +17303,11 @@ async function syncDirectory(path5) { } } async function createTemporaryFile(path5) { - const directory = dirname11(path5); - const prefix = `.${basename2(path5)}.tmp-`; + const directory = dirname13(path5); + const prefix = `.${basename4(path5)}.tmp-`; const flags = constants4.O_WRONLY | constants4.O_CREAT | constants4.O_EXCL | NO_FOLLOW; for (let attempt = 0; attempt < 10; attempt += 1) { - const temporaryPath = join20(directory, `${prefix}${randomBytes(16).toString("hex")}`); + const temporaryPath = join27(directory, `${prefix}${randomBytes(16).toString("hex")}`); try { return { path: temporaryPath, file: await open3(temporaryPath, flags, DEFAULT_FILE_MODE) }; } catch (error) { @@ -15440,7 +17343,7 @@ async function atomicReplace(path5, content, mode, label, expectedExists) { } await rename7(temporaryPath, path5); renamed = true; - await syncDirectory(dirname11(path5)); + await syncDirectory(dirname13(path5)); } finally { await temporaryFile?.close().catch(() => void 0); if (temporaryPath !== void 0 && !renamed) { @@ -15471,30 +17374,30 @@ function envValue(options) { return options.env ?? process.env; } function projectConfigPath(options) { - return options.projectConfigPath ?? join20(options.cwd ?? process.cwd(), "opencode.json"); + return options.projectConfigPath ?? join27(options.cwd ?? process.cwd(), "opencode.json"); } function defaultGlobalConfigPath(options) { const env = envValue(options); const home = env.HOME?.trim() || homedir7(); - const xdg = env.XDG_CONFIG_HOME?.trim() || join20(home, ".config"); - return join20(xdg, "opencode", "opencode.json"); + const xdg = env.XDG_CONFIG_HOME?.trim() || join27(home, ".config"); + return join27(xdg, "opencode", "opencode.json"); } function globalConfigCandidates(options) { if (options.globalConfigPath !== void 0) return [options.globalConfigPath]; const canonical = defaultGlobalConfigPath(options); const home = envValue(options).HOME?.trim() || homedir7(); - const legacy = join20(home, ".opencode", "opencode.json"); + const legacy = join27(home, ".opencode", "opencode.json"); return [.../* @__PURE__ */ new Set([canonical, legacy])]; } function activePresetCandidatesList(options) { if (options.activePresetCandidates !== void 0) { - return options.activePresetCandidates.map((p) => resolve11(p)); + return options.activePresetCandidates.map((p) => resolve19(p)); } - const projectPreset = join20(dirname11(projectConfigPath(options)), ".pantheon", "active-preset.json"); + const projectPreset = join27(dirname13(projectConfigPath(options)), ".pantheon", "active-preset.json"); const globalPresets = globalConfigCandidates(options).map( - (p) => join20(dirname11(p), ".pantheon", "active-preset.json") + (p) => join27(dirname13(p), ".pantheon", "active-preset.json") ); - return [...new Set([projectPreset, ...globalPresets].map((p) => resolve11(p)))]; + return [...new Set([projectPreset, ...globalPresets].map((p) => resolve19(p)))]; } function presetPathForScope(options, scope) { const candidates = activePresetCandidatesList(options); @@ -15506,7 +17409,7 @@ function presetPathForScope(options, scope) { const second = candidates[1]; if (second) return second; const globalCandidates = globalConfigCandidates(options).map( - (p) => resolve11(join20(dirname11(p), ".pantheon", "active-preset.json")) + (p) => resolve19(join27(dirname13(p), ".pantheon", "active-preset.json")) ); const fallback = globalCandidates[0] ?? candidates[0]; if (!fallback) throw new ModelCommandError("global preset path is unavailable"); @@ -15636,7 +17539,7 @@ function validateMutationAuthorization(args, scope) { } async function writeActivePresetAtomically(path5, data, current) { const backupPath = `${path5}.bak`; - await mkdir7(dirname11(path5), { recursive: true }); + await mkdir7(dirname13(path5), { recursive: true }); const originalMode = current.mode ?? DEFAULT_FILE_MODE; const backupMode = originalMode & 384; const backup = await regularPath(backupPath, "configuration backup"); @@ -16064,25 +17967,175 @@ function createModelCommand(options = {}) { // src/pantheon/native-memory-tools.ts import { - existsSync as existsSync13, - mkdirSync as mkdirSync9, - readdirSync as readdirSync5, - readFileSync as readFileSync11, - realpathSync as realpathSync5, - writeFileSync as writeFileSync7 + existsSync as existsSync20, + mkdirSync as mkdirSync12, + readdirSync as readdirSync6, + readFileSync as readFileSync18, + realpathSync as realpathSync9, + writeFileSync as writeFileSync10 } from "node:fs"; -import { join as join21, resolve as resolve12, sep as sep7 } from "node:path"; +import { join as join29, resolve as resolve21, sep as sep10 } from "node:path"; +import { DatabaseSync as DatabaseSync5 } from "node:sqlite"; + +// src/pantheon/memory-federation.ts +import { existsSync as existsSync19, readFileSync as readFileSync17, realpathSync as realpathSync8 } from "node:fs"; +import { homedir as homedir8 } from "node:os"; +import { basename as basename5, join as join28, resolve as resolve20 } from "node:path"; import { DatabaseSync as DatabaseSync4 } from "node:sqlite"; +var NOT_EXPIRED_SQL = "(expires_at IS NULL OR expires_at > ?)"; +function safeRealpath(dir) { + try { + return realpathSync8(dir); + } catch { + return resolve20(dir); + } +} +function resolveFederatedRepoDirs(primaryWorkspaceDir, options = {}) { + const candidates = []; + if (Array.isArray(options.explicitRepos)) { + candidates.push(...options.explicitRepos); + } + const rawEnv = options.federatedEnv ?? process.env.PANTHEON_FEDERATED_REPOS ?? ""; + if (rawEnv.trim()) { + for (const part of rawEnv.split(/[,;]/)) { + const trimmed = part.trim(); + if (trimmed) candidates.push(trimmed); + } + } + const manifestFile = options.manifestPath ?? join28(homedir8(), ".pantheon", "federation.json"); + if (existsSync19(manifestFile)) { + try { + const parsed = JSON.parse(readFileSync17(manifestFile, "utf8")); + if (Array.isArray(parsed.repos)) { + for (const item of parsed.repos) { + if (typeof item === "string" && item.trim()) candidates.push(item.trim()); + } + } + } catch { + } + } + const primaryStore = safeRealpath(resolveSharedPantheonRoot(primaryWorkspaceDir)); + const seenStores = /* @__PURE__ */ new Set([primaryStore]); + const peers = []; + for (const candidate of candidates) { + const abs = resolve20(candidate); + if (!existsSync19(abs)) continue; + const peerStore = safeRealpath(resolveSharedPantheonRoot(abs)); + if (seenStores.has(peerStore)) continue; + const dbPath = join28(peerStore, ".pantheon", "memory", "memory.db"); + if (!existsSync19(dbPath)) continue; + seenStores.add(peerStore); + peers.push(peerStore); + } + return peers; +} +function querySinglePeerDb(peerRoot, rawQuery, nowIso, limit, namespace) { + const dbPath = join28(peerRoot, ".pantheon", "memory", "memory.db"); + if (!existsSync19(dbPath)) return []; + const repoName = basename5(peerRoot) || peerRoot; + let db; + try { + db = new DatabaseSync4(dbPath, { readOnly: true }); + const tokens = rawQuery.replace(/[^\p{L}\p{N}_-]+/gu, " ").trim().split(/\s+/).filter((t) => t.length >= 2); + if (tokens.length > 0) { + try { + const ftsExpr = tokens.map((t) => `"${t.replace(/"/g, '""')}"*`).join(" OR "); + let ftsSql = ` + SELECT m.namespace, m.key, m.value, m.metadata, m.created_at, bm25(memories_fts) AS score + FROM memories_fts + JOIN memories m ON m.id = memories_fts.rowid + WHERE memories_fts MATCH ? AND (m.expires_at IS NULL OR m.expires_at > ?) + `; + const ftsParams = [ftsExpr, nowIso]; + if (namespace) { + ftsSql += " AND m.namespace = ?"; + ftsParams.push(namespace); + } + ftsSql += " ORDER BY score LIMIT ?"; + ftsParams.push(limit); + const rows2 = db.prepare(ftsSql).all(...ftsParams); + if (rows2.length > 0) { + return rows2.map((r) => ({ ...r, sourceRepo: repoName, sourcePath: peerRoot })); + } + } catch { + } + } + const escaped = rawQuery.replace(/[\\%_]/g, "\\$&"); + let sql = ` + SELECT namespace, key, value, metadata, created_at + FROM memories + WHERE (value LIKE ? ESCAPE '\\' OR key LIKE ? ESCAPE '\\') + AND ${NOT_EXPIRED_SQL} + `; + const params = [`%${escaped}%`, `%${escaped}%`, nowIso]; + if (namespace) { + sql += " AND namespace = ?"; + params.push(namespace); + } + sql += " ORDER BY id DESC LIMIT ?"; + params.push(limit); + const rows = db.prepare(sql).all(...params); + return rows.map((r) => ({ ...r, sourceRepo: repoName, sourcePath: peerRoot })); + } catch { + return []; + } finally { + try { + db?.close(); + } catch { + } + } +} +function searchFederatedMemories(primaryWorkspaceDir, query, options = {}) { + const peers = resolveFederatedRepoDirs(primaryWorkspaceDir, options); + if (peers.length === 0) return []; + const nowIso = (/* @__PURE__ */ new Date()).toISOString(); + const limit = Math.max(1, Math.min(options.limit ?? 10, 100)); + const results = []; + for (const peer of peers) { + const hits = querySinglePeerDb(peer, query, nowIso, limit, options.namespace); + results.push(...hits); + if (results.length >= limit) break; + } + return results.slice(0, limit); +} +function getFederatedStats(primaryWorkspaceDir, options = {}) { + const peers = resolveFederatedRepoDirs(primaryWorkspaceDir, options); + const nowIso = (/* @__PURE__ */ new Date()).toISOString(); + const repos = []; + let total = 0; + for (const peer of peers) { + const dbPath = join28(peer, ".pantheon", "memory", "memory.db"); + let count = 0; + let db; + try { + db = new DatabaseSync4(dbPath, { readOnly: true }); + const row = db.prepare(`SELECT count(*) as count FROM memories WHERE ${NOT_EXPIRED_SQL}`).get(nowIso); + count = typeof row?.count === "number" ? row.count : 0; + } catch { + count = 0; + } finally { + try { + db?.close(); + } catch { + } + } + repos.push({ repo: basename5(peer) || peer, path: peer, total: count }); + total += count; + } + return { total, repos }; +} + +// src/pantheon/native-memory-tools.ts var SAFE_SEGMENT_RE2 = /^[a-zA-Z0-9._:-]{1,128}$/; var MAX_MEMORY_VALUE_BYTES = 65536; function isSafeSegment(value) { return typeof value === "string" && SAFE_SEGMENT_RE2.test(value) && value !== "." && value !== ".." && !value.includes("..") && !value.includes("/") && !value.includes("\\"); } function resolveConfinedPath(baseDir, ...segments) { - mkdirSync9(baseDir, { recursive: true }); - const canonicalBase = realpathSync5(baseDir); - const candidate = resolve12(canonicalBase, ...segments); - const prefix = canonicalBase.endsWith(sep7) ? canonicalBase : `${canonicalBase}${sep7}`; + mkdirSync12(baseDir, { recursive: true }); + const canonicalBase = realpathSync9(baseDir); + const candidate = resolve21(canonicalBase, ...segments); + const prefix = canonicalBase.endsWith(sep10) ? canonicalBase : `${canonicalBase}${sep10}`; if (candidate !== canonicalBase && !candidate.startsWith(prefix)) { throw new Error("Path traversal denied: target escapes confined directory"); } @@ -16098,12 +18151,12 @@ function runAutoMigration(workspaceDir) { } function getMemoryDb(workspaceDir) { runAutoMigration(workspaceDir); - const memoryDir = join21(workspaceDir, ".pantheon", "memory"); - mkdirSync9(memoryDir, { recursive: true }); + const memoryDir = join29(workspaceDir, ".pantheon", "memory"); + mkdirSync12(memoryDir, { recursive: true }); const dbPath = resolveConfinedPath(memoryDir, "memory.db"); const cached = dbCache.get(dbPath); if (cached) return cached; - const db = new DatabaseSync4(dbPath); + const db = new DatabaseSync5(dbPath); db.exec(` PRAGMA busy_timeout = 3000; PRAGMA journal_mode = WAL; @@ -16149,10 +18202,10 @@ function getMemoryDb(workspaceDir) { dbCache.set(dbPath, db); return db; } -function jsonResult3(payload) { +function jsonResult5(payload) { return { output: JSON.stringify(payload) }; } -var NOT_EXPIRED_SQL = "(expires_at IS NULL OR expires_at > ?)"; +var NOT_EXPIRED_SQL2 = "(expires_at IS NULL OR expires_at > ?)"; function createNativeMemoryAndPersistenceTools(fallbackDir) { return [ { @@ -16177,21 +18230,21 @@ function createNativeMemoryAndPersistenceTools(fallbackDir) { const key = input.key; const value = input.value; if (typeof ns !== "string" || !ns.trim() || typeof key !== "string" || !key.trim()) { - return jsonResult3({ + return jsonResult5({ ok: false, error: "namespace and key are required non-empty strings" }); } if (typeof value !== "string" || !value.trim()) { - return jsonResult3({ + return jsonResult5({ ok: false, error: "value is required and must be a non-empty string" }); } if (Buffer.byteLength(value, "utf8") > MAX_MEMORY_VALUE_BYTES) { - return jsonResult3({ ok: false, error: "value exceeds maximum size of 64 KiB" }); + return jsonResult5({ ok: false, error: "value exceeds maximum size of 64 KiB" }); } - const cwd = resolveToolCwd(context, fallbackDir); + const cwd = resolveMemoryStoreCwd(context, fallbackDir); const db = getMemoryDb(cwd); const nowIso = (/* @__PURE__ */ new Date()).toISOString(); db.prepare( @@ -16210,9 +18263,9 @@ function createNativeMemoryAndPersistenceTools(fallbackDir) { nowIso, typeof input.expires_at === "string" ? input.expires_at : null ); - return jsonResult3({ ok: true, status: "stored", namespace: ns.trim(), key: key.trim() }); + return jsonResult5({ ok: true, status: "stored", namespace: ns.trim(), key: key.trim() }); } catch (err) { - return jsonResult3({ + return jsonResult5({ ok: false, error: err instanceof Error ? err.message : String(err) }); @@ -16237,19 +18290,19 @@ function createNativeMemoryAndPersistenceTools(fallbackDir) { const ns = input.namespace; const key = input.key; if (typeof ns !== "string" || !ns.trim() || typeof key !== "string" || !key.trim()) { - return jsonResult3({ ok: false, error: "namespace and key are required" }); + return jsonResult5({ ok: false, error: "namespace and key are required" }); } - const cwd = resolveToolCwd(context, fallbackDir); + const cwd = resolveMemoryStoreCwd(context, fallbackDir); const db = getMemoryDb(cwd); const nowIso = (/* @__PURE__ */ new Date()).toISOString(); const row = db.prepare( `SELECT namespace, key, value, metadata, created_at, expires_at FROM memories - WHERE namespace = ? AND key = ? AND ${NOT_EXPIRED_SQL}` + WHERE namespace = ? AND key = ? AND ${NOT_EXPIRED_SQL2}` ).get(ns.trim(), key.trim(), nowIso); - return jsonResult3(row ?? { ok: false, error: "not_found" }); + return jsonResult5(row ?? { ok: false, error: "not_found" }); } catch (err) { - return jsonResult3({ + return jsonResult5({ ok: false, error: err instanceof Error ? err.message : String(err) }); @@ -16266,7 +18319,11 @@ function createNativeMemoryAndPersistenceTools(fallbackDir) { properties: { query: { type: "string", description: "Search query terms" }, namespace: { type: "string", description: "Optional namespace filter" }, - top_k: { type: "number", description: "Maximum results to return (default 10)" } + top_k: { type: "number", description: "Maximum results to return (default 10)" }, + federated: { + type: "boolean", + description: "Include federated peer repositories (default true when configured)" + } } }, output: {}, @@ -16274,14 +18331,17 @@ function createNativeMemoryAndPersistenceTools(fallbackDir) { try { const rawQuery = typeof input.query === "string" ? input.query.trim() : ""; if (!rawQuery) { - return jsonResult3({ ok: false, error: "query is required", count: 0, results: [] }); + return jsonResult5({ ok: false, error: "query is required", count: 0, results: [] }); } const limit = typeof input.top_k === "number" && Number.isFinite(input.top_k) && input.top_k > 0 ? Math.min(Math.floor(input.top_k), 100) : 10; const ns = typeof input.namespace === "string" && input.namespace.trim() ? input.namespace.trim() : void 0; - const cwd = resolveToolCwd(context, fallbackDir); + const useFederated = input.federated !== false; + const cwd = resolveMemoryStoreCwd(context, fallbackDir); const db = getMemoryDb(cwd); const nowIso = (/* @__PURE__ */ new Date()).toISOString(); const tokens = rawQuery.replace(/[^\p{L}\p{N}_-]+/gu, " ").trim().split(/\s+/).filter((t) => t.length >= 2); + let localRows = []; + let matchedFts = false; if (tokens.length > 0) { try { const ftsExpr = tokens.map((t) => `"${t.replace(/"/g, '""')}"*`).join(" OR "); @@ -16298,31 +18358,40 @@ function createNativeMemoryAndPersistenceTools(fallbackDir) { } ftsSql += " ORDER BY score LIMIT ?"; ftsParams.push(limit); - const rows2 = db.prepare(ftsSql).all(...ftsParams); - if (rows2.length > 0) { - return jsonResult3({ ok: true, count: rows2.length, results: rows2 }); + const rows = db.prepare(ftsSql).all(...ftsParams); + if (rows.length > 0) { + localRows = rows; + matchedFts = true; } } catch { } } - const escaped = rawQuery.replace(/[\\%_]/g, "\\$&"); - let sql = ` - SELECT namespace, key, value, metadata, created_at - FROM memories - WHERE (value LIKE ? ESCAPE '\\' OR key LIKE ? ESCAPE '\\') - AND ${NOT_EXPIRED_SQL} - `; - const params = [`%${escaped}%`, `%${escaped}%`, nowIso]; - if (ns) { - sql += " AND namespace = ?"; - params.push(ns); + if (!matchedFts) { + const escaped = rawQuery.replace(/[\\%_]/g, "\\$&"); + let sql = ` + SELECT namespace, key, value, metadata, created_at + FROM memories + WHERE (value LIKE ? ESCAPE '\\' OR key LIKE ? ESCAPE '\\') + AND ${NOT_EXPIRED_SQL2} + `; + const params = [`%${escaped}%`, `%${escaped}%`, nowIso]; + if (ns) { + sql += " AND namespace = ?"; + params.push(ns); + } + sql += " ORDER BY id DESC LIMIT ?"; + params.push(limit); + localRows = db.prepare(sql).all(...params); } - sql += " ORDER BY id DESC LIMIT ?"; - params.push(limit); - const rows = db.prepare(sql).all(...params); - return jsonResult3({ ok: true, count: rows.length, results: rows }); + const remaining = Math.max(0, limit - localRows.length); + const peerRows = useFederated && remaining > 0 ? searchFederatedMemories(cwd, rawQuery, { + ...ns ? { namespace: ns } : {}, + limit: remaining + }) : []; + const combined = [...localRows, ...peerRows]; + return jsonResult5({ ok: true, count: combined.length, results: combined }); } catch (err) { - return jsonResult3({ + return jsonResult5({ ok: false, error: err instanceof Error ? err.message : String(err) }); @@ -16347,19 +18416,19 @@ function createNativeMemoryAndPersistenceTools(fallbackDir) { const ns = input.namespace; const key = input.key; if (typeof ns !== "string" || !ns.trim() || typeof key !== "string" || !key.trim()) { - return jsonResult3({ ok: false, error: "namespace and key are required" }); + return jsonResult5({ ok: false, error: "namespace and key are required" }); } - const cwd = resolveToolCwd(context, fallbackDir); + const cwd = resolveMemoryStoreCwd(context, fallbackDir); const db = getMemoryDb(cwd); const info = db.prepare("DELETE FROM memories WHERE namespace = ? AND key = ?").run(ns.trim(), key.trim()); - return jsonResult3({ + return jsonResult5({ ok: true, deleted: info.changes > 0, namespace: ns.trim(), key: key.trim() }); } catch (err) { - return jsonResult3({ + return jsonResult5({ ok: false, error: err instanceof Error ? err.message : String(err) }); @@ -16380,11 +18449,11 @@ function createNativeMemoryAndPersistenceTools(fallbackDir) { output: {}, execute: async (input, context) => { try { - const cwd = resolveToolCwd(context, fallbackDir); + const cwd = resolveMemoryStoreCwd(context, fallbackDir); const db = getMemoryDb(cwd); const nowIso = (/* @__PURE__ */ new Date()).toISOString(); const limit = typeof input.limit === "number" && Number.isFinite(input.limit) && input.limit > 0 ? Math.min(Math.floor(input.limit), 200) : 50; - let sql = `SELECT namespace, key, created_at FROM memories WHERE ${NOT_EXPIRED_SQL}`; + let sql = `SELECT namespace, key, created_at FROM memories WHERE ${NOT_EXPIRED_SQL2}`; const params = [nowIso]; if (typeof input.namespace === "string" && input.namespace.trim()) { sql += " AND namespace = ?"; @@ -16393,9 +18462,9 @@ function createNativeMemoryAndPersistenceTools(fallbackDir) { sql += " ORDER BY id DESC LIMIT ?"; params.push(limit); const rows = db.prepare(sql).all(...params); - return jsonResult3({ ok: true, count: rows.length, entries: rows }); + return jsonResult5({ ok: true, count: rows.length, entries: rows }); } catch (err) { - return jsonResult3({ + return jsonResult5({ ok: false, error: err instanceof Error ? err.message : String(err) }); @@ -16415,16 +18484,22 @@ function createNativeMemoryAndPersistenceTools(fallbackDir) { output: {}, execute: async (_input, context) => { try { - const cwd = resolveToolCwd(context, fallbackDir); + const cwd = resolveMemoryStoreCwd(context, fallbackDir); const db = getMemoryDb(cwd); const nowIso = (/* @__PURE__ */ new Date()).toISOString(); - const total = db.prepare(`SELECT count(*) as count FROM memories WHERE ${NOT_EXPIRED_SQL}`).get(nowIso); + const total = db.prepare(`SELECT count(*) as count FROM memories WHERE ${NOT_EXPIRED_SQL2}`).get(nowIso); const byNamespace = db.prepare( - `SELECT namespace, count(*) as count FROM memories WHERE ${NOT_EXPIRED_SQL} GROUP BY namespace` + `SELECT namespace, count(*) as count FROM memories WHERE ${NOT_EXPIRED_SQL2} GROUP BY namespace` ).all(nowIso); - return jsonResult3({ ok: true, total: total?.count ?? 0, byNamespace }); + const fed = getFederatedStats(cwd); + return jsonResult5({ + ok: true, + total: total?.count ?? 0, + byNamespace, + ...fed.repos.length > 0 ? { federated: fed } : {} + }); } catch (err) { - return jsonResult3({ + return jsonResult5({ ok: false, error: err instanceof Error ? err.message : String(err) }); @@ -16450,22 +18525,22 @@ function createNativeMemoryAndPersistenceTools(fallbackDir) { const sessionId = input.session_id; const ns = input.namespace ?? "checkpoints"; if (!isSafeSegment(sessionId) || !isSafeSegment(ns)) { - return jsonResult3({ + return jsonResult5({ ok: false, error: "session_id and namespace must be safe identifiers without path traversal" }); } if (typeof input.content !== "string" || !input.content.trim()) { - return jsonResult3({ ok: false, error: "content must be a non-empty string" }); + return jsonResult5({ ok: false, error: "content must be a non-empty string" }); } - const cwd = resolveToolCwd(context, fallbackDir); + const cwd = resolveMemoryStoreCwd(context, fallbackDir); runAutoMigration(cwd); - const baseDir = join21(cwd, ".pantheon", "persistence"); + const baseDir = join29(cwd, ".pantheon", "persistence"); const dir = resolveConfinedPath(baseDir, ns); - mkdirSync9(dir, { recursive: true }); + mkdirSync12(dir, { recursive: true }); const filePath = resolveConfinedPath(dir, `${sessionId}.json`); const nowIso = (/* @__PURE__ */ new Date()).toISOString(); - writeFileSync7( + writeFileSync10( filePath, JSON.stringify( { @@ -16479,14 +18554,14 @@ function createNativeMemoryAndPersistenceTools(fallbackDir) { ), "utf8" ); - return jsonResult3({ + return jsonResult5({ ok: true, status: "saved", session_id: sessionId, updated_at: nowIso }); } catch (err) { - return jsonResult3({ + return jsonResult5({ ok: false, error: err instanceof Error ? err.message : String(err) }); @@ -16511,32 +18586,32 @@ function createNativeMemoryAndPersistenceTools(fallbackDir) { const sessionId = input.session_id; const ns = input.namespace ?? "checkpoints"; if (!isSafeSegment(sessionId) || !isSafeSegment(ns)) { - return jsonResult3({ + return jsonResult5({ ok: false, error: "session_id and namespace must be safe identifiers without path traversal" }); } - const cwd = resolveToolCwd(context, fallbackDir); + const cwd = resolveMemoryStoreCwd(context, fallbackDir); runAutoMigration(cwd); - const baseDir = join21(cwd, ".pantheon", "persistence"); + const baseDir = join29(cwd, ".pantheon", "persistence"); const dir = resolveConfinedPath(baseDir, ns); const filePath = resolveConfinedPath(dir, `${sessionId}.json`); - if (!existsSync13(filePath)) { + if (!existsSync20(filePath)) { const globalDir = resolveSafeGlobalConfigDir(); if (globalDir) { - const globalNsDir = join21(globalDir, ".pantheon", "persistence", ns); - if (existsSync13(join21(globalNsDir, `${sessionId}.json`))) { + const globalNsDir = join29(globalDir, ".pantheon", "persistence", ns); + if (existsSync20(join29(globalNsDir, `${sessionId}.json`))) { const globalFile = resolveConfinedPath(globalNsDir, `${sessionId}.json`); - if (existsSync13(globalFile)) { - return jsonResult3(JSON.parse(readFileSync11(globalFile, "utf8"))); + if (existsSync20(globalFile)) { + return jsonResult5(JSON.parse(readFileSync18(globalFile, "utf8"))); } } } - return jsonResult3({ ok: false, error: "not_found", session_id: sessionId }); + return jsonResult5({ ok: false, error: "not_found", session_id: sessionId }); } - return jsonResult3(JSON.parse(readFileSync11(filePath, "utf8"))); + return jsonResult5(JSON.parse(readFileSync18(filePath, "utf8"))); } catch (err) { - return jsonResult3({ + return jsonResult5({ ok: false, error: err instanceof Error ? err.message : String(err) }); @@ -16564,14 +18639,14 @@ function createNativeMemoryAndPersistenceTools(fallbackDir) { execute: async (input, context) => { try { const title = typeof input.title === "string" ? input.title.trim() : ""; - if (!title) return jsonResult3({ ok: false, error: "title is required" }); + if (!title) return jsonResult5({ ok: false, error: "title is required" }); const rawId = typeof input.id === "string" && input.id.trim() ? input.id.trim() : `goal-${Date.now()}`; if (!isSafeSegment(rawId)) { - return jsonResult3({ ok: false, error: "id must be a safe identifier" }); + return jsonResult5({ ok: false, error: "id must be a safe identifier" }); } - const cwd = resolveToolCwd(context, fallbackDir); + const cwd = resolveMemoryStoreCwd(context, fallbackDir); runAutoMigration(cwd); - const goalsDir = join21(cwd, ".pantheon", "goals"); + const goalsDir = join29(cwd, ".pantheon", "goals"); const filePath = resolveConfinedPath(goalsDir, `${rawId}.json`); const nowIso = (/* @__PURE__ */ new Date()).toISOString(); const goal = { @@ -16582,10 +18657,10 @@ function createNativeMemoryAndPersistenceTools(fallbackDir) { created_at: nowIso, updated_at: nowIso }; - writeFileSync7(filePath, JSON.stringify(goal, null, 2), "utf8"); - return jsonResult3({ ok: true, goal }); + writeFileSync10(filePath, JSON.stringify(goal, null, 2), "utf8"); + return jsonResult5({ ok: true, goal }); } catch (err) { - return jsonResult3({ + return jsonResult5({ ok: false, error: err instanceof Error ? err.message : String(err) }); @@ -16605,25 +18680,25 @@ function createNativeMemoryAndPersistenceTools(fallbackDir) { output: {}, execute: async (input, context) => { try { - const cwd = resolveToolCwd(context, fallbackDir); + const cwd = resolveMemoryStoreCwd(context, fallbackDir); runAutoMigration(cwd); - const goalsDir = join21(cwd, ".pantheon", "goals"); - mkdirSync9(goalsDir, { recursive: true }); + const goalsDir = join29(cwd, ".pantheon", "goals"); + mkdirSync12(goalsDir, { recursive: true }); if (typeof input.id === "string" && input.id.trim()) { const id = input.id.trim(); if (!isSafeSegment(id)) { - return jsonResult3({ ok: false, error: "id must be a safe identifier" }); + return jsonResult5({ ok: false, error: "id must be a safe identifier" }); } const filePath = resolveConfinedPath(goalsDir, `${id}.json`); - if (!existsSync13(filePath)) return jsonResult3({ ok: false, error: "not_found", id }); - return jsonResult3(JSON.parse(readFileSync11(filePath, "utf8"))); + if (!existsSync20(filePath)) return jsonResult5({ ok: false, error: "not_found", id }); + return jsonResult5(JSON.parse(readFileSync18(filePath, "utf8"))); } - const files = readdirSync5(goalsDir).filter((f) => f.endsWith(".json")).sort(); + const files = readdirSync6(goalsDir).filter((f) => f.endsWith(".json")).sort(); const latest = files.at(-1); - if (!latest) return jsonResult3({ ok: false, error: "no_active_goals" }); - return jsonResult3(JSON.parse(readFileSync11(resolveConfinedPath(goalsDir, latest), "utf8"))); + if (!latest) return jsonResult5({ ok: false, error: "no_active_goals" }); + return jsonResult5(JSON.parse(readFileSync18(resolveConfinedPath(goalsDir, latest), "utf8"))); } catch (err) { - return jsonResult3({ + return jsonResult5({ ok: false, error: err instanceof Error ? err.message : String(err) }); @@ -16632,7 +18707,7 @@ function createNativeMemoryAndPersistenceTools(fallbackDir) { }, { name: "goal_update", - description: "Update progress or status on an active session goal.", + description: 'Update progress notes or status on an active session goal. Use "notes" (not "progress") for progress text.', input: { type: "object", additionalProperties: false, @@ -16640,7 +18715,7 @@ function createNativeMemoryAndPersistenceTools(fallbackDir) { properties: { id: { type: "string", description: "Goal identifier" }, status: { type: "string", description: "Updated status (active, paused, completed)" }, - notes: { type: "string", description: "Progress notes" } + notes: { type: "string", description: 'Progress notes (use "notes", not "progress")' } } }, output: {}, @@ -16648,24 +18723,24 @@ function createNativeMemoryAndPersistenceTools(fallbackDir) { try { const id = typeof input.id === "string" ? input.id.trim() : ""; if (!isSafeSegment(id)) { - return jsonResult3({ ok: false, error: "valid goal id is required" }); + return jsonResult5({ ok: false, error: "valid goal id is required" }); } - const cwd = resolveToolCwd(context, fallbackDir); + const cwd = resolveMemoryStoreCwd(context, fallbackDir); runAutoMigration(cwd); - const goalsDir = join21(cwd, ".pantheon", "goals"); + const goalsDir = join29(cwd, ".pantheon", "goals"); const filePath = resolveConfinedPath(goalsDir, `${id}.json`); - if (!existsSync13(filePath)) return jsonResult3({ ok: false, error: "not_found", id }); - const existing = JSON.parse(readFileSync11(filePath, "utf8")); + if (!existsSync20(filePath)) return jsonResult5({ ok: false, error: "not_found", id }); + const existing = JSON.parse(readFileSync18(filePath, "utf8")); const updated = { ...existing, status: typeof input.status === "string" ? input.status : existing.status, ...typeof input.notes === "string" ? { notes: input.notes } : {}, updated_at: (/* @__PURE__ */ new Date()).toISOString() }; - writeFileSync7(filePath, JSON.stringify(updated, null, 2), "utf8"); - return jsonResult3({ ok: true, goal: updated }); + writeFileSync10(filePath, JSON.stringify(updated, null, 2), "utf8"); + return jsonResult5({ ok: true, goal: updated }); } catch (err) { - return jsonResult3({ + return jsonResult5({ ok: false, error: err instanceof Error ? err.message : String(err) }); @@ -16689,24 +18764,24 @@ function createNativeMemoryAndPersistenceTools(fallbackDir) { try { const id = typeof input.id === "string" ? input.id.trim() : ""; if (!isSafeSegment(id)) { - return jsonResult3({ ok: false, error: "valid goal id is required" }); + return jsonResult5({ ok: false, error: "valid goal id is required" }); } - const cwd = resolveToolCwd(context, fallbackDir); + const cwd = resolveMemoryStoreCwd(context, fallbackDir); runAutoMigration(cwd); - const goalsDir = join21(cwd, ".pantheon", "goals"); + const goalsDir = join29(cwd, ".pantheon", "goals"); const filePath = resolveConfinedPath(goalsDir, `${id}.json`); - if (!existsSync13(filePath)) return jsonResult3({ ok: false, error: "not_found", id }); - const existing = JSON.parse(readFileSync11(filePath, "utf8")); + if (!existsSync20(filePath)) return jsonResult5({ ok: false, error: "not_found", id }); + const existing = JSON.parse(readFileSync18(filePath, "utf8")); const updated = { ...existing, status: "completed", ...typeof input.summary === "string" ? { summary: input.summary } : {}, updated_at: (/* @__PURE__ */ new Date()).toISOString() }; - writeFileSync7(filePath, JSON.stringify(updated, null, 2), "utf8"); - return jsonResult3({ ok: true, goal: updated }); + writeFileSync10(filePath, JSON.stringify(updated, null, 2), "utf8"); + return jsonResult5({ ok: true, goal: updated }); } catch (err) { - return jsonResult3({ + return jsonResult5({ ok: false, error: err instanceof Error ? err.message : String(err) }); @@ -16716,14 +18791,159 @@ function createNativeMemoryAndPersistenceTools(fallbackDir) { ]; } +// src/pantheon/review-verdict.ts +var MAX_AUTO_REMEDIATIONS = 2; +function jsonResult6(payload) { + return { output: JSON.stringify(payload) }; +} +function normalizeFindings(raw) { + if (!Array.isArray(raw)) return []; + const out = []; + for (const item of raw) { + if (!item || typeof item !== "object") continue; + const rec = item; + const msg = typeof rec.message === "string" ? rec.message.trim() : ""; + if (!msg) continue; + const sev = rec.severity === "critical" || rec.severity === "major" || rec.severity === "minor" ? rec.severity : "major"; + out.push({ + severity: sev, + ...typeof rec.file === "string" && rec.file.trim() ? { file: rec.file.trim() } : {}, + message: msg, + ...typeof rec.suggestion === "string" && rec.suggestion.trim() ? { suggestion: rec.suggestion.trim() } : {} + }); + } + return out; +} +function formatRemediationPrompt(params) { + const lines = [ + `[THEMIS REVIEW ${params.verdict} \u2014 AUTO REMEDIATION]`, + `Target specialist: @${params.targetAgent}`, + `Summary: ${params.summary}` + ]; + if (params.findings.length > 0) { + lines.push("Findings to fix:"); + for (const f of params.findings) { + const loc = f.file ? ` (${f.file})` : ""; + const fix = f.suggestion ? ` \u2014 Fix: ${f.suggestion}` : ""; + lines.push(`- [${f.severity}]${loc} ${f.message}${fix}`); + } + } + lines.push("Remediate the blocking issues above and re-run targeted verification."); + return lines.join("\n"); +} +function createReviewVerdictTool(sessionDomain) { + const remediationCounts = /* @__PURE__ */ new Map(); + return { + name: "pantheon_review_verdict", + description: "Emit a structured Themis review verdict (APPROVE | APPROVE_WITH_NOTES | BLOCK) with typed findings. Emits a reactive PantheonBus event and dispatches bounded synthetic remediation when verdict is BLOCK.", + input: { + type: "object", + additionalProperties: false, + required: ["verdict", "summary"], + properties: { + verdict: { + type: "string", + enum: ["APPROVE", "APPROVE_WITH_NOTES", "BLOCK"], + description: "Final structured review verdict" + }, + summary: { type: "string", description: "Concise review verdict summary" }, + targetAgent: { + type: "string", + description: "Specialist agent responsible for remediation (e.g. hermes, aphrodite)" + }, + stepKey: { type: "string", description: "Optional associated step-ledger key" }, + findings: { + type: "array", + description: "Structured review findings", + items: { + type: "object", + properties: { + severity: { type: "string", enum: ["critical", "major", "minor"] }, + file: { type: "string" }, + message: { type: "string" }, + suggestion: { type: "string" } + } + } + } + } + }, + output: {}, + execute: async (input, context) => { + const verdict = input.verdict === "APPROVE" || input.verdict === "APPROVE_WITH_NOTES" || input.verdict === "BLOCK" ? input.verdict : null; + const summary = typeof input.summary === "string" ? input.summary.trim() : ""; + if (!verdict) return jsonResult6({ ok: false, error: "Invalid verdict" }); + if (!summary) return jsonResult6({ ok: false, error: "summary is required" }); + const targetAgent = typeof input.targetAgent === "string" && input.targetAgent.trim() ? input.targetAgent.trim().replace(/^@/, "") : "hermes"; + const findings = normalizeFindings(input.findings); + const ctxRec = context ?? {}; + const sessionID = typeof ctxRec.sessionID === "string" ? ctxRec.sessionID : void 0; + getSharedBus().emit("review:verdict", { + verdict, + targetAgent, + ...sessionID ? { sessionID } : {}, + summary, + findingsCount: findings.length, + timestamp: Date.now() + }); + let syntheticTriggered = false; + let syntheticSessionID; + let remediationAttempt = 0; + if (verdict === "BLOCK" && sessionID && typeof sessionDomain?.synthetic === "function") { + const key = `${sessionID}:${targetAgent}`; + const prev = remediationCounts.get(key) ?? 0; + if (prev < MAX_AUTO_REMEDIATIONS) { + remediationAttempt = prev + 1; + remediationCounts.set(key, remediationAttempt); + const text2 = formatRemediationPrompt({ verdict, summary, targetAgent, findings }); + try { + let dispatchSid = sessionID; + if (typeof sessionDomain.get === "function") { + const info = await sessionDomain.get({ sessionID }).catch(() => void 0); + if (typeof info?.parentID === "string" && info.parentID.trim()) { + dispatchSid = info.parentID.trim(); + } + } + if (dispatchSid === sessionID && typeof sessionDomain.switchAgent === "function") { + await sessionDomain.switchAgent({ sessionID: dispatchSid, agent: targetAgent }).catch(() => { + }); + } + await sessionDomain.synthetic({ + sessionID: dispatchSid, + text: text2, + description: `Themis BLOCK remediation -> @${targetAgent}`, + metadata: { targetAgent, verdict, remediationAttempt }, + resume: true + }); + syntheticTriggered = true; + syntheticSessionID = dispatchSid; + } catch { + syntheticTriggered = false; + } + } + } else if (verdict !== "BLOCK" && sessionID) { + remediationCounts.delete(`${sessionID}:${targetAgent}`); + } + return jsonResult6({ + ok: true, + verdict, + targetAgent, + findingsCount: findings.length, + syntheticTriggered, + ...syntheticSessionID ? { syntheticSessionID } : {}, + ...remediationAttempt > 0 ? { remediationAttempt, maxRemediations: MAX_AUTO_REMEDIATIONS } : {} + }); + } + }; +} + // src/pantheon/skill-search-tool.ts -import { existsSync as existsSync14, readdirSync as readdirSync6, readFileSync as readFileSync12 } from "node:fs"; -import { homedir as homedir8 } from "node:os"; -import { join as join22 } from "node:path"; +import { existsSync as existsSync21, readdirSync as readdirSync7, readFileSync as readFileSync19 } from "node:fs"; +import { homedir as homedir9 } from "node:os"; +import { join as join30 } from "node:path"; // scripts/skill-search.mjs import { spawnSync } from "node:child_process"; -import { pathToFileURL } from "node:url"; +import { pathToFileURL as pathToFileURL2 } from "node:url"; var FIND_TIMEOUT_MS = 15e3; var DEFAULT_LIMIT = 5; var ANSI_SGR = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, "g"); @@ -16766,10 +18986,10 @@ function parseSkillSearchOutput(raw, { limit = DEFAULT_LIMIT } = {}) { } return found; } -function searchSkills(query, { limit = DEFAULT_LIMIT, owner, spawn: spawn2 = spawnSync } = {}) { +function searchSkills(query, { limit = DEFAULT_LIMIT, owner, spawn: spawn3 = spawnSync } = {}) { const args = ["skills", "find", String(query)]; if (owner !== void 0) args.push("--owner", String(owner)); - const result = spawn2("npx", args, { + const result = spawn3("npx", args, { encoding: "utf8", timeout: FIND_TIMEOUT_MS, stdio: ["ignore", "pipe", "pipe"] @@ -16783,7 +19003,7 @@ function searchSkills(query, { limit = DEFAULT_LIMIT, owner, spawn: spawn2 = spa } const entries = parseSkillSearchOutput(raw, { limit }); if (entries.length === 0) { - const retry = spawn2("npx", args, { + const retry = spawn3("npx", args, { encoding: "utf8", timeout: FIND_TIMEOUT_MS, stdio: ["ignore", "pipe", "pipe"] @@ -16798,8 +19018,8 @@ function searchSkills(query, { limit = DEFAULT_LIMIT, owner, spawn: spawn2 = spa } var GITHUB_TIMEOUT_MS = 1e4; var ANTHROPIC_SKILLS_REPO = "anthropics/skills"; -function searchAnthropicCatalog(query, { limit = DEFAULT_LIMIT, spawn: spawn2 = spawnSync } = {}) { - const result = spawn2( +function searchAnthropicCatalog(query, { limit = DEFAULT_LIMIT, spawn: spawn3 = spawnSync } = {}) { + const result = spawn3( "gh", ["api", `repos/${ANTHROPIC_SKILLS_REPO}/contents/skills`, "--jq", ".[].name"], { encoding: "utf8", timeout: GITHUB_TIMEOUT_MS, stdio: ["ignore", "pipe", "pipe"] } @@ -16824,10 +19044,10 @@ function searchAnthropicCatalog(query, { limit = DEFAULT_LIMIT, spawn: spawn2 = })) }; } -function searchGithubSkills(query, { limit = DEFAULT_LIMIT, spawn: spawn2 = spawnSync } = {}) { +function searchGithubSkills(query, { limit = DEFAULT_LIMIT, spawn: spawn3 = spawnSync } = {}) { const terms = String(query).split(/\s+/).filter((term) => term.length > 1).slice(0, 3).map((term) => encodeURIComponent(term)).join("+"); if (terms === "") return { ok: true, entries: [] }; - const result = spawn2( + const result = spawn3( "gh", ["api", `search/code?q=filename:SKILL.md+${terms}&per_page=${Math.min(limit, 10)}`], { encoding: "utf8", timeout: GITHUB_TIMEOUT_MS, stdio: ["ignore", "pipe", "pipe"] } @@ -16860,14 +19080,14 @@ function searchGithubSkills(query, { limit = DEFAULT_LIMIT, spawn: spawn2 = spaw var SKILL_SEARCH_SOURCES = Object.freeze(["anthropic", "skills-sh", "github"]); var SEARCH_CACHE = /* @__PURE__ */ new Map(); var CACHE_TTL_MS = 24 * 60 * 60 * 1e3; -function searchSkillSources(query, { limit = DEFAULT_LIMIT, owner, sources = SKILL_SEARCH_SOURCES, spawn: spawn2 = spawnSync } = {}) { +function searchSkillSources(query, { limit = DEFAULT_LIMIT, owner, sources = SKILL_SEARCH_SOURCES, spawn: spawn3 = spawnSync } = {}) { const cacheKey = JSON.stringify({ query: String(query).toLowerCase().trim(), limit, owner, sources }); - if (spawn2 === spawnSync && SEARCH_CACHE.has(cacheKey)) { + if (spawn3 === spawnSync && SEARCH_CACHE.has(cacheKey)) { const cached = SEARCH_CACHE.get(cacheKey); if (Date.now() - cached.timestamp < CACHE_TTL_MS) { return cached.result; @@ -16877,7 +19097,7 @@ function searchSkillSources(query, { limit = DEFAULT_LIMIT, owner, sources = SKI const out = []; const failures = []; for (const source of sources) { - const result = source === "anthropic" ? searchAnthropicCatalog(query, { limit: perTier, spawn: spawn2 }) : source === "skills-sh" ? searchSkills(query, { limit: perTier, owner, spawn: spawn2 }) : source === "github" ? searchGithubSkills(query, { limit: perTier, spawn: spawn2 }) : { ok: false, error: `unknown source: ${source}` }; + const result = source === "anthropic" ? searchAnthropicCatalog(query, { limit: perTier, spawn: spawn3 }) : source === "skills-sh" ? searchSkills(query, { limit: perTier, owner, spawn: spawn3 }) : source === "github" ? searchGithubSkills(query, { limit: perTier, spawn: spawn3 }) : { ok: false, error: `unknown source: ${source}` }; if (result.ok) out.push(...result.entries.map((entry) => ({ ...entry, source }))); else failures.push(`${source}: ${result.error}`); } @@ -16898,7 +19118,7 @@ function searchSkillSources(query, { limit = DEFAULT_LIMIT, owner, sources = SKI entries: out.slice(0, limit), failures }; - if (spawn2 === spawnSync && finalResult.ok) { + if (spawn3 === spawnSync && finalResult.ok) { SEARCH_CACHE.set(cacheKey, { timestamp: Date.now(), result: finalResult }); } return finalResult; @@ -16936,7 +19156,7 @@ function main(args = process.argv.slice(2)) { } console.log(JSON.stringify(result.entries, null, 1)); } -var invokedDirectly = process.argv[1] !== void 0 && import.meta.url === pathToFileURL(process.argv[1]).href; +var invokedDirectly = process.argv[1] !== void 0 && import.meta.url === pathToFileURL2(process.argv[1]).href; if (invokedDirectly) main(); // src/pantheon/skill-search-tool.ts @@ -16976,16 +19196,16 @@ function scanInstalledSkills(cwd = process.cwd()) { } const scanDir = (baseDir, scope) => { try { - if (!existsSync14(baseDir)) return; - const entries = readdirSync6(baseDir, { withFileTypes: true }); + if (!existsSync21(baseDir)) return; + const entries = readdirSync7(baseDir, { withFileTypes: true }); for (const entry of entries) { if (!entry.isDirectory() && !entry.isSymbolicLink()) continue; const skillName = entry.name; if (skillName.startsWith(".")) continue; - const skillMd = join22(baseDir, skillName, "SKILL.md"); - if (existsSync14(skillMd)) { + const skillMd = join30(baseDir, skillName, "SKILL.md"); + if (existsSync21(skillMd)) { try { - const raw = readFileSync12(skillMd, "utf8"); + const raw = readFileSync19(skillMd, "utf8"); const { name, description } = extractSkillMetadata(raw, skillName); const id = (name || skillName).trim(); map.set(id.toLowerCase(), { @@ -17001,12 +19221,12 @@ function scanInstalledSkills(cwd = process.cwd()) { } catch { } }; - const xdgConfig = process.env.XDG_CONFIG_HOME || join22(homedir8(), ".config"); - scanDir(join22(xdgConfig, "opencode", "skills"), "global"); - scanDir(join22(homedir8(), ".agents", "skills"), "global"); - scanDir(join22(cwd, ".opencode", "skills"), "project"); - scanDir(join22(cwd, ".agents", "skills"), "project"); - scanDir(join22(cwd, "skills"), "project"); + const xdgConfig = process.env.XDG_CONFIG_HOME || join30(homedir9(), ".config"); + scanDir(join30(xdgConfig, "opencode", "skills"), "global"); + scanDir(join30(homedir9(), ".agents", "skills"), "global"); + scanDir(join30(cwd, ".opencode", "skills"), "project"); + scanDir(join30(cwd, ".agents", "skills"), "project"); + scanDir(join30(cwd, "skills"), "project"); return map; } var TOOL_DESCRIPTION3 = "Advisory discovery tool for skills. Queries installed Pantheon skills and external registries (Anthropic catalog, skills.sh, GitHub). Returns matched skill IDs, descriptions, install counts, and provenance tiers. Zeus uses this to recommend project-scoped skills (.agents/skills/) before proactively prompting the user via the question tool."; @@ -17178,188 +19398,152 @@ function createV2SkillSearchDefinition(defaultDir) { }; } -// src/pantheon/step-ledger.ts -import { existsSync as existsSync15, mkdirSync as mkdirSync10, readFileSync as readFileSync13, realpathSync as realpathSync6, writeFileSync as writeFileSync8 } from "node:fs"; -import { join as join23, resolve as resolve13, sep as sep8 } from "node:path"; -var SAFE_STEP_KEY_RE = /^[a-zA-Z0-9._:-]{1,128}$/; -var stepReflex = new ThemisReflexController({ maxRetries: 2 }); -function assertSafeStepKey(stepKey) { - if (typeof stepKey !== "string" || !SAFE_STEP_KEY_RE.test(stepKey) || stepKey.includes("..")) { - throw new Error("stepKey must be a safe alphanumeric identifier (1..128 chars)"); - } - return stepKey; -} -function resolveLedgerPath(workspaceDir) { - const dir = join23(workspaceDir, ".pantheon", "ledger"); - mkdirSync10(dir, { recursive: true }); - const canonicalDir = realpathSync6(dir); - const filePath = resolve13(canonicalDir, "step-ledger.json"); - const prefix = canonicalDir.endsWith(sep8) ? canonicalDir : `${canonicalDir}${sep8}`; - if (!filePath.startsWith(prefix)) { - throw new Error("Path traversal denied for step-ledger.json"); - } - return filePath; +// src/pantheon/worktree-orchestrator.ts +import { execFile as execFile5 } from "node:child_process"; +import { existsSync as existsSync22, mkdirSync as mkdirSync13, realpathSync as realpathSync10 } from "node:fs"; +import { basename as basename6, dirname as dirname14, join as join31, resolve as resolve22 } from "node:path"; +import { promisify as promisify4 } from "node:util"; +var execFileAsync4 = promisify4(execFile5); +var SAFE_TASK_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/; +function isAbortError(err) { + return err instanceof Error && err.name === "AbortError"; +} +function sanitizeTaskSlug(raw) { + const base = basename6(raw.trim()).replace(/[^a-zA-Z0-9._-]/g, "-"); + if (!base || !SAFE_TASK_RE.test(base) || base.includes("..")) { + return `wt-${Date.now()}`; + } + return base; +} +function resolvePantheonWorktreePath(sourceDirectory, taskName) { + const sourceReal = existsSync22(sourceDirectory) ? realpathSync10(resolve22(sourceDirectory)) : resolve22(sourceDirectory); + const parent = dirname14(sourceReal); + const repoName = basename6(sourceReal) || "workspace"; + const taskSlug = sanitizeTaskSlug(taskName); + return join31(parent, ".pantheon-worktrees", repoName, taskSlug); +} +function isInsideOrDotPantheon(sourceDirectory, candidate) { + const srcReal = existsSync22(sourceDirectory) ? realpathSync10(resolve22(sourceDirectory)) : resolve22(sourceDirectory); + const candResolved = resolve22(candidate); + return candResolved === srcReal || candResolved.startsWith(`${srcReal}/`) || candResolved.includes("/.pantheon/") || candResolved.includes("\\.pantheon\\"); +} +async function runGit2(cwd, args, signal) { + if (signal?.aborted) { + const abortErr = new Error("Worktree operation aborted"); + abortErr.name = "AbortError"; + throw abortErr; + } + const { stdout } = await execFileAsync4("git", [...args], { + cwd, + signal, + timeout: 15e3, + maxBuffer: 4 * 1024 * 1024 + }); + return stdout; } -function readStepLedger(workspaceDir) { - const filePath = resolveLedgerPath(workspaceDir); - if (!existsSync15(filePath)) { - return { version: 1, steps: {} }; - } - try { - const parsed = JSON.parse(readFileSync13(filePath, "utf8")); - if (parsed && typeof parsed.steps === "object" && parsed.steps !== null) { - return { version: 1, steps: parsed.steps }; +function createPantheonWorktreeDefinition() { + return { + id: "pantheon-worktree", + create: async (input, context) => { + const source = resolve22(input.sourceDirectory); + const requestedDir = input.directory ? resolve22(input.directory) : ""; + const targetDir = !requestedDir || isInsideOrDotPantheon(source, requestedDir) ? resolvePantheonWorktreePath(source, basename6(requestedDir) || `wt-${Date.now()}`) : requestedDir; + if (input.branch && (!SAFE_TASK_RE.test(input.branch) || input.branch.startsWith("-"))) { + throw new Error(`Unsafe git ref "${input.branch}" for worktree creation`); + } + mkdirSync13(dirname14(targetDir), { recursive: true }); + const args = ["worktree", "add", "--detach", targetDir]; + if (input.branch) args.push(input.branch); + await runGit2(source, args, context.signal); + return { directory: existsSync22(targetDir) ? realpathSync10(targetDir) : targetDir }; + }, + remove: async (input, context) => { + const dir = resolve22(input.directory); + const parent = dirname14(dir); + const args = ["worktree", "remove"]; + if (input.force) args.push("--force"); + args.push(dir); + try { + await runGit2(existsSync22(dir) ? dir : parent, args, context.signal); + } catch (err) { + if (isAbortError(err)) throw err; + throw err; + } + }, + list: async (sourceDirectory, context) => { + const source = resolve22(sourceDirectory); + const raw = await runGit2(source, ["worktree", "list", "--porcelain"], context.signal); + const entries = []; + const srcReal = existsSync22(source) ? realpathSync10(source) : source; + for (const line of raw.split(/\r?\n/)) { + if (!line.startsWith("worktree ")) continue; + const wtPath = line.slice("worktree ".length).trim(); + if (!wtPath) continue; + const wtReal = existsSync22(wtPath) ? realpathSync10(wtPath) : wtPath; + entries.push({ + directory: wtReal, + type: wtReal === srcReal ? "root" : "worktree" + }); + } + return entries; } - } catch { - } - return { version: 1, steps: {} }; -} -function writeStepLedger(workspaceDir, store2) { - const filePath = resolveLedgerPath(workspaceDir); - writeFileSync8(filePath, `${JSON.stringify(store2, null, 2)} -`, "utf8"); -} -function canTransitionStepToDone(step) { - if (step.verificationExitCode !== 0 || step.lastVerifiedAt === null) { - return { - allowed: false, - reason: `Step "${step.stepKey}" cannot transition to done: no passing verification command (exitCode === 0) has been recorded.` - }; - } - if (step.lastMutationAt !== null && step.lastVerifiedAt < step.lastMutationAt) { - return { - allowed: false, - reason: `Step "${step.stepKey}" cannot transition to done: files were mutated after the last verification run. Re-run the verification slice first.` - }; - } - return { allowed: true }; + }; } -function jsonResult4(payload) { +function jsonResult7(payload) { return { output: JSON.stringify(payload) }; } -function createStepLedgerTool(fallbackDir) { +function createWorktreeTool(fallbackDir) { + const driver = createPantheonWorktreeDefinition(); return { - name: "pantheon_step_ledger", - description: "Manage atomic Step-Ledger execution contracts with hard verification gates: a step can transition to done ONLY after a verification command exits 0 following the last file mutation.", + name: "pantheon_worktree", + description: "Manage isolated git worktrees strictly outside the main repository under /.pantheon-worktrees// (actions: create | list | remove).", input: { type: "object", additionalProperties: false, required: ["action"], properties: { - action: { - type: "string", - enum: ["init_step", "record_mutation", "record_verification", "complete_step", "status"], - description: "Ledger operation to perform" - }, - stepKey: { type: "string", description: "Unique atomic step identifier" }, - objective: { type: "string", description: "Bounded step objective" }, - agent: { type: "string", description: "Assigned specialist agent" }, - files: { - type: "array", - items: { type: "string" }, - description: "Mutated file paths for record_mutation" - }, - command: { type: "string", description: "Executed verification slice command" }, - exitCode: { type: "number", description: "Exit code of the verification command" }, - durationMs: { type: "number", description: "Duration of verification command in ms" } + action: { type: "string", enum: ["create", "list", "remove"] }, + task: { type: "string", description: "Short task slug for sibling worktree folder" }, + branch: { type: "string", description: "Optional existing git branch/ref to check out" }, + directory: { type: "string", description: "Target worktree directory (for remove)" }, + force: { type: "boolean", description: "Force worktree removal even with dirty files" } } }, output: {}, execute: async (input, context) => { try { - const action = typeof input.action === "string" ? input.action : "status"; - const cwd = resolveToolCwd(context, fallbackDir); - const store2 = readStepLedger(cwd); - const now = Date.now(); - const nowIso = new Date(now).toISOString(); - if (action === "status") { - if (typeof input.stepKey === "string" && input.stepKey.trim()) { - const key2 = assertSafeStepKey(input.stepKey.trim()); - const step2 = store2.steps[key2]; - if (!step2) return jsonResult4({ ok: false, error: "step_not_found", stepKey: key2 }); - return jsonResult4({ ok: true, step: step2, gate: canTransitionStepToDone(step2) }); - } - return jsonResult4({ ok: true, steps: Object.values(store2.steps) }); - } - const key = assertSafeStepKey(input.stepKey); - if (action === "init_step") { - const objective = typeof input.objective === "string" ? input.objective.trim() : ""; - if (!objective) return jsonResult4({ ok: false, error: "objective is required" }); - const agent = typeof input.agent === "string" && input.agent.trim() ? input.agent.trim() : "specialist"; - const entry = { - stepKey: key, - objective, - agent, - state: "in_progress", - mutatedFiles: [], - lastMutationAt: null, - lastVerifiedAt: null, - updatedAt: nowIso - }; - store2.steps[key] = entry; - writeStepLedger(cwd, store2); - return jsonResult4({ ok: true, step: entry }); - } - const step = store2.steps[key]; - if (!step) { - return jsonResult4({ ok: false, error: `Step "${key}" is not initialized` }); - } - if (action === "record_mutation") { - const files = Array.isArray(input.files) ? input.files.map(String) : []; - const merged = Array.from(/* @__PURE__ */ new Set([...step.mutatedFiles, ...files])); - step.mutatedFiles = merged; - step.lastMutationAt = now; - if (step.state === "done") step.state = "in_progress"; - step.updatedAt = nowIso; - writeStepLedger(cwd, store2); - return jsonResult4({ ok: true, step }); + const action = typeof input.action === "string" ? input.action : "list"; + const workspaceDir = resolveSharedPantheonRoot(resolveToolCwd(context, fallbackDir)); + const ac = new AbortController(); + if (action === "list") { + const entries = await driver.list(workspaceDir, { signal: ac.signal }); + return jsonResult7({ ok: true, entries }); } - if (action === "record_verification") { - const command = typeof input.command === "string" ? input.command.trim() : ""; - const exitCode = typeof input.exitCode === "number" ? input.exitCode : 1; - const durationMs = typeof input.durationMs === "number" ? input.durationMs : 0; - if (!command) return jsonResult4({ ok: false, error: "command is required" }); - step.verificationCommand = command; - step.verificationExitCode = exitCode; - step.lastVerifiedAt = now; - step.updatedAt = nowIso; - if (exitCode === 0) { - stepReflex.evaluate(key, step.agent, []); - const receipt = createExecutionReceipt({ - taskID: key, - agent: step.agent, - files: step.mutatedFiles.map((f) => ({ path: f, content: `${key}:${f}:${now}` })), - testSlice: { command, exitCode: 0, durationMs } - }); - step.receiptId = receipt.receiptId; - writeStepLedger(cwd, store2); - return jsonResult4({ ok: true, verified: true, receiptId: receipt.receiptId, step }); - } - const reflex = stepReflex.evaluate(key, step.agent, [ + if (action === "create") { + const task = typeof input.task === "string" && input.task.trim() ? input.task.trim() : `wt-${Date.now()}`; + const targetDir = resolvePantheonWorktreePath(workspaceDir, task); + const res = await driver.create( { - file: step.mutatedFiles[0] ?? key, - error: `Verification command "${command}" failed with exit code ${exitCode}` - } - ]); - if (reflex.action === "escalate") { - step.state = "blocked"; - } - writeStepLedger(cwd, store2); - return jsonResult4({ ok: false, verified: false, reflex, step }); + sourceDirectory: workspaceDir, + directory: targetDir, + ...typeof input.branch === "string" && input.branch.trim() ? { branch: input.branch.trim() } : {} + }, + { signal: ac.signal } + ); + return jsonResult7({ ok: true, action: "create", directory: res.directory }); } - if (action === "complete_step") { - const gate = canTransitionStepToDone(step); - if (!gate.allowed) { - return jsonResult4({ ok: false, error: gate.reason, step }); - } - step.state = "done"; - step.updatedAt = nowIso; - writeStepLedger(cwd, store2); - return jsonResult4({ ok: true, status: "done", receiptId: step.receiptId, step }); + if (action === "remove") { + const target = typeof input.directory === "string" && input.directory.trim() ? input.directory.trim() : typeof input.task === "string" && input.task.trim() ? resolvePantheonWorktreePath(workspaceDir, input.task.trim()) : ""; + if (!target) return jsonResult7({ ok: false, error: "directory or task is required" }); + await driver.remove( + { directory: target, force: input.force === true }, + { signal: ac.signal } + ); + return jsonResult7({ ok: true, action: "remove", directory: target }); } - return jsonResult4({ ok: false, error: `Unsupported action: ${action}` }); + return jsonResult7({ ok: false, error: `Unsupported action: ${action}` }); } catch (err) { - return jsonResult4({ + return jsonResult7({ ok: false, error: err instanceof Error ? err.message : String(err) }); @@ -17486,28 +19670,30 @@ function coerceHashlineEditArgs(input) { } return { ok: true, args: { file, edits } }; } -var hashlineEdit = createHashlineEditTool(); -async function executeHashlineEdit(input, context) { - const ctx = toolContext(context); - const callerAgent = (ctx.agent ?? "").toLowerCase().trim(); - if (callerAgent && callerAgent !== "zeus" && NON_EDIT_AGENTS.has(callerAgent)) { +function createHashlineEditExecutor(fallbackDir) { + const hashlineTool = createHashlineEditTool(fallbackDir); + return async function executeHashlineEdit(input, context) { + const ctx = toolContext(context); + const callerAgent = (ctx.agent ?? "").toLowerCase().trim(); + if (callerAgent && callerAgent !== "zeus" && NON_EDIT_AGENTS.has(callerAgent)) { + return { + output: `hashline_edit denied: agent '${callerAgent}' is not permitted to edit files directly.` + }; + } + const coerced = coerceHashlineEditArgs(input); + if (!coerced.ok) return { output: coerced.error }; + let result; + try { + result = await hashlineTool.execute(coerced.args, ctx); + } catch (err) { + return { output: errorText("hashline_edit failed", err) }; + } + if (typeof result === "string") return { output: result }; return { - output: `hashline_edit denied: agent '${callerAgent}' is not permitted to edit files directly.` + output: result.output, + ...result.title === void 0 ? {} : { title: result.title }, + ...result.metadata === void 0 ? {} : { metadata: result.metadata } }; - } - const coerced = coerceHashlineEditArgs(input); - if (!coerced.ok) return { output: coerced.error }; - let result; - try { - result = await hashlineEdit.execute(coerced.args, ctx); - } catch (err) { - return { output: errorText("hashline_edit failed", err) }; - } - if (typeof result === "string") return { output: result }; - return { - output: result.output, - ...result.title === void 0 ? {} : { title: result.title }, - ...result.metadata === void 0 ? {} : { metadata: result.metadata } }; } var COST_INPUT = { @@ -17700,7 +19886,7 @@ var todoreadTool = { }; } }; -var execAsync = promisify2(exec); +var execAsync = promisify5(exec); var SHELL_TIMEOUT_MS = 12e4; var SHELL_INPUT = { type: "object", @@ -17760,7 +19946,7 @@ function createV2ToolDefinitions(visionRuntime, shadow = {}, jevRuntime, hostLoc description: "Edit a file anchored by hashline refs (LINE#TAG) instead of raw line numbers. Ops: replace (ref..endRef or single ref \u2192 lines), append/prepend (anchor ref \u2192 content), delete (ref..endRef). ALL refs must be validated against the ORIGINAL file before anything is written; on mismatch the tool returns an error with a re-tagged excerpt and a Did-you-mean suggestion, and nothing is modified.", input: HASHLINE_EDIT_INPUT, output: {}, - execute: executeHashlineEdit + execute: createHashlineEditExecutor(hostLocationDirectory) }, { name: "pantheon_cost", @@ -17787,10 +19973,13 @@ function createV2ToolDefinitions(visionRuntime, shadow = {}, jevRuntime, hostLoc definitions.push(createShellTool(hostLocationDirectory)); definitions.push(createV2SkillSearchDefinition(hostLocationDirectory)); definitions.push(createDeepworkTool(hostLocationDirectory)); - definitions.push(createStepLedgerTool(hostLocationDirectory)); + definitions.push(createStepLedgerTool(hostLocationDirectory, shadow.sessionDomain)); definitions.push(createAgentForgeTool(hostLocationDirectory)); definitions.push(...createNativeMemoryAndPersistenceTools(hostLocationDirectory)); definitions.push(...createCodemapTools(hostLocationDirectory)); + definitions.push(...createAstTools(hostLocationDirectory)); + definitions.push(createReviewVerdictTool(shadow.sessionDomain)); + definitions.push(createWorktreeTool(hostLocationDirectory)); if (visionRuntime) definitions.push(createV2VisionTool(visionRuntime)); if (jevRuntime) definitions.push(createV2JevDecisionDefinition(jevRuntime)); return definitions; @@ -17914,7 +20103,7 @@ function loadRuntimeOverrides(workspaceDir) { try { const read = (filePath) => { try { - return readFileSync14(filePath, "utf8"); + return readFileSync20(filePath, "utf8"); } catch { return void 0; } @@ -17977,8 +20166,8 @@ function readCanonicalRoster() { path4.join(process.cwd(), "src", "agents", "roster.json") ]; for (const p of candidates) { - if (existsSync16(p)) { - const raw = readFileSync14(p, "utf8"); + if (existsSync23(p)) { + const raw = readFileSync20(p, "utf8"); const data = JSON.parse(raw); if (data && typeof data.agents === "object") return data.agents; } @@ -18100,10 +20289,18 @@ var CANONICAL_SLASH_COMMANDS = [ name: "pantheon-audit", description: "Run zero-token heuristic static scan and Themis 3-layer security review" }, + { + name: "pantheon-consolidate", + description: "Merge and consolidate memory entries" + }, { name: "pantheon-focus", description: "Manage persistent session goals and focus boundaries across compactions" }, + { + name: "pantheon-forge", + description: "Interactive wizard to detect repository stacks and forge tailored specialists" + }, { name: "pantheon-model", description: "Inspect or configure per-agent model overrides in active-preset.json" @@ -18112,10 +20309,6 @@ var CANONICAL_SLASH_COMMANDS = [ name: "pantheon-optimize", description: "Analyze and prune stale artifacts, worktrees, and context overhead" }, - { - name: "pantheon-settings", - description: "Open the interactive Pantheon TUI settings and Quotas & Spend window" - }, { name: "pantheon-vision", description: "Inspect or configure multimodal vision gateway and model status" @@ -18125,13 +20318,14 @@ function resolveCanonicalCommandsDir() { const candidates = [ fileURLToPath5(new URL("commands", import.meta.url)), fileURLToPath5(new URL("../commands", import.meta.url)), + fileURLToPath5(new URL("../../commands", import.meta.url)), fileURLToPath5(new URL("../src/commands", import.meta.url)), fileURLToPath5(new URL("../../src/commands", import.meta.url)), fileURLToPath5(new URL("src/commands", import.meta.url)), path4.join(activeHostWorkspaceDir ?? process.cwd(), "src", "commands") ]; for (const candidate of candidates) { - if (existsSync16(candidate)) return candidate; + if (existsSync23(candidate)) return candidate; } return void 0; } @@ -18140,8 +20334,8 @@ function readCanonicalCommandTemplate(commandName, fallbackDescription) { const dir = resolveCanonicalCommandsDir(); if (dir) { const mdPath = path4.join(dir, `${commandName}.md`); - if (existsSync16(mdPath)) { - const raw = readFileSync14(mdPath, "utf8"); + if (existsSync23(mdPath)) { + const raw = readFileSync20(mdPath, "utf8"); const body = raw.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, "").trim(); if (body) return body; } @@ -18227,10 +20421,12 @@ function transformReferences(draft) { const candidates = [ fileURLToPath5(new URL("../AGENTS.global.md", import.meta.url)), fileURLToPath5(new URL("../../AGENTS.global.md", import.meta.url)), + fileURLToPath5(new URL("../../../AGENTS.global.md", import.meta.url)), fileURLToPath5(new URL("../AGENTS.md", import.meta.url)), - fileURLToPath5(new URL("../../AGENTS.md", import.meta.url)) + fileURLToPath5(new URL("../../AGENTS.md", import.meta.url)), + fileURLToPath5(new URL("../../../AGENTS.md", import.meta.url)) ]; - const resolvedPath = candidates.find((p) => existsSync16(p)) ?? fileURLToPath5(new URL("../AGENTS.md", import.meta.url)); + const resolvedPath = candidates.find((p) => existsSync23(p)) ?? fileURLToPath5(new URL("../AGENTS.md", import.meta.url)); draft.add("pantheon-agents", { type: "local", path: resolvedPath, @@ -18247,7 +20443,7 @@ function resolveCanonicalSkillsDir() { path4.join(activeHostWorkspaceDir ?? process.cwd(), "src", "skills") ]; for (const candidate of candidates) { - if (existsSync16(candidate)) return candidate; + if (existsSync23(candidate)) return candidate; } return void 0; } @@ -18273,15 +20469,15 @@ function transformSkills(draft) { const editor = draft; if (typeof editor.add === "function") { try { - const entries = readdirSync7(skillsDir, { withFileTypes: true }); + const entries = readdirSync8(skillsDir, { withFileTypes: true }); for (const entry of entries) { if (!entry.isDirectory()) continue; const skillId = entry.name; const skillMdPath = path4.join(skillsDir, skillId, "SKILL.md"); - if (!existsSync16(skillMdPath)) continue; + if (!existsSync23(skillMdPath)) continue; try { if (typeof editor.get === "function" && editor.get(skillId)) continue; - const content = readFileSync14(skillMdPath, "utf8"); + const content = readFileSync20(skillMdPath, "utf8"); const { name, description } = parseSkillFrontmatter(content, skillId); editor.add({ id: skillId, @@ -18367,7 +20563,8 @@ async function registerV2Tools(context, boundedRead, jevRuntime) { { complexitySink: (record2) => { p3Sink.emit({ ...record2, mode: "shadow" }); - } + }, + ...host.session !== void 0 ? { sessionDomain: host.session } : {} }, runtime, host.location?.directory @@ -18378,6 +20575,9 @@ async function registerV2Tools(context, boundedRead, jevRuntime) { await toolCtx.transform((draft) => { draft.namespace({ name: "pantheon", description: "Pantheon orchestration tools" }); for (const def of toolDefs) { + if ((def.name === "todowrite" || def.name === "todoread") && draft.get?.(def.name) !== void 0) { + continue; + } draft.add({ name: def.name, description: def.description, @@ -18610,7 +20810,7 @@ async function registerV2SessionHooks(context) { try { if (process.env.PANTHEON_HOOK_CANARY_LIFETIME_PROOF) { try { - appendFileSync2( + appendFileSync3( process.env.PANTHEON_HOOK_CANARY_LIFETIME_PROOF, "plugin:session.hook:context\n" ); @@ -18715,8 +20915,8 @@ function appendV2HookLog(line) { if (body === "") return false; try { const dir = path4.join(process.cwd(), ".pantheon", "logs"); - mkdirSync11(dir, { recursive: true }); - appendFileSync2(path4.join(dir, "hooks.log"), `${body} + mkdirSync14(dir, { recursive: true }); + appendFileSync3(path4.join(dir, "hooks.log"), `${body} `, "utf8"); return true; } catch { @@ -18912,6 +21112,16 @@ async function registerV2ToolHooks(context, subagentOrigins, boundedReadOrigins, throw new Error(guardrailVerdict.message); } } + const reproAgent = agent !== void 0 ? normalizeDelegationAgent(agent) : void 0; + const reproVerdict = evaluateReproductionGate({ + cwd: activeHostWorkspaceDir ?? process.cwd(), + tool: input.tool, + ...reproAgent ? { agent: reproAgent } : {}, + ...output.args !== null && typeof output.args === "object" && !Array.isArray(output.args) ? { args: output.args } : {} + }); + if (!reproVerdict.allowed) { + throw new Error(reproVerdict.message); + } const boundedReadOrigin = boundedReadOrigins?.capture(event); const eventTool = event?.tool; if (eventTool === BOUNDED_READ_TOOL && boundedReadOrigin === void 0) { @@ -18962,7 +21172,8 @@ async function registerV2ToolHooks(context, subagentOrigins, boundedReadOrigins, } try { const v2ExecuteAfter = createV2ExecuteAfter({ - sandbox: resolveV2SandboxConfig(context.options) + sandbox: resolveV2SandboxConfig(context.options), + cwd: () => activeHostWorkspaceDir ?? process.cwd() }); await toolCtx.hook("execute.after", async (event) => { const benchStartedAt = Date.now(); @@ -19046,7 +21257,7 @@ async function registerV2PermissionHook(context, subagentOrigins) { const proofPath = process.env.PANTHEON_HOOK_CANARY_PERMISSION_PROOF; if (!proofPath || !event || !Array.isArray(event.resources)) return; try { - appendFileSync2( + appendFileSync3( proofPath, `permission.evaluate ${JSON.stringify({ action: event.action, @@ -19164,7 +21375,7 @@ function writeV2AdmissionProof(label, detail) { const proofPath = process.env.PANTHEON_HOOK_CANARY_PERMISSION_PROOF; if (!proofPath) return; try { - appendFileSync2(proofPath, `${label} ${JSON.stringify(detail)} + appendFileSync3(proofPath, `${label} ${JSON.stringify(detail)} `); } catch { } @@ -19313,6 +21524,18 @@ var plugin = define({ () => false ); if (!toolsRegistered) markUnsupported("tool-transform"); + if (typeof setupHost.worktree?.transform === "function") { + try { + await setupHost.worktree.transform((draft) => { + draft.add(createPantheonWorktreeDefinition()); + }); + } catch { + markUnsupported("worktree-transform"); + } + } + if (hostLocationDir) { + activeCleanups.push(wireCockpitBusRecorder(hostLocationDir)); + } const compactionCtx = setupHost.session; if (compactionCtx?.hook) { const goalStore = new GoalStore({ @@ -19325,7 +21548,7 @@ var plugin = define({ try { if (process.env.PANTHEON_HOOK_CANARY_LIFETIME_PROOF) { try { - appendFileSync2( + appendFileSync3( process.env.PANTHEON_HOOK_CANARY_LIFETIME_PROOF, "plugin:session.hook:compaction\n" ); diff --git a/src/plugins/tui/dist/tui.d.ts b/src/plugins/tui/dist/tui.d.ts index 8bdbd624..b863c723 100644 --- a/src/plugins/tui/dist/tui.d.ts +++ b/src/plugins/tui/dist/tui.d.ts @@ -58,7 +58,7 @@ export type SidebarDataEvent = Parameters[0]; * the literals while making a name outside the union a type error (surfaced by * `tsc -p tsconfig.build.json`), and the sidebar test asserts the same names * against the installed union at runtime. */ -export declare const SIDEBAR_REFRESH_EVENTS: readonly ["session.created", "session.renamed", "session.metadata.updated", "session.moved", "session.idle", "session.status", "session.deleted"]; +export declare const SIDEBAR_REFRESH_EVENTS: readonly ["session.created", "session.renamed", "session.metadata.updated", "session.moved", "session.idle", "session.status", "session.deleted", "session.execution.started", "session.execution.succeeded", "session.execution.failed", "session.execution.interrupted", "session.message.content.updated", "session.tool.input.started", "session.tool.called", "session.tool.success", "session.tool.failed", "session.step.ended", "session.usage.updated", "session.permissions"]; export type PresetInfo = { name: string | null; source: 'env' | 'file' | null; @@ -227,8 +227,24 @@ export type ToolCallSummary = { total: number; failures: number; }; +export type ToolDomain = 'mem' | 'ctx' | 'code' | 'edit' | 'read' | 'shell' | 'agent' | 'mcp'; +export type ToolDomainSummary = ToolCallSummary & { + byDomain: Partial>; + activeTool: string | null; +}; +/** Classifica uma tool (nativa, OpenCode ou MCP externa) em domínio curto e + * verbo de 3–4 caracteres para Sidebar/Dispatch. Pure. */ +export declare function classifyToolPart(rawName: unknown): { + domain: ToolDomain; + verb: string; +}; +/** Resume chamadas de ferramentas por domínio nativo + tool em execução. Pure. */ +export declare function summarizeToolDomains(messages: readonly any[] | null | undefined): ToolDomainSummary; /** Conta chamadas de ferramentas e eventuais falhas/erros. Pure. */ export declare function countToolCalls(messages: readonly any[] | null | undefined): ToolCallSummary; +/** Formata a quebra compacta por domínio (`mem:2 ctx:1 code:1 · ✦ memory_search`) + * para caber na largura da sidebar. Retorna null sem dados. Pure. */ +export declare function formatToolDomainLine(summary: ToolDomainSummary | null | undefined, max?: number): string | null; export declare function formatToolCallLine(summary: ToolCallSummary | null | undefined, locale?: string): string | null; export type CompactionInfo = { count: number; @@ -545,6 +561,22 @@ export type SubagentCall = { export declare function collectSubagentCalls(messages: readonly any[] | null | undefined): Map; export type DelegationState = 'running' | 'completed' | 'failed' | 'interrupted'; export type DelegationTone = 'warning' | 'error' | 'success'; +export type ChildAttention = 'question' | 'permission' | 'error'; +/** Atividade em tempo real extraída das mensagens em cache de um subagente. */ +export type ChildActivity = { + activeVerb: string | null; + activeTool: string | null; + attention: ChildAttention | null; + recentTools: string[]; + filesTouched: string[]; + lastSnippet: string | null; +}; +/** Extrai atividade ao vivo, alertas de bloqueio e histórico recente de um filho + * a partir de suas mensagens em cache. Pure, fail-open. */ +export declare function extractChildActivity(messages: readonly any[] | null | undefined, status?: string, hostAttention?: { + permission?: boolean; + question?: boolean; +}): ChildActivity | null; /** Grace window for a child that has not started yet. V2's `session.status()` * returns `idle` both for "created but not started" and for "finished", so an * idle/unknown/absent child whose own last activity (`time.updated`, falling @@ -579,6 +611,8 @@ export type DelegationView = { kindOrigin: DispatchKindOrigin; /** The parent asked for this child to run in the background. */ background: boolean; + /** Atividade ao vivo extraída do filho (quando em cache). */ + activity?: ChildActivity | null; }; /** Map the host's live session status to a display state. V2 exposes only * `"idle" | "running"` through the TUI context (the client union adds `retry` @@ -631,13 +665,15 @@ export type DispatchEntry = { export type CollectDispatchOptions = { now?: number; calls?: Map; + activities?: Map; + includeChildActivity?: boolean; }; /** Token counters of a child, null when the host published none of them. Pure. */ export declare function dispatchTokens(tokens: unknown): DispatchTokens | null; /** One child `SessionInfo` + its live status → `DispatchEntry`. The call only * ever adds the kind and the description; an absent one leaves the entry fully * renderable. Pure. */ -export declare function toDispatchEntry(child: any, status: string | undefined, now?: number, call?: SubagentCall | null): DispatchEntry; +export declare function toDispatchEntry(child: any, status: string | undefined, now?: number, call?: SubagentCall | null, activity?: ChildActivity | null): DispatchEntry; /** The delegation tree of `sessionID` — every child `session.family` returns, * root excluded, each enriched from `session.get`/`session.status` and the * parent's `subagent` calls. Empty when the family API is unavailable or the @@ -647,6 +683,9 @@ export declare function toDispatchEntry(child: any, status: string | undefined, * deduplicated before the walk, so a duplicate can never double a row or its * cost. */ export declare function collectDispatch(context: any, sessionID: string | undefined, options?: CollectDispatchOptions): DispatchEntry[]; +/** Enrich pre-collected dispatch entries with live child activity from cached + * child transcripts (used by the full-width dispatch panel). */ +export declare function enrichDispatchEntries(context: any, entries: readonly DispatchEntry[]): DispatchEntry[]; /** Sidebar blocks in render order. Spacing is derived from this list instead of * from the view, so a hidden block can never leave an empty gap behind. * Note: The custom Todo block was removed from the sidebar composition because @@ -770,10 +809,11 @@ export declare function completedSummaryText(completed: number | null | undefine /** The `· falhas` suffix of the finished summary, null when nothing failed. * Pure. */ export declare function failedSuffixText(failures: number | null | undefined): string | null; -/** One rendered live row: its text plus the session it navigates to. */ +/** One rendered live row: its text, attention tone and session id. */ export type DispatchRunningLine = { id: string; text: string; + tone?: DelegationTone; }; /** Everything the `Dispatch` block renders, already joined and capped. */ export type DispatchBlockView = { @@ -1064,6 +1104,8 @@ export type SidebarModel = { tokenAnatomyLine: Accessor; /** Contagem de chamadas de ferramentas e falhas. */ toolCallsLine: Accessor; + /** Quebra por domínio de tools nativas + tool ativa. */ + toolCallsDetailLine: Accessor; /** Badge de compactação (ex: "1x compact"). */ compactionBadge: Accessor; /** Badge de turnos da sessão (ex: "↻ 4 turns"). */ diff --git a/src/plugins/tui/dist/tui.d.ts.map b/src/plugins/tui/dist/tui.d.ts.map index ed260f33..6a49eeb4 100644 --- a/src/plugins/tui/dist/tui.d.ts.map +++ b/src/plugins/tui/dist/tui.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"tui.d.ts","names":[],"sources":["../src/context-gauge.ts","../src/model-usage-limits.ts","../src/sidebar-width.ts","../src/index.tsx"],"mappings":";;;;KAEY;qBAEC;qBACA;qBACA;KAED;UAiBK;EACf;EACA,QAAQ;EACR;;wBAOc,iBAAiB,kBAAkB;wBAOnC,iBAAiB;wBAMjB,oBAAoB;wBAQpB,iBAAiB,iBAAiB;wBAOlC,WACd,oCACA,mBAAkB;EACf;EAAgB;;wBA+CL,YAAY;;;;qBChHf;qBACA;qBACA;;;;;;;;wBCyHG,UAAU;;;;qBCvBb;;;;qBAMA;;;qBAGA;qBACA;;YAED,mBAAmB,WAAW;;;;;;;;;;qBAU7B;YAmBD;EAAe;EAAqB;;;YAGpC;EAAuB;EAAgB;;;YAEvC;EAAoB,QAAQ,eAAe;;;YAE3C;EAAuB,MAAM;EAAY,WAAW;;;;wBAQhD,qBAAqB,iBAAiB;;wBAqDtC,cAAc,KAAK,qCAAqC;;;wBAUlD,0BACpB,KAAK,oCACL,cACC,QAAQ;;;wBAeK,iBAAiB,cAAc;;;wBAgB/B,WAAW;;;wBAWX,aAAa,cAAc;;;wBAU3B,kBAAkB;;;wBAQlB,qBAAqB,iBAAiB;;;;wBAmBtC,oBAAoB,wBAAwB;YAwChD;EAAyB;EAAgB;EAAiB;;;wBAuItD,4BACd,8BACA,mBACA,4BACA,kCACC;;wBAUa,sBACd,uBACA,oCACA;;wBAgBc,mBAAmB;YAYvB;EAAiB;EAAgB;EAAiB;;;;;;;wBAO9C,iBACd,0BACA;EACG;EAAe;;;;;;wBAsBJ,oBACd,0BACA,yCACA,kCACC;;;;;wBAqBa,qBAAqB,OAAO,qBAAqB;;;;;wBAQjD,uBACd,aAAa;;;;;wBAeC,gBAAgB;;;;;;;wBAehB,wBACd,6CACA;;;;;;;;;;;;;wBAwBc,oBACd,6CACA;;;YAmDU;EAAuB;EAAyB;;;;;YAKhD;EACV;EACA;EACA;EACA;EACA,MAAM;;;YAII;EACV,QAAQ;EACR,SAAS;EACT,OAAO;;;;;;;;;wBAUO,iBACd,OAAO,qBACP,iCACA,iDACA;EAAwB;EAAa;EAAgB;IACpD;YAgDS;EACV;EACA;;;wBAIc,eACd,8CACC;wBAgCa,kBAAkB;wBAWlB,mBAAmB,SAAS;YAahC;EACV;EACA;EACA;;;wBAIc,oBAAoB,cAAc;wBAYlC,uBAAuB,SAAS;wBAehC,wBACd,SAAS;EACN;EAAsB;;YAWf;EACV;EACA;;;wBAIc,eAAe,8CAA8C;wBAuB7D,mBACd,SAAS,oCACT;YAgBU;EACV;EACA;;;wBAIc,sBAAsB,8CAA8C;;wBAiCpE,wBAAwB;wBASxB,sBACd,eAAe;;wBAcD,eAAe;wBASf,iBAAiB,eAAe;wBAQhC,kBAAkB,MAAK;;qBAmB1B;qBACA;qBACA;;;qBAGA;;YAGD;EAAe;EAAe;EAAgB;;;;;;wBAM1C,kBAAkB,2BAA2B;;YA0BjD;EACV,SAAS;EACT;EACA;EACA;;;;wBAKc,kBACd,eAAe,cACf,sBACC;;wBAaa,kBAAkB;;;;wBASlB,gBAAgB;;YAapB;EAAkB;EAAe;EAAgB;;;;wBAI7C,eAAe,eAAe,eAAe;;wBAS7C,kBAAkB,KAAK;;wBAmCvB,iBAAiB;;wBAKjB,kBAAkB,eAAe;;wBAQjC,kBAAkB;;wBAQlB,mBAAmB,KAAK;;;wBAYxB,qBAAqB,gBAAgB;;qBAaxC;;;wBAIG,SAAS;YAiBb;;;YAIA;EAAa;EAAiB,QAAQ;;;qBAGrC;;qBAEA;;wBAmBG,aAAa,iBAAiB,SAAS;;;;wBASvC,eAAe,iBAAiB;;;;;;wBA2BhC,gBAAgB,8CAA8C;;;wBAmB9D,eAAe,gBAAgB,aAAa;;;YAQhD;;wBAGI,SAAS,QAAQ,aAAa;;wBAO9B,YAAY,MAAM;;YAKtB;EAAgB,SAAS;EAAY;;;wBAGjC,iBACd,gBAAgB,YAChB,sBACC;;wBAOa,eAAe;YAgBnB;EAAoB;EAAe;EAAkB;;;;wBASjD,gBAAgB,2CAA2C;;;wBAY3D,iBAAiB;;;qBAoBpB;;;qBAGA;;;;qBAIA;;;;;qBAKA;;;YAID,WACV,cACA,yBACA;EAAW;EAAa;EAAiB;EAAsB;MAC5D;EAAU;;;;qBAIF,gBAAgB;;;;;;;YAwBjB;EACV;EACA;EACA;EACA;;;;wBAKc,wBAAwB,oCAAoC;;;;;wBAwB5D,oBACd;EACG;EAAe;;;;YAYR;EACV,SAAS;EACT;EACA;;;;;;wBAOoB,gBACpB,mBACA,OAAM,UACL,QAAQ;;;wBA8BK,kBAAkB,UAAU;;;wBAe5B,gBACd;EAAS;EAAa;EAA0B;GAChD;;qBAiBW;qBACA;;qBAEA;;qBAEA;;qBAEA;;qBAEA;;qBAEA;;YAGD;EAAgB;EAAsB;;;;;KAK7C;;wBAQW;;wBAMA,qBAAqB;;;wBAMrB,gBAAgB;;;wBAQhB,aAAa;EAC3B;IAAS;IAAc;;EACvB;IAAc;IAAc;;;;;;wBAWd,eAAe;;;wBAaf,UAAU;;;;;;wBAUV,kBACd,gBACA;EAAQ;EAAc;GACtB;;;;;wBAiBc,iBAAiB,QAAQ;;;;;;;wBAkBzB,cAAc,eAAe;;;;wBAoB7B,QAAQ,eAAe;;qBAQ1B;;;;wBAKG,iBAAiB,oBAAoB;YAsBzC;YACA;;YAGA;EAAsB,MAAM;EAAqB,QAAQ;;;;wBAsBrD,uBAAuB,uBAAuB;;wBAY9C,sBAAsB,iBAAiB;;;;wBAQvC,qBACd;EAAQ;EAAuB;uBAC9B;;YAQS;;EAEV;EACA;EACA;EACA;;;;;;;;wBAsCc,qBACd,8CACC,YAAY;YA6BH;YACA;;;;;;;;;;qBAWC;;YAGD;;EAEV;;EAEA;EACA,OAAO;;EAEP;;EAEA;;EAEA;;EAEA;;EAEA;;;EAGA,MAAM;;EAEN,YAAY;;EAEZ;;;;;;;;;wBAUc,0BACd,4BACA;EAAS;EAAkB;GAC3B,cACA,mBACC;;;;;wBAoBa,2BAA2B,mBAAmB;;;;;;;;wBAoB9C,iBACd,YACA,4BACA,cACA,OAAO,sBACN;;;wBA4Ba,aAAa;;YA0BjB;EACV;EACA;EACA;EACA;EACA;;;;;YAMU;EACV,MAAM;EACN;EACA;EACA;EACA,QAAQ;;;;;YAME;EACV;EACA,QAAQ,YAAY;;;wBAeN,eAAe,kBAAkB;;;;wBA2BjC,gBACd,YACA,4BACA,cACA,OAAO,sBACN;;;;;;;;;wBAuBa,gBACd,cACA,+BACA,UAAS,yBACR;;;;;YAwCS;;YAGA;EAAiB,KAAK;EAAiB;;;;;;;;qBAQtC,aAAa,OAAO;;;;;;wBAWjB,iBAAiB,eAAe,oBAAoB;;qBAmBvD;;qBAEA;;;qBAGA;;qBAEA;;qBAEA;;;qBAGA;;;qBAGA;;qBAEA;;qBAEA;;qBAEA;;qBAEA;;;;;;qBAMA;;;;wBAUG,mBACd,MAAM,iCACN;;;;wBAUc,sBACd,oCACA;;;;wBAac,uBAAuB;;;;wBAiBvB,gBAAgB,MAAM,gBAAgB;;;wBAStC,kBACd,MAAM,KAAK,2CACX;;wBAUc,kBAAkB,MAAM,KAAK;;;;wBAQ7B,mBAAmB;;;wBAMnB,kBAAkB,gBAAgB;;;;;;;;wBAgBlC,oBACd,MAAM,gBACN,cACA,gBACA;;;;;YAuCU;EACV;EACA;EACA;EACA,MAAM;EACN;;;;;;;wBAQc,uBAAuB,gBAAgB,mBAAmB;;;;;wBA4C1D,kBAAkB,KAAK,iBAAiB;;;wBAwBxC,sBAAsB,gBAAgB;;;;;wBAWtC,qBACd,sCACA,iCACA;;;wBAiBc,iBAAiB;;YAQrB;EAAwB;EAAY;;;YAGpC;EACV;EACA;EACA;EACA;EACA;EACA,SAAS;EACT;EACA;EACA,QAAQ;EACR;EACA;;;;;;;wBAcc,mBACd,gBAAgB,kBAChB,cACA,gBACA,eACC;;;qBA8DU;;;qBAGA;;qBAEA;;qBAEA;;qBAEA;;qBAEA;;qBAEA;;qBAEA;;qBAEA;;qBAEA;;;qBAGA;qBACA;qBACA;qBACA;qBACA;;qBAEA;;qBAEA;;qBAOA,6BAA6B,SAAS,OAAO;;;wBAQ1C,qBAAqB,kBAAkB,kBAAkB;;;;wBAOzD,mBACd,yCACA,cACA;;;;;wBAac,oBACd,kBAAkB;;wBAgCJ,kBAAkB,eAAe;;;;;wBASjC,oBAAoB,OAAO,0BAA0B;;;;wBAkBrD,kBAAkB,gBAAgB;;;;;;wBAWlC,qBACd,OAAO,eACP;EAAW;EAAc;EAAgB;;;wBAyB3B,eAAe,+BAA+B;;;wBAQ9C,kBAAkB,QAAQ;;;;;wBAgB1B,oBACd,OAAO,kCACP;EAAW;EAAoB;;;;;YAiCrB;EACV;EACA;EACA;EACA;;wBAGc,oBAAoB,gBAAgB;;;;wBAsBpC,oBACd,eACA,uBACA;EACG;EAAe;EAAa;;;;wBAWjB,uBAAuB,eAAe,aAAa;;;YAUvD;EAAqB;EAAY,OAAO;EAAiB;;;wBAGrD,kBACd,kBAAkB,oCAClB;EAAW;EAAc;EAAgB;IACxC;;YAYS;;YAYA;EACV,QAAQ;EACR;EACA;EACA;;;;;qBAMW,kCAAkC;;;;wBA6C/B,2BACd,QAAQ,qBACR,OAAO,KAAK,mFACZ,OAAO,KAAK;;;;wBAsCE,oBAAoB,cAAc;;;YAyBtC;WACD;WACA;WACA;WACA;;;;;;wBAiBK,kBAAkB;;;;YAmBtB;EACV,SAAS,SAAS;EAClB,MAAM,SAAS;EACf,OAAO;EACP,QAAQ;EACR,QAAQ;EACR,QAAQ,SAAS;EACjB,SAAS;IAAW;IAAe,MAAM;;EACzC,YAAY;EACZ,eAAe;EACf,UAAU;EACV,YAAY;EACZ,OAAO;EACP,QAAQ;EACR,OAAO;EACP;EACA;EACA;EACA;EACA;;;;;;;wBAQc,yBACd,cACA,aAAa,qBACZ;;wBA0Ha,qBACd,0BACA;;;;;;wBAkBc,mBAAmB;;;;wBASnB,kBACd;EAAU,YAAY;eACtB;YAaU;EAAyB;EAAY;EAAe,OAAO;;;;;;wBAMvD,4BACd,UAAU,oBAAoB,kBAC9B,SAAS,cAAc;EACpB,WAAW;EAAwB,UAAU,YAAY;;;;;qBA6NjD;;;;YAgGD;EACV,iBAAiB;EACjB,SAAS;EACT,QAAQ;;;EAGR,YAAY;;;EAGZ,SAAS;;;EAGT,QAAQ,SAAS;;EAEjB,aAAa,SAAS;;;EAGtB,UAAU,SAAS;;EAEnB,QAAQ,SAAS;EACjB,YAAY;EACZ,OAAO;EACP,QAAQ,SAAS;;;EAGjB,UAAU;;EAEV,iBAAiB,SAAS;;EAE1B,MAAM;;EAEN,YAAY,SAAS;;EAErB,MAAM,SAAS;;;EAGf,OAAO,SAAS;;EAEhB,cAAc,SAAS;;EAEvB,YAAY;IAAW;IAAe;IAAe;;;EAErD,UAAU,SAAS;;EAEnB,cAAc;;EAEd,kBAAkB;;EAElB,eAAe;;EAEf,iBAAiB;;EAEjB,YAAY;;EAEZ,mBAAmB;IAAW;IAAsB;;;EAEpD,kBAAkB;IAAW;IAAsB;;;EAEnD,kBAAkB;;EAElB,YAAY;;EAEZ,UAAU;;;;;;wBAOI,mBACd,cACA,qCACA,UAAS,UACR;;;;wBAssCa,wBACd,QAAQ,qBACR,OAAO,KAAK,uDACZ,OAAO,KACL;;;;;;;wBAgBY,yBACd,OAAO,KAAK,uDACZ,OAAO,qBACN;;;;;YA0MS;EACV,QAAQ,SAAS;EACjB,SAAS;;wBAGK,kBAAkB,cAAc,sCAAsC;cA0DhF;;EAEW,MAAA,SAAA"} +{"version":3,"file":"tui.d.ts","names":[],"sources":["../src/context-gauge.ts","../src/model-usage-limits.ts","../src/sidebar-width.ts","../src/index.tsx"],"mappings":";;;;KAEY;qBAEC;qBACA;qBACA;KAED;UAiBK;EACf;EACA,QAAQ;EACR;;wBAOc,iBAAiB,kBAAkB;wBAOnC,iBAAiB;wBAMjB,oBAAoB;wBAQpB,iBAAiB,iBAAiB;wBAOlC,WACd,oCACA,mBAAkB;EACf;EAAgB;;wBA+CL,YAAY;;;;qBChHf;qBACA;qBACA;;;;;;;;wBCyHG,UAAU;;;;qBCpBb;;;;qBAMA;;;qBAGA;qBACA;;YAED,mBAAmB,WAAW;;;;;;;;;;qBAU7B;YA+BD;EAAe;EAAqB;;;YAGpC;EAAuB;EAAgB;;;YAEvC;EAAoB,QAAQ,eAAe;;;YAE3C;EAAuB,MAAM;EAAY,WAAW;;;;wBAQhD,qBAAqB,iBAAiB;;wBAqDtC,cAAc,KAAK,qCAAqC;;;wBAUlD,0BACpB,KAAK,oCACL,cACC,QAAQ;;;wBAeK,iBAAiB,cAAc;;;wBAgB/B,WAAW;;;wBAWX,aAAa,cAAc;;;wBAU3B,kBAAkB;;;wBAQlB,qBAAqB,iBAAiB;;;;wBAmBtC,oBAAoB,wBAAwB;YAwChD;EAAyB;EAAgB;EAAiB;;;wBAuItD,4BACd,8BACA,mBACA,4BACA,kCACC;;wBAUa,sBACd,uBACA,oCACA;;wBAgBc,mBAAmB;YAYvB;EAAiB;EAAgB;EAAiB;;;;;;;wBAO9C,iBACd,0BACA;EACG;EAAe;;;;;;wBAsBJ,oBACd,0BACA,yCACA,kCACC;;;;;wBAqBa,qBAAqB,OAAO,qBAAqB;;;;;wBAQjD,uBACd,aAAa;;;;;wBAeC,gBAAgB;;;;;;;wBAehB,wBACd,6CACA;;;;;;;;;;;;;wBAwBc,oBACd,6CACA;;;YAmDU;EAAuB;EAAyB;;;;;YAKhD;EACV;EACA;EACA;EACA;EACA,MAAM;;;YAII;EACV,QAAQ;EACR,SAAS;EACT,OAAO;;;;;;;;;wBAUO,iBACd,OAAO,qBACP,iCACA,iDACA;EAAwB;EAAa;EAAgB;IACpD;YAgDS;EACV;EACA;;;wBAIc,eACd,8CACC;wBAgCa,kBAAkB;wBAWlB,mBAAmB,SAAS;YAahC;EACV;EACA;EACA;;;wBAIc,oBAAoB,cAAc;wBAYlC,uBAAuB,SAAS;wBAehC,wBACd,SAAS;EACN;EAAsB;;YAWf;EACV;EACA;;YAGU;YAEA,oBAAoB;EAC9B,UAAU,QAAQ,OAAO;EACzB;;;;wBAwEc,iBAAiB;EAAqB,QAAQ;EAAY;;;wBAuD1D,qBACd,8CACC;;wBA2Ba,eAAe,8CAA8C;;;wBAO7D,qBACd,SAAS,sCACT;wBA2Bc,mBACd,SAAS,oCACT;YAgBU;EACV;EACA;;;wBAIc,sBAAsB,8CAA8C;;wBAiCpE,wBAAwB;wBASxB,sBACd,eAAe;;wBAcD,eAAe;wBASf,iBAAiB,eAAe;wBAQhC,kBAAkB,MAAK;;qBAmB1B;qBACA;qBACA;;;qBAGA;;YAGD;EAAe;EAAe;EAAgB;;;;;;wBAM1C,kBAAkB,2BAA2B;;YA0BjD;EACV,SAAS;EACT;EACA;EACA;;;;wBAKc,kBACd,eAAe,cACf,sBACC;;wBAaa,kBAAkB;;;;wBASlB,gBAAgB;;YAapB;EAAkB;EAAe;EAAgB;;;;wBAI7C,eAAe,eAAe,eAAe;;wBAS7C,kBAAkB,KAAK;;wBAmCvB,iBAAiB;;wBAKjB,kBAAkB,eAAe;;wBAQjC,kBAAkB;;wBAQlB,mBAAmB,KAAK;;;wBAYxB,qBAAqB,gBAAgB;;qBAaxC;;;wBAIG,SAAS;YAiBb;;;YAIA;EAAa;EAAiB,QAAQ;;;qBAGrC;;qBAEA;;wBAmBG,aAAa,iBAAiB,SAAS;;;;wBASvC,eAAe,iBAAiB;;;;;;wBA2BhC,gBAAgB,8CAA8C;;;wBAyB9D,eAAe,gBAAgB,aAAa;;;YAQhD;;wBAGI,SAAS,QAAQ,aAAa;;wBAO9B,YAAY,MAAM;;YAKtB;EAAgB,SAAS;EAAY;;;wBAGjC,iBACd,gBAAgB,YAChB,sBACC;;wBAOa,eAAe;YAgBnB;EAAoB;EAAe;EAAkB;;;;wBASjD,gBAAgB,2CAA2C;;;wBAY3D,iBAAiB;;;qBAoBpB;;;qBAGA;;;;qBAIA;;;;;qBAKA;;;YAID,WACV,cACA,yBACA;EAAW;EAAa;EAAiB;EAAsB;MAC5D;EAAU;;;;qBAIF,gBAAgB;;;;;;;YAwBjB;EACV;EACA;EACA;EACA;;;;wBAKc,wBAAwB,oCAAoC;;;;;wBAwB5D,oBACd;EACG;EAAe;;;;YAYR;EACV,SAAS;EACT;EACA;;;;;;wBAOoB,gBACpB,mBACA,OAAM,UACL,QAAQ;;;wBA8BK,kBAAkB,UAAU;;;wBAe5B,gBACd;EAAS;EAAa;EAA0B;GAChD;;qBAiBW;qBACA;;qBAEA;;qBAEA;;qBAEA;;qBAEA;;qBAEA;;YAGD;EAAgB;EAAsB;;;;;KAK7C;;wBAQW;;wBAMA,qBAAqB;;;wBAMrB,gBAAgB;;;wBAQhB,aAAa;EAC3B;IAAS;IAAc;;EACvB;IAAc;IAAc;;;;;;wBAWd,eAAe;;;wBAaf,UAAU;;;;;;wBAUV,kBACd,gBACA;EAAQ;EAAc;GACtB;;;;;wBAiBc,iBAAiB,QAAQ;;;;;;;wBAkBzB,cAAc,eAAe;;;;wBAoB7B,QAAQ,eAAe;;qBAQ1B;;;;wBAKG,iBAAiB,oBAAoB;YAsBzC;YACA;;YAGA;EAAsB,MAAM;EAAqB,QAAQ;;;;wBAsBrD,uBAAuB,uBAAuB;;wBAY9C,sBAAsB,iBAAiB;;;;wBAQvC,qBACd;EAAQ;EAAuB;uBAC9B;;YAQS;;EAEV;EACA;EACA;EACA;;;;;;;;wBAsCc,qBACd,8CACC,YAAY;YA6BH;YACA;YACA;;YAGA;EACV;EACA;EACA,WAAW;EACX;EACA;EACA;;;;wBAcc,qBACd,6CACA,iBACA;EAAkB;EAAsB;IACvC;;;;;;;;;;qBAyFU;;YAGD;;EAEV;;EAEA;EACA,OAAO;;EAEP;;EAEA;;EAEA;;EAEA;;EAEA;;;EAGA,MAAM;;EAEN,YAAY;;EAEZ;;EAEA,WAAW;;;;;;;;;wBAUG,0BACd,4BACA;EAAS;EAAkB;GAC3B,cACA,mBACC;;;;;wBAoBa,2BAA2B,mBAAmB;;;;;;;;wBAoB9C,iBACd,YACA,4BACA,cACA,OAAO,sBACN;;;wBA4Ba,aAAa;;YA0BjB;EACV;EACA;EACA;EACA;EACA;;;;;YAMU;EACV,MAAM;EACN;EACA;EACA;EACA,QAAQ;;;;;YAME;EACV;EACA,QAAQ,YAAY;EACpB,aAAa,YAAY;EACzB;;;wBAec,eAAe,kBAAkB;;;;wBA2BjC,gBACd,YACA,4BACA,cACA,OAAO,qBACP,WAAW,uBACV;;;;;;;;;wBAwBa,gBACd,cACA,+BACA,UAAS,yBACR;;;wBA8Da,sBACd,cACA,kBAAkB,kBACjB;;;;;YAgBS;;YAGA;EAAiB,KAAK;EAAiB;;;;;;;;qBAQtC,aAAa,OAAO;;;;;;wBAWjB,iBAAiB,eAAe,oBAAoB;;qBAmBvD;;qBAEA;;;qBAGA;;qBAEA;;qBAEA;;;qBAGA;;;qBAGA;;qBAEA;;qBAEA;;qBAEA;;qBAEA;;;;;;qBAMA;;;;wBAUG,mBACd,MAAM,iCACN;;;;wBAUc,sBACd,oCACA;;;;wBAac,uBAAuB;;;;wBAiBvB,gBAAgB,MAAM,gBAAgB;;;wBAStC,kBACd,MAAM,KAAK,2CACX;;wBAUc,kBAAkB,MAAM,KAAK;;;;wBAQ7B,mBAAmB;;;wBAMnB,kBAAkB,gBAAgB;;;;;;;;wBA8ClC,oBACd,MAAM,gBACN,cACA,gBACA;;;;;YAsCU;EACV;EACA;EACA;EACA,MAAM;EACN;;;;;;;wBAQc,uBAAuB,gBAAgB,mBAAmB;;;;;wBA4C1D,kBAAkB,KAAK,iBAAiB;;;wBAwBxC,sBAAsB,gBAAgB;;;;;wBAWtC,qBACd,sCACA,iCACA;;;wBAiBc,iBAAiB;;YAQrB;EAAwB;EAAY;EAAc,OAAO;;;YAGzD;EACV;EACA;EACA;EACA;EACA;EACA,SAAS;EACT;EACA;EACA,QAAQ;EACR;EACA;;;;;;;wBAcc,mBACd,gBAAgB,kBAChB,cACA,gBACA,eACC;;;qBA+DU;;;qBAGA;;qBAEA;;qBAEA;;qBAEA;;qBAEA;;qBAEA;;qBAEA;;qBAEA;;qBAEA;;;qBAGA;qBACA;qBACA;qBACA;qBACA;;qBAEA;;qBAEA;;qBAOA,6BAA6B,SAAS,OAAO;;;wBAQ1C,qBAAqB,kBAAkB,kBAAkB;;;;wBAOzD,mBACd,yCACA,cACA;;;;;wBAac,oBACd,kBAAkB;;wBAgCJ,kBAAkB,eAAe;;;;;wBASjC,oBAAoB,OAAO,0BAA0B;;;;wBAkBrD,kBAAkB,gBAAgB;;;;;;wBAWlC,qBACd,OAAO,eACP;EAAW;EAAc;EAAgB;;;wBAsC3B,eAAe,+BAA+B;;;wBAQ9C,kBAAkB,QAAQ;;;;;wBAgB1B,oBACd,OAAO,kCACP;EAAW;EAAoB;;;;;YAsDrB;EACV;EACA;EACA;EACA;;wBAGc,oBAAoB,gBAAgB;;;;wBAsBpC,oBACd,eACA,uBACA;EACG;EAAe;EAAa;;;;wBAWjB,uBAAuB,eAAe,aAAa;;;YAUvD;EAAqB;EAAY,OAAO;EAAiB;;;wBAGrD,kBACd,kBAAkB,oCAClB;EAAW;EAAc;EAAgB;IACxC;;YAYS;;YAYA;EACV,QAAQ;EACR;EACA;EACA;;;;;qBAMW,kCAAkC;;;;wBA6C/B,2BACd,QAAQ,qBACR,OAAO,KAAK,mFACZ,OAAO,KAAK;;;;wBAsCE,oBAAoB,cAAc;;;YAyBtC;WACD;WACA;WACA;WACA;;;;;;wBAiBK,kBAAkB;;;;YAmBtB;EACV,SAAS,SAAS;EAClB,MAAM,SAAS;EACf,OAAO;EACP,QAAQ;EACR,QAAQ;EACR,QAAQ,SAAS;EACjB,SAAS;IAAW;IAAe,MAAM;;EACzC,YAAY;EACZ,eAAe;EACf,UAAU;EACV,YAAY;EACZ,OAAO;EACP,QAAQ;EACR,OAAO;EACP;EACA;EACA;EACA;EACA;;;;;;;wBAQc,yBACd,cACA,aAAa,qBACZ;;wBA0Ha,qBACd,0BACA;;;;;;wBAkBc,mBAAmB;;;;wBASnB,kBACd;EAAU,YAAY;eACtB;YAaU;EAAyB;EAAY;EAAe,OAAO;;;;;;wBAMvD,4BACd,UAAU,oBAAoB,kBAC9B,SAAS,cAAc;EACpB,WAAW;EAAwB,UAAU,YAAY;;;;;qBA6NjD;;;;YAgGD;EACV,iBAAiB;EACjB,SAAS;EACT,QAAQ;;;EAGR,YAAY;;;EAGZ,SAAS;;;EAGT,QAAQ,SAAS;;EAEjB,aAAa,SAAS;;;EAGtB,UAAU,SAAS;;EAEnB,QAAQ,SAAS;EACjB,YAAY;EACZ,OAAO;EACP,QAAQ,SAAS;;;EAGjB,UAAU;;EAEV,iBAAiB,SAAS;;EAE1B,MAAM;;EAEN,YAAY,SAAS;;EAErB,MAAM,SAAS;;;EAGf,OAAO,SAAS;;EAEhB,cAAc,SAAS;;EAEvB,YAAY;IAAW;IAAe;IAAe;;;EAErD,UAAU,SAAS;;EAEnB,cAAc;;EAEd,kBAAkB;;EAElB,eAAe;;EAEf,qBAAqB;;EAErB,iBAAiB;;EAEjB,YAAY;;EAEZ,mBAAmB;IAAW;IAAsB;;;EAEpD,kBAAkB;IAAW;IAAsB;;;EAEnD,kBAAkB;;EAElB,YAAY;;EAEZ,UAAU;;;;;;wBAOI,mBACd,cACA,qCACA,UAAS,UACR;;;;wBAiwCa,wBACd,QAAQ,qBACR,OAAO,KAAK,uDACZ,OAAO,KACL;;;;;;;wBAgBY,yBACd,OAAO,KAAK,uDACZ,OAAO,qBACN;;;;;YAmTS;EACV,QAAQ,SAAS;EACjB,SAAS;;wBAGK,kBAAkB,cAAc,sCAAsC;cA0DhF;;EAEW,MAAA,SAAA"} diff --git a/src/plugins/tui/dist/tui.js b/src/plugins/tui/dist/tui.js index 473cbc22..2bd7b24a 100644 --- a/src/plugins/tui/dist/tui.js +++ b/src/plugins/tui/dist/tui.js @@ -3,2663 +3,4707 @@ import { execFile } from "node:child_process"; import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"; import { mkdir, readFile, rename, stat, unlink, writeFile } from "node:fs/promises"; import { homedir } from "node:os"; -import { dirname, join, resolve } from "node:path"; +import { basename, dirname, join, relative, resolve, sep } from "node:path"; import { Plugin } from "@opencode/plugin/tui"; import { ErrorBoundary, For, Show, createEffect, createMemo, createSignal, on, onCleanup, onMount } from "solid-js"; -import { DatabaseSync } from "node:sqlite"; import { fileURLToPath } from "node:url"; -//#region src/context-gauge.ts -const CONTEXT_BAR_CELLS = 12; -const CONTEXT_BAR_FILLED_CELL = "▰"; -const CONTEXT_BAR_EMPTY_CELL = "▱"; -const BAR_SHAPES = { - block: { - filled: "▰", - empty: "▱", - mark: "│" - }, - line: { - filled: "━", - empty: "─", - mark: "┼" - }, - smooth: { - filled: "█", - empty: "░", - mark: "┆" - }, - ascii: { - filled: "=", - empty: "-", - mark: "|" - }, - dots: { - filled: "●", - empty: "○", - mark: "│" - }, - braille: { - filled: "⣿", - empty: "⣀", - mark: "⡇" +import { DatabaseSync } from "node:sqlite"; +//#region src/mermaid-ascii.ts +function cleanLabel(raw) { + return raw.replace(//gi, " / ").replace(/^["'`]|["'`]$/g, "").replace(/\s+/g, " ").trim(); +} +function splitOperandsOutsideDelimiters(text) { + const out = []; + let cur = ""; + let quote = null; + let bracketDepth = 0; + for (let i = 0; i < text.length; i += 1) { + const ch = text[i] ?? ""; + if (quote) { + if (ch === quote) quote = null; + cur += ch; + continue; + } + if (ch === "\"" || ch === "'") { + quote = ch; + cur += ch; + continue; + } + if (ch === "[" || ch === "(" || ch === "{") { + bracketDepth += 1; + cur += ch; + continue; + } + if ((ch === "]" || ch === ")" || ch === "}") && bracketDepth > 0) { + bracketDepth -= 1; + cur += ch; + continue; + } + if (ch === "&" && bracketDepth === 0) { + const part = cur.trim(); + if (part) out.push(part); + cur = ""; + continue; + } + cur += ch; } -}; -function numberOrNull$1(value) { - return typeof value === "number" && Number.isFinite(value) ? value : null; + const tail = cur.trim(); + if (tail) out.push(tail); + return out; } -function contextUsageTone(percent) { - if (percent > 90) return "error"; - if (percent > 50) return "warning"; - if (percent > 25) return "success"; - return "info"; +function parseNodeToken(token) { + const trimmed = token.trim(); + if (trimmed === "[*]") return { + id: "__star__", + label: "●" + }; + const match = /^([A-Za-z0-9_.:-]+)\s*(?:\[\[([^\]]*)\]\]|\(\(([^)]*)\)\)|\(\[([^\]]*)\]\)|\{\{([^}]*)\}\}|\[([^\]]*)\]|\(([^)]*)\)|\{([^}]*)\})?$/.exec(trimmed); + if (!match) return { + id: trimmed.replace(/[^A-Za-z0-9_.:-]/g, "") || trimmed, + label: cleanLabel(trimmed) + }; + const id = match[1] ?? trimmed; + const rawLabel = match[2] ?? match[3] ?? match[4] ?? match[5] ?? match[6] ?? match[7] ?? match[8]; + return rawLabel !== void 0 ? { + id, + label: cleanLabel(rawLabel) + } : { id }; } -function formatTokenCount(tokens) { - const value = numberOrNull$1(tokens); - if (value === null || value < 0) return null; - return Math.round(value).toLocaleString("en-US"); +function truncateText(text, maxLen) { + if (maxLen <= 1) return text.slice(0, Math.max(0, maxLen)); + if (text.length <= maxLen) return text; + return `${text.slice(0, maxLen - 1)}…`; } -function formatContextWindow(limit) { - const value = numberOrNull$1(limit); - if (value === null || value <= 0) return null; - if (value >= 1e6) return `${(value / 1e6).toFixed(1)}M`; - if (value >= 1e3) return `${Math.floor(value / 1e3)}K`; - return `${Math.floor(value)}`; +function drawBox(label, maxWidth, indent = "") { + const text = truncateText(label, Math.max(8, maxWidth - indent.length - 4)); + const bar = "─".repeat(text.length + 2); + return [ + `${indent}╭${bar}╮`, + `${indent}│ ${text} │`, + `${indent}╰${bar}╯` + ]; } -function contextBarFilled(percent, cells = 12) { - const total = Math.max(1, Math.floor(cells)); - const filled = Math.round(percent / 100 * total); - if (!Number.isFinite(filled)) return 0; - return Math.min(total, Math.max(0, filled)); +const ARROW_PATTERN = String.raw`(?:(?:-->|-\.->|==>)\|([^|]+)\||--\s+([^->\n]+?)\s+-->|-\.\s*([^.]+?)\s*\.->|==\s*([^=]+?)\s*==>|-->|-\.->|==>|---)`; +const EDGE_RE = new RegExp(String.raw`^(.*?)\s+${ARROW_PATTERN}\s+(.*)$`); +function splitChainOperands(line) { + const arrowTokenRe = new RegExp(String.raw`\s+(${ARROW_PATTERN})\s+`, "g"); + const parts = []; + const connectors = []; + let lastIdx = 0; + for (const m of line.matchAll(arrowTokenRe)) { + const idx = m.index ?? 0; + parts.push(line.slice(lastIdx, idx).trim()); + const arrow = m[1] ?? ""; + const labelRaw = m[2] ?? m[3] ?? m[4] ?? m[5]; + connectors.push({ + label: labelRaw ? cleanLabel(labelRaw) : void 0, + dashed: arrow.includes("-.") + }); + lastIdx = idx + m[0].length; + } + parts.push(line.slice(lastIdx).trim()); + return { + parts, + connectors + }; +} +function parseFlowchart(lines) { + const nodes = /* @__PURE__ */ new Map(); + const edges = []; + let direction = "TD"; + const ensureNode = (id, label) => { + const existing = nodes.get(id); + if (existing) { + if (label && existing.label === existing.id) existing.label = label; + return; + } + nodes.set(id, { + id, + label: label ?? id + }); + }; + for (const rawLine of lines) { + const stripped = rawLine.trim(); + if (!stripped || stripped.startsWith("%%")) continue; + if (/^(flowchart|graph)\s+/i.test(stripped)) { + if (/\bLR\b|\bRL\b/i.test(stripped)) direction = "LR"; + continue; + } + if (/^(classDef|style|linkStyle|click|class|direction|subgraph|end)\b/i.test(stripped)) continue; + for (const stmt of stripped.split(";")) { + const s = stmt.trim(); + if (!s) continue; + if (EDGE_RE.test(` ${s} `) || [ + "-->", + "-.->", + "==>", + "---" + ].some((tok) => s.includes(tok))) { + const { parts, connectors } = splitChainOperands(s); + if (parts.length >= 2 && connectors.length === parts.length - 1) { + for (let i = 0; i < connectors.length; i += 1) { + const leftGroup = splitOperandsOutsideDelimiters(parts[i] ?? ""); + const rightGroup = splitOperandsOutsideDelimiters(parts[i + 1] ?? ""); + const conn = connectors[i]; + for (const lTok of leftGroup) { + const left = parseNodeToken(lTok); + ensureNode(left.id, left.label); + for (const rTok of rightGroup) { + const right = parseNodeToken(rTok); + ensureNode(right.id, right.label); + edges.push({ + from: left.id, + to: right.id, + label: conn?.label, + dashed: Boolean(conn?.dashed) + }); + } + } + } + continue; + } + } + const single = parseNodeToken(s); + if (single.id) ensureNode(single.id, single.label); + } + } + return { + direction, + nodes, + edges + }; +} +function renderHorizontalChain(chain, edges, maxWidth) { + if (chain.length < 2 || chain.length > 5) return null; + const boxes = chain.map((n) => drawBox(n.label, 28)); + const edgeWidths = edges.map((e) => e.label ? Math.max(5, e.label.length + 4) : 4); + if (boxes.reduce((sum, b) => sum + (b[0]?.length ?? 0), 0) + edgeWidths.reduce((sum, w) => sum + w, 0) > maxWidth) return null; + const top = []; + const mid = []; + const bot = []; + for (let i = 0; i < boxes.length; i += 1) { + const box = boxes[i]; + if (!box) continue; + top.push(box[0] ?? ""); + mid.push(box[1] ?? ""); + bot.push(box[2] ?? ""); + if (i < edges.length) { + const ew = edgeWidths[i] ?? 4; + const lbl = edges[i]?.label; + const arrowMid = `${(edges[i]?.dashed ? "╌" : "─").repeat(ew - 1)}►`; + const arrowTop = lbl ? ` ${lbl}`.padEnd(ew, " ") : " ".repeat(ew); + top.push(arrowTop); + mid.push(arrowMid); + bot.push(" ".repeat(ew)); + } + } + return [ + top.join(""), + mid.join(""), + bot.join("") + ]; } -function contextBar(percent, options = 12) { - const value = numberOrNull$1(percent); - if (value === null) return null; - const total = Math.max(1, Math.floor(typeof options === "number" ? options : options?.cells ?? 12)); - const shapeKey = typeof options === "object" && options?.shape && options.shape in BAR_SHAPES ? options.shape : "block"; - const glyphs = BAR_SHAPES[shapeKey] ?? BAR_SHAPES.block; - const evenMark = typeof options === "object" ? Boolean(options?.evenMark) : false; - const filledCount = contextBarFilled(value, total); - const emptyCount = total - filledCount; - if (!evenMark || total < 4) return { - filled: glyphs.filled.repeat(filledCount), - empty: glyphs.empty.repeat(emptyCount) +function renderFlowchart(lines, maxWidth) { + const { direction, nodes, edges } = parseFlowchart(lines); + if (nodes.size === 0) return null; + const outEdges = /* @__PURE__ */ new Map(); + const inDegree = /* @__PURE__ */ new Map(); + const incomingSources = /* @__PURE__ */ new Map(); + for (const id of nodes.keys()) { + outEdges.set(id, []); + inDegree.set(id, 0); + incomingSources.set(id, []); + } + for (const e of edges) { + outEdges.get(e.from)?.push(e); + inDegree.set(e.to, (inDegree.get(e.to) ?? 0) + 1); + incomingSources.get(e.to)?.push(e.from); + } + const isSimpleChain = edges.length === nodes.size - 1 && [...outEdges.values()].every((list) => list.length <= 1) && [...inDegree.values()].every((deg) => deg <= 1); + if (direction === "LR" && isSimpleChain) { + const startId = [...nodes.keys()].find((id) => (inDegree.get(id) ?? 0) === 0); + if (startId) { + const chain = []; + const chainEdges = []; + let cur = startId; + const seen = /* @__PURE__ */ new Set(); + while (cur && !seen.has(cur)) { + seen.add(cur); + const node = nodes.get(cur); + if (!node) break; + chain.push(node); + const nextEdge = outEdges.get(cur)?.[0]; + if (!nextEdge) break; + chainEdges.push(nextEdge); + cur = nextEdge.to; + } + const horiz = renderHorizontalChain(chain, chainEdges, maxWidth); + if (horiz) return horiz; + } + } + const out = []; + const visited = /* @__PURE__ */ new Set(); + const renderedJoin = /* @__PURE__ */ new Set(); + const renderSubtree = (nodeId, prefix, isRoot, edgeFromParent) => { + const node = nodes.get(nodeId); + if (!node) return; + const deg = inDegree.get(nodeId) ?? 0; + if (!isRoot && deg > 1 && !renderedJoin.has(nodeId)) { + if ((incomingSources.get(nodeId) ?? []).some((src) => !visited.has(src) && src !== edgeFromParent?.from)) { + const lbl = edgeFromParent?.label ? ` (${edgeFromParent.label})` : ""; + out.push(`${prefix} ╰─► converges at ${truncateText(node.label, Math.max(12, maxWidth - prefix.length - 20))}${lbl}`); + return; + } + renderedJoin.add(nodeId); + } + if (visited.has(nodeId)) { + const lbl = edgeFromParent?.label ? ` (${edgeFromParent.label})` : ""; + out.push(`${prefix} ╰─► ↺ ${truncateText(node.label, Math.max(12, maxWidth - prefix.length - 10))}${lbl}`); + return; + } + visited.add(nodeId); + if (!isRoot && deg > 1) { + const sources = (incomingSources.get(nodeId) ?? []).map((s) => nodes.get(s)?.id ?? s).filter((v, i, arr) => arr.indexOf(v) === i); + out.push(`${prefix} (from ${sources.join(", ")})`); + } + const box = drawBox(node.label, maxWidth, prefix); + out.push(...box); + const children = outEdges.get(nodeId) ?? []; + if (children.length === 0) return; + if (children.length === 1 && children[0]) { + const child = children[0]; + const stemX = `${prefix} `; + const lineChar = child.dashed ? "┆" : "│"; + const lbl = child.label ? ` ${child.label}` : ""; + out.push(`${stemX}${lineChar}${lbl}`); + out.push(`${stemX}▼`); + renderSubtree(child.to, prefix, false, child); + return; + } + for (let i = 0; i < children.length; i += 1) { + const child = children[i]; + if (!child) continue; + const isLast = i === children.length - 1; + const branch = isLast ? "└──►" : "├──►"; + const edgeTag = child.label ? `[${child.label}] ` : ""; + const childPrefix = `${prefix} ${isLast ? " " : "│ "}`; + out.push(`${prefix} ${branch} ${edgeTag}${truncateText(nodes.get(child.to)?.label ?? child.to, Math.max(12, maxWidth - prefix.length - edgeTag.length - 8))}`); + const grandChildren = outEdges.get(child.to) ?? []; + if (!visited.has(child.to)) { + visited.add(child.to); + if (grandChildren.length > 0) for (let j = 0; j < grandChildren.length; j += 1) { + const gc = grandChildren[j]; + if (!gc) continue; + if ((inDegree.get(gc.to) ?? 0) > 1) { + if ((incomingSources.get(gc.to) ?? []).some((s) => !visited.has(s))) { + out.push(`${childPrefix} ╰─► converges at ${truncateText(nodes.get(gc.to)?.label ?? gc.to, Math.max(12, maxWidth - childPrefix.length - 20))}`); + continue; + } + } + out.push(`${childPrefix} │`); + out.push(`${childPrefix} ▼`); + renderSubtree(gc.to, childPrefix, false, gc); + } + } + } }; - const mid = Math.floor(total / 2); - const mark = glyphs.mark ?? "|"; - if (filledCount <= mid) { - const emptyBefore = mid - filledCount; - const emptyAfter = Math.max(0, emptyCount - emptyBefore - 1); - return { - filled: glyphs.filled.repeat(filledCount), - empty: `${glyphs.empty.repeat(emptyBefore)}${mark}${glyphs.empty.repeat(emptyAfter)}` + const roots = [...nodes.keys()].filter((id) => (inDegree.get(id) ?? 0) === 0); + const queue = roots.length > 0 ? roots : [...nodes.keys()].slice(0, 1); + for (let i = 0; i < queue.length; i += 1) { + const rootId = queue[i]; + if (!rootId || visited.has(rootId)) continue; + if (out.length > 0) out.push(""); + renderSubtree(rootId, "", true); + } + for (const id of nodes.keys()) if (!visited.has(id)) { + if (out.length > 0) out.push(""); + renderSubtree(id, "", true); + } + return out; +} +function renderSequence(lines, maxWidth) { + const participants = /* @__PURE__ */ new Map(); + const messages = []; + const addParticipant = (id, label) => { + if (!participants.has(id)) participants.set(id, cleanLabel(label ?? id)); + else if (label) participants.set(id, cleanLabel(label)); + }; + for (const raw of lines) { + const s = raw.trim(); + if (!s || s.startsWith("%%") || /^sequenceDiagram\b/i.test(s)) continue; + const partMatch = /^(?:participant|actor)\s+([A-Za-z0-9_.-]+)(?:\s+as\s+(.+))?$/i.exec(s); + if (partMatch?.[1]) { + addParticipant(partMatch[1], partMatch[2]); + continue; + } + const msgMatch = /^([A-Za-z0-9_.-]+)\s*(-->>|->>|-->|->)\s*([A-Za-z0-9_.-]+)\s*:\s*(.*)$/.exec(s); + if (msgMatch?.[1] && msgMatch[2] && msgMatch[3]) { + addParticipant(msgMatch[1]); + addParticipant(msgMatch[3]); + messages.push({ + from: msgMatch[1], + to: msgMatch[3], + text: cleanLabel(msgMatch[4] ?? ""), + dashed: msgMatch[2].startsWith("--") + }); + } + } + if (participants.size === 0 || messages.length === 0) return null; + const ids = [...participants.keys()]; + const count = ids.length; + const colStep = Math.floor((maxWidth - 4) / Math.max(1, count - 1)); + if (count >= 2 && count <= 4 && colStep >= 18) { + const centers = ids.map((_, idx) => 5 + idx * Math.min(colStep, 22)); + const totalW = (centers[count - 1] ?? 10) + 8; + const out = []; + const topLine = Array(totalW).fill(" "); + const midLine = Array(totalW).fill(" "); + const botLine = Array(totalW).fill(" "); + for (let i = 0; i < count; i += 1) { + const id = ids[i]; + if (!id) continue; + const label = truncateText(participants.get(id) ?? id, 12); + const boxW = label.length + 4; + const start = Math.max(0, (centers[i] ?? 0) - Math.floor(boxW / 2)); + const top = `╭${"─".repeat(label.length + 2)}╮`; + const mid = `│ ${label} │`; + const bot = `╰${"─".repeat(label.length + 2)}╯`; + for (let k = 0; k < boxW; k += 1) if (start + k < totalW) { + topLine[start + k] = top[k]; + midLine[start + k] = mid[k]; + botLine[start + k] = k === (centers[i] ?? 0) - start ? "┬" : bot[k]; + } + } + out.push(topLine.join("").trimEnd(), midLine.join("").trimEnd(), botLine.join("").trimEnd()); + const emptyLifelines = () => { + const arr = Array(totalW).fill(" "); + for (const c of centers) arr[c] = "│"; + return arr; + }; + for (const msg of messages) { + const iFrom = ids.indexOf(msg.from); + const iTo = ids.indexOf(msg.to); + if (iFrom < 0 || iTo < 0) continue; + const cFrom = centers[iFrom] ?? 0; + const cTo = centers[iTo] ?? 0; + const left = Math.min(cFrom, cTo); + const right = Math.max(cFrom, cTo); + const labelRow = emptyLifelines(); + const msgText = truncateText(msg.text, Math.max(6, right - left - 2)); + for (let k = 0; k < msgText.length; k += 1) if (left + 2 + k < totalW) labelRow[left + 2 + k] = msgText[k]; + out.push(labelRow.join("").trimEnd()); + const arrowRow = emptyLifelines(); + const wire = msg.dashed ? "┄" : "─"; + for (let x = left + 1; x < right; x += 1) arrowRow[x] = wire; + if (cFrom < cTo) { + arrowRow[left] = "├"; + arrowRow[right - 1] = "►"; + } else { + arrowRow[left + 1] = "◄"; + arrowRow[right] = "┤"; + } + out.push(arrowRow.join("").trimEnd()); + } + out.push(emptyLifelines().join("").trimEnd()); + return out; + } + return messages.map((m, idx) => { + const arrow = m.dashed ? "╌╌►" : "──►"; + const fromLbl = participants.get(m.from) ?? m.from; + const toLbl = participants.get(m.to) ?? m.to; + return truncateText(`${idx + 1}. [${fromLbl}] ${arrow} [${toLbl}]: ${m.text}`, maxWidth); + }); +} +function renderStateDiagram(lines, maxWidth) { + return renderFlowchart(lines.map((line) => { + const trimmed = line.trim(); + if (/^stateDiagram(?:-v2)?$/i.test(trimmed)) return "flowchart TD"; + const arrowWithLabel = /^(.+?)\s*-->\s*(.+?)\s*:\s*(.+)$/.exec(trimmed); + if (arrowWithLabel?.[1] && arrowWithLabel[2] && arrowWithLabel[3]) return `${arrowWithLabel[1].trim()} -->|${arrowWithLabel[3].trim()}| ${arrowWithLabel[2].trim()}`; + return line; + }), maxWidth); +} +function renderMermaidToUnicode(rawLines, maxWidth = 76) { + const firstMeaningful = rawLines.map((l) => l.trim()).find((l) => l && !l.startsWith("%%")) ?? ""; + if (/^(?:flowchart|graph)\b/i.test(firstMeaningful)) { + const rendered = renderFlowchart(rawLines, maxWidth); + if (rendered && rendered.length > 0) return { + header: "[Diagram: Flowchart]", + lines: rendered + }; + } else if (/^sequenceDiagram\b/i.test(firstMeaningful)) { + const rendered = renderSequence(rawLines, maxWidth); + if (rendered && rendered.length > 0) return { + header: "[Diagram: Sequence]", + lines: rendered + }; + } else if (/^stateDiagram/i.test(firstMeaningful)) { + const rendered = renderStateDiagram(rawLines, maxWidth); + if (rendered && rendered.length > 0) return { + header: "[Diagram: State]", + lines: rendered }; } - const filledBefore = mid; - const filledAfter = Math.max(0, filledCount - filledBefore - 1); return { - filled: `${glyphs.filled.repeat(filledBefore)}${mark}${glyphs.filled.repeat(filledAfter)}`, - empty: glyphs.empty.repeat(emptyCount) + header: "[Mermaid Diagram]", + lines: rawLines.map((l) => ` ${l.trim()}`).filter((l) => l.trim().length > 0) }; } -function formatSpent(cost) { - const value = numberOrNull$1(cost); - if (value === null || value < 0) return null; - return `$${value.toFixed(2)}`; +const GFM_ALERT_RE = /^>\s*\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]\s*$/i; +function resolveArtifactRoots(workspaceDir) { + const roots = []; + const seen = /* @__PURE__ */ new Set(); + const pushRoot = (candidate) => { + try { + if (!existsSync(candidate)) return; + const real = realpathSync(candidate); + if (!seen.has(real)) { + seen.add(real); + roots.push(real); + } + } catch {} + }; + pushRoot(workspaceDir); + try { + let cur = resolve(workspaceDir); + for (let depth = 0; depth < 24; depth += 1) { + const dotGit = join(cur, ".git"); + if (existsSync(dotGit)) { + if (statSync(dotGit).isFile()) { + const content = readFileSync(dotGit, "utf8"); + const match = /^gitdir:\s*(.+)$/m.exec(content); + if (match?.[1]) { + const gitDir = resolve(cur, match[1].trim()); + const commonFile = join(gitDir, "commondir"); + const commonGitDir = existsSync(commonFile) ? resolve(gitDir, readFileSync(commonFile, "utf8").trim()) : basename(dirname(gitDir)) === "worktrees" ? dirname(dirname(gitDir)) : null; + if (commonGitDir && basename(commonGitDir) === ".git") pushRoot(dirname(commonGitDir)); + } + } + break; + } + const parent = dirname(cur); + if (parent === cur) break; + cur = parent; + } + } catch {} + return roots; } -//#endregion -//#region src/model-usage-limits.ts -/** Shared bounds for cached recent model-usage aggregation. */ -const MODEL_USAGE_VISIBLE_CEILING = 3; -const MODEL_USAGE_MESSAGE_LIMIT = 400; -const MODEL_USAGE_SESSION_LIMIT = 8; -//#endregion -//#region src/autonomy-state.ts -const DEFAULT_GOAL_LOOP_PREFS = { - enabled: false, - cooldownMs: 5e3, - maxContinuations: 25 -}; -const GOAL_LOOP_ENABLED_CYCLE = Object.freeze(["enabled", "disabled"]); -const MAX_CONTINUATIONS_CYCLE = Object.freeze([ - "10", - "25", - "50", - "100", - "200" -]); -const COOLDOWN_MS_CYCLE = Object.freeze([ - "1000", - "2000", - "5000", - "10000" -]); -const DEFAULT_DECISION_BUDGETS = { - monthlyUsd: 5, - perDecisionUsd: .1 -}; -/** Format USD compactly for a cycler cell ("$5", "$0.10"). */ -function formatUsd(value) { - return `$${value < 1 ? value.toFixed(2) : String(Math.round(value))}`; +function extractTitle(content, fallbackFile) { + for (const line of content.split(/\r?\n/)) { + const match = /^#\s+(.+?)\s*$/.exec(line.trim()); + if (match?.[1]) return match[1].trim(); + } + return fallbackFile.replace(/\.md$/i, ""); } -/** Build the USD step ladder used by the budget cyclers. */ -const MONTHLY_USD_CYCLE = Object.freeze([ - 1, - 2, - 5, - 10, - 20, - 50, - 100 -].map((value) => formatUsd(value))); -const PER_DECISION_USD_CYCLE = Object.freeze([ - .01, - .025, - .05, - .1, - .25, - .5, - 1 -].map((value) => formatUsd(value))); -/** Parse a staged USD cell back to a number; junk keeps the input. */ -function parseUsd(cell) { - const value = Number(cell.replace("$", "")); - return Number.isFinite(value) && value > 0 ? value : null; +function addArtifactFile(out, seenPaths, root, filePath, kind) { + try { + const real = realpathSync(filePath); + if (seenPaths.has(real)) return; + const st = statSync(real); + if (!st.isFile()) return; + const raw = readFileSync(real, "utf8"); + const lineCount = raw === "" ? 0 : raw.split(/\r?\n/).length; + const relPath = relative(root, real).replace(/\\/g, "/"); + const badge = kind === "plan" ? "PLAN" : kind === "report" ? "REPORT" : "ADR"; + seenPaths.add(real); + out.push({ + id: real, + kind, + badge, + title: extractTitle(raw, basename(real)), + path: real, + relPath, + modifiedMs: st.mtimeMs, + lineCount, + bytes: st.size + }); + } catch {} } -function buildAutonomyTab(input) { - const isPt = input.languagePref === "pt-BR"; - return { - id: "autonomy", - title: isPt ? "Autonomia" : "Autonomy", - groups: [ - { - title: isPt ? "Loop Contínuo (auto-continuação de sessões multi-turn)" : "Auto-Continue Loop (multi-turn session auto-continuation)", - rows: [ - { - id: "autonomy.goal_loop.enabled", - name: isPt ? "Loop Contínuo" : "Auto-Continue Loop", - value: input.goalLoop.enabled ? "enabled" : "disabled", - cycle: GOAL_LOOP_ENABLED_CYCLE, - note: isPt ? "continua tarefas multi-turn quando a sessão fica ociosa" + (input.goalLoopRestartPending ? " · [!] reinício necessário para aplicar (restart)" : " · aplicado após reiniciar o OpenCode") : "auto-continues multi-turn tasks when session goes idle" + (input.goalLoopRestartPending ? " · [!] restart required to apply" : " · applies after OpenCode restart") - }, - { - id: "autonomy.goal_loop.maxContinuations", - name: isPt ? "Limite continuações" : "Max continuations", - value: String(input.goalLoop.maxContinuations), - cycle: MAX_CONTINUATIONS_CYCLE, - note: isPt ? "1..200 — teto de segurança contra loops infinitos" : "1..200 — safety ceiling to prevent runaway tasks" - }, - { - id: "autonomy.goal_loop.cooldownMs", - name: isPt ? "Pausa entre turnos (ms)" : "Cooldown (ms)", - value: String(input.goalLoop.cooldownMs), - cycle: COOLDOWN_MS_CYCLE, - note: isPt ? "intervalo entre turnos autônomos (mín 1000ms)" : "delay between autonomous turns (min 1000ms)" - } - ] - }, - { - title: isPt ? "Orçamentos de Decisão (Jev)" : "Decision Budgets (Jev)", - rows: [{ - id: "autonomy.budget.monthly", - name: isPt ? "Teto Mensal (USD)" : "Monthly Budget Cap", - value: formatUsd(input.budgets.monthlyUsd), - cycle: MONTHLY_USD_CYCLE, - note: isPt ? "teto mensal em USD para arbitragem do Jev" : "monthly USD ceiling for gated arbitrator decisions" - }, { - id: "autonomy.budget.perDecision", - name: isPt ? "Teto por Consulta" : "Per-Decision Cap", - value: formatUsd(input.budgets.perDecisionUsd), - cycle: PER_DECISION_USD_CYCLE, - note: isPt ? "teto de custo por decisão — acima disso é recusada" : "price cap — gated decisions above this are refused" - }] - }, - { - title: isPt ? "Gradiente de Decisão (política de referência · governado por J1 e Orçamentos)" : "Decision Gradient (reference policy · governed by J1 & Budgets)", - rows: [ - { - id: "autonomy.gradient.solo", - name: isPt ? "Decisão solo" : "Decide solo", - value: isPt ? "autônomo" : "autonomous", - note: isPt ? "ações rotineiras de baixo risco · reversível sem travas (sem portão)" : "reversible & low-risk edits, routine fixes (no gate)" - }, - { - id: "autonomy.gradient.jev", - name: isPt ? "Decisão Jev" : "Jev decides", - value: isPt ? "arbitrado" : "arbitrated", - note: isPt ? "ambiguidade de tipos e rotas · configurado nos Tetos de Orçamento acima" : "typed ambiguity & candidate ranking · configured via Budgets above" - }, - { - id: "autonomy.gradient.human", - name: isPt ? "Aprovação humana" : "Human decides", - value: isPt ? "revisão humana" : "human review", - note: isPt ? "ações destrutivas e de alto risco · configurado no limiar do Portão J1" : "high-risk & destructive operations · configured via J1 Gate" - } - ] +function scanPantheonArtifacts(workspaceDir) { + if (!workspaceDir || !existsSync(workspaceDir)) return []; + const roots = resolveArtifactRoots(workspaceDir); + const out = []; + const seenPaths = /* @__PURE__ */ new Set(); + for (const root of roots) { + const deepworkDir = join(root, ".pantheon", "deepwork"); + if (existsSync(deepworkDir)) try { + for (const entry of readdirSync(deepworkDir, { withFileTypes: true })) { + if (!entry.isDirectory()) continue; + const slugDir = join(deepworkDir, entry.name); + for (const file of readdirSync(slugDir, { withFileTypes: true })) { + if (!file.isFile() || !file.name.endsWith(".md")) continue; + const kind = file.name.startsWith("VERIFICATION") ? "report" : "plan"; + addArtifactFile(out, seenPaths, root, join(slugDir, file.name), kind); + } } - ] - }; -} -//#endregion -//#region src/decision-router-state.ts -/** -* decision-router-state.ts — the Decision Model section of the settings window. -* -* TUI-local replica of the user-level decision-router config -* (scripts/install/decision-router-config.mjs — the bundle must stay -* self-contained); tests/tui-decision-router-state.test.mjs pins the schema -* version, the exact key set and the provider matrix against that source. -* -* The runtime re-reads this file on EVERY gated call (jev-decision-tool.ts), -* so a write here applies live — no restart. The strict exact-key schema is -* load-bearing: any unknown key fail-closes the runtime to disabled/local, -* so the writer validates before persisting. -* -* Egress consent is CLI-owned: the window never writes `egress_consent`, and -* refuses to enable the router while remote candidates exist without it. -*/ -const DECISION_ENABLED_CYCLE = Object.freeze(["enabled", "disabled"]); -/** Exact top-level key set — anything else fail-closes the runtime. */ -const DECISION_CONFIG_KEYS = Object.freeze([ - "egress_consent", - "enabled", - "enabled_candidates", - "schema_version", - "selection" -]); -const DEFAULT_DECISION_CONFIG = Object.freeze({ - schema_version: 2, - enabled: false, - selection: Object.freeze({ mode: "local" }), - egress_consent: false, - enabled_candidates: Object.freeze([]) -}); -/** The runtime's provider→model matrix (drift-pinned against the installer source). */ -const DECISION_KNOWN_PROVIDERS = Object.freeze([ - "openai-decisions", - "typesafe-jev", - "opencode-console-jev", - "openrouter-jev", - "vercel-gateway-jev", - "cloudflare-workers-jev" -]); -const DECISION_CONSENT_CYCLE = Object.freeze(["not granted", "granted"]); -/** provider → model, straight from the runtime matrix (drift-pinned in tests). */ -const DECISION_KNOWN_MODELS = Object.freeze({ - "openai-decisions": "gpt-6-luna", - "typesafe-jev": "jev-1.14.0", - "opencode-console-jev": "jev-1.13", - "openrouter-jev": "typesafe/jev-1.13", - "vercel-gateway-jev": "typesafe-ai/jev", - "cloudflare-workers-jev": "clef" -}); -/** -* Credential surface per provider: the ENV VAR the host provider entry reads -* (`{env:VAR}` indirection — the window NEVER holds key values) plus the setup -* note. Drift-pinned against the installer/runtime sources in tests. -*/ -const DECISION_PROVIDER_CREDENTIALS = Object.freeze({ - "openai-decisions": { - note: "host-configured model — provision via `decision-router setup-model openai-decisions`", - notePt: "modelo do host — configure via `decision-router setup-model openai-decisions`" - }, - "typesafe-jev": { - env: "TYPESAFE_API_KEY", - note: "export TYPESAFE_API_KEY=… then restart", - notePt: "export TYPESAFE_API_KEY=… e depois reinicie" - }, - "opencode-console-jev": { - note: "rides your OpenCode login — no separate key", - notePt: "utiliza login do OpenCode — sem chave separada" - }, - "openrouter-jev": { - env: "OPENROUTER_API_KEY", - note: "export OPENROUTER_API_KEY=… then restart", - notePt: "export OPENROUTER_API_KEY=… e depois reinicie" - }, - "vercel-gateway-jev": { - env: "AI_GATEWAY_API_KEY", - note: "export AI_GATEWAY_API_KEY=… then restart", - notePt: "export AI_GATEWAY_API_KEY=… e depois reinicie" - }, - "cloudflare-workers-jev": { - env: "CLOUDFLARE_API_TOKEN", - note: "needs accountId (setup-model --account-id=…) + CLOUDFLARE_API_TOKEN", - notePt: "requer accountId (setup-model --account-id=…) + CLOUDFLARE_API_TOKEN" + } catch {} + const reportsDir = join(root, ".pantheon", "reports"); + if (existsSync(reportsDir)) try { + for (const file of readdirSync(reportsDir, { withFileTypes: true })) { + if (!file.isFile() || !file.name.endsWith(".md")) continue; + addArtifactFile(out, seenPaths, root, join(reportsDir, file.name), "report"); + } + } catch {} + for (const adrDir of [join(root, "docs", "adr"), join(root, ".pantheon", "memory-bank", "adr")]) { + if (!existsSync(adrDir)) continue; + try { + for (const file of readdirSync(adrDir, { withFileTypes: true })) { + if (!file.isFile() || !file.name.endsWith(".md")) continue; + if (file.name.toLowerCase() === "readme.md") continue; + addArtifactFile(out, seenPaths, root, join(adrDir, file.name), "adr"); + } + } catch {} + } } -}); -const DECISION_TARGET_CYCLE = Object.freeze(DECISION_KNOWN_PROVIDERS.map((provider) => `${provider}/${DECISION_KNOWN_MODELS[provider]}`)); -function decisionRouterConfigPath(env = process.env) { - const xdg = env.XDG_CONFIG_HOME; - const home = env.HOME ?? ""; - const root = xdg ?? join(home, ".config"); - return join(root, "pantheon", "decision-router.json"); + return out.sort((a, b) => b.modifiedMs - a.modifiedMs || a.relPath.localeCompare(b.relPath)); } -/** Fail-open read: a missing file is the default; an invalid one is reported, not guessed. */ -function readDecisionRouterConfig(env = process.env) { - let raw; - try { - raw = JSON.parse(readFileSync(decisionRouterConfigPath(env), "utf8")); - } catch (error) { - if (error?.code === "ENOENT") return { - config: cloneDefault(), - corrupt: false - }; - return { - config: cloneDefault(), - corrupt: true - }; +function wrapLine(text, width) { + const max = Number.isInteger(width) && width >= 20 ? width : 76; + if (text.length <= max) return [text]; + const rows = []; + let rest = text; + while (rest.length > max) { + let split = rest.lastIndexOf(" ", max); + if (split < Math.floor(max * .4)) split = max; + rows.push(rest.slice(0, split).trimEnd()); + rest = rest.slice(split).trimStart(); } - if (isValidDecisionConfig(raw)) return { - config: raw, - corrupt: false - }; - return { - config: cloneDefault(), - corrupt: true - }; + if (rest.length > 0) rows.push(rest); + return rows; } -function cloneDefault() { - return { - schema_version: DEFAULT_DECISION_CONFIG.schema_version, - enabled: DEFAULT_DECISION_CONFIG.enabled, - selection: { ...DEFAULT_DECISION_CONFIG.selection }, - egress_consent: DEFAULT_DECISION_CONFIG.egress_consent, - enabled_candidates: [...DEFAULT_DECISION_CONFIG.enabled_candidates] - }; +function simplifyLinks(line) { + return line.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_m, label, target) => { + if (target.startsWith("file://")) { + const clean = target.replace(/^file:\/\//, ""); + const hashIdx = clean.indexOf("#"); + const pathPart = hashIdx >= 0 ? clean.slice(0, hashIdx) : clean; + const anchor = hashIdx >= 0 ? clean.slice(hashIdx) : ""; + const base = basename(pathPart); + return base === label ? `${label}${anchor}` : `${label} (${base}${anchor})`; + } + return label; + }); } -/** The exact-key, exact-shape validation the runtime applies (fail-closed otherwise). */ -function isValidDecisionConfig(value) { - if (typeof value !== "object" || value === null || Array.isArray(value)) return false; - const record = value; - const keys = Object.keys(record).sort(); - if (keys.length !== DECISION_CONFIG_KEYS.length) return false; - for (const key of DECISION_CONFIG_KEYS) if (!keys.includes(key)) return false; - if (record.schema_version !== 2) return false; - if (typeof record.enabled !== "boolean") return false; - if (typeof record.egress_consent !== "boolean") return false; - if (!isValidSelection(record.selection)) return false; - if (!Array.isArray(record.enabled_candidates)) return false; - for (const candidate of record.enabled_candidates) { - if (typeof candidate !== "object" || candidate === null) return false; - const entry = candidate; - if (typeof entry.provider !== "string" || typeof entry.model !== "string") return false; - if (Object.keys(entry).length !== 2) return false; +function formatArtifactLines(markdown, width = 76) { + const max = Number.isInteger(width) && width >= 20 ? width : 76; + const out = []; + let inMermaid = false; + let mermaidBuffer = []; + let inCode = false; + let activeAlert = null; + for (const rawLine of markdown.split(/\r?\n/)) { + const trimmed = rawLine.trim(); + if (/^```mermaid/i.test(trimmed)) { + inMermaid = true; + inCode = true; + mermaidBuffer = []; + continue; + } + if (/^```/.test(trimmed)) { + if (inCode) { + if (inMermaid) { + const rendered = renderMermaidToUnicode(mermaidBuffer, max); + out.push(rendered.header); + for (const dLine of rendered.lines) out.push(dLine); + mermaidBuffer = []; + } + inCode = false; + inMermaid = false; + out.push(""); + } else { + inCode = true; + const lang = trimmed.slice(3).trim(); + out.push(lang ? `[Code: ${lang}]` : "[Code]"); + } + continue; + } + if (inCode) { + if (inMermaid) mermaidBuffer.push(rawLine); + else out.push(...wrapLine(` ${trimmed}`, max)); + continue; + } + const alertMatch = GFM_ALERT_RE.exec(trimmed); + if (alertMatch?.[1]) { + activeAlert = alertMatch[1].toUpperCase(); + out.push(`[${activeAlert}]`); + continue; + } + if (trimmed.startsWith(">")) { + const body = simplifyLinks(trimmed.replace(/^>\s?/, "")); + const prefix = activeAlert ? " " : "> "; + if (body === "") continue; + out.push(...wrapLine(`${prefix}${body}`, max)); + continue; + } + activeAlert = null; + if (trimmed === "---" || trimmed === "***") { + out.push("─".repeat(Math.min(max, 64))); + continue; + } + if (trimmed === "") { + if (out.length > 0 && out[out.length - 1] !== "") out.push(""); + continue; + } + const cleaned = simplifyLinks(rawLine).replace(/\*\*/g, ""); + const hMatch = /^(#{1,3})\s+(.+)$/.exec(cleaned.trim()); + if (hMatch?.[1] && hMatch[2]) { + const level = hMatch[1].length; + const heading = level === 1 ? hMatch[2].toUpperCase() : hMatch[2]; + if (out.length > 0 && out[out.length - 1] !== "") out.push(""); + out.push(...wrapLine(level === 1 ? heading : `${"· ".repeat(level - 1)}${heading}`, max)); + continue; + } + const bulletMatch = /^[-*]\s+(.+)$/.exec(cleaned.trim()); + if (bulletMatch?.[1]) { + out.push(...wrapLine(`• ${bulletMatch[1]}`, max)); + continue; + } + out.push(...wrapLine(cleaned.trimEnd(), max)); } - return true; + while (out.length > 0 && out[out.length - 1] === "") out.pop(); + return out; } -function isValidSelection(value) { - if (typeof value !== "object" || value === null) return false; - const selection = value; - if (selection.mode !== "local" && selection.mode !== "auto" && selection.mode !== "explicit") return false; - const keys = Object.keys(selection).sort(); - for (const key of keys) if (key !== "mode" && key !== "provider" && key !== "model") return false; - if (selection.provider !== void 0 && typeof selection.provider !== "string") return false; - if (selection.model !== void 0 && typeof selection.model !== "string") return false; - return true; +function paginateArtifactLines(lines, pageSize = 16) { + const size = Number.isInteger(pageSize) && pageSize > 0 ? pageSize : 16; + if (lines.length === 0) return [[]]; + const pages = []; + for (let i = 0; i < lines.length; i += size) pages.push(lines.slice(i, i + size)); + return pages; } -/** Stable serializer: exact keys in sorted order, 2-space, trailing newline. */ -function serializeDecisionConfig(config) { - const ordered = { - egress_consent: config.egress_consent, - enabled: config.enabled, - enabled_candidates: config.enabled_candidates.map((candidate) => ({ - model: candidate.model, - provider: candidate.provider - })), - schema_version: config.schema_version, - selection: { - mode: config.selection.mode, - ...config.selection.model !== void 0 ? { model: config.selection.model } : {}, - ...config.selection.provider !== void 0 ? { provider: config.selection.provider } : {} - } - }; - return `${JSON.stringify(ordered, null, 2)}\n`; +function artifactKindLabel(kind, isPt = false) { + if (kind === "plan") return isPt ? "Plano" : "Plan"; + if (kind === "report") return isPt ? "Relatório" : "Report"; + return "ADR"; } +Object.freeze([ + "auto", + "pt-BR", + "en" +]); /** -* Enable/disable the router in a config copy. The guard mirrors the runtime's -* fail-close: with remote candidates and no egress consent, an enabled flag -* would be a lie — enabling requires consent, or a local-only selection. -* Never touches `egress_consent` (CLI-owned). +* Resolve effective language: 'pt-BR' or 'en'. +* Defaults to 'pt-BR' if system locale contains 'pt', if Intl locale is pt, +* or if system timezone is Brazilian/Portuguese; otherwise 'en'. */ -function setDecisionEnabled(config, enabled) { - if (enabled) { - if (!(config.selection.mode === "local" || config.enabled_candidates.length === 0) && !config.egress_consent) return { - ok: false, - reason: "remote candidates need egress consent — toggle Egress consent in this tab, then enable" - }; - } - return { - ok: true, - config: { - ...config, - enabled - } - }; +function resolveLanguage(preference = "auto", env = process.env) { + if (preference === "pt-BR") return "pt-BR"; + if (preference === "en") return "en"; + if ((env.LC_ALL ?? env.LC_MESSAGES ?? env.LANG ?? env.LANGUAGE ?? "").toLowerCase().startsWith("pt")) return "pt-BR"; + try { + if (Intl.DateTimeFormat().resolvedOptions().locale.toLowerCase().startsWith("pt")) return "pt-BR"; + } catch {} + try { + const tz = (env.TZ ?? Intl.DateTimeFormat().resolvedOptions().timeZone ?? "").toLowerCase(); + if (tz.includes("sao_paulo") || tz.includes("brazil") || tz.includes("fortaleza") || tz.includes("recife") || tz.includes("manaus") || tz.includes("belem") || tz.includes("cuiaba") || tz.includes("campo_grande") || tz.includes("porto_velho") || tz.includes("rio_branco") || tz.includes("boa_vista") || tz.includes("maceio") || tz.includes("bahia") || tz.includes("noronha") || tz.includes("araguaina") || tz.includes("santarem") || tz.includes("lisbon") || tz.includes("madeira") || tz.includes("azores")) return "pt-BR"; + } catch {} + return "en"; } -/** Atomic-ish write mirroring the canonical writer's privacy posture (0600). */ -function writeDecisionRouterConfig(config, env = process.env) { - if (!isValidDecisionConfig(config)) throw new TypeError("Refusing to persist an invalid decision-router configuration"); - const path = decisionRouterConfigPath(env); - mkdirSync(dirname(path), { - recursive: true, - mode: 448 - }); - const temp = `${path}.tui.tmp`; - writeFileSync(temp, serializeDecisionConfig(config), { mode: 384 }); - renameSync(temp, path); - chmodSync(path, 384); +//#endregion +//#region src/tui-prefs.ts +const PREFS_SYMBOL = Symbol.for("pantheon.tui.prefs.v1"); +const DRAFT_PREVIEW_SYMBOL = Symbol.for("pantheon.tui.draft_preview.v1"); +function stash() { + return globalThis[PREFS_SYMBOL]; } -const DECISION_SELECTION_CYCLE = Object.freeze([ - "local", - "auto", - "explicit" -]); -/** Stage a selection/consent row into a config copy; unknown rows are no-ops. */ -function applyDecisionRow(config, id, value) { - const next = { - ...config, - selection: { ...config.selection }, - enabled_candidates: [...config.enabled_candidates] - }; - switch (id) { - case "decision.selection.mode": { - const mode = value; - if (mode !== "local" && mode !== "auto" && mode !== "explicit") return config; - next.selection.mode = mode; - if (mode === "local") next.enabled_candidates = []; - return next; - } - case "decision.selection.target": { - const separator = value.indexOf("/"); - if (separator <= 0) return config; - const provider = value.slice(0, separator); - const model = value.slice(separator + 1); - if (!DECISION_KNOWN_PROVIDERS.includes(provider)) return config; - if (DECISION_KNOWN_MODELS[provider] !== model) return config; - next.selection = { - mode: "explicit", - provider, - model - }; - next.enabled_candidates = [{ - provider, - model - }]; - return next; +function getDraftPreviewSignal() { + const g = globalThis; + if (!g[DRAFT_PREVIEW_SYMBOL]) g[DRAFT_PREVIEW_SYMBOL] = createSignal(void 0); + return g[DRAFT_PREVIEW_SYMBOL]; +} +/** Set the active draft preview overlay (used by settings window to provide live preview). */ +function setTuiDraftPreview(draft) { + const [, setDraft] = getDraftPreviewSignal(); + setDraft(draft && Object.keys(draft).length > 0 ? { ...draft } : void 0); +} +/** Clear the active draft preview overlay. */ +function clearTuiDraftPreview() { + const [, setDraft] = getDraftPreviewSignal(); + setDraft(void 0); +} +/** The active draft preview accessor. */ +function tuiDraftPreview() { + const [draft] = getDraftPreviewSignal(); + return draft(); +} +/** Create (or reuse) the durable prefs store. Fail-open: without host +* storage the consumers fall back to DEFAULT_TUI_PREFS (read-only). */ +function initTuiPrefs(context) { + if (stash() !== void 0) return; + try { + const handle = context.storage?.store?.("tui-prefs", { initial: DEFAULT_TUI_PREFS }); + if (handle !== void 0) { + globalThis[PREFS_SYMBOL] = handle; + if (!handle[0]?.layout || typeof handle[0]?.sidebar?.context?.turnCost !== "boolean" || typeof handle[0]?.sidebar?.context?.tokenAnatomy !== "boolean") handle[1]((draft) => { + if (!draft.layout) draft.layout = { ...DEFAULT_TUI_PREFS.layout }; + if (draft.sidebar?.context) { + if (typeof draft.sidebar.context.turnCost !== "boolean") draft.sidebar.context.turnCost = true; + if (typeof draft.sidebar.context.tokenAnatomy !== "boolean") draft.sidebar.context.tokenAnatomy = true; + } + }).catch(() => {}); } - case "decision.consent": - next.egress_consent = value === "granted"; - return next; - default: return config; + } catch {} +} +/** Deep clone and overlay staged settings draft onto base TuiPrefs. */ +function previewTuiPrefs(base, draft) { + if (!draft || Object.keys(draft).length === 0) return base; + let hasTui = false; + for (const k of Object.keys(draft)) if (k.startsWith("tui.")) { + hasTui = true; + break; } + if (!hasTui) return base; + const normalized = normalizeTuiPrefs(base); + const effective = { + version: 1, + layout: { ...normalized.layout }, + ...normalized.theme ? { theme: { ...normalized.theme } } : {}, + sidebar: { + header: { ...normalized.sidebar.header }, + ...normalized.sidebar.pinnedSessions ? { pinnedSessions: [...normalized.sidebar.pinnedSessions] } : {}, + blocks: { ...normalized.sidebar.blocks }, + context: { ...normalized.sidebar.context } + }, + footer: { ...normalized.footer } + }; + for (const [id, value] of Object.entries(draft)) if (id.startsWith("tui.")) applyTuiRow(effective, id, value); + return effective; } -/** Provider ids as they appear in the host auth store / config providers. */ -const PROVIDER_AUTH_NAMES = Object.freeze({ - "openai-decisions": Object.freeze(["openai"]), - "typesafe-jev": Object.freeze(["typesafe-ai"]), - "opencode-console-jev": Object.freeze([]), - "openrouter-jev": Object.freeze(["openrouter"]), - "vercel-gateway-jev": Object.freeze(["vercel-ai-gateway", "vercel"]), - "cloudflare-workers-jev": Object.freeze(["cloudflare-workers-ai"]) -}); -/** -* TWO recognition forms (field feedback beta.6: keys registered via -* `opencode auth login` showed MISSING because only env vars were checked): -* env var set → 'env'; provider present in the host auth store → 'auth -* store'; provider entry in opencode.json providers → 'config'. Values are -* NEVER read — existence only. -*/ -function credentialStatus(provider, env, authProviders, configProviders) { - const credential = DECISION_PROVIDER_CREDENTIALS[provider]; - if (credential?.env !== void 0 && env[credential.env]) return "env"; - for (const name of PROVIDER_AUTH_NAMES[provider] ?? []) if (authProviders.has(name)) return "auth store"; - for (const name of PROVIDER_AUTH_NAMES[provider] ?? []) if (configProviders.has(name)) return "config"; - if (provider === "opencode-console-jev") return "auth store"; - return "missing"; +/** The raw persisted prefs from host storage (no draft overlay). */ +function savedTuiPrefs() { + const s = stash()?.[0]; + if (!s) return DEFAULT_TUI_PREFS; + return normalizeTuiPrefs(s); } -function buildDecisionTab(read, env = process.env, authProviders = /* @__PURE__ */ new Set(), configProviders = /* @__PURE__ */ new Set(), languagePref) { - const isPt = languagePref === "pt-BR"; - const { config, corrupt } = read; - const rows = [{ - id: "decision.enabled", - name: isPt ? "Assistente Jev" : "Jev Assistant", - value: config.enabled ? "enabled" : "disabled", - ...corrupt ? {} : { cycle: DECISION_ENABLED_CYCLE }, - note: corrupt ? isPt ? "config inválida — runtime fail-closes; repare via `decision-router setup-model`" : "config unreadable/invalid — runtime fail-closes; repair via `decision-router setup-model`" : isPt ? "aplica em tempo real — arbitragem de decisões relida a cada chamada" : "applies live — the runtime re-reads this on every gated call" - }, { - id: "decision.selection.mode", - name: isPt ? "Modo de Operação" : "Operation Mode", - value: config.selection.mode, - ...corrupt ? {} : { cycle: DECISION_SELECTION_CYCLE }, - note: isPt ? "local = no seu PC (grátis); auto/explícito = modelo nuvem (OpenRouter)" : "local routes on-device; auto/explicit pick a remote decision model" - }]; - const explicitTarget = config.selection.provider ? `${config.selection.provider}/${config.selection.model ?? ""}` : DECISION_TARGET_CYCLE[0] ?? "openrouter-jev/typesafe/jev-1.13"; - rows.push({ - id: "decision.selection.target", - name: isPt ? "Modelo de Decisão" : "Decision Model", - value: config.selection.mode === "local" ? config.selection.provider ? `${config.selection.provider}/${config.selection.model ?? ""}` : "local (on-device)" : explicitTarget, - ...corrupt ? {} : { cycle: DECISION_TARGET_CYCLE }, - note: isPt ? config.selection.mode === "local" ? "ciclar seleciona modelo remoto e ativa modo explícito" : "provedor/modelo ativo — define candidato para arbitragem" : config.selection.mode === "local" ? "cycle to select a remote model and activate explicit mode" : "provider/model — sets the candidate list" - }); - if ((config.enabled_candidates?.length ?? 0) > 0) rows.push({ - id: "decision.candidates", - name: isPt ? "Candidatos ativos" : "Candidates", - value: String(config.enabled_candidates.length), - note: config.egress_consent ? config.enabled_candidates.map((candidate) => `${candidate.provider}/${candidate.model}`).join(", ") : isPt ? "egress consent NÃO concedido — rotas remotas bloqueadas" : "egress consent NOT granted — remote routes fail closed" - }); - rows.push({ - id: "decision.consent", - name: isPt ? "Acesso à Nuvem" : "Cloud API Access", - value: config.egress_consent ? "granted" : "not granted", - ...corrupt ? {} : { cycle: DECISION_CONSENT_CYCLE }, - note: isPt ? config.egress_consent ? "granted = rotas remotas podem consultar gateway de API (com teto de custo)" : "not granted = chamadas remotas bloqueadas; requer granted para nuvem" : config.egress_consent ? "granted = remote decision routes may call their gateway (budget-capped)" : "not granted = remote routes fail closed; grant to allow cloud calls" - }); - return { - id: "decision", - title: isPt ? "Decisão" : "Decision", - groups: [{ - title: isPt ? "Assistente de Decisão (Jev)" : "Decision Assistant (Jev)", - rows - }, { - title: isPt ? "Credenciais (status apenas — valores nunca gravados na janela)" : "Credentials (status only — values never enter the window)", - rows: DECISION_KNOWN_PROVIDERS.map((provider) => { - const status = credentialStatus(provider, env, authProviders, configProviders); - const credential = DECISION_PROVIDER_CREDENTIALS[provider] ?? { note: "" }; - return { - id: `decision.key.${provider}`, - name: provider, - value: status === "missing" ? "MISSING" : status, - note: isPt ? credential.notePt ?? credential.note : credential.note - }; - }) - }] - }; +/** The live reactive prefs (read properties inside memos/JSX — tracked). +* When a settings window has an active draft, preview overlays on top +* of durable storage in real time. */ +function tuiPrefs() { + const base = savedTuiPrefs(); + const preview = tuiDraftPreview(); + if (!preview) return base; + return previewTuiPrefs(base, preview); } -//#endregion -//#region src/pantheon-settings-state.ts -/** Mirrors routing.yml `behaviors:` — drift-pinned by the registry test. */ -const SETTINGS_BEHAVIORS = Object.freeze([ - { - id: "skill-auto-continue", - kind: "install", - title: "Auto-continue skill", - description: "Continue multi-step todos while keeping safety gates." +/** Stage a mutation against the durable store; resolves when persisted. */ +function mutateTuiPrefs(mutation) { + const handle = stash(); + if (handle === void 0) return Promise.resolve(); + return handle[1](mutation); +} +const GAUGE_STYLES = Object.freeze([ + "both", + "bar", + "percent", + "off" +]); +const ENABLED_CYCLE = Object.freeze(["enabled", "disabled"]); +const BAR_SHAPES_CYCLE = Object.freeze([ + "smooth", + "line", + "block", + "ascii", + "dots", + "braille" +]); +const BAR_WIDTHS_CYCLE = Object.freeze([ + "standard", + "compact", + "wide", + "full" +]); +const LAYOUT_PRESETS_CYCLE = Object.freeze(["comfortable", "compact"]); +const SEPARATOR_STYLES_CYCLE = Object.freeze([ + "spaces", + "pipes", + "dots", + "slashes" +]); +const SETTINGS_VIEW_MODES = Object.freeze([ + "docked", + "fullscreen", + "dialog" +]); +const LANGUAGE_CYCLE = Object.freeze([ + "auto", + "pt-BR", + "en" +]); +const THEME_MODES_CYCLE = Object.freeze([ + "auto", + "dark", + "light" +]); +const ACCENT_COLORS_CYCLE = Object.freeze([ + "host", + "pantheon", + "emerald", + "cyan", + "amber", + "purple", + "rose" +]); +const ACCENT_PALETTE = { + host: { + primary: "#fba970", + hover: "#fdba74", + muted: "#a1a1aa" }, - { - id: "skill-tdd-with-agents", - kind: "install", - title: "TDD with agents skill", - description: "RED, GREEN, REFACTOR test-driven implementation." + pantheon: { + primary: "#fba970", + hover: "#fdba74", + muted: "#a1a1aa" }, - { - id: "skill-code-review-checklist", - kind: "install", - title: "Code review checklist skill", - description: "Systematic code review and quality gates." + emerald: { + primary: "#10b981", + hover: "#34d399", + muted: "#059669" }, - { - id: "skill-prompt-refinery", - kind: "install", - title: "Prompt refinery skill", - description: "Vague requests refined — silent adjust, >> full contract." + cyan: { + primary: "#06b6d4", + hover: "#22d3ee", + muted: "#0891b2" }, - { - id: "gate-idle-todo-enforcer", - kind: "runtime", - title: "Idle todo enforcer", - description: "Continues pending todos when a session goes idle." + amber: { + primary: "#f59e0b", + hover: "#fbbf24", + muted: "#d97706" }, - { - id: "gate-context-pruner", - kind: "runtime", - title: "Context pruner", - description: "Prunes repeated tool output before summarization." + purple: { + primary: "#a855f7", + hover: "#c084fc", + muted: "#9333ea" }, - { - id: "gate-j1-risk-gate", - kind: "runtime", - title: "J1 risk gate", - description: "High-risk tool calls demand explicit human approval." + rose: { + primary: "#f43f5e", + hover: "#fb7185", + muted: "#e11d48" } -]); -new Set(SETTINGS_BEHAVIORS.map((b) => b.id)); -function isBehaviorDisabled(effective, id) { - return effective[id]?.action === "disable"; -} -const TOGGLE_REASON = "toggled in /pantheon-settings"; -/** -* Toggle (a targeted write keeps the toggle semantics: a `replace` entry is -* never destroyed — disabling keeps its `content`, re-enabling restores the -* replace; a settings-written disable is removed outright, no toggle noise). -*/ -function toggledOverrides(effective, id, reason = TOGGLE_REASON) { - const next = { ...effective }; - const entry = next[id]; - if (entry?.action === "disable") { - if (entry.content !== void 0) next[id] = entry.reason === reason ? { - action: "replace", - content: entry.content - } : { - action: "replace", - content: entry.content, - ...entry.reason !== void 0 ? { reason: entry.reason } : {} - }; - else delete next[id]; - } else next[id] = entry?.content !== void 0 ? { - action: "disable", - reason, - content: entry.content - } : { - action: "disable", - reason - }; - return next; -} -/** Set an explicit on/off target (the cycler's save path) via the toggle semantics. */ -function setOverrideState(effective, id, target, reason = TOGGLE_REASON) { - const disabled = isBehaviorDisabled(effective, id); - if (target === "disabled" === disabled) return effective; - return toggledOverrides(effective, id, reason); -} -function serializeOverrides(effective) { - const ordered = {}; - for (const id of Object.keys(effective).sort()) ordered[id] = effective[id]; - return `${JSON.stringify(ordered, null, 2)}\n`; -} -/** Merge for DISPLAY only, mirroring the runtime precedence: project wins per id. */ -function mergedOverrides(load) { - return { - ...load.global, - ...load.project - }; -} -function canWriteOverrides(load) { - return !load.corruptGlobal; -} -/** Neutral tab for out-of-range indexes (noUncheckedIndexedAccess guard). */ -const EMPTY_TAB = { - id: "empty", - title: "", - groups: [] }; -/** Flat, in-order rows of a tab (the up/down navigation space). */ -function tabRows(tab) { - return tab.groups.flatMap((group) => group.rows); -} -function findRow(tab, id) { - return tabRows(tab).find((row) => row.id === id); -} -/** Step through the cycle with wrap-around; non-cyclable rows return the input. */ -function cycleValue(value, cycle, direction) { - if (cycle.length === 0) return value; - const index = cycle.indexOf(value); - if (index === -1) return cycle[0] ?? value; - return cycle[(index + direction + cycle.length) % cycle.length] ?? value; +function resolveAccentColor(accent, contextTheme) { + if (!accent || accent === "host") return contextTheme?.text?.feedback?.warning?.base ?? contextTheme?.text?.base ?? "#fba970"; + return ACCENT_PALETTE[accent]?.primary ?? "#fba970"; } -function stageValue(draft, row, direction) { - if (row.cycle === void 0) return draft; - const staged = cycleValue(draft[row.id] ?? row.value, row.cycle, direction); - if (staged === row.value) { - if (draft[row.id] === void 0) return draft; - const next = { ...draft }; - delete next[row.id]; - return next; +const DEFAULT_TUI_PREFS = { + version: 1, + layout: { + preset: "comfortable", + separator: "spaces", + settingsView: "docked", + language: "auto" + }, + theme: { + mode: "auto", + accent: "host" + }, + sidebar: { + header: { + version: true, + preset: true, + session: true + }, + pinnedSessions: [], + blocks: { + context: true, + git: true, + todo: false, + dispatch: true + }, + context: { + gauge: "both", + barShape: "smooth", + barWidth: "standard", + evenMark: false, + tokens: true, + spent: true, + modelUsage: true, + performance: true, + localSpend: true, + turnCost: true, + tokenAnatomy: true + } + }, + footer: { + prompt: true, + home: true } - return { - ...draft, - [row.id]: staged - }; +}; +function asBool(value, fallback) { + return typeof value === "boolean" ? value : fallback; } -/** Stage an explicit target value for one row (the Defaults action path). */ -function stageRowToValue(draft, row, target) { - if (!row.cycle?.includes(target)) return draft; - if (target === row.value) { - if (draft[row.id] === void 0) return draft; - const next = { ...draft }; - delete next[row.id]; - return next; - } +/** Deep-merge stored JSON over the defaults; unknown keys and junk are ignored. */ +function normalizeTuiPrefs(raw) { + const stored = typeof raw === "object" && raw !== null ? raw : {}; + const layout = typeof stored.layout === "object" && stored.layout !== null ? stored.layout : {}; + const sidebar = typeof stored.sidebar === "object" && stored.sidebar !== null ? stored.sidebar : {}; + const header = typeof sidebar.header === "object" && sidebar.header !== null ? sidebar.header : {}; + const blocks = typeof sidebar.blocks === "object" && sidebar.blocks !== null ? sidebar.blocks : {}; + const context = typeof sidebar.context === "object" && sidebar.context !== null ? sidebar.context : {}; + const footer = typeof stored.footer === "object" && stored.footer !== null ? stored.footer : {}; + const rawTheme = typeof stored.theme === "object" && stored.theme !== null ? stored.theme : {}; + const themeMode = THEME_MODES_CYCLE.includes(rawTheme.mode) ? rawTheme.mode : DEFAULT_TUI_PREFS.theme?.mode ?? "auto"; + const themeAccent = ACCENT_COLORS_CYCLE.includes(rawTheme.accent) ? rawTheme.accent : DEFAULT_TUI_PREFS.theme?.accent ?? "host"; + const preset = LAYOUT_PRESETS_CYCLE.includes(layout.preset) ? layout.preset : DEFAULT_TUI_PREFS.layout.preset; + const separator = SEPARATOR_STYLES_CYCLE.includes(layout.separator) ? layout.separator : DEFAULT_TUI_PREFS.layout.separator; + const settingsView = SETTINGS_VIEW_MODES.includes(layout.settingsView) ? layout.settingsView : DEFAULT_TUI_PREFS.layout.settingsView; + const language = LANGUAGE_CYCLE.includes(layout.language) ? layout.language : DEFAULT_TUI_PREFS.layout.language; + const gauge = GAUGE_STYLES.includes(context.gauge) ? context.gauge : DEFAULT_TUI_PREFS.sidebar.context.gauge; + const barShape = BAR_SHAPES_CYCLE.includes(context.barShape) ? context.barShape : DEFAULT_TUI_PREFS.sidebar.context.barShape; + const barWidth = BAR_WIDTHS_CYCLE.includes(context.barWidth) ? context.barWidth : DEFAULT_TUI_PREFS.sidebar.context.barWidth; + const evenMark = asBool(context.evenMark, DEFAULT_TUI_PREFS.sidebar.context.evenMark); return { - ...draft, - [row.id]: target - }; -} -/** -* Stage every cyclable row's DEFAULT value of a tab. Rows already at their -* default have their staged entry dropped; rows staged elsewhere keep it -* until the Defaults action targets them. -*/ -function stageDefaults(draft, tab) { - let next = draft; - for (const row of tabRows(tab)) { - if (row.cycle === void 0 || row.def === void 0) continue; - const candidate = next[row.id] ?? row.value; - if (candidate === row.def) { - if (next[row.id] !== void 0) { - const copy = { ...next }; - delete copy[row.id]; - next = copy; + version: 1, + layout: { + preset, + separator, + settingsView, + language + }, + theme: { + mode: themeMode, + accent: themeAccent + }, + sidebar: { + header: { + version: asBool(header.version, true), + preset: asBool(header.preset, true), + session: asBool(header.session, true) + }, + pinnedSessions: Array.isArray(sidebar.pinnedSessions) ? sidebar.pinnedSessions.filter((s) => typeof s === "string") : [], + blocks: { + context: asBool(blocks.context, true), + git: asBool(blocks.git, true), + todo: asBool(blocks.todo, false), + dispatch: asBool(blocks.dispatch, true) + }, + context: { + gauge, + barShape, + barWidth, + evenMark, + tokens: asBool(context.tokens, true), + spent: asBool(context.spent, true), + modelUsage: asBool(context.modelUsage, true), + performance: asBool(context.performance, true), + localSpend: asBool(context.localSpend, true), + turnCost: asBool(context.turnCost, true), + tokenAnatomy: asBool(context.tokenAnatomy, true) } - continue; + }, + footer: { + prompt: asBool(footer.prompt, true), + home: asBool(footer.home, true) } - next = stageRowToValue(next, { - ...row, - value: candidate - }, row.def); - } - return next; -} -/** Drop every staged entry of one tab (ctrl+r). */ -function resetTab(draft, tab) { - const ids = new Set(tabRows(tab).map((row) => row.id)); - const next = {}; - for (const [id, value] of Object.entries(draft)) if (!ids.has(id)) next[id] = value; - return next; -} -function draftCount(draft) { - return Object.keys(draft).length; -} -function draftDirty(draft) { - return draftCount(draft) > 0; -} -function tabDirty(draft, tab) { - return tabRows(tab).some((row) => draft[row.id] !== void 0); + }; } -/** Apply every staged entry; failures are collected, never thrown. */ -function applyDraft(draft, writer) { - const applied = []; - const failed = []; - for (const [id, value] of Object.entries(draft)) { - const result = writer(id, value); - if (result.ok) applied.push(id); - else failed.push({ - id, - reason: result.reason ?? "write failed" - }); - } +const onOff = ENABLED_CYCLE; +const row = (id, name, value, note) => ({ + id, + name, + value: value ? "enabled" : "disabled", + cycle: onOff, + note +}); +function buildTuiTab(prefs, languagePref) { + const isPt = resolveLanguage(languagePref ?? prefs.layout?.language) === "pt-BR"; return { - applied, - failed + id: "tui", + title: "TUI", + groups: [ + { + title: isPt ? "Predefinição & Layout" : "Preset & Layout", + rows: [ + { + id: "tui.layout.preset", + name: isPt ? "Predefinição de layout" : "Layout preset", + value: prefs.layout?.preset ?? DEFAULT_TUI_PREFS.layout.preset, + cycle: LAYOUT_PRESETS_CYCLE, + note: isPt ? "comfortable | compact — define espaçamento e bordas" : "comfortable | compact — sets spacing & borders" + }, + { + id: "tui.layout.separator", + name: isPt ? "Separador" : "Separator", + value: prefs.layout?.separator ?? DEFAULT_TUI_PREFS.layout.separator, + cycle: SEPARATOR_STYLES_CYCLE, + note: isPt ? "spaces | pipes | dots | slashes — glifos na linha de status" : "spaces | pipes | dots | slashes — status line glyphs" + }, + { + id: "tui.layout.settingsView", + name: isPt ? "Superfície de configurações" : "Settings surface", + value: tuiRowValue(prefs, "tui.layout.settingsView") ?? "docked", + cycle: SETTINGS_VIEW_MODES, + note: isPt ? "docked (acima do prompt) | fullscreen | dialog" : "docked (above prompt) | fullscreen router page | dialog overlay" + }, + { + id: "tui.layout.language", + name: isPt ? "Idioma / Language" : "Language / Idioma", + value: tuiRowValue(prefs, "tui.layout.language") ?? "auto", + cycle: LANGUAGE_CYCLE, + note: isPt ? "auto (detecta via fuso/locale) | pt-BR (Português) | en (English)" : "auto (detect via timezone/locale) | pt-BR (Português) | en (English)" + } + ] + }, + { + title: isPt ? "Cores & Tema" : "Colors & Theme", + rows: [{ + id: "tui.theme.mode", + name: isPt ? "Modo do tema" : "Theme mode", + value: tuiRowValue(prefs, "tui.theme.mode") ?? "auto", + cycle: THEME_MODES_CYCLE, + note: isPt ? "auto (segue o OpenCode) | dark | light" : "auto (follow OpenCode theme) | dark | light" + }, { + id: "tui.theme.accent", + name: isPt ? "Cor de destaque" : "Accent color", + value: tuiRowValue(prefs, "tui.theme.accent") ?? "host", + cycle: ACCENT_COLORS_CYCLE, + note: isPt ? "host (segue tema) | pantheon | emerald | cyan | amber | purple | rose" : "host (follow theme) | pantheon | emerald | cyan | amber | purple | rose" + }] + }, + { + title: isPt ? "Barras & Medidores" : "Bars & Gauges", + rows: [ + { + id: "tui.sidebar.context.barShape", + name: isPt ? "Formato da barra" : "Bar shape", + value: prefs.sidebar.context.barShape, + cycle: BAR_SHAPES_CYCLE, + note: "line (━─) | block (▰▱) | smooth (█░) | ascii (=) | dots (●○) | braille" + }, + { + id: "tui.sidebar.context.barWidth", + name: isPt ? "Largura da barra" : "Bar width", + value: prefs.sidebar.context.barWidth, + cycle: BAR_WIDTHS_CYCLE, + note: isPt ? "standard (12) | compact (8) | wide (16) | full (20 células)" : "standard (12) | compact (8) | wide (16) | full (20 cells)" + }, + row("tui.sidebar.context.evenMark", isPt ? "Marca central (50%)" : "Even-use mark", prefs.sidebar.context.evenMark, isPt ? "| indicador aos 50% nas barras de medição" : "| indicator at 50% midpoint in gauge bars"), + { + id: "tui.sidebar.context.gauge", + name: isPt ? "Estilo do medidor" : "Gauge style", + value: prefs.sidebar.context.gauge, + cycle: GAUGE_STYLES, + note: "both | bar | percent | off — `▰▱ 42% of 200k`" + } + ] + }, + { + title: isPt ? "Cabeçalho da barra lateral" : "Sidebar header", + rows: [ + row("tui.sidebar.header.version", isPt ? "Linha de versão" : "Version line", prefs.sidebar.header.version, isPt ? "linha `Pantheon v…`" : "the `Pantheon v…` line"), + row("tui.sidebar.header.preset", isPt ? "Linha de preset" : "Preset line", prefs.sidebar.header.preset, isPt ? "linha `▸ preset · provider`" : "the `▸ preset · provider` line"), + row("tui.sidebar.header.session", isPt ? "Linha de sessão" : "Session line", prefs.sidebar.header.session, isPt ? "título da sessão ativa" : "the active session title") + ] + }, + { + title: isPt ? "Blocos da barra lateral" : "Sidebar blocks", + rows: [ + row("tui.sidebar.block.context", isPt ? "Bloco de contexto" : "Context block", prefs.sidebar.blocks.context, isPt ? "tokens, medidor, custo, uso de modelos" : "tokens, gauge, spend, model usage"), + row("tui.sidebar.block.git", isPt ? "Bloco do Git" : "Git block", prefs.sidebar.blocks.git, isPt ? "branch + contagem de alterações" : "branch + working-tree counts"), + row("tui.sidebar.block.dispatch", isPt ? "Bloco Dispatch" : "Dispatch block", prefs.sidebar.blocks.dispatch, isPt ? "delegações em tempo real" : "live delegations + rollup") + ] + }, + { + title: isPt ? "Detalhe do bloco de contexto" : "Context block detail", + rows: [ + row("tui.sidebar.context.tokens", isPt ? "Linha de tokens" : "Tokens row", prefs.sidebar.context.tokens, isPt ? "contagem bruta de tokens" : "the raw token count line"), + row("tui.sidebar.context.spent", isPt ? "Linha de custo" : "Spent row", prefs.sidebar.context.spent, isPt ? "linha `$… gastos na sessão`" : "the `$… spent in session` line"), + row("tui.sidebar.context.modelUsage", isPt ? "Tabela de uso de modelos" : "Model usage table", prefs.sidebar.context.modelUsage, isPt ? "resumo de chamadas por modelo" : "per-model tokens/USD"), + row("tui.sidebar.context.performance", isPt ? "Linha de desempenho" : "Performance row", prefs.sidebar.context.performance, isPt ? "tokens/segundo e latência" : "cache % + tok/s"), + row("tui.sidebar.context.turnCost", isPt ? "Custo do turno" : "Turn cost", prefs.sidebar.context.turnCost, isPt ? "linha `Turn: $… (prev: $…)`" : "the `Turn: $… (prev: $…)` line"), + row("tui.sidebar.context.tokenAnatomy", isPt ? "Anatomia de tokens" : "Token anatomy", prefs.sidebar.context.tokenAnatomy, isPt ? "linha `↑in ↓out ✦think`" : "the `↑in ↓out ✦think` line"), + row("tui.sidebar.context.localSpend", isPt ? "Linha de custo local" : "Local spend row", prefs.sidebar.context.localSpend, isPt ? "totais de hoje / 30 dias" : "hoje / 30d totals") + ] + }, + { + title: isPt ? "Rodapés" : "Footers", + rows: [row("tui.footer.prompt", isPt ? "Prompt inferior" : "Prompt footer", prefs.footer.prompt, isPt ? "linha `▸preset · ✦n ativos` durante delegações" : "the `▸preset · ✦n ativos` line while delegations run"), row("tui.footer.home", isPt ? "Status inicial" : "Home status", prefs.footer.home, isPt ? "linha `Pantheon v…` sob o prompt inicial" : "the `Pantheon v…` line under the home prompt")] + } + ] }; } -/** The rows that succeeded and are still in the draft (failed ones stay staged). */ -function settledDraft(draft, applied) { - const next = {}; - for (const [id, value] of Object.entries(draft)) if (!applied.includes(id)) next[id] = value; - return next; -} -const GATES_ENABLED_CYCLE = Object.freeze(["enabled", "disabled"]); -const OVERRIDES_SCOPE_CYCLE = Object.freeze(["global", "project"]); -function buildGatesTab(load, languagePref, overridesScope) { - const isPt = languagePref === "pt-BR"; - const merged = mergedOverrides(load); - const editingProject = overridesScope === "project"; - const rowFor = (behavior) => { - const fromProject = load.project[behavior.id] !== void 0; - const effective = editingProject ? isBehaviorDisabled({ - ...load.global, - ...load.project - }, behavior.id) : isBehaviorDisabled(load.global, behavior.id); - const writable = editingProject ? true : !fromProject && canWriteOverrides(load); +/** +* Apply one staged row INTO a prefs draft (in place — the storage mutate +* callback hands an immer-style draft). Unknown ids or junk values are no-ops. +*/ +function applyTuiRow(draft, id, value) { + const enabled = value === "enabled"; + switch (id) { + case "tui.layout.preset": + if (LAYOUT_PRESETS_CYCLE.includes(value)) { + if (!draft.layout) draft.layout = { ...DEFAULT_TUI_PREFS.layout }; + draft.layout.preset = value; + } + return; + case "tui.layout.separator": + if (SEPARATOR_STYLES_CYCLE.includes(value)) { + if (!draft.layout) draft.layout = { ...DEFAULT_TUI_PREFS.layout }; + draft.layout.separator = value; + } + return; + case "tui.layout.settingsView": + if (SETTINGS_VIEW_MODES.includes(value)) { + if (!draft.layout) draft.layout = { ...DEFAULT_TUI_PREFS.layout }; + draft.layout.settingsView = value; + } + return; + case "tui.layout.language": + if (LANGUAGE_CYCLE.includes(value)) { + if (!draft.layout) draft.layout = { ...DEFAULT_TUI_PREFS.layout }; + draft.layout.language = value; + } + return; + case "tui.theme.mode": + if (THEME_MODES_CYCLE.includes(value)) { + if (!draft.theme) draft.theme = { ...DEFAULT_TUI_PREFS.theme }; + draft.theme.mode = value; + } + return; + case "tui.theme.accent": + if (ACCENT_COLORS_CYCLE.includes(value)) { + if (!draft.theme) draft.theme = { ...DEFAULT_TUI_PREFS.theme }; + draft.theme.accent = value; + } + return; + case "tui.sidebar.context.barShape": + if (BAR_SHAPES_CYCLE.includes(value)) draft.sidebar.context.barShape = value; + return; + case "tui.sidebar.context.barWidth": + if (BAR_WIDTHS_CYCLE.includes(value)) draft.sidebar.context.barWidth = value; + return; + case "tui.sidebar.context.evenMark": + draft.sidebar.context.evenMark = enabled; + return; + case "tui.sidebar.header.version": + draft.sidebar.header.version = enabled; + return; + case "tui.sidebar.header.preset": + draft.sidebar.header.preset = enabled; + return; + case "tui.sidebar.header.session": + draft.sidebar.header.session = enabled; + return; + case "tui.sidebar.block.context": + draft.sidebar.blocks.context = enabled; + return; + case "tui.sidebar.block.git": + draft.sidebar.blocks.git = enabled; + return; + case "tui.sidebar.block.todo": + draft.sidebar.blocks.todo = enabled; + return; + case "tui.sidebar.block.dispatch": + draft.sidebar.blocks.dispatch = enabled; + return; + case "tui.sidebar.context.gauge": + if (GAUGE_STYLES.includes(value)) draft.sidebar.context.gauge = value; + return; + case "tui.sidebar.context.tokens": + draft.sidebar.context.tokens = enabled; + return; + case "tui.sidebar.context.spent": + draft.sidebar.context.spent = enabled; + return; + case "tui.sidebar.context.modelUsage": + draft.sidebar.context.modelUsage = enabled; + return; + case "tui.sidebar.context.performance": + draft.sidebar.context.performance = enabled; + return; + case "tui.sidebar.context.localSpend": + draft.sidebar.context.localSpend = enabled; + return; + case "tui.sidebar.context.turnCost": + draft.sidebar.context.turnCost = enabled; + return; + case "tui.sidebar.context.tokenAnatomy": + draft.sidebar.context.tokenAnatomy = enabled; + return; + case "tui.footer.prompt": + draft.footer.prompt = enabled; + return; + case "tui.footer.home": + draft.footer.home = enabled; + return; + default: return; + } +} +/** Read the current pref value for a row id ('enabled'/'disabled'/gauge/custom). */ +function tuiRowValue(prefs, id) { + if (id === "tui.layout.preset") return prefs.layout?.preset ?? DEFAULT_TUI_PREFS.layout.preset; + if (id === "tui.layout.separator") return prefs.layout?.separator ?? DEFAULT_TUI_PREFS.layout.separator; + if (id === "tui.layout.settingsView") return prefs.layout?.settingsView ?? DEFAULT_TUI_PREFS.layout.settingsView ?? "docked"; + if (id === "tui.layout.language") return prefs.layout?.language ?? "auto"; + if (id === "tui.theme.mode") return prefs.theme?.mode ?? DEFAULT_TUI_PREFS.theme?.mode ?? "auto"; + if (id === "tui.theme.accent") return prefs.theme?.accent ?? DEFAULT_TUI_PREFS.theme?.accent ?? "host"; + if (id === "tui.sidebar.context.barShape") return prefs.sidebar.context.barShape; + if (id === "tui.sidebar.context.barWidth") return prefs.sidebar.context.barWidth; + if (id === "tui.sidebar.context.gauge") return prefs.sidebar.context.gauge; + if (id === "tui.sidebar.context.evenMark") return prefs.sidebar.context.evenMark ? "enabled" : "disabled"; + const enabled = (() => { + switch (id) { + case "tui.sidebar.header.version": return prefs.sidebar.header.version; + case "tui.sidebar.header.preset": return prefs.sidebar.header.preset; + case "tui.sidebar.header.session": return prefs.sidebar.header.session; + case "tui.sidebar.block.context": return prefs.sidebar.blocks.context; + case "tui.sidebar.block.git": return prefs.sidebar.blocks.git; + case "tui.sidebar.block.todo": return prefs.sidebar.blocks.todo; + case "tui.sidebar.block.dispatch": return prefs.sidebar.blocks.dispatch; + case "tui.sidebar.context.tokens": return prefs.sidebar.context.tokens; + case "tui.sidebar.context.spent": return prefs.sidebar.context.spent; + case "tui.sidebar.context.modelUsage": return prefs.sidebar.context.modelUsage; + case "tui.sidebar.context.performance": return prefs.sidebar.context.performance; + case "tui.sidebar.context.localSpend": return prefs.sidebar.context.localSpend; + case "tui.sidebar.context.turnCost": return prefs.sidebar.context.turnCost; + case "tui.sidebar.context.tokenAnatomy": return prefs.sidebar.context.tokenAnatomy; + case "tui.footer.prompt": return prefs.footer.prompt; + case "tui.footer.home": return prefs.footer.home; + default: return; + } + })(); + return enabled === void 0 ? void 0 : enabled ? "enabled" : "disabled"; +} +function isSessionPinned(sessionID) { + if (!sessionID) return false; + const list = tuiPrefs().sidebar.pinnedSessions; + return Array.isArray(list) && list.includes(sessionID); +} +//#endregion +//#region src/artifacts.tsx +/** @jsxImportSource @opentui/solid */ +/** +* artifacts.tsx — Interactive `/pantheon-artifacts` (and `/artifacts`) TUI dialog. +* +* Scans `.pantheon/deepwork//*.md`, `.pantheon/reports/*.md`, and +* `docs/adr/*.md` (resolving linked git worktrees back to the main repository), +* lets users browse artifacts with keyboard or mouse, and renders paginated +* terminal-friendly views of plans, reports, and ADRs. +*/ +function readArtifactContent(entry) { + try { + return readFileSync(entry.path, "utf8"); + } catch { + return ""; + } +} +function lineColor(line, fg, muted, warn) { + if (/^\[(?:IMPORTANT|WARNING|CAUTION)\]/.test(line)) return warn ?? "#fba970"; + if (/^\[(?:NOTE|TIP|Mermaid Diagram|Code)/.test(line)) return "#60a5fa"; + if (line.startsWith("• ")) return fg; + if (line.startsWith("· ") || line === line.toUpperCase() && /[A-Z]/.test(line) && line.length > 3) return fg; + if (line.startsWith("─")) return muted; + return muted ?? fg; +} +function ArtifactsDialogContent(props) { + const activeEntry = () => props.entries[props.selected()]; + const pageCount = () => Math.max(1, props.pages().length); + const currentRows = () => props.pages()[Math.min(props.page(), pageCount() - 1)] ?? []; + const rule = "─".repeat(76); + return (() => { + var _el$ = createElement("box"), _el$2 = createElement("box"), _el$3 = createElement("box"), _el$4 = createElement("box"), _el$5 = createElement("text"), _el$6 = createElement("text"), _el$7 = createElement("box"), _el$8 = createElement("text"), _el$0 = createElement("box"), _el$1 = createElement("text"), _el$12 = createElement("box"), _el$13 = createElement("text"), _el$14 = createElement("box"), _el$15 = createElement("box"), _el$23 = createElement("text"), _el$24 = createElement("box"), _el$25 = createElement("text"); + insertNode(_el$, _el$2); + insertNode(_el$, _el$0); + insertNode(_el$, _el$12); + insertNode(_el$, _el$14); + setProp(_el$, "flexDirection", "column"); + setProp(_el$, "borderStyle", "rounded"); + setProp(_el$, "paddingLeft", 2); + setProp(_el$, "paddingRight", 2); + setProp(_el$, "paddingTop", 1); + setProp(_el$, "paddingBottom", 1); + insertNode(_el$2, _el$3); + insertNode(_el$2, _el$7); + setProp(_el$2, "flexDirection", "row"); + setProp(_el$2, "alignItems", "center"); + setProp(_el$2, "justifyContent", "space-between"); + insertNode(_el$3, _el$4); + insertNode(_el$3, _el$6); + setProp(_el$3, "flexDirection", "row"); + setProp(_el$3, "alignItems", "center"); + insertNode(_el$4, _el$5); + setProp(_el$4, "paddingLeft", 1); + setProp(_el$4, "paddingRight", 1); + setProp(_el$4, "marginRight", 1); + setProp(_el$5, "fg", "#000000"); + setProp(_el$5, "attributes", 1); + insert(_el$5, () => props.isPt ? "ARTEFATOS" : "ARTIFACTS"); + setProp(_el$6, "attributes", 1); + insert(_el$6, (() => { + var _c$ = memo(() => !!(props.mode() === "read" && activeEntry())); + return () => _c$() ? activeEntry()?.title.slice(0, 52) : memo(() => !!props.isPt)() ? `Planos, Relatórios & ADRs (${props.entries.length})` : `Plans, Reports & ADRs (${props.entries.length})`; + })()); + insertNode(_el$7, _el$8); + setProp(_el$7, "onMouseDown", () => props.onClose()); + insertNode(_el$8, createTextNode(`[ Esc / Q ]`)); + insertNode(_el$0, _el$1); + setProp(_el$0, "flexDirection", "row"); + setProp(_el$0, "height", 1); + setProp(_el$0, "marginTop", 1); + setProp(_el$0, "marginBottom", 1); + insert(_el$1, rule); + insert(_el$, createComponent(Show, { + get when() { + return memo(() => props.mode() === "read")() && activeEntry() !== void 0; + }, + get fallback() { + return (() => { + var _el$26 = createElement("box"); + setProp(_el$26, "flexDirection", "column"); + setProp(_el$26, "minHeight", 10); + insert(_el$26, createComponent(Show, { + get when() { + return props.entries.length > 0; + }, + get fallback() { + return (() => { + var _el$27 = createElement("box"), _el$28 = createElement("text"), _el$29 = createElement("text"), _el$30 = createElement("text"), _el$32 = createElement("text"), _el$34 = createElement("text"); + insertNode(_el$27, _el$28); + insertNode(_el$27, _el$29); + insertNode(_el$27, _el$30); + insertNode(_el$27, _el$32); + insertNode(_el$27, _el$34); + setProp(_el$27, "flexDirection", "column"); + setProp(_el$28, "attributes", 1); + insert(_el$28, () => props.isPt ? "Nenhum artefato encontrado neste workspace." : "No artifacts found in this workspace."); + setProp(_el$29, "marginTop", 1); + insert(_el$29, () => props.isPt ? "Onde o Pantheon salva artefatos:" : "Where Pantheon stores artifacts:"); + insertNode(_el$30, createTextNode(`• .pantheon/deepwork/<slug>/PLAN.md (/pantheon-deepwork / @athena)`)); + insertNode(_el$32, createTextNode(`• .pantheon/reports/*.md (@apollo / @themis)`)); + insertNode(_el$34, createTextNode(`• docs/adr/*.md (@mnemosyne)`)); + effect((_p$) => { + var _v$9 = props.fg, _v$0 = props.muted, _v$1 = props.muted, _v$10 = props.muted, _v$11 = props.muted; + _v$9 !== _p$.e && (_p$.e = setProp(_el$28, "fg", _v$9, _p$.e)); + _v$0 !== _p$.t && (_p$.t = setProp(_el$29, "fg", _v$0, _p$.t)); + _v$1 !== _p$.a && (_p$.a = setProp(_el$30, "fg", _v$1, _p$.a)); + _v$10 !== _p$.o && (_p$.o = setProp(_el$32, "fg", _v$10, _p$.o)); + _v$11 !== _p$.i && (_p$.i = setProp(_el$34, "fg", _v$11, _p$.i)); + return _p$; + }, { + e: void 0, + t: void 0, + a: void 0, + o: void 0, + i: void 0 + }); + return _el$27; + })(); + }, + get children() { + return createComponent(For, { + get each() { + return props.entries.slice(0, 12); + }, + children: (entry, idx) => { + const isSelected = () => idx() === props.selected(); + const kindTag = `[${artifactKindLabel(entry.kind, props.isPt).toUpperCase()}]`.padEnd(13); + const title = (entry.title.length > 30 ? `${entry.title.slice(0, 29)}…` : entry.title).padEnd(32); + const pathTail = entry.relPath.length > 26 ? `…${entry.relPath.slice(-25)}` : entry.relPath; + return (() => { + var _el$36 = createElement("box"), _el$37 = createElement("text"), _el$38 = createElement("text"), _el$39 = createElement("text"), _el$40 = createElement("text"); + insertNode(_el$36, _el$37); + insertNode(_el$36, _el$38); + insertNode(_el$36, _el$39); + insertNode(_el$36, _el$40); + setProp(_el$36, "flexDirection", "row"); + spread(_el$36, mergeProps(() => isSelected() ? { backgroundColor: "#262626" } : {}, { "onMouseDown": () => { + if (isSelected()) props.onOpen(idx()); + else props.onSelect(idx()); + } }), true); + setProp(_el$37, "attributes", 1); + setProp(_el$37, "wrapMode", "none"); + insert(_el$37, () => isSelected() ? "▸ " : " "); + setProp(_el$38, "wrapMode", "none"); + insert(_el$38, kindTag); + setProp(_el$39, "wrapMode", "none"); + spread(_el$39, mergeProps({ get fg() { + return memo(() => !!isSelected())() ? props.fg : props.muted; + } }, () => isSelected() ? { attributes: 1 } : {}), true); + insert(_el$39, title); + setProp(_el$40, "wrapMode", "none"); + insert(_el$40, () => `${pathTail} (${entry.lineCount}L)`); + effect((_p$) => { + var _v$12 = isSelected() ? props.warn ?? "#fba970" : props.muted, _v$13 = isSelected() ? props.warn ?? "#fba970" : "#60a5fa", _v$14 = props.muted; + _v$12 !== _p$.e && (_p$.e = setProp(_el$37, "fg", _v$12, _p$.e)); + _v$13 !== _p$.t && (_p$.t = setProp(_el$38, "fg", _v$13, _p$.t)); + _v$14 !== _p$.a && (_p$.a = setProp(_el$40, "fg", _v$14, _p$.a)); + return _p$; + }, { + e: void 0, + t: void 0, + a: void 0 + }); + return _el$36; + })(); + } + }); + } + })); + return _el$26; + })(); + }, + get children() { + var _el$10 = createElement("box"), _el$11 = createElement("text"); + insertNode(_el$10, _el$11); + setProp(_el$10, "flexDirection", "column"); + setProp(_el$10, "minHeight", 12); + setProp(_el$11, "marginBottom", 1); + insert(_el$11, () => `${activeEntry()?.relPath ?? ""} · ${activeEntry()?.lineCount ?? 0} ${props.isPt ? "linhas" : "lines"}`); + insert(_el$10, createComponent(For, { + get each() { + return currentRows(); + }, + children: (line) => (() => { + var _el$41 = createElement("text"); + insert(_el$41, line === "" ? " " : line); + effect((_$p) => setProp(_el$41, "fg", lineColor(line, props.fg, props.muted, props.warn), _$p)); + return _el$41; + })() + }), null); + effect((_$p) => setProp(_el$11, "fg", props.muted, _$p)); + return _el$10; + } + }), _el$12); + insertNode(_el$12, _el$13); + setProp(_el$12, "flexDirection", "row"); + setProp(_el$12, "height", 1); + setProp(_el$12, "marginTop", 1); + insert(_el$13, rule); + insertNode(_el$14, _el$15); + insertNode(_el$14, _el$24); + setProp(_el$14, "flexDirection", "row"); + setProp(_el$14, "alignItems", "center"); + setProp(_el$14, "justifyContent", "space-between"); + setProp(_el$14, "marginTop", 1); + insertNode(_el$15, _el$23); + setProp(_el$15, "flexDirection", "row"); + setProp(_el$15, "alignItems", "center"); + setProp(_el$15, "flexShrink", 1); + insert(_el$15, createComponent(Show, { + get when() { + return props.mode() === "read"; + }, + get children() { + return [(() => { + var _el$16 = createElement("box"), _el$17 = createElement("text"); + insertNode(_el$16, _el$17); + setProp(_el$16, "backgroundColor", "#262626"); + setProp(_el$16, "paddingLeft", 1); + setProp(_el$16, "paddingRight", 1); + setProp(_el$16, "marginRight", 1); + setProp(_el$16, "flexShrink", 0); + setProp(_el$16, "onMouseDown", () => props.onBack()); + setProp(_el$17, "fg", "#ffffff"); + setProp(_el$17, "wrapMode", "none"); + insert(_el$17, () => props.isPt ? "‹ Lista" : "‹ List"); + return _el$16; + })(), createComponent(Show, { + get when() { + return pageCount() > 1; + }, + get children() { + return [ + (() => { + var _el$18 = createElement("box"), _el$19 = createElement("text"); + insertNode(_el$18, _el$19); + setProp(_el$18, "backgroundColor", "#262626"); + setProp(_el$18, "paddingLeft", 1); + setProp(_el$18, "paddingRight", 1); + setProp(_el$18, "marginRight", 1); + setProp(_el$18, "flexShrink", 0); + setProp(_el$18, "onMouseDown", () => props.onPrevPage()); + setProp(_el$19, "fg", "#ffffff"); + setProp(_el$19, "wrapMode", "none"); + insert(_el$19, () => props.isPt ? "‹ Anterior" : "‹ Prev"); + return _el$18; + })(), + (() => { + var _el$20 = createElement("text"); + setProp(_el$20, "marginRight", 1); + setProp(_el$20, "wrapMode", "none"); + insert(_el$20, () => `${props.page() + 1}/${pageCount()}`); + effect((_$p) => setProp(_el$20, "fg", props.muted, _$p)); + return _el$20; + })(), + (() => { + var _el$21 = createElement("box"), _el$22 = createElement("text"); + insertNode(_el$21, _el$22); + setProp(_el$21, "backgroundColor", "#262626"); + setProp(_el$21, "paddingLeft", 1); + setProp(_el$21, "paddingRight", 1); + setProp(_el$21, "marginRight", 1); + setProp(_el$21, "flexShrink", 0); + setProp(_el$21, "onMouseDown", () => props.onNextPage()); + setProp(_el$22, "fg", "#ffffff"); + setProp(_el$22, "wrapMode", "none"); + insert(_el$22, () => props.isPt ? "Próxima ›" : "Next ›"); + return _el$21; + })() + ]; + } + })]; + } + }), _el$23); + setProp(_el$23, "wrapMode", "none"); + insert(_el$23, (() => { + var _c$2 = memo(() => props.mode() === "read"); + return () => _c$2() ? props.isPt ? "b lista · n/p pág · esc" : "b list · n/p page · esc" : props.isPt ? "↑/↓ mover · enter abrir · esc fechar" : "↑/↓ move · enter open · esc close"; + })()); + insertNode(_el$24, _el$25); + setProp(_el$24, "paddingLeft", 2); + setProp(_el$24, "paddingRight", 2); + setProp(_el$24, "flexShrink", 0); + setProp(_el$24, "onMouseDown", () => { + if (props.mode() === "list" && props.entries.length > 0) props.onOpen(); + else props.onClose(); + }); + setProp(_el$25, "fg", "#000000"); + setProp(_el$25, "attributes", 1); + setProp(_el$25, "wrapMode", "none"); + insert(_el$25, (() => { + var _c$3 = memo(() => !!(props.mode() === "list" && props.entries.length > 0)); + return () => _c$3() ? props.isPt ? "Abrir" : "Open" : props.isPt ? "Fechar" : "Close"; + })()); + effect((_p$) => { + var _v$ = props.warn ?? "#fba970", _v$2 = props.warn ?? "#fba970", _v$3 = props.fg, _v$4 = props.muted, _v$5 = props.muted, _v$6 = props.muted, _v$7 = props.muted, _v$8 = props.warn ?? "#fba970"; + _v$ !== _p$.e && (_p$.e = setProp(_el$, "borderColor", _v$, _p$.e)); + _v$2 !== _p$.t && (_p$.t = setProp(_el$4, "backgroundColor", _v$2, _p$.t)); + _v$3 !== _p$.a && (_p$.a = setProp(_el$6, "fg", _v$3, _p$.a)); + _v$4 !== _p$.o && (_p$.o = setProp(_el$8, "fg", _v$4, _p$.o)); + _v$5 !== _p$.i && (_p$.i = setProp(_el$1, "fg", _v$5, _p$.i)); + _v$6 !== _p$.n && (_p$.n = setProp(_el$13, "fg", _v$6, _p$.n)); + _v$7 !== _p$.s && (_p$.s = setProp(_el$23, "fg", _v$7, _p$.s)); + _v$8 !== _p$.h && (_p$.h = setProp(_el$24, "backgroundColor", _v$8, _p$.h)); + return _p$; + }, { + e: void 0, + t: void 0, + a: void 0, + o: void 0, + i: void 0, + n: void 0, + s: void 0, + h: void 0 + }); + return _el$; + })(); +} +function openArtifactsDialog(context, workspaceDir, options) { + const entries = scanPantheonArtifacts(workspaceDir); + const initialIndex = options?.initialArtifactId ? entries.findIndex((entry) => entry.id === options.initialArtifactId) : -1; + const resolvedIndex = initialIndex >= 0 ? initialIndex : 0; + const isPt = resolveLanguage(tuiPrefs().layout?.language) === "pt-BR"; + const [open, setOpen] = createSignal(false); + const [selected, setSelected] = createSignal(resolvedIndex); + const [mode, setMode] = createSignal(initialIndex >= 0 || entries.length === 1 ? "read" : "list"); + const [page, setPage] = createSignal(0); + const pages = () => { + const entry = entries[selected()]; + if (!entry) return [[]]; + return paginateArtifactLines(formatArtifactLines(readArtifactContent(entry), 76)); + }; + let dismiss = () => {}; + const openSelected = (idx) => { + if (entries.length === 0) return; + if (typeof idx === "number") setSelected(Math.min(Math.max(idx, 0), entries.length - 1)); + setPage(0); + setMode("read"); + }; + try { + context.keymap.layer(() => ({ + mode: "global", + priority: 1, + enabled: () => open(), + commands: [ + { + id: "pantheon.artifacts.close", + title: "Close artifacts viewer", + bind: "escape,q", + run: () => { + if (!open()) return false; + dismiss(); + } + }, + { + id: "pantheon.artifacts.up", + title: "Previous artifact", + bind: "up,k", + run: () => { + if (!open() || mode() !== "list" || entries.length === 0) return false; + setSelected((cur) => Math.max(0, cur - 1)); + } + }, + { + id: "pantheon.artifacts.down", + title: "Next artifact", + bind: "down,j", + run: () => { + if (!open() || mode() !== "list" || entries.length === 0) return false; + setSelected((cur) => Math.min(entries.length - 1, cur + 1)); + } + }, + { + id: "pantheon.artifacts.open-item", + title: "Open selected artifact", + bind: "enter,space", + run: () => { + if (!open()) return false; + if (mode() === "list" && entries.length > 0) openSelected(); + else dismiss(); + } + }, + { + id: "pantheon.artifacts.back", + title: "Back to artifacts list", + bind: "b,backspace", + run: () => { + if (!open()) return false; + if (mode() === "read") setMode("list"); + } + }, + { + id: "pantheon.artifacts.next-page", + title: "Next artifact page", + bind: "n,right", + run: () => { + if (!open() || mode() !== "read") return false; + setPage((cur) => Math.min(cur + 1, Math.max(0, pages().length - 1))); + } + }, + { + id: "pantheon.artifacts.prev-page", + title: "Previous artifact page", + bind: "p,left", + run: () => { + if (!open() || mode() !== "read") return false; + setPage((cur) => Math.max(0, cur - 1)); + } + } + ] + })); + } catch {} + const close = () => setOpen(false); + dismiss = () => { + try { + context.ui.dialog.clear(); + } catch {} + close(); + }; + setOpen(true); + try { + const theme = context.theme?.text ?? {}; + const warn = theme?.feedback?.warning?.base ?? "#fba970"; + context.ui.dialog.show(() => createComponent(ArtifactsDialogContent, { + entries, + selected, + mode, + page, + pages, + isPt, + get fg() { + return theme.base; + }, + get muted() { + return theme.muted; + }, + warn, + onSelect: (idx) => setSelected(idx), + onOpen: (idx) => openSelected(idx), + onBack: () => setMode("list"), + onPrevPage: () => setPage((cur) => Math.max(0, cur - 1)), + onNextPage: () => setPage((cur) => Math.min(cur + 1, Math.max(0, pages().length - 1))), + onClose: dismiss + }), close); + context.ui.dialog.set({ + size: "large", + centered: true + }); + } catch { + setOpen(false); + } +} +//#endregion +//#region src/cockpit-state.ts +/** +* cockpit-state.ts — Pure selectors, Gantt renderers, Work Map topology, and +* Gate Matrix aggregation for the TUI Mission Control Cockpit (`Overview`, +* `Swarm`, `Flightdeck`). +*/ +function formatGanttBar(startMs, endMs, minMs, maxMs, width = 24) { + const span = Math.max(1, maxMs - minMs); + const s = Math.max(0, Math.min(width - 1, Math.floor((startMs - minMs) / span * width))); + const e = Math.max(s + 1, Math.min(width, Math.ceil((endMs - minMs) / span * width))); + const cells = []; + for (let i = 0; i < width; i += 1) cells.push(i >= s && i < e ? "█" : "░"); + return cells.join(""); +} +function formatGateMatrixGlyphs(allowed, approved, waiting, blocked) { + const cap = (n, ch) => ch.repeat(Math.min(12, Math.max(0, n))); + const parts = [ + cap(allowed, "■"), + cap(approved, "▣"), + cap(waiting, "□"), + cap(blocked, "✗") + ].filter(Boolean); + return parts.length > 0 ? parts.join(" ") : "■"; +} +function renderWorkMapLines(counts) { + const subs = String(counts.subagents).padStart(2, " "); + const arts = String(counts.artifacts).padStart(2, " "); + const stps = `${counts.stepsDone}/${counts.stepsTotal}`; + return [ + ` [You] ────── [Zeus] ────── [Swarm (${subs})]`, + ` │ │`, + ` [Artifacts ${arts}] ─┼─ [Step Ledger ${stps}] ─ [Review & Gates]`, + ` │`, + ` [FTS5 Memory] ─┴─ [AST + LSP Diagnostics]` + ]; +} +function loadStepEntries(workspaceDir) { + const ledgerPath = join(workspaceDir, ".pantheon", "ledger", "step-ledger.json"); + if (!existsSync(ledgerPath)) return []; + try { + const parsed = JSON.parse(readFileSync(ledgerPath, "utf8")); + return Object.values(parsed.steps ?? {}).map((s) => ({ + stepKey: String(s.stepKey ?? ""), + objective: String(s.objective ?? ""), + agent: String(s.agent ?? "specialist"), + state: String(s.state ?? "pending"), + ...typeof s.taskType === "string" ? { taskType: s.taskType } : {}, + mutatedCount: Array.isArray(s.mutatedFiles) ? s.mutatedFiles.length : 0, + ...typeof s.receiptId === "string" ? { receiptId: s.receiptId } : {}, + hasBaselineTree: typeof s.baselineTree === "string" && s.baselineTree.length === 40, + updatedAt: String(s.updatedAt ?? "") + })).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)); + } catch { + return []; + } +} +function resolveSharedTelemetryRoot(workspaceDir) { + try { + let cur = resolve(workspaceDir); + for (let i = 0; i < 10; i += 1) { + const gitEntry = join(cur, ".git"); + if (existsSync(gitEntry)) { + const statText = readFileSync(gitEntry, "utf8"); + const gitDirMatch = /^gitdir:\s*(.+)$/m.exec(statText); + if (gitDirMatch?.[1]) { + const gitDir = resolve(cur, gitDirMatch[1].trim()); + const commonPath = join(gitDir, "commondir"); + if (existsSync(commonPath)) { + const commonDir = resolve(gitDir, readFileSync(commonPath, "utf8").trim()); + if (commonDir.endsWith(`${sep}.git`)) return dirname(commonDir); + } + } + return cur; + } + const parent = dirname(cur); + if (parent === cur) break; + cur = parent; + } + } catch {} + return workspaceDir; +} +function loadPersistedCockpitEvents(workspaceDir) { + try { + const root = resolveSharedTelemetryRoot(workspaceDir); + const filePath = join(root, ".pantheon", "telemetry", "cockpit-events.ndjson"); + if (!existsSync(filePath)) return []; + const lines = readFileSync(filePath, "utf8").split(/\r?\n/).filter(Boolean); + const out = []; + for (const line of lines.slice(-60)) try { + const parsed = JSON.parse(line); + if (typeof parsed.kind === "string" && typeof parsed.detail === "string") out.push({ + kind: parsed.kind, + timestamp: typeof parsed.timestamp === "number" ? parsed.timestamp : Date.now(), + agent: typeof parsed.agent === "string" ? parsed.agent : "pantheon", + detail: parsed.detail, + severity: parsed.severity === "ok" || parsed.severity === "warn" || parsed.severity === "error" ? parsed.severity : "info" + }); + } catch {} + return out; + } catch { + return []; + } +} +function buildCockpitSnapshot(input) { + const ctxTokens = Math.max(0, input.contextTokens ?? 0); + const ctxWindow = Math.max(1, input.contextWindow ?? 2e5); + const ctxPct = Math.min(100, Math.round(ctxTokens / ctxWindow * 100)); + const filled = Math.min(20, Math.round(ctxPct / 100 * 20)); + const gauge = `[${"█".repeat(filled)}${"░".repeat(20 - filled)}] ${ctxPct}%`; + const artifacts = input.workspaceDir ? scanPantheonArtifacts(input.workspaceDir) : []; + const steps = input.workspaceDir ? loadStepEntries(input.workspaceDir) : []; + const stepsDone = steps.filter((s) => s.state === "done").length; + const runningCount = input.children.filter((c) => c.status === "running").length; + const completedCount = input.children.filter((c) => c.status === "completed").length; + const failedCount = input.children.filter((c) => c.status === "failed" || c.status === "interrupted").length; + const childCost = input.children.reduce((acc, c) => acc + c.cost, 0); + const minMs = input.children.reduce((m, c) => Math.min(m, c.startedAt), Infinity); + const maxMs = input.children.reduce((m, c) => Math.max(m, c.updatedAt), 0); + const safeMin = Number.isFinite(minMs) ? minMs : 0; + const safeMax = maxMs > safeMin ? maxMs : safeMin + 1e3; + const swarmRows = input.children.map((c) => ({ + ...c, + durationSec: Math.max(0, Math.round((c.updatedAt - c.startedAt) / 100) / 10), + ganttBar: formatGanttBar(c.startedAt, Math.max(c.startedAt + 1, c.updatedAt), safeMin, safeMax) + })); + const persistedEvents = input.workspaceDir ? loadPersistedCockpitEvents(input.workspaceDir) : []; + const mergedEvents = [...input.events ?? [], ...persistedEvents]; + const dedup = /* @__PURE__ */ new Map(); + for (const ev of mergedEvents) dedup.set(`${ev.kind}:${ev.timestamp}:${ev.agent}:${ev.detail}`, ev); + const events = Array.from(dedup.values()).sort((a, b) => b.timestamp - a.timestamp).slice(0, 40); + const allowed = stepsDone + events.filter((e) => e.severity === "ok").length + completedCount; + const approved = steps.filter((s) => Boolean(s.receiptId)).length; + const waiting = steps.filter((s) => s.state === "in_progress" || s.state === "pending").length + runningCount; + const blocked = steps.filter((s) => s.state === "blocked" || s.state === "rolled_back").length + events.filter((e) => e.severity === "error").length + failedCount; + const velocityBlocks = input.children.length > 0 ? input.children.slice(0, 14).map((c) => c.tokens > 2e4 ? "█" : c.tokens > 1e4 ? "▆" : c.tokens > 3e3 ? "▄" : "▂").join("") : "▁▃▅▆▄▂"; + return { + sessionTitle: input.sessionTitle?.trim() || (input.isPt ? "Sessão ativa" : "Active Session"), + modelName: input.modelName?.trim() || "auto", + overview: { + contextTokens: ctxTokens, + contextWindow: ctxWindow, + contextPercent: ctxPct, + contextGauge: gauge, + sessionCost: input.sessionCost ?? childCost, + cacheRate: input.cacheRate ?? 0, + subagentCount: input.children.length, + runningCount, + velocityBars: velocityBlocks, + workMap: renderWorkMapLines({ + subagents: input.children.length, + artifacts: artifacts.length, + stepsDone, + stepsTotal: steps.length + }), + surfaces: [ + { + label: "Native Tools (30)", + status: "active" + }, + { + label: "FTS5 Memory + Worktree", + status: "ready" + }, + { + label: "Step-Ledger & Checkpoints", + status: `${stepsDone}/${steps.length} done` + }, + { + label: "LSP + Per-Edit Guardrails", + status: "active" + }, + { + label: "Artifacts & Mermaid", + status: `${artifacts.length} file(s)` + } + ] + }, + swarm: { + activeCount: runningCount, + completedCount, + failedCount, + totalCost: childCost, + rows: swarmRows + }, + flightdeck: { + allowed, + approved, + waiting, + blocked, + gateGlyphs: formatGateMatrixGlyphs(allowed, approved, waiting, blocked), + gateSummary: `${allowed} allowed · ${approved} receipts · ${waiting} active · ${blocked} blocked`, + steps, + logs: events + } + }; +} +/** +* Render a deterministic Markdown + Mermaid Flightdeck replay trace ready for +* archival under `.pantheon/reports/` and inspection via `/pantheon-artifacts`. +*/ +function formatCockpitReplayArtifact(snapshot, now = /* @__PURE__ */ new Date()) { + const filename = `cockpit-replay-${now.toISOString().replace(/[:.]/g, "-").slice(0, 19)}.md`; + const relPath = `.pantheon/reports/${filename}`; + const seqLines = [ + "```mermaid", + "sequenceDiagram", + " participant You", + " participant Zeus" + ]; + const seenAgents = /* @__PURE__ */ new Set(); + for (const row of snapshot.swarm.rows.slice(0, 12)) { + const cleanAgent = row.agent.replace(/[^A-Za-z0-9_-]/g, "") || "specialist"; + if (!seenAgents.has(cleanAgent)) { + seenAgents.add(cleanAgent); + seqLines.push(` participant ${cleanAgent}`); + } + seqLines.push(` Zeus->>${cleanAgent}: ${row.kind} ($${row.cost.toFixed(3)}, ${row.durationSec}s)`); + seqLines.push(` ${cleanAgent}-->>Zeus: ${row.status}`); + } + if (snapshot.swarm.rows.length === 0) { + seqLines.push(" You->>Zeus: active session telemetry snapshot"); + seqLines.push(" Zeus-->>You: Flightdeck gate check"); + } + seqLines.push("```"); + const ganttRows = snapshot.swarm.rows.length > 0 ? snapshot.swarm.rows.map((r) => `| \`@${r.agent}\` | ${r.status} | \`${r.ganttBar}\` | ${r.durationSec}s | $${r.cost.toFixed(4)} |`).join("\n") : "| _none_ | — | `░░░░░░░░░░░░` | 0s | $0.0000 |"; + const stepLines = snapshot.flightdeck.steps.length > 0 ? snapshot.flightdeck.steps.map((s) => `- **${s.stepKey}** (\`${s.state}\`, \`@${s.agent}\`) — ${s.objective}`).join("\n") : "- No step-ledger entries recorded."; + const eventLines = snapshot.flightdeck.logs.length > 0 ? snapshot.flightdeck.logs.map((e) => `- \`[${e.kind}]\` **@${e.agent}**: ${e.detail}`).join("\n") : "- No semantic bus events recorded."; + return { + filename, + relPath, + markdown: [ + `# Pantheon Cockpit Flightdeck Replay`, + "", + `- **Session:** ${snapshot.sessionTitle}`, + `- **Model:** ${snapshot.modelName}`, + `- **Captured At:** ${now.toISOString()}`, + `- **Spend / Context:** $${snapshot.overview.sessionCost.toFixed(4)} · ${snapshot.overview.contextTokens} tokens (${snapshot.overview.contextPercent}%)`, + `- **Gate Matrix:** ${snapshot.flightdeck.gateSummary}`, + "", + "## Execution Replay Diagram", + "", + ...seqLines, + "", + "## Swarm Concurrency Timeline", + "", + "| Agent | Status | Gantt Window | Duration | Cost |", + "|---|---|---|---|---|", + ganttRows, + "", + "## Step-Ledger Checkpoints", + "", + stepLines, + "", + "## Semantic Event Stream", + "", + eventLines, + "" + ].join("\n") + }; +} +/** Confined export helper writing a Cockpit replay trace under `/.pantheon/reports/`. */ +function writeCockpitReplayArtifact(workspaceDir, snapshot, now = /* @__PURE__ */ new Date()) { + const reportsDir = join(workspaceDir, ".pantheon", "reports"); + mkdirSync(reportsDir, { recursive: true }); + const canonicalReports = realpathSync(reportsDir); + const artifact = formatCockpitReplayArtifact(snapshot, now); + const target = resolve(canonicalReports, artifact.filename); + const prefix = canonicalReports.endsWith(sep) ? canonicalReports : `${canonicalReports}${sep}`; + if (!target.startsWith(prefix)) throw new Error("Cockpit replay target escaped .pantheon/reports"); + writeFileSync(target, artifact.markdown, "utf8"); + return artifact.relPath; +} +//#endregion +//#region src/cockpit.tsx +/** @jsxImportSource @opentui/solid */ +/** +* cockpit.tsx — High-Density TUI Mission Control Cockpit (Overview, Swarm, +* Flightdeck) rendered natively on `@opentui/solid` via `ui.router.register`. +*/ +const ROUTE_NAME$1 = "pantheon.cockpit"; +const ROUTE_MODE$1 = "pantheon-cockpit"; +const TABS = [ + { + id: "overview", + label: "1 Overview", + key: "1" + }, + { + id: "swarm", + label: "2 Swarm", + key: "2" + }, + { + id: "flightdeck", + label: "3 Flightdeck", + key: "3" + } +]; +let routerReady = false; +let cockpitController; +const [cockpitOpen, setCockpitOpen] = createSignal(false); +function collectLiveChildren(context, rootSessionID) { + try { + const rawList = context?.data?.session?.list?.(); + if (!Array.isArray(rawList)) return []; + return rawList.filter((s) => s && typeof s.id === "string" && (!rootSessionID || s.parentID === rootSessionID)).slice(0, 20).map((s) => { + const statusRaw = context?.data?.session?.status?.(s.id); + const status = statusRaw === "busy" || statusRaw === "running" ? "running" : statusRaw === "error" ? "failed" : statusRaw === "interrupted" ? "interrupted" : "completed"; + const created = typeof s.time?.created === "number" ? s.time.created : Date.now(); + const updated = typeof s.time?.updated === "number" ? s.time.updated : created; + return { + id: s.id, + agent: String(s.agent ?? s.title ?? "specialist").split(/\s+/)[0] ?? "specialist", + kind: String(s.kind ?? "task"), + status, + cost: typeof s.cost === "number" ? s.cost : 0, + startedAt: created, + updatedAt: updated, + tokens: typeof s.tokens?.input === "number" ? s.tokens.input + (s.tokens?.output ?? 0) : 0, + model: typeof s.model === "string" ? s.model : void 0 + }; + }); + } catch { + return []; + } +} +function collectHostLogs() { + const g = globalThis; + if (!Array.isArray(g.__pantheonCockpitLogs)) return []; + return g.__pantheonCockpitLogs; +} +function collectSessionTelemetry(context, sessionID) { + const sInfo = sessionID ? context?.data?.session?.info?.(sessionID) : void 0; + const messages = sessionID ? context?.data?.session?.messages?.(sessionID) ?? [] : []; + let contextTokens = typeof sInfo?.tokens?.input === "number" ? sInfo.tokens.input : 0; + let modelName = typeof sInfo?.model === "string" ? sInfo.model : void 0; + let totalCost = typeof sInfo?.cost === "number" ? sInfo.cost : 0; + let sawMsgCost = false; + if (Array.isArray(messages) && messages.length > 0) { + for (const msg of messages) { + if (!msg || typeof msg !== "object") continue; + if (typeof msg.cost === "number" && Number.isFinite(msg.cost)) { + totalCost += msg.cost; + sawMsgCost = true; + } + } + for (let i = messages.length - 1; i >= 0; i--) { + const msg = messages[i]; + if (msg?.role === "assistant" || msg?.type === "assistant") { + const t = msg.tokens; + if (t && typeof t === "object") { + const total = (Number(t.input) || 0) + (Number(t.output) || 0) + (Number(t.reasoning) || 0) + (Number(t.cache?.read) || 0) + (Number(t.cache?.write) || 0); + if (total > 0) { + contextTokens = total; + if (!modelName && typeof msg.modelID === "string") modelName = msg.modelID; + break; + } + } + } + } + } + const modelsCatalog = context?.data?.provider?.models?.() ?? []; + let contextWindow = 1e6; + if (Array.isArray(modelsCatalog) && modelName) { + const hit = modelsCatalog.find((m) => m?.id === modelName || m?.modelID === modelName); + if (typeof hit?.limit?.context === "number" && hit.limit.context > 0) contextWindow = hit.limit.context; + } + return { + title: typeof sInfo?.title === "string" ? sInfo.title : void 0, + modelName, + contextTokens, + contextWindow, + sessionCost: sawMsgCost || typeof sInfo?.cost === "number" ? totalCost : void 0 + }; +} +function CockpitView(props) { + const isPt = () => resolveLanguage(tuiPrefs().layout?.language) === "pt-BR"; + const [tab, setTab] = createSignal("overview"); + const [selectedRow, setSelectedRow] = createSignal(0); + const [showDetail, setShowDetail] = createSignal(false); + const [exportNote, setExportNote] = createSignal(null); + const [tick, setTick] = createSignal(0); + const activeSid = () => props.sessionID ?? (props.context?.ui?.router?.current?.()?.type === "session" ? props.context.ui.router.current().sessionID : void 0); + const snapshot = () => { + tick(); + const sid = activeSid(); + const telemetry = collectSessionTelemetry(props.context, sid); + return buildCockpitSnapshot({ + workspaceDir: props.workspaceDir, + sessionTitle: telemetry.title, + modelName: telemetry.modelName, + contextTokens: telemetry.contextTokens, + contextWindow: telemetry.contextWindow, + sessionCost: telemetry.sessionCost, + children: collectLiveChildren(props.context, sid), + events: collectHostLogs(), + isPt: isPt() + }); + }; + const fg = () => props.context?.theme?.text?.base; + const muted = () => props.context?.theme?.text?.muted ?? fg(); + const accent = () => resolveAccentColor(tuiPrefs().theme?.accent, props.context?.theme); + const success = () => props.context?.theme?.text?.feedback?.success?.base ?? accent(); + const errFg = () => props.context?.theme?.text?.feedback?.error?.base ?? accent(); + onMount(() => { + setCockpitOpen(true); + let popMode; + try { + popMode = props.context?.keymap?.mode?.push?.(ROUTE_MODE$1); + } catch {} + const timer = setInterval(() => setTick((t) => t + 1), 1500); + cockpitController = { + setTab: (id) => { + setTab(id); + setSelectedRow(0); + }, + nextTab: () => { + const idx = TABS.findIndex((t) => t.id === tab()); + const next = TABS[(idx + 1) % TABS.length]; + if (next) setTab(next.id); + }, + prevTab: () => { + const idx = TABS.findIndex((t) => t.id === tab()); + const prev = TABS[(idx - 1 + TABS.length) % TABS.length]; + if (prev) setTab(prev.id); + }, + moveRow: (delta) => { + const snap = snapshot(); + const max = tab() === "swarm" ? snap.swarm.rows.length : tab() === "flightdeck" ? Math.max(snap.flightdeck.steps.length, snap.flightdeck.logs.length) : 0; + if (max <= 0) return; + setSelectedRow((cur) => Math.max(0, Math.min(max - 1, cur + delta))); + }, + toggleDetail: () => setShowDetail((v) => !v), + exportReplay: () => { + try { + const relPath = writeCockpitReplayArtifact(props.workspaceDir, snapshot()); + setExportNote(relPath); + setTick((t) => t + 1); + } catch { + setExportNote("export_failed"); + } + }, + refresh: () => setTick((t) => t + 1), + close: props.onClose + }; + onCleanup(() => { + clearInterval(timer); + cockpitController = void 0; + setCockpitOpen(false); + try { + popMode?.(); + } catch {} + }); + }); + return (() => { + var _el$ = createElement("box"), _el$2 = createElement("box"), _el$3 = createElement("box"), _el$4 = createElement("text"), _el$6 = createElement("text"), _el$7 = createElement("box"), _el$8 = createElement("text"), _el$0 = createElement("box"), _el$1 = createElement("text"), _el$39 = createElement("text"), _el$41 = createElement("text"); + insertNode(_el$, _el$2); + insertNode(_el$, _el$0); + insertNode(_el$, _el$1); + insertNode(_el$, _el$39); + insertNode(_el$, _el$41); + setProp(_el$, "flexDirection", "column"); + setProp(_el$, "paddingLeft", 2); + setProp(_el$, "paddingRight", 2); + setProp(_el$, "paddingTop", 1); + setProp(_el$, "paddingBottom", 1); + insertNode(_el$2, _el$3); + insertNode(_el$2, _el$7); + setProp(_el$2, "flexDirection", "row"); + setProp(_el$2, "justifyContent", "space-between"); + insertNode(_el$3, _el$4); + insertNode(_el$3, _el$6); + setProp(_el$3, "flexDirection", "row"); + insertNode(_el$4, createTextNode(`◈ PANTHEON COCKPIT `)); + setProp(_el$4, "attributes", 1); + insert(_el$6, () => `· ${snapshot().sessionTitle} (${snapshot().modelName})`); + insertNode(_el$7, _el$8); + insertNode(_el$8, createTextNode(`[ Esc / Q ]`)); + setProp(_el$0, "flexDirection", "row"); + setProp(_el$0, "marginTop", 1); + setProp(_el$0, "gap", 2); + insert(_el$0, createComponent(For, { + each: TABS, + children: (t) => { + const active = () => tab() === t.id; + return (() => { + var _el$43 = createElement("box"), _el$44 = createElement("text"); + insertNode(_el$43, _el$44); + setProp(_el$43, "onMouseDown", () => setTab(t.id)); + insert(_el$44, () => `[${t.label}]`); + effect((_p$) => { + var _v$16 = active() ? accent() : muted(), _v$17 = active() ? 1 : 0; + _v$16 !== _p$.e && (_p$.e = setProp(_el$44, "fg", _v$16, _p$.e)); + _v$17 !== _p$.t && (_p$.t = setProp(_el$44, "attributes", _v$17, _p$.t)); + return _p$; + }, { + e: void 0, + t: void 0 + }); + return _el$43; + })(); + } + })); + insertNode(_el$1, createTextNode(`────────────────────────────────────────────────────────────────────────`)); + insert(_el$, createComponent(Show, { + get when() { + return tab() === "overview"; + }, + get children() { + var _el$11 = createElement("box"), _el$12 = createElement("text"), _el$14 = createElement("text"), _el$15 = createElement("box"), _el$16 = createElement("text"), _el$18 = createElement("box"), _el$19 = createElement("text"); + insertNode(_el$11, _el$12); + insertNode(_el$11, _el$14); + insertNode(_el$11, _el$15); + insertNode(_el$11, _el$18); + setProp(_el$11, "flexDirection", "column"); + setProp(_el$11, "marginTop", 1); + insertNode(_el$12, createTextNode(`Token Meter & Context`)); + setProp(_el$12, "attributes", 1); + insert(_el$14, () => `Velocity: ${snapshot().overview.velocityBars} Context: ${snapshot().overview.contextGauge} Spend: $${snapshot().overview.sessionCost.toFixed(4)}`); + insertNode(_el$15, _el$16); + setProp(_el$15, "marginTop", 1); + setProp(_el$15, "flexDirection", "column"); + insertNode(_el$16, createTextNode(`Runtime Surfaces & Health`)); + setProp(_el$16, "attributes", 1); + insert(_el$15, createComponent(For, { + get each() { + return snapshot().overview.surfaces; + }, + children: (item) => (() => { + var _el$45 = createElement("text"); + insert(_el$45, () => ` ● ${item.label.padEnd(28)} ${item.status}`); + effect((_$p) => setProp(_el$45, "fg", fg(), _$p)); + return _el$45; + })() + }), null); + insertNode(_el$18, _el$19); + setProp(_el$18, "marginTop", 1); + setProp(_el$18, "flexDirection", "column"); + insertNode(_el$19, createTextNode(`Work Map (Topology)`)); + setProp(_el$19, "attributes", 1); + insert(_el$18, createComponent(For, { + get each() { + return snapshot().overview.workMap; + }, + children: (line) => (() => { + var _el$46 = createElement("text"); + insert(_el$46, line); + effect((_$p) => setProp(_el$46, "fg", muted(), _$p)); + return _el$46; + })() + }), null); + effect((_p$) => { + var _v$ = accent(), _v$2 = fg(), _v$3 = accent(), _v$4 = accent(); + _v$ !== _p$.e && (_p$.e = setProp(_el$12, "fg", _v$, _p$.e)); + _v$2 !== _p$.t && (_p$.t = setProp(_el$14, "fg", _v$2, _p$.t)); + _v$3 !== _p$.a && (_p$.a = setProp(_el$16, "fg", _v$3, _p$.a)); + _v$4 !== _p$.o && (_p$.o = setProp(_el$19, "fg", _v$4, _p$.o)); + return _p$; + }, { + e: void 0, + t: void 0, + a: void 0, + o: void 0 + }); + return _el$11; + } + }), _el$39); + insert(_el$, createComponent(Show, { + get when() { + return tab() === "swarm"; + }, + get children() { + var _el$21 = createElement("box"), _el$22 = createElement("text"), _el$23 = createElement("box"); + insertNode(_el$21, _el$22); + insertNode(_el$21, _el$23); + setProp(_el$21, "flexDirection", "column"); + setProp(_el$21, "marginTop", 1); + setProp(_el$22, "attributes", 1); + insert(_el$22, () => `● ${snapshot().swarm.activeCount} active ✓ ${snapshot().swarm.completedCount} done ✗ ${snapshot().swarm.failedCount} failed · $${snapshot().swarm.totalCost.toFixed(4)}`); + setProp(_el$23, "marginTop", 1); + setProp(_el$23, "flexDirection", "column"); + insert(_el$23, createComponent(Show, { + get when() { + return snapshot().swarm.rows.length > 0; + }, + get fallback() { + return (() => { + var _el$47 = createElement("text"); + insert(_el$47, () => isPt() ? "Nenhum subagente registrado nesta sessão ainda." : "No subagent delegations recorded in this session yet."); + effect((_$p) => setProp(_el$47, "fg", muted(), _$p)); + return _el$47; + })(); + }, + get children() { + return createComponent(For, { + get each() { + return snapshot().swarm.rows.slice(0, 12); + }, + children: (row, idx) => { + const sel = () => idx() === selectedRow(); + const marker = row.status === "running" ? "●" : row.status === "failed" ? "✗" : "✓"; + return (() => { + var _el$48 = createElement("box"), _el$49 = createElement("text"); + insertNode(_el$48, _el$49); + setProp(_el$48, "flexDirection", "column"); + setProp(_el$48, "onMouseDown", () => { + setSelectedRow(idx()); + setShowDetail((v) => !v); + }); + insert(_el$49, () => `${sel() ? "▸" : " "} ${marker} @${row.agent.padEnd(11)} ${row.ganttBar} ${String(row.durationSec).padStart(5)}s $${row.cost.toFixed(3)}`); + insert(_el$48, createComponent(Show, { + get when() { + return memo(() => !!sel())() && showDetail(); + }, + get children() { + var _el$50 = createElement("text"); + insert(_el$50, () => ` id=${row.id} kind=${row.kind} tokens=${row.tokens} model=${row.model ?? "inherited"}`); + effect((_$p) => setProp(_el$50, "fg", muted(), _$p)); + return _el$50; + } + }), null); + effect((_$p) => setProp(_el$49, "fg", sel() ? accent() : fg(), _$p)); + return _el$48; + })(); + } + }); + } + })); + effect((_$p) => setProp(_el$22, "fg", fg(), _$p)); + return _el$21; + } + }), _el$39); + insert(_el$, createComponent(Show, { + get when() { + return tab() === "flightdeck"; + }, + get children() { + var _el$24 = createElement("box"), _el$25 = createElement("text"), _el$27 = createElement("text"), _el$28 = createElement("text"), _el$29 = createElement("box"), _el$30 = createElement("text"), _el$32 = createElement("box"), _el$33 = createElement("text"), _el$35 = createElement("box"), _el$36 = createElement("box"), _el$37 = createElement("text"); + insertNode(_el$24, _el$25); + insertNode(_el$24, _el$27); + insertNode(_el$24, _el$28); + insertNode(_el$24, _el$29); + insertNode(_el$24, _el$32); + insertNode(_el$24, _el$35); + setProp(_el$24, "flexDirection", "column"); + setProp(_el$24, "marginTop", 1); + insertNode(_el$25, createTextNode(`GATE (Safety, Guardrails & Step-Ledger)`)); + setProp(_el$25, "attributes", 1); + insert(_el$27, () => ` ${snapshot().flightdeck.gateGlyphs}`); + insert(_el$28, () => ` ${snapshot().flightdeck.gateSummary}`); + insertNode(_el$29, _el$30); + setProp(_el$29, "marginTop", 1); + setProp(_el$29, "flexDirection", "column"); + insertNode(_el$30, createTextNode(`Step-Ledger & Active Tasks`)); + setProp(_el$30, "attributes", 1); + insert(_el$29, createComponent(Show, { + get when() { + return snapshot().flightdeck.steps.length > 0; + }, + get fallback() { + return (() => { + var _el$51 = createElement("text"); + insertNode(_el$51, createTextNode(` (no active step-ledger entries)`)); + effect((_$p) => setProp(_el$51, "fg", muted(), _$p)); + return _el$51; + })(); + }, + get children() { + return createComponent(For, { + get each() { + return snapshot().flightdeck.steps.slice(0, 6); + }, + children: (st) => (() => { + var _el$53 = createElement("text"); + insert(_el$53, () => ` ▸ ${st.stepKey.padEnd(20)} [${st.state.padEnd(11)}] @${st.agent} ${st.objective.slice(0, 36)}`); + effect((_$p) => setProp(_el$53, "fg", st.state === "blocked" || st.state === "rolled_back" ? errFg() : success(), _$p)); + return _el$53; + })() + }); + } + }), null); + insertNode(_el$32, _el$33); + setProp(_el$32, "marginTop", 1); + setProp(_el$32, "flexDirection", "column"); + insertNode(_el$33, createTextNode(`Semantic Event Stream`)); + setProp(_el$33, "attributes", 1); + insert(_el$32, createComponent(Show, { + get when() { + return snapshot().flightdeck.logs.length > 0; + }, + get fallback() { + return (() => { + var _el$54 = createElement("text"); + insertNode(_el$54, createTextNode(` (no bus telemetry events captured yet)`)); + effect((_$p) => setProp(_el$54, "fg", muted(), _$p)); + return _el$54; + })(); + }, + get children() { + return createComponent(For, { + get each() { + return snapshot().flightdeck.logs.slice(0, 8); + }, + children: (ev) => (() => { + var _el$56 = createElement("text"); + insert(_el$56, () => ` [${ev.kind}] @${ev.agent}: ${ev.detail.slice(0, 56)}`); + effect((_$p) => setProp(_el$56, "fg", ev.severity === "error" ? errFg() : muted(), _$p)); + return _el$56; + })() + }); + } + }), null); + insertNode(_el$35, _el$36); + setProp(_el$35, "marginTop", 1); + setProp(_el$35, "flexDirection", "row"); + setProp(_el$35, "gap", 2); + insertNode(_el$36, _el$37); + setProp(_el$36, "onMouseDown", () => cockpitController?.exportReplay()); + insertNode(_el$37, createTextNode(`[ x Export Replay Trace ]`)); + setProp(_el$37, "attributes", 1); + insert(_el$35, createComponent(Show, { + get when() { + return exportNote(); + }, + children: (note) => (() => { + var _el$57 = createElement("text"); + insert(_el$57, () => `✓ ${note()}`); + effect((_$p) => setProp(_el$57, "fg", success(), _$p)); + return _el$57; + })() + }), null); + effect((_p$) => { + var _v$5 = accent(), _v$6 = fg(), _v$7 = muted(), _v$8 = accent(), _v$9 = accent(), _v$0 = accent(); + _v$5 !== _p$.e && (_p$.e = setProp(_el$25, "fg", _v$5, _p$.e)); + _v$6 !== _p$.t && (_p$.t = setProp(_el$27, "fg", _v$6, _p$.t)); + _v$7 !== _p$.a && (_p$.a = setProp(_el$28, "fg", _v$7, _p$.a)); + _v$8 !== _p$.o && (_p$.o = setProp(_el$30, "fg", _v$8, _p$.o)); + _v$9 !== _p$.i && (_p$.i = setProp(_el$33, "fg", _v$9, _p$.i)); + _v$0 !== _p$.n && (_p$.n = setProp(_el$37, "fg", _v$0, _p$.n)); + return _p$; + }, { + e: void 0, + t: void 0, + a: void 0, + o: void 0, + i: void 0, + n: void 0 + }); + return _el$24; + } + }), _el$39); + insertNode(_el$39, createTextNode(`────────────────────────────────────────────────────────────────────────`)); + setProp(_el$39, "marginTop", 1); + insertNode(_el$41, createTextNode(`1-3 tabs · Tab/Shift+Tab switch · ↑↓ select · Enter detail · x replay · r refresh · Esc/q close`)); + effect((_p$) => { + var _v$1 = accent(), _v$10 = fg(), _v$11 = props.onClose, _v$12 = muted(), _v$13 = muted(), _v$14 = muted(), _v$15 = muted(); + _v$1 !== _p$.e && (_p$.e = setProp(_el$4, "fg", _v$1, _p$.e)); + _v$10 !== _p$.t && (_p$.t = setProp(_el$6, "fg", _v$10, _p$.t)); + _v$11 !== _p$.a && (_p$.a = setProp(_el$7, "onMouseDown", _v$11, _p$.a)); + _v$12 !== _p$.o && (_p$.o = setProp(_el$8, "fg", _v$12, _p$.o)); + _v$13 !== _p$.i && (_p$.i = setProp(_el$1, "fg", _v$13, _p$.i)); + _v$14 !== _p$.n && (_p$.n = setProp(_el$39, "fg", _v$14, _p$.n)); + _v$15 !== _p$.s && (_p$.s = setProp(_el$41, "fg", _v$15, _p$.s)); + return _p$; + }, { + e: void 0, + t: void 0, + a: void 0, + o: void 0, + i: void 0, + n: void 0, + s: void 0 + }); + return _el$; + })(); +} +function plainReturnRoute(cur) { + if (!cur || typeof cur.type !== "string") return void 0; + if (cur.type === "session" && typeof cur.sessionID === "string") return { + type: "session", + sessionID: cur.sessionID + }; + if (cur.type === "home") return { type: "home" }; +} +function setupPantheonCockpit(context, resolveCwd) { + const ui = context?.ui; + if (typeof ui?.router?.register === "function") try { + ui.router.register({ + name: ROUTE_NAME$1, + render: ({ data }) => { + const ret = data?.returnRoute; + const onClose = () => { + if (ret) ui.router.navigate(ret); + else ui.router.navigate({ type: "home" }); + }; + return createComponent(CockpitView, { + context, + get workspaceDir() { + return resolveCwd(); + }, + get sessionID() { + return memo(() => !!(ret && ret.type === "session"))() ? ret.sessionID : void 0; + }, + onClose + }); + } + }); + routerReady = true; + } catch { + routerReady = false; + } + const routeGated = () => { + try { + const r = ui?.router?.current?.(); + return r?.type === "plugin" && r.name === ROUTE_NAME$1; + } catch { + return false; + } + }; + const commands = [ + { + id: "pantheon.cockpit.tab1", + title: "Overview tab", + bind: "1", + run: () => { + cockpitController?.setTab("overview"); + } + }, + { + id: "pantheon.cockpit.tab2", + title: "Swarm tab", + bind: "2", + run: () => { + cockpitController?.setTab("swarm"); + } + }, + { + id: "pantheon.cockpit.tab3", + title: "Flightdeck tab", + bind: "3", + run: () => { + cockpitController?.setTab("flightdeck"); + } + }, + { + id: "pantheon.cockpit.next", + title: "Next Cockpit tab", + bind: "tab", + run: () => { + cockpitController?.nextTab(); + } + }, + { + id: "pantheon.cockpit.prev", + title: "Previous Cockpit tab", + bind: "shift+tab", + run: () => { + cockpitController?.prevTab(); + } + }, + { + id: "pantheon.cockpit.up", + title: "Previous row", + bind: "up,k", + run: () => { + cockpitController?.moveRow(-1); + } + }, + { + id: "pantheon.cockpit.down", + title: "Next row", + bind: "down,j", + run: () => { + cockpitController?.moveRow(1); + } + }, + { + id: "pantheon.cockpit.detail", + title: "Toggle row detail", + bind: "enter", + run: () => { + cockpitController?.toggleDetail(); + } + }, + { + id: "pantheon.cockpit.export", + title: "Export Flightdeck replay trace", + bind: "x", + run: () => { + cockpitController?.exportReplay(); + } + }, + { + id: "pantheon.cockpit.refresh", + title: "Refresh Cockpit", + bind: "r", + run: () => { + cockpitController?.refresh(); + } + }, + { + id: "pantheon.cockpit.close", + title: "Close Cockpit", + bind: "escape,q", + run: () => { + cockpitController?.close(); + } + } + ]; + try { + context.keymap?.layer?.(() => ({ + mode: ROUTE_MODE$1, + priority: 1, + enabled: () => routeGated() || cockpitOpen(), + commands + })); + context.keymap?.layer?.(() => ({ + mode: "global", + priority: 1, + enabled: () => cockpitOpen(), + commands + })); + } catch {} +} +function openPantheonCockpit(context, workspaceDir) { + const ui = context?.ui; + if (routerReady && typeof ui?.router?.navigate === "function") { + let returnRoute; + try { + const cur = ui.router.current(); + if (!(cur?.type === "plugin" && cur.name === ROUTE_NAME$1)) returnRoute = plainReturnRoute(cur); + } catch { + returnRoute = void 0; + } + ui.router.navigate({ + type: "plugin", + name: ROUTE_NAME$1, + ...returnRoute ? { data: { returnRoute } } : {} + }); + return; + } + try { + const curSid = ui?.router?.current?.()?.type === "session" ? ui.router.current().sessionID : void 0; + ui?.dialog?.show?.(() => createComponent(CockpitView, { + context, + workspaceDir, + sessionID: curSid, + onClose: () => ui?.dialog?.clear?.() + }), () => {}); + ui?.dialog?.set?.({ + size: "large", + centered: true + }); + } catch {} +} +//#endregion +//#region src/context-gauge.ts +const CONTEXT_BAR_CELLS = 12; +const CONTEXT_BAR_FILLED_CELL = "▰"; +const CONTEXT_BAR_EMPTY_CELL = "▱"; +const BAR_SHAPES = { + block: { + filled: "▰", + empty: "▱", + mark: "│" + }, + line: { + filled: "━", + empty: "─", + mark: "┼" + }, + smooth: { + filled: "█", + empty: "░", + mark: "┆" + }, + ascii: { + filled: "=", + empty: "-", + mark: "|" + }, + dots: { + filled: "●", + empty: "○", + mark: "│" + }, + braille: { + filled: "⣿", + empty: "⣀", + mark: "⡇" + } +}; +function numberOrNull$1(value) { + return typeof value === "number" && Number.isFinite(value) ? value : null; +} +function contextUsageTone(percent) { + if (percent > 90) return "error"; + if (percent > 50) return "warning"; + if (percent > 25) return "success"; + return "info"; +} +function formatTokenCount(tokens) { + const value = numberOrNull$1(tokens); + if (value === null || value < 0) return null; + return Math.round(value).toLocaleString("en-US"); +} +function formatContextWindow(limit) { + const value = numberOrNull$1(limit); + if (value === null || value <= 0) return null; + if (value >= 1e6) return `${(value / 1e6).toFixed(1)}M`; + if (value >= 1e3) return `${Math.floor(value / 1e3)}K`; + return `${Math.floor(value)}`; +} +function contextBarFilled(percent, cells = 12) { + const total = Math.max(1, Math.floor(cells)); + const filled = Math.round(percent / 100 * total); + if (!Number.isFinite(filled)) return 0; + return Math.min(total, Math.max(0, filled)); +} +function contextBar(percent, options = 12) { + const value = numberOrNull$1(percent); + if (value === null) return null; + const total = Math.max(1, Math.floor(typeof options === "number" ? options : options?.cells ?? 12)); + const shapeKey = typeof options === "object" && options?.shape && options.shape in BAR_SHAPES ? options.shape : "block"; + const glyphs = BAR_SHAPES[shapeKey] ?? BAR_SHAPES.block; + const evenMark = typeof options === "object" ? Boolean(options?.evenMark) : false; + const filledCount = contextBarFilled(value, total); + const emptyCount = total - filledCount; + if (!evenMark || total < 4) return { + filled: glyphs.filled.repeat(filledCount), + empty: glyphs.empty.repeat(emptyCount) + }; + const mid = Math.floor(total / 2); + const mark = glyphs.mark ?? "|"; + if (filledCount <= mid) { + const emptyBefore = mid - filledCount; + const emptyAfter = Math.max(0, emptyCount - emptyBefore - 1); + return { + filled: glyphs.filled.repeat(filledCount), + empty: `${glyphs.empty.repeat(emptyBefore)}${mark}${glyphs.empty.repeat(emptyAfter)}` + }; + } + const filledBefore = mid; + const filledAfter = Math.max(0, filledCount - filledBefore - 1); + return { + filled: `${glyphs.filled.repeat(filledBefore)}${mark}${glyphs.filled.repeat(filledAfter)}`, + empty: glyphs.empty.repeat(emptyCount) + }; +} +function formatSpent(cost) { + const value = numberOrNull$1(cost); + if (value === null || value < 0) return null; + return `$${value.toFixed(2)}`; +} +//#endregion +//#region src/model-usage-limits.ts +/** Shared bounds for cached recent model-usage aggregation. */ +const MODEL_USAGE_VISIBLE_CEILING = 3; +const MODEL_USAGE_MESSAGE_LIMIT = 400; +const MODEL_USAGE_SESSION_LIMIT = 8; +//#endregion +//#region src/autonomy-state.ts +const DEFAULT_GOAL_LOOP_PREFS = { + enabled: false, + cooldownMs: 5e3, + maxContinuations: 25 +}; +const GOAL_LOOP_ENABLED_CYCLE = Object.freeze(["enabled", "disabled"]); +const MAX_CONTINUATIONS_CYCLE = Object.freeze([ + "10", + "25", + "50", + "100", + "200" +]); +const COOLDOWN_MS_CYCLE = Object.freeze([ + "1000", + "2000", + "5000", + "10000" +]); +const DEFAULT_DECISION_BUDGETS = { + monthlyUsd: 5, + perDecisionUsd: .1 +}; +/** Format USD compactly for a cycler cell ("$5", "$0.10"). */ +function formatUsd(value) { + return `$${value < 1 ? value.toFixed(2) : String(Math.round(value))}`; +} +/** Build the USD step ladder used by the budget cyclers. */ +const MONTHLY_USD_CYCLE = Object.freeze([ + 1, + 2, + 5, + 10, + 20, + 50, + 100 +].map((value) => formatUsd(value))); +const PER_DECISION_USD_CYCLE = Object.freeze([ + .01, + .025, + .05, + .1, + .25, + .5, + 1 +].map((value) => formatUsd(value))); +/** Parse a staged USD cell back to a number; junk keeps the input. */ +function parseUsd(cell) { + const value = Number(cell.replace("$", "")); + return Number.isFinite(value) && value > 0 ? value : null; +} +function buildAutonomyTab(input) { + const isPt = input.languagePref === "pt-BR"; + return { + id: "autonomy", + title: isPt ? "Autonomia" : "Autonomy", + groups: [ + { + title: isPt ? "Loop Contínuo (auto-continuação de sessões multi-turn)" : "Auto-Continue Loop (multi-turn session auto-continuation)", + rows: [ + { + id: "autonomy.goal_loop.enabled", + name: isPt ? "Loop Contínuo" : "Auto-Continue Loop", + value: input.goalLoop.enabled ? "enabled" : "disabled", + cycle: GOAL_LOOP_ENABLED_CYCLE, + note: isPt ? "continua tarefas multi-turn quando a sessão fica ociosa" + (input.goalLoopRestartPending ? " · [!] reinício necessário para aplicar (restart)" : " · aplicado após reiniciar o OpenCode") : "auto-continues multi-turn tasks when session goes idle" + (input.goalLoopRestartPending ? " · [!] restart required to apply" : " · applies after OpenCode restart") + }, + { + id: "autonomy.goal_loop.maxContinuations", + name: isPt ? "Limite continuações" : "Max continuations", + value: String(input.goalLoop.maxContinuations), + cycle: MAX_CONTINUATIONS_CYCLE, + note: isPt ? "1..200 — teto de segurança contra loops infinitos" : "1..200 — safety ceiling to prevent runaway tasks" + }, + { + id: "autonomy.goal_loop.cooldownMs", + name: isPt ? "Pausa entre turnos (ms)" : "Cooldown (ms)", + value: String(input.goalLoop.cooldownMs), + cycle: COOLDOWN_MS_CYCLE, + note: isPt ? "intervalo entre turnos autônomos (mín 1000ms)" : "delay between autonomous turns (min 1000ms)" + } + ] + }, + { + title: isPt ? "Orçamentos de Decisão (Jev)" : "Decision Budgets (Jev)", + rows: [{ + id: "autonomy.budget.monthly", + name: isPt ? "Teto Mensal (USD)" : "Monthly Budget Cap", + value: formatUsd(input.budgets.monthlyUsd), + cycle: MONTHLY_USD_CYCLE, + note: isPt ? "teto mensal em USD para arbitragem do Jev" : "monthly USD ceiling for gated arbitrator decisions" + }, { + id: "autonomy.budget.perDecision", + name: isPt ? "Teto por Consulta" : "Per-Decision Cap", + value: formatUsd(input.budgets.perDecisionUsd), + cycle: PER_DECISION_USD_CYCLE, + note: isPt ? "teto de custo por decisão — acima disso é recusada" : "price cap — gated decisions above this are refused" + }] + }, + { + title: isPt ? "Gradiente de Decisão (política de referência · governado por J1 e Orçamentos)" : "Decision Gradient (reference policy · governed by J1 & Budgets)", + rows: [ + { + id: "autonomy.gradient.solo", + name: isPt ? "Decisão solo" : "Decide solo", + value: isPt ? "autônomo" : "autonomous", + note: isPt ? "ações rotineiras de baixo risco · reversível sem travas (sem portão)" : "reversible & low-risk edits, routine fixes (no gate)" + }, + { + id: "autonomy.gradient.jev", + name: isPt ? "Decisão Jev" : "Jev decides", + value: isPt ? "arbitrado" : "arbitrated", + note: isPt ? "ambiguidade de tipos e rotas · configurado nos Tetos de Orçamento acima" : "typed ambiguity & candidate ranking · configured via Budgets above" + }, + { + id: "autonomy.gradient.human", + name: isPt ? "Aprovação humana" : "Human decides", + value: isPt ? "revisão humana" : "human review", + note: isPt ? "ações destrutivas e de alto risco · configurado no limiar do Portão J1" : "high-risk & destructive operations · configured via J1 Gate" + } + ] + } + ] + }; +} +//#endregion +//#region src/decision-router-state.ts +/** +* decision-router-state.ts — the Decision Model section of the settings window. +* +* TUI-local replica of the user-level decision-router config +* (scripts/install/decision-router-config.mjs — the bundle must stay +* self-contained); tests/tui-decision-router-state.test.mjs pins the schema +* version, the exact key set and the provider matrix against that source. +* +* The runtime re-reads this file on EVERY gated call (jev-decision-tool.ts), +* so a write here applies live — no restart. The strict exact-key schema is +* load-bearing: any unknown key fail-closes the runtime to disabled/local, +* so the writer validates before persisting. +* +* Egress consent is CLI-owned: the window never writes `egress_consent`, and +* refuses to enable the router while remote candidates exist without it. +*/ +const DECISION_ENABLED_CYCLE = Object.freeze(["enabled", "disabled"]); +/** Exact top-level key set — anything else fail-closes the runtime. */ +const DECISION_CONFIG_KEYS = Object.freeze([ + "egress_consent", + "enabled", + "enabled_candidates", + "schema_version", + "selection" +]); +const DEFAULT_DECISION_CONFIG = Object.freeze({ + schema_version: 2, + enabled: false, + selection: Object.freeze({ mode: "local" }), + egress_consent: false, + enabled_candidates: Object.freeze([]) +}); +/** The runtime's provider→model matrix (drift-pinned against the installer source). */ +const DECISION_KNOWN_PROVIDERS = Object.freeze([ + "openai-decisions", + "typesafe-jev", + "opencode-console-jev", + "openrouter-jev", + "vercel-gateway-jev", + "cloudflare-workers-jev" +]); +const DECISION_CONSENT_CYCLE = Object.freeze(["not granted", "granted"]); +/** provider → model, straight from the runtime matrix (drift-pinned in tests). */ +const DECISION_KNOWN_MODELS = Object.freeze({ + "openai-decisions": "gpt-6-luna", + "typesafe-jev": "jev-1.14.0", + "opencode-console-jev": "jev-1.13", + "openrouter-jev": "typesafe/jev-1.13", + "vercel-gateway-jev": "typesafe-ai/jev", + "cloudflare-workers-jev": "clef" +}); +/** +* Credential surface per provider: the ENV VAR the host provider entry reads +* (`{env:VAR}` indirection — the window NEVER holds key values) plus the setup +* note. Drift-pinned against the installer/runtime sources in tests. +*/ +const DECISION_PROVIDER_CREDENTIALS = Object.freeze({ + "openai-decisions": { + note: "host-configured model — provision via `decision-router setup-model openai-decisions`", + notePt: "modelo do host — configure via `decision-router setup-model openai-decisions`" + }, + "typesafe-jev": { + env: "TYPESAFE_API_KEY", + note: "export TYPESAFE_API_KEY=… then restart", + notePt: "export TYPESAFE_API_KEY=… e depois reinicie" + }, + "opencode-console-jev": { + note: "rides your OpenCode login — no separate key", + notePt: "utiliza login do OpenCode — sem chave separada" + }, + "openrouter-jev": { + env: "OPENROUTER_API_KEY", + note: "export OPENROUTER_API_KEY=… then restart", + notePt: "export OPENROUTER_API_KEY=… e depois reinicie" + }, + "vercel-gateway-jev": { + env: "AI_GATEWAY_API_KEY", + note: "export AI_GATEWAY_API_KEY=… then restart", + notePt: "export AI_GATEWAY_API_KEY=… e depois reinicie" + }, + "cloudflare-workers-jev": { + env: "CLOUDFLARE_API_TOKEN", + note: "needs accountId (setup-model --account-id=…) + CLOUDFLARE_API_TOKEN", + notePt: "requer accountId (setup-model --account-id=…) + CLOUDFLARE_API_TOKEN" + } +}); +const DECISION_TARGET_CYCLE = Object.freeze(DECISION_KNOWN_PROVIDERS.map((provider) => `${provider}/${DECISION_KNOWN_MODELS[provider]}`)); +function decisionRouterConfigPath(env = process.env) { + const xdg = env.XDG_CONFIG_HOME; + const home = env.HOME ?? ""; + const root = xdg ?? join(home, ".config"); + return join(root, "pantheon", "decision-router.json"); +} +/** Fail-open read: a missing file is the default; an invalid one is reported, not guessed. */ +function readDecisionRouterConfig(env = process.env) { + let raw; + try { + raw = JSON.parse(readFileSync(decisionRouterConfigPath(env), "utf8")); + } catch (error) { + if (error?.code === "ENOENT") return { + config: cloneDefault(), + corrupt: false + }; return { - id: `gate.${behavior.id}`, - name: fromProject ? `${behavior.title} (${isPt ? "projeto" : "project"})` : behavior.title, - value: (editingProject ? effective : isBehaviorDisabled(merged, behavior.id)) ? "disabled" : "enabled", - ...writable ? { cycle: GATES_ENABLED_CYCLE } : {}, - note: !editingProject && fromProject ? isPt ? "arquivo do projeto tem precedência · edite .pantheon/overrides.json" : "project file wins at runtime — edit .pantheon/overrides.json" : editingProject ? isPt ? "salva em .pantheon/overrides.json (escopo do projeto)" : "saves to .pantheon/overrides.json (project scope)" : behavior.description + config: cloneDefault(), + corrupt: true }; + } + if (isValidDecisionConfig(raw)) return { + config: raw, + corrupt: false + }; + return { + config: cloneDefault(), + corrupt: true }; - const install = SETTINGS_BEHAVIORS.filter((behavior) => behavior.kind === "install"); - const runtime = SETTINGS_BEHAVIORS.filter((behavior) => behavior.kind === "runtime"); - const groups = []; - if (overridesScope !== void 0) groups.push({ - title: isPt ? "Escopo das regras" : "Rules Scope", - rows: [{ - id: "gates.scope", - name: isPt ? "Escopo de edição" : "Edit scope", - value: overridesScope, - cycle: OVERRIDES_SCOPE_CYCLE, - note: isPt ? "alterne entre global (~/.config/opencode) e projeto (.pantheon)" : "switch between global (~/.config/opencode) and project (.pantheon)" - }] - }); - groups.push({ - title: isPt ? "Skills instaladas" : "Install skills", - rows: install.map(rowFor) - }, { - title: isPt ? "Portões de execução" : "Runtime gates", - rows: runtime.map(rowFor) - }); +} +function cloneDefault() { return { - id: "gates", - title: "Gates", - groups + schema_version: DEFAULT_DECISION_CONFIG.schema_version, + enabled: DEFAULT_DECISION_CONFIG.enabled, + selection: { ...DEFAULT_DECISION_CONFIG.selection }, + egress_consent: DEFAULT_DECISION_CONFIG.egress_consent, + enabled_candidates: [...DEFAULT_DECISION_CONFIG.enabled_candidates] }; } -function buildAboutTab(version, extra) { - const isPt = extra?.languagePref === "pt-BR"; - const sysRows = [{ - id: "about.version", - name: isPt ? "Versão" : "Version", - value: `v${version}`, - note: isPt ? "OpenCode 2.x nativo — contrato V1 descontinuado" : "OpenCode 2.x only — the V1 contract is removed" - }, { - id: "about.behaviors", - name: isPt ? "Comportamentos" : "Behaviors", - value: String(SETTINGS_BEHAVIORS.length), - note: isPt ? "portões e skills de governança registradas" : "registered governance gates and skills" - }]; - if (extra?.nodeVersion) sysRows.push({ - id: "about.runtime", - name: "Runtime Node.js", - value: `v${extra.nodeVersion}`, - note: extra.platform ? `${isPt ? "plataforma" : "platform"}: ${extra.platform}` : "" +/** The exact-key, exact-shape validation the runtime applies (fail-closed otherwise). */ +function isValidDecisionConfig(value) { + if (typeof value !== "object" || value === null || Array.isArray(value)) return false; + const record = value; + const keys = Object.keys(record).sort(); + if (keys.length !== DECISION_CONFIG_KEYS.length) return false; + for (const key of DECISION_CONFIG_KEYS) if (!keys.includes(key)) return false; + if (record.schema_version !== 2) return false; + if (typeof record.enabled !== "boolean") return false; + if (typeof record.egress_consent !== "boolean") return false; + if (!isValidSelection(record.selection)) return false; + if (!Array.isArray(record.enabled_candidates)) return false; + for (const candidate of record.enabled_candidates) { + if (typeof candidate !== "object" || candidate === null) return false; + const entry = candidate; + if (typeof entry.provider !== "string" || typeof entry.model !== "string") return false; + if (Object.keys(entry).length !== 2) return false; + } + return true; +} +function isValidSelection(value) { + if (typeof value !== "object" || value === null) return false; + const selection = value; + if (selection.mode !== "local" && selection.mode !== "auto" && selection.mode !== "explicit") return false; + const keys = Object.keys(selection).sort(); + for (const key of keys) if (key !== "mode" && key !== "provider" && key !== "model") return false; + if (selection.provider !== void 0 && typeof selection.provider !== "string") return false; + if (selection.model !== void 0 && typeof selection.model !== "string") return false; + return true; +} +/** Stable serializer: exact keys in sorted order, 2-space, trailing newline. */ +function serializeDecisionConfig(config) { + const ordered = { + egress_consent: config.egress_consent, + enabled: config.enabled, + enabled_candidates: config.enabled_candidates.map((candidate) => ({ + model: candidate.model, + provider: candidate.provider + })), + schema_version: config.schema_version, + selection: { + mode: config.selection.mode, + ...config.selection.model !== void 0 ? { model: config.selection.model } : {}, + ...config.selection.provider !== void 0 ? { provider: config.selection.provider } : {} + } + }; + return `${JSON.stringify(ordered, null, 2)}\n`; +} +/** +* Enable/disable the router in a config copy. The guard mirrors the runtime's +* fail-close: with remote candidates and no egress consent, an enabled flag +* would be a lie — enabling requires consent, or a local-only selection. +* Never touches `egress_consent` (CLI-owned). +*/ +function setDecisionEnabled(config, enabled) { + if (enabled) { + if (!(config.selection.mode === "local" || config.enabled_candidates.length === 0) && !config.egress_consent) return { + ok: false, + reason: "remote candidates need egress consent — toggle Egress consent in this tab, then enable" + }; + } + return { + ok: true, + config: { + ...config, + enabled + } + }; +} +/** Atomic-ish write mirroring the canonical writer's privacy posture (0600). */ +function writeDecisionRouterConfig(config, env = process.env) { + if (!isValidDecisionConfig(config)) throw new TypeError("Refusing to persist an invalid decision-router configuration"); + const path = decisionRouterConfigPath(env); + mkdirSync(dirname(path), { + recursive: true, + mode: 448 }); - const govRows = [ - { - id: "about.preset", - name: isPt ? "Predefinição" : "Active Preset", - value: extra?.preset ?? "none", - note: isPt ? "modelo global ativo do Pantheon" : "global model preset active in Pantheon" - }, - { - id: "about.decision", - name: isPt ? "Assistente Jev" : "Decision Router", - value: extra?.decisionEnabled ? isPt ? "ativado" : "enabled" : isPt ? "desativado" : "disabled", - note: isPt ? "arbitragem de modelos e candidatos" : "model and candidate arbitration" - }, - { - id: "about.j1", - name: isPt ? "Portão J1" : "J1 Risk Gate", - value: extra?.j1Mode ?? "shadow", - note: isPt ? "portão de risco de segurança operacional" : "operational safety risk score gate" + const temp = `${path}.tui.tmp`; + writeFileSync(temp, serializeDecisionConfig(config), { mode: 384 }); + renameSync(temp, path); + chmodSync(path, 384); +} +const DECISION_SELECTION_CYCLE = Object.freeze([ + "local", + "auto", + "explicit" +]); +/** Stage a selection/consent row into a config copy; unknown rows are no-ops. */ +function applyDecisionRow(config, id, value) { + const next = { + ...config, + selection: { ...config.selection }, + enabled_candidates: [...config.enabled_candidates] + }; + switch (id) { + case "decision.selection.mode": { + const mode = value; + if (mode !== "local" && mode !== "auto" && mode !== "explicit") return config; + next.selection.mode = mode; + if (mode === "local") next.enabled_candidates = []; + return next; } - ]; - const refRows = [{ - id: "about.license", - name: isPt ? "Licença" : "License", - value: "MIT", - note: "Open source · Pantheon Project" + case "decision.selection.target": { + const separator = value.indexOf("/"); + if (separator <= 0) return config; + const provider = value.slice(0, separator); + const model = value.slice(separator + 1); + if (!DECISION_KNOWN_PROVIDERS.includes(provider)) return config; + if (DECISION_KNOWN_MODELS[provider] !== model) return config; + next.selection = { + mode: "explicit", + provider, + model + }; + next.enabled_candidates = [{ + provider, + model + }]; + return next; + } + case "decision.consent": + next.egress_consent = value === "granted"; + return next; + default: return config; + } +} +/** Provider ids as they appear in the host auth store / config providers. */ +const PROVIDER_AUTH_NAMES = Object.freeze({ + "openai-decisions": Object.freeze(["openai"]), + "typesafe-jev": Object.freeze(["typesafe-ai"]), + "opencode-console-jev": Object.freeze([]), + "openrouter-jev": Object.freeze(["openrouter"]), + "vercel-gateway-jev": Object.freeze(["vercel-ai-gateway", "vercel"]), + "cloudflare-workers-jev": Object.freeze(["cloudflare-workers-ai"]) +}); +/** +* TWO recognition forms (field feedback beta.6: keys registered via +* `opencode auth login` showed MISSING because only env vars were checked): +* env var set → 'env'; provider present in the host auth store → 'auth +* store'; provider entry in opencode.json providers → 'config'. Values are +* NEVER read — existence only. +*/ +function credentialStatus(provider, env, authProviders, configProviders) { + const credential = DECISION_PROVIDER_CREDENTIALS[provider]; + if (credential?.env !== void 0 && env[credential.env]) return "env"; + for (const name of PROVIDER_AUTH_NAMES[provider] ?? []) if (authProviders.has(name)) return "auth store"; + for (const name of PROVIDER_AUTH_NAMES[provider] ?? []) if (configProviders.has(name)) return "config"; + if (provider === "opencode-console-jev") return "auth store"; + return "missing"; +} +function buildDecisionTab(read, env = process.env, authProviders = /* @__PURE__ */ new Set(), configProviders = /* @__PURE__ */ new Set(), languagePref) { + const isPt = languagePref === "pt-BR"; + const { config, corrupt } = read; + const rows = [{ + id: "decision.enabled", + name: isPt ? "Assistente Jev" : "Jev Assistant", + value: config.enabled ? "enabled" : "disabled", + ...corrupt ? {} : { cycle: DECISION_ENABLED_CYCLE }, + note: corrupt ? isPt ? "config inválida — runtime fail-closes; repare via `decision-router setup-model`" : "config unreadable/invalid — runtime fail-closes; repair via `decision-router setup-model`" : isPt ? "aplica em tempo real — arbitragem de decisões relida a cada chamada" : "applies live — the runtime re-reads this on every gated call" }, { - id: "about.repo", - name: isPt ? "Repositório" : "Repository", - value: "ils15/pantheon-opencode", - note: "github.com/ils15/pantheon-opencode" - }]; - const groups = [{ - title: isPt ? "Sistema & Plataforma" : "System & Platform", - rows: sysRows + id: "decision.selection.mode", + name: isPt ? "Modo de Operação" : "Operation Mode", + value: config.selection.mode, + ...corrupt ? {} : { cycle: DECISION_SELECTION_CYCLE }, + note: isPt ? "local = no seu PC (grátis); auto/explícito = modelo nuvem (OpenRouter)" : "local routes on-device; auto/explicit pick a remote decision model" }]; - if (extra?.preset !== void 0 || extra?.decisionEnabled !== void 0) groups.push({ - title: isPt ? "Governança & Roteamento" : "Governance & Routing", - rows: govRows - }); - groups.push({ - title: isPt ? "Projeto & Referências" : "Project & References", - rows: refRows + const explicitTarget = config.selection.provider ? `${config.selection.provider}/${config.selection.model ?? ""}` : DECISION_TARGET_CYCLE[0] ?? "openrouter-jev/typesafe/jev-1.13"; + rows.push({ + id: "decision.selection.target", + name: isPt ? "Modelo de Decisão" : "Decision Model", + value: config.selection.mode === "local" ? config.selection.provider ? `${config.selection.provider}/${config.selection.model ?? ""}` : "local (on-device)" : explicitTarget, + ...corrupt ? {} : { cycle: DECISION_TARGET_CYCLE }, + note: isPt ? config.selection.mode === "local" ? "ciclar seleciona modelo remoto e ativa modo explícito" : "provedor/modelo ativo — define candidato para arbitragem" : config.selection.mode === "local" ? "cycle to select a remote model and activate explicit mode" : "provider/model — sets the candidate list" }); - return { - id: "about", - title: isPt ? "Sobre" : "About", - groups - }; -} -function buildChangelogTab(version, items = [], languagePref) { - const isPt = languagePref === "pt-BR"; - const rows = []; - if (items.length > 0) items.forEach((item, index) => { - rows.push({ - id: `changelog.item.${index + 1}`, - name: item.title.slice(0, 26), - value: "", - note: item.detail - }); + if ((config.enabled_candidates?.length ?? 0) > 0) rows.push({ + id: "decision.candidates", + name: isPt ? "Candidatos ativos" : "Candidates", + value: String(config.enabled_candidates.length), + note: config.egress_consent ? config.enabled_candidates.map((candidate) => `${candidate.provider}/${candidate.model}`).join(", ") : isPt ? "egress consent NÃO concedido — rotas remotas bloqueadas" : "egress consent NOT granted — remote routes fail closed" }); - else rows.push({ - id: "changelog.info", - name: isPt ? "Versão" : "Release", - value: `v${version}`, - note: isPt ? "veja o histórico completo no CHANGELOG.md ou no GitHub" : "view full history in CHANGELOG.md or GitHub releases" + rows.push({ + id: "decision.consent", + name: isPt ? "Acesso à Nuvem" : "Cloud API Access", + value: config.egress_consent ? "granted" : "not granted", + ...corrupt ? {} : { cycle: DECISION_CONSENT_CYCLE }, + note: isPt ? config.egress_consent ? "granted = rotas remotas podem consultar gateway de API (com teto de custo)" : "not granted = chamadas remotas bloqueadas; requer granted para nuvem" : config.egress_consent ? "granted = remote decision routes may call their gateway (budget-capped)" : "not granted = remote routes fail closed; grant to allow cloud calls" }); return { - id: "changelog", - title: isPt ? "Changelog" : "Changelog", + id: "decision", + title: isPt ? "Decisão" : "Decision", groups: [{ - title: isPt ? `Novidades na versão v${version}` : `What's New in v${version}`, + title: isPt ? "Assistente de Decisão (Jev)" : "Decision Assistant (Jev)", rows }, { - title: isPt ? "Referências de Versão" : "Release References", - rows: [{ - id: "changelog.docs", - name: isPt ? "Documentação" : "Documentation", - value: "CHANGELOG.md", - note: isPt ? "incluído na raiz do plugin e do repositório" : "shipped at plugin root and repository root" - }, { - id: "changelog.repo", - name: isPt ? "Repositório GitHub" : "GitHub Repository", - value: "ils15/pantheon-opencode", - note: isPt ? "versões, pull requests e discussões" : "releases, pull requests and discussion" - }] + title: isPt ? "Credenciais (status apenas — valores nunca gravados na janela)" : "Credentials (status only — values never enter the window)", + rows: DECISION_KNOWN_PROVIDERS.map((provider) => { + const status = credentialStatus(provider, env, authProviders, configProviders); + const credential = DECISION_PROVIDER_CREDENTIALS[provider] ?? { note: "" }; + return { + id: `decision.key.${provider}`, + name: provider, + value: status === "missing" ? "MISSING" : status, + note: isPt ? credential.notePt ?? credential.note : credential.note + }; + }) }] }; } //#endregion -//#region src/update-notice.ts -/** -* Update notifier core (TUI-local copy — the bundle must stay self-contained, -* same precedent as cost-data.ts/model-pricing.ts). -* -* Pin + notify, never silent auto-update: one notice per newer version, -* TTL-cached, offline-safe, and a stable install is never advertised a beta -* (the update guard owns that crossing). docs/design/2.0-settings-and-install.md -*/ -const UPDATE_CHECK_TTL_MS = 216e5; -const isBetaOrRc = (version) => /-(?:beta|rc)\.\d+$/.test(String(version).trim()); -/** True when `latestVersion` is strictly newer and compatible with `currentVersion` channel. */ -function isNewerUpdateAvailable(currentVersion, latestVersion) { - const current = String(currentVersion).trim(); - const latest = String(latestVersion).trim(); - if (!current || !latest) return false; - if (!isBetaOrRc(current) && isBetaOrRc(latest)) return false; - return comparePantheonVersions(latest, current) > 0; -} -/** Package specifier matching the running release line (`@beta` on prereleases). */ -function packageSpecForVersion(version) { - return isBetaOrRc(version) ? "pantheon-opencode@beta" : "pantheon-opencode"; -} -/** Format a bilingual toast title + message for a newly discovered update. */ -function formatUpdateToast(currentVersion, latestVersion, isPt = false) { - const spec = packageSpecForVersion(currentVersion); - if (isPt) return { - title: `Pantheon v${latestVersion} disponível`, - message: `Atualize em /pantheon-settings (Atualizações) ou \`opencode plugin update ${spec}\`` - }; - return { - title: `Pantheon v${latestVersion} available`, - message: `Update in /pantheon-settings (Updates) or \`opencode plugin update ${spec}\`` - }; -} -/** Compact persistent badge rendered in Home footer and Sidebar header when an update exists. */ -function formatUpdateBadge(currentVersion, latestVersion, options = {}) { - if (!latestVersion || !isNewerUpdateAvailable(currentVersion, latestVersion)) return null; - const version = latestVersion.trim().replace(/^v/i, ""); - if (options.compact) return `↑ v${version} (/pantheon-settings)`; - return options.isPt ? `↑ v${version} disponível · /pantheon-settings` : `↑ v${version} available · /pantheon-settings`; -} -/** Resolve cached newer version from persisted check state (no network call needed). */ -function resolveCachedAvailableUpdate(currentVersion, state) { - if (!state) return null; - const candidate = state.lastKnownLatestVersion ?? state.lastNotifiedVersion; - if (!candidate) return null; - return isNewerUpdateAvailable(currentVersion, candidate) ? candidate : null; -} -/** Stamp `lastKnownLatestVersion` onto an `UpdateCheckState` without altering TTL/notice fields. */ -function withKnownLatest(state, latestVersion) { - if (!latestVersion) return state; - return { - ...state, - lastKnownLatestVersion: latestVersion - }; -} -let availableUpdateState = null; -const availableUpdateListeners = /* @__PURE__ */ new Set(); -function getAvailableUpdateVersion() { - return availableUpdateState; -} -function setAvailableUpdateVersion(version) { - const normalized = version && version.trim() !== "" ? version.trim() : null; - if (normalized === availableUpdateState) return; - availableUpdateState = normalized; - for (const listener of availableUpdateListeners) try { - listener(availableUpdateState); - } catch {} -} -function subscribeAvailableUpdate(listener) { - availableUpdateListeners.add(listener); - return () => { - availableUpdateListeners.delete(listener); - }; -} -/** Semver-ish compare for X.Y.Z[-(beta|rc).N]; prereleases sort before their release. */ -function comparePantheonVersions(left, right) { - const parse = (version) => { - const match = String(version).trim().match(/^(\d+)\.(\d+)\.(\d+)(?:-(beta|rc)\.(\d+))?$/); - if (!match) return null; - const [, major = "", minor = "", patch = "", stage = "", stageNum = ""] = match; - const stageRank = stage === "beta" ? 1 : stage === "rc" ? 2 : 3; - return { - core: [ - +major, - +minor, - +patch - ], - stageRank, - stageNum: stage !== "" ? +stageNum : Number.POSITIVE_INFINITY - }; - }; - const a = parse(left); - const b = parse(right); - if (!a || !b) return 0; - const [aMajor, aMinor, aPatch] = a.core; - const [bMajor, bMinor, bPatch] = b.core; - if (aMajor !== bMajor) return aMajor - bMajor; - if (aMinor !== bMinor) return aMinor - bMinor; - if (aPatch !== bPatch) return aPatch - bPatch; - if (a.stageRank !== b.stageRank) return a.stageRank - b.stageRank; - return a.stageNum - b.stageNum; -} -function pickUpdateNotice(input) { - const { currentVersion, latestVersion, state = {}, nowMs = Date.now(), isPt = false } = input; - const ttlMs = input.ttlMs ?? 216e5; - if (nowMs - (state.lastCheckMs ?? 0) < ttlMs) return null; - if (state.lastNotifiedVersion === latestVersion) return null; - if (!isNewerUpdateAvailable(currentVersion, latestVersion)) return null; - return { - version: latestVersion, - message: formatUpdateToast(currentVersion, latestVersion, isPt).message - }; -} -/** The state to persist after a check (notified or not) for the TTL. */ -function nextCheckState(previous, notice, nowMs) { - const lastNotifiedVersion = notice?.version ?? previous.lastNotifiedVersion; - return { - lastCheckMs: nowMs, - ...lastNotifiedVersion !== void 0 ? { lastNotifiedVersion } : {} - }; -} -//#endregion -//#region src/doctor-state.ts -/** -* doctor-state.ts — the Doctor section of the settings window (read-only). -* -* TUI-local replica (the bundle must stay self-contained — the installed copy -* physically lacks the repo tree, so doctor.mjs itself is unreachable). Only -* the FILE-DERIVABLE checks are mirrored here; everything that spawns -* processes, reads the network, or writes (MCP smoke, python validators, git, -* venv pins, --fix quarantines) stays in the CLI and the section says so. -* -* The install-state path mirrors doctor's checkInstallVersionDrift -* (`/opencode/.pantheon/install-state.json`); the Node floor is -* drift-pinned against scripts/node-engine-policy.mjs by -* tests/tui-doctor-state.test.mjs. -*/ -/** Drift-pinned against scripts/node-engine-policy.mjs MIN_SUPPORTED_NODE_VERSION. */ -const MIN_SUPPORTED_NODE_VERSION = "26.4.0"; -function opencodePantheonDir(env = process.env) { - const xdg = env.XDG_CONFIG_HOME; - const home = env.HOME ?? ""; - const root = xdg ?? join(home, ".config"); - return join(root, "opencode", ".pantheon"); +//#region src/pantheon-settings-state.ts +/** Mirrors routing.yml `behaviors:` — drift-pinned by the registry test. */ +const SETTINGS_BEHAVIORS = Object.freeze([ + { + id: "skill-auto-continue", + kind: "install", + title: "Auto-continue skill", + description: "Continue multi-step todos while keeping safety gates." + }, + { + id: "skill-tdd-with-agents", + kind: "install", + title: "TDD with agents skill", + description: "RED, GREEN, REFACTOR test-driven implementation." + }, + { + id: "skill-code-review-checklist", + kind: "install", + title: "Code review checklist skill", + description: "Systematic code review and quality gates." + }, + { + id: "skill-prompt-refinery", + kind: "install", + title: "Prompt refinery skill", + description: "Vague requests refined — silent adjust, >> full contract." + }, + { + id: "gate-idle-todo-enforcer", + kind: "runtime", + title: "Idle todo enforcer", + description: "Continues pending todos when a session goes idle." + }, + { + id: "gate-context-pruner", + kind: "runtime", + title: "Context pruner", + description: "Prunes repeated tool output before summarization." + }, + { + id: "gate-j1-risk-gate", + kind: "runtime", + title: "J1 risk gate", + description: "High-risk tool calls demand explicit human approval." + } +]); +new Set(SETTINGS_BEHAVIORS.map((b) => b.id)); +function isBehaviorDisabled(effective, id) { + return effective[id]?.action === "disable"; } +const TOGGLE_REASON = "toggled in /pantheon-settings"; /** -* H2: the installed package version (install-state) vs the running one. -* Fail-open: a missing/unreadable state file means "unknown", not a failure — -* pre-2.0 installs may not have one. +* Toggle (a targeted write keeps the toggle semantics: a `replace` entry is +* never destroyed — disabling keeps its `content`, re-enabling restores the +* replace; a settings-written disable is removed outright, no toggle noise). */ -function classifyInstallVersion(runningVersion, env = process.env) { - let installed = null; - try { - const path = join(opencodePantheonDir(env), "install-state.json"); - const raw = JSON.parse(readFileSync(path, "utf8")); - if (typeof raw?.pantheon_version === "string" && raw.pantheon_version !== "") installed = raw.pantheon_version; - } catch { - installed = null; - } - if (installed === null) return { - status: "unknown", - installed: null - }; - const compared = comparePantheonVersions(installed, runningVersion); - if (compared === 0) return { - status: "ok", - installed - }; - return { - status: compared < 0 ? "older" : "newer", - installed +function toggledOverrides(effective, id, reason = TOGGLE_REASON) { + const next = { ...effective }; + const entry = next[id]; + if (entry?.action === "disable") { + if (entry.content !== void 0) next[id] = entry.reason === reason ? { + action: "replace", + content: entry.content + } : { + action: "replace", + content: entry.content, + ...entry.reason !== void 0 ? { reason: entry.reason } : {} + }; + else delete next[id]; + } else next[id] = entry?.content !== void 0 ? { + action: "disable", + reason, + content: entry.content + } : { + action: "disable", + reason }; + return next; } -function isSupportedNodeFloor(version) { - const match = /^v?(\d+)\.(\d+)\.(\d+)(?:-([^+]+))?(?:\+([\w.-]+))?$/.exec(String(version)); - const minimum = /^v?(\d+)\.(\d+)\.(\d+)/.exec(MIN_SUPPORTED_NODE_VERSION); - if (!match || !minimum) return false; - const [, major = "", minor = "", patch = "", prerelease = ""] = match; - if (prerelease !== "") return false; - const [, minMajor = "0", minMinor = "0", minPatch = "0"] = minimum; - const currentParts = [ - +major, - +minor, - +patch - ]; - const minimumParts = [ - +minMajor, - +minMinor, - +minPatch - ]; - for (let index = 0; index < 3; index += 1) { - const currentPart = currentParts[index] ?? 0; - const minimumPart = minimumParts[index] ?? 0; - if (currentPart !== minimumPart) return currentPart > minimumPart; - } - return true; +/** Set an explicit on/off target (the cycler's save path) via the toggle semantics. */ +function setOverrideState(effective, id, target, reason = TOGGLE_REASON) { + const disabled = isBehaviorDisabled(effective, id); + if (target === "disabled" === disabled) return effective; + return toggledOverrides(effective, id, reason); } -/** K: validate both overrides files against the window's registry. */ -function classifyOverridesHealth(load) { - if (load.corruptGlobal) return { - status: "corrupt", - unknownIds: [] - }; - const known = new Set(SETTINGS_BEHAVIORS.map((behavior) => behavior.id)); - const unknownIds = Object.keys({ +function serializeOverrides(effective) { + const ordered = {}; + for (const id of Object.keys(effective).sort()) ordered[id] = effective[id]; + return `${JSON.stringify(ordered, null, 2)}\n`; +} +/** Merge for DISPLAY only, mirroring the runtime precedence: project wins per id. */ +function mergedOverrides(load) { + return { ...load.global, ...load.project - }).filter((id) => !known.has(id)); - return { - status: unknownIds.length > 0 ? "unknown-ids" : "clean", - unknownIds }; } -function classifyDecisionConfigHealth(env = process.env) { - if (!existsSync(join(env.XDG_CONFIG_HOME ?? join(env.HOME ?? "", ".config"), "pantheon", "decision-router.json"))) return { status: "absent" }; - return readDecisionRouterConfig(env).corrupt ? { status: "corrupt" } : { status: "ok" }; +function canWriteOverrides(load) { + return !load.corruptGlobal; } -function buildDoctorTab(input) { - const env = input.env ?? process.env; - const rows = []; - const version = classifyInstallVersion(input.runningVersion, env); - rows.push({ - id: "doctor.version", - name: "Install version", - value: version.status === "ok" ? `v${version.installed} — matches` : version.status === "older" ? `v${version.installed} older` : version.status === "newer" ? `v${version.installed} newer` : "unknown", - note: version.status === "older" ? "refresh with `pantheon-opencode update`" : "read from /opencode/.pantheon/install-state.json" - }); - const nodeOk = isSupportedNodeFloor(input.nodeVersion); - rows.push({ - id: "doctor.node", - name: "Node runtime", - value: input.nodeVersion.replace(/^v/, ""), - note: nodeOk ? `meets the >= ${MIN_SUPPORTED_NODE_VERSION} floor` : `below the >= ${MIN_SUPPORTED_NODE_VERSION} floor — tooling may refuse` - }); - const overrides = classifyOverridesHealth(input.load); - rows.push({ - id: "doctor.overrides", - name: "Overrides", - value: overrides.status === "clean" ? "valid" : overrides.status === "corrupt" ? "unreadable" : `${overrides.unknownIds.length} unknown id(s)`, - note: overrides.status === "unknown-ids" ? `${overrides.unknownIds.join(", ")} — harmless; repair with doctor --fix` : overrides.status === "corrupt" ? "writes are refused until repaired (doctor --fix)" : "both files parse against the behavior registry" - }); - const decision = classifyDecisionConfigHealth(env); - rows.push({ - id: "doctor.decision", - name: "Decision config", - value: decision.status === "ok" ? "valid" : decision.status === "corrupt" ? "corrupt" : "absent", - note: decision.status === "corrupt" ? "runtime fail-closes to disabled · read from /pantheon/decision-router.json" : "read from /pantheon/decision-router.json" - }); +/** Neutral tab for out-of-range indexes (noUncheckedIndexedAccess guard). */ +const EMPTY_TAB = { + id: "empty", + title: "", + groups: [] +}; +/** Flat, in-order rows of a tab (the up/down navigation space). */ +function tabRows(tab) { + return tab.groups.flatMap((group) => group.rows); +} +function findRow(tab, id) { + return tabRows(tab).find((row) => row.id === id); +} +/** Step through the cycle with wrap-around; non-cyclable rows return the input. */ +function cycleValue(value, cycle, direction) { + if (cycle.length === 0) return value; + const index = cycle.indexOf(value); + if (index === -1) return cycle[0] ?? value; + return cycle[(index + direction + cycle.length) % cycle.length] ?? value; +} +function stageValue(draft, row, direction) { + if (row.cycle === void 0) return draft; + const staged = cycleValue(draft[row.id] ?? row.value, row.cycle, direction); + if (staged === row.value) { + if (draft[row.id] === void 0) return draft; + const next = { ...draft }; + delete next[row.id]; + return next; + } return { - id: "doctor", - title: "Doctor", - groups: [{ - title: "Health (file-derived)", - rows - }, { rows: [{ - id: "doctor.cli", - name: "Full check", - value: "`pantheon-opencode doctor`", - note: "MCP smoke, venv pins, git stay in the CLI" - }] }] + ...draft, + [row.id]: staged + }; +} +/** Stage an explicit target value for one row (the Defaults action path). */ +function stageRowToValue(draft, row, target) { + if (!row.cycle?.includes(target)) return draft; + if (target === row.value) { + if (draft[row.id] === void 0) return draft; + const next = { ...draft }; + delete next[row.id]; + return next; + } + return { + ...draft, + [row.id]: target }; } -Object.freeze([ - "auto", - "pt-BR", - "en" -]); /** -* Resolve effective language: 'pt-BR' or 'en'. -* Defaults to 'pt-BR' if system locale contains 'pt', if Intl locale is pt, -* or if system timezone is Brazilian/Portuguese; otherwise 'en'. +* Stage every cyclable row's DEFAULT value of a tab. Rows already at their +* default have their staged entry dropped; rows staged elsewhere keep it +* until the Defaults action targets them. */ -function resolveLanguage(preference = "auto", env = process.env) { - if (preference === "pt-BR") return "pt-BR"; - if (preference === "en") return "en"; - if ((env.LC_ALL ?? env.LC_MESSAGES ?? env.LANG ?? env.LANGUAGE ?? "").toLowerCase().startsWith("pt")) return "pt-BR"; - try { - if (Intl.DateTimeFormat().resolvedOptions().locale.toLowerCase().startsWith("pt")) return "pt-BR"; - } catch {} - try { - const tz = (env.TZ ?? Intl.DateTimeFormat().resolvedOptions().timeZone ?? "").toLowerCase(); - if (tz.includes("sao_paulo") || tz.includes("brazil") || tz.includes("fortaleza") || tz.includes("recife") || tz.includes("manaus") || tz.includes("belem") || tz.includes("cuiaba") || tz.includes("campo_grande") || tz.includes("porto_velho") || tz.includes("rio_branco") || tz.includes("boa_vista") || tz.includes("maceio") || tz.includes("bahia") || tz.includes("noronha") || tz.includes("araguaina") || tz.includes("santarem") || tz.includes("lisbon") || tz.includes("madeira") || tz.includes("azores")) return "pt-BR"; - } catch {} - return "en"; +function stageDefaults(draft, tab) { + let next = draft; + for (const row of tabRows(tab)) { + if (row.cycle === void 0 || row.def === void 0) continue; + const candidate = next[row.id] ?? row.value; + if (candidate === row.def) { + if (next[row.id] !== void 0) { + const copy = { ...next }; + delete copy[row.id]; + next = copy; + } + continue; + } + next = stageRowToValue(next, { + ...row, + value: candidate + }, row.def); + } + return next; } -//#endregion -//#region src/j1-gate-status.ts -const J1_FLAG_ENV = "PANTHEON_J1_RISK_SCORE"; -const J1_THRESHOLD_ENV = "PANTHEON_J1_ENFORCE_THRESHOLD"; -const J1_THRESHOLD_DEFAULT = .8; -/** `1`/`on`/`true` map to `shadow` for back-compatibility with the shipped setup. */ -const FLAG_ON = /* @__PURE__ */ new Set([ - "1", - "on", - "true", - "shadow" -]); -function j1ModeFromEnv(env = process.env) { - const raw = (env["PANTHEON_J1_RISK_SCORE"] ?? "").trim().toLowerCase(); - if (raw === "enforce") return "enforce"; - if (raw === "warn") return "warn"; - return FLAG_ON.has(raw) ? "shadow" : "off"; +/** Drop every staged entry of one tab (ctrl+r). */ +function resetTab(draft, tab) { + const ids = new Set(tabRows(tab).map((row) => row.id)); + const next = {}; + for (const [id, value] of Object.entries(draft)) if (!ids.has(id)) next[id] = value; + return next; +} +function draftCount(draft) { + return Object.keys(draft).length; } -/** Invalid or out-of-range values fall back to the default — a typo must not disable the gate. */ -function j1ThresholdFromEnv(env = process.env) { - const text = (env["PANTHEON_J1_ENFORCE_THRESHOLD"] ?? "").trim(); - if (text === "") return J1_THRESHOLD_DEFAULT; - const raw = Number(text); - if (!Number.isFinite(raw) || raw < 0 || raw > 1) return J1_THRESHOLD_DEFAULT; - return raw; +function draftDirty(draft) { + return draftCount(draft) > 0; } -const MODE_DESCRIPTION_EN = { - off: "nothing fires (hard zero)", - shadow: "observe + record; invisible in the session", - warn: "RESERVED — behaves as shadow in this release", - enforce: "high-risk scores DENY the tool call (fail-open on gate unavailability)" -}; -const MODE_DESCRIPTION_PT = { - off: "desativado (hard zero)", - shadow: "observa + registra telemetria (modo silencioso)", - warn: "RESERVADO (RESERVED) — comporta-se como shadow nesta versão", - enforce: "alto risco bloqueia a ferramenta (fail-open se indisponível)" -}; -function buildJ1Tab(env, disabledByOverride, languagePref) { - const isPt = resolveLanguage(languagePref) === "pt-BR"; - const mode = j1ModeFromEnv(env); - const threshold = j1ThresholdFromEnv(env); - const gateState = disabledByOverride ? "disabled via overrides" : mode === "off" ? "off (env unset)" : "active"; - const desc = isPt ? MODE_DESCRIPTION_PT[mode] : MODE_DESCRIPTION_EN[mode]; +function tabDirty(draft, tab) { + return tabRows(tab).some((row) => draft[row.id] !== void 0); +} +/** Apply every staged entry; failures are collected, never thrown. */ +function applyDraft(draft, writer) { + const applied = []; + const failed = []; + for (const [id, value] of Object.entries(draft)) { + const result = writer(id, value); + if (result.ok) applied.push(id); + else failed.push({ + id, + reason: result.reason ?? "write failed" + }); + } return { - id: "j1", - title: isPt ? "Segurança J1" : "J1 Safety", - groups: [{ - title: isPt ? "Portão de Segurança (J1)" : "Safety Risk Gate (J1)", - rows: [ - { - id: "j1.mode", - name: isPt ? "Modo de Operação" : "Operation Mode", - value: mode, - note: `${desc} · ${isPt ? "reinício necessário (restart applies)" : "restart applies"}` - }, - { - id: "j1.threshold", - name: isPt ? "Limiar de bloqueio" : "Enforce threshold", - value: String(threshold), - note: isPt ? "bloqueia em ou acima · 0..1 · padrão 0.8" : "deny at or above · 0..1 · default 0.8" - }, - { - id: "j1.gate", - name: isPt ? "Portão de Segurança" : "Safety Risk Gate", - value: gateState, - note: `${J1_FLAG_ENV} / ${J1_THRESHOLD_ENV} · ${isPt ? "lido na inicialização" : "read once at startup"}` - } - ] - }] + applied, + failed }; } -//#endregion -//#region src/legacy-audit.ts -/** -* legacy-audit.ts — Self-contained Legacy & Drift Auditor for the TUI Settings panel. -* -* Scans global (~/.config/opencode) and workspace () scopes for: -* - Dead V1 hooks/files (pantheon-hooks.*, tiers.json, fastembed_cache, .migration-checkpoint) -* - Unmigrated legacy stores (memory.db, persistence/{global,project}.db, goals.json) -* - Redundant copied canonical Pantheon assets shadowed by native plugin transforms -* - Drifted copied TUI plugins (plugins/pantheon-tui version != running plugin version) -* - Old configuration backup sidecars (opencode.json.bak*, active-preset.json.bak*) -* -* Always migrates unmigrated legacy context/memory/goals BEFORE deleting obsolete stores, -* and NEVER touches user-created custom agents or custom user skills. -*/ -const SAFE_SEGMENT_RE = /^[a-zA-Z0-9._:-]{1,128}$/; -const CANONICAL_AGENT_MD_FILES = Object.freeze([ - "aphrodite.md", - "apollo.md", - "artemis.md", - "athena.md", - "demeter.md", - "gaia.md", - "hephaestus.md", - "hermes.md", - "iris.md", - "mnemosyne.md", - "nyx.md", - "prometheus.md", - "talos.md", - "themis.md", - "zeus.md" -]); -const CANONICAL_COMMAND_MD_FILES = Object.freeze([ - "pantheon.md", - "pantheon-audit.md", - "pantheon-deepwork.md", - "pantheon-focus.md", - "pantheon-model.md", - "pantheon-optimize.md", - "pantheon-settings.md", - "pantheon-vision.md" -]); -const CANONICAL_SKILL_IDS = Object.freeze([ - "agent-coordination", - "agent-forge", - "artifact-management", - "auto-continue", - "clonedeps", - "code-review-checklist", - "codemap", - "context-compression", - "fast-path-execution", - "git-workflow-and-versioning", - "incremental-implementation", - "instruction-forge", - "loop-engineering", - "memory-bank", - "prompt-refinery", - "reflect", - "security-hardening", - "session-goal", - "simplify", - "spec-driven-development", - "tdd-with-agents", - "test-slicing", - "verification-planning", - "visual-review-pipeline", - "worktrees" -]); -const LEGACY_INSTRUCTION_FILES = Object.freeze([ - "zeus-execution-rules.instructions.md", - "zeus-orchestration.instructions.md", - "zeus-workflow.instructions.md" -]); -function resolveAuditGlobalDir(env = process.env) { - if (env.PANTHEON_HOME?.trim()) return resolve(env.PANTHEON_HOME.trim()); - if (env.XDG_CONFIG_HOME?.trim()) return join(resolve(env.XDG_CONFIG_HOME.trim()), "opencode"); - if (env.NODE_TEST_CONTEXT) return void 0; - const home = env.HOME?.trim(); - return home ? join(resolve(home), ".config", "opencode") : void 0; +/** The rows that succeeded and are still in the draft (failed ones stay staged). */ +function settledDraft(draft, applied) { + const next = {}; + for (const [id, value] of Object.entries(draft)) if (!applied.includes(id)) next[id] = value; + return next; } -function formatBytes(bytes) { - if (bytes < 1024) return `${bytes} B`; - if (bytes < 1048576) return `${(bytes / 1024).toFixed(1)} KB`; - return `${(bytes / 1048576).toFixed(2)} MB`; +const GATES_ENABLED_CYCLE = Object.freeze(["enabled", "disabled"]); +const OVERRIDES_SCOPE_CYCLE = Object.freeze(["global", "project"]); +function buildGatesTab(load, languagePref, overridesScope) { + const isPt = languagePref === "pt-BR"; + const merged = mergedOverrides(load); + const editingProject = overridesScope === "project"; + const rowFor = (behavior) => { + const fromProject = load.project[behavior.id] !== void 0; + const effective = editingProject ? isBehaviorDisabled({ + ...load.global, + ...load.project + }, behavior.id) : isBehaviorDisabled(load.global, behavior.id); + const writable = editingProject ? true : !fromProject && canWriteOverrides(load); + return { + id: `gate.${behavior.id}`, + name: fromProject ? `${behavior.title} (${isPt ? "projeto" : "project"})` : behavior.title, + value: (editingProject ? effective : isBehaviorDisabled(merged, behavior.id)) ? "disabled" : "enabled", + ...writable ? { cycle: GATES_ENABLED_CYCLE } : {}, + note: !editingProject && fromProject ? isPt ? "arquivo do projeto tem precedência · edite .pantheon/overrides.json" : "project file wins at runtime — edit .pantheon/overrides.json" : editingProject ? isPt ? "salva em .pantheon/overrides.json (escopo do projeto)" : "saves to .pantheon/overrides.json (project scope)" : behavior.description + }; + }; + const install = SETTINGS_BEHAVIORS.filter((behavior) => behavior.kind === "install"); + const runtime = SETTINGS_BEHAVIORS.filter((behavior) => behavior.kind === "runtime"); + const groups = []; + if (overridesScope !== void 0) groups.push({ + title: isPt ? "Escopo das regras" : "Rules Scope", + rows: [{ + id: "gates.scope", + name: isPt ? "Escopo de edição" : "Edit scope", + value: overridesScope, + cycle: OVERRIDES_SCOPE_CYCLE, + note: isPt ? "alterne entre global (~/.config/opencode) e projeto (.pantheon)" : "switch between global (~/.config/opencode) and project (.pantheon)" + }] + }); + groups.push({ + title: isPt ? "Skills instaladas" : "Install skills", + rows: install.map(rowFor) + }, { + title: isPt ? "Portões de execução" : "Runtime gates", + rows: runtime.map(rowFor) + }); + return { + id: "gates", + title: "Gates", + groups + }; } -function toSafeSegment(raw, fallback = "default") { - const str = String(raw ?? "").trim().replace(/[^a-zA-Z0-9._:-]/g, "_").slice(0, 128); - if (!str || str === "." || str === ".." || !SAFE_SEGMENT_RE.test(str)) return fallback; - return str; +function buildAboutTab(version, extra) { + const isPt = extra?.languagePref === "pt-BR"; + const sysRows = [{ + id: "about.version", + name: isPt ? "Versão" : "Version", + value: `v${version}`, + note: isPt ? "OpenCode 2.x nativo — contrato V1 descontinuado" : "OpenCode 2.x only — the V1 contract is removed" + }, { + id: "about.behaviors", + name: isPt ? "Comportamentos" : "Behaviors", + value: String(SETTINGS_BEHAVIORS.length), + note: isPt ? "portões e skills de governança registradas" : "registered governance gates and skills" + }]; + if (extra?.nodeVersion) sysRows.push({ + id: "about.runtime", + name: "Runtime Node.js", + value: `v${extra.nodeVersion}`, + note: extra.platform ? `${isPt ? "plataforma" : "platform"}: ${extra.platform}` : "" + }); + const govRows = [ + { + id: "about.preset", + name: isPt ? "Predefinição" : "Active Preset", + value: extra?.preset ?? "none", + note: isPt ? "modelo global ativo do Pantheon" : "global model preset active in Pantheon" + }, + { + id: "about.decision", + name: isPt ? "Assistente Jev" : "Decision Router", + value: extra?.decisionEnabled ? isPt ? "ativado" : "enabled" : isPt ? "desativado" : "disabled", + note: isPt ? "arbitragem de modelos e candidatos" : "model and candidate arbitration" + }, + { + id: "about.j1", + name: isPt ? "Portão J1" : "J1 Risk Gate", + value: extra?.j1Mode ?? "shadow", + note: isPt ? "portão de risco de segurança operacional" : "operational safety risk score gate" + } + ]; + const refRows = [{ + id: "about.license", + name: isPt ? "Licença" : "License", + value: "MIT", + note: "Open source · Pantheon Project" + }, { + id: "about.repo", + name: isPt ? "Repositório" : "Repository", + value: "ils15/pantheon-opencode", + note: "github.com/ils15/pantheon-opencode" + }]; + const toolRows = [ + { + id: "about.tools.memory", + name: isPt ? "Memória FTS5" : "FTS5 Memory", + value: isPt ? "ativo · 6 tools" : "active · 6 tools", + note: "memory_store, memory_recall, memory_search, memory_forget, memory_list, memory_stats" + }, + { + id: "about.tools.persistence", + name: isPt ? "Checkpoints & Metas" : "Checkpoints & Goals", + value: isPt ? "ativo · 6 tools" : "active · 6 tools", + note: "context_save, context_get, goal_create, goal_get, goal_update, goal_done" + }, + { + id: "about.tools.codemap", + name: isPt ? "Codemap & AST" : "Codemap & AST", + value: isPt ? "ativo · 5 tools" : "active · 5 tools", + note: "code_index, code_query, code_neighbors, ast_search, ast_rewrite" + }, + { + id: "about.tools.edit", + name: isPt ? "Edição & Execução" : "Edit & Execution", + value: isPt ? "ativo · 4 tools" : "active · 4 tools", + note: "hashline_edit, shell, todowrite, todoread" + }, + { + id: "about.tools.governance", + name: isPt ? "Orquestração & Custos" : "Orchestration & Cost", + value: isPt ? "ativo · 9 tools" : "active · 9 tools", + note: "pantheon_cost, pantheon_model, pantheon_skill_search, pantheon_deepwork, pantheon_step_ledger, pantheon_agent_forge, pantheon_local_decision, pantheon_review_verdict, pantheon_worktree" + } + ]; + const groups = [{ + title: isPt ? "Sistema & Plataforma" : "System & Platform", + rows: sysRows + }]; + if (extra?.preset !== void 0 || extra?.decisionEnabled !== void 0) groups.push({ + title: isPt ? "Governança & Roteamento" : "Governance & Routing", + rows: govRows + }); + groups.push({ + title: isPt ? "Projeto & Referências" : "Project & References", + rows: refRows + }); + groups.push({ + title: isPt ? "Ferramentas Nativas (30)" : "Native Tools (30)", + rows: toolRows + }); + return { + id: "about", + title: isPt ? "Sobre" : "About", + groups + }; } -function measurePathBytes(targetPath, depth = 0) { - if (depth > 8) return 0; - try { - const st = statSync(targetPath); - if (st.isFile()) return st.size; - if (!st.isDirectory()) return 0; - let total = 0; - for (const entry of readdirSync(targetPath, { withFileTypes: true })) total += measurePathBytes(join(targetPath, entry.name), depth + 1); - return total; - } catch { - return 0; - } +function buildChangelogTab(version, items = [], languagePref) { + const isPt = languagePref === "pt-BR"; + const rows = []; + if (items.length > 0) items.forEach((item, index) => { + rows.push({ + id: `changelog.item.${index + 1}`, + name: item.title.slice(0, 26), + value: "", + note: item.detail + }); + }); + else rows.push({ + id: "changelog.info", + name: isPt ? "Versão" : "Release", + value: `v${version}`, + note: isPt ? "veja o histórico completo no CHANGELOG.md ou no GitHub" : "view full history in CHANGELOG.md or GitHub releases" + }); + return { + id: "changelog", + title: isPt ? "Changelog" : "Changelog", + groups: [{ + title: isPt ? `Novidades na versão v${version}` : `What's New in v${version}`, + rows + }, { + title: isPt ? "Referências de Versão" : "Release References", + rows: [{ + id: "changelog.docs", + name: isPt ? "Documentação" : "Documentation", + value: "CHANGELOG.md", + note: isPt ? "incluído na raiz do plugin e do repositório" : "shipped at plugin root and repository root" + }, { + id: "changelog.repo", + name: isPt ? "Repositório GitHub" : "GitHub Repository", + value: "ils15/pantheon-opencode", + note: isPt ? "versões, pull requests e discussões" : "releases, pull requests and discussion" + }] + }] + }; } -function samePath(a, b) { - if (resolve(a) === resolve(b)) return true; - if (!existsSync(a) || !existsSync(b)) return false; - try { - return realpathSync(a) === realpathSync(b); - } catch { - return false; - } +//#endregion +//#region src/update-notice.ts +/** +* Update notifier core (TUI-local copy — the bundle must stay self-contained, +* same precedent as cost-data.ts/model-pricing.ts). +* +* Pin + notify, never silent auto-update: one notice per newer version, +* TTL-cached, offline-safe, and a stable install is never advertised a beta +* (the update guard owns that crossing). docs/design/2.0-settings-and-install.md +*/ +const UPDATE_CHECK_TTL_MS = 216e5; +const isBetaOrRc = (version) => /-(?:beta|rc)\.\d+$/.test(String(version).trim()); +/** True when `latestVersion` is strictly newer and compatible with `currentVersion` channel. */ +function isNewerUpdateAvailable(currentVersion, latestVersion) { + const current = String(currentVersion).trim(); + const latest = String(latestVersion).trim(); + if (!current || !latest) return false; + if (!isBetaOrRc(current) && isBetaOrRc(latest)) return false; + return comparePantheonVersions(latest, current) > 0; } -function isConfinedWithin(rootDir, targetPath) { - try { - const realRoot = realpathSync(rootDir); - const parentReal = realpathSync(dirname(targetPath)); - return parentReal === realRoot || parentReal.startsWith(`${realRoot}/`); - } catch { - return false; - } +/** Package specifier matching the running release line (`@beta` on prereleases). */ +function packageSpecForVersion(version) { + return isBetaOrRc(version) ? "pantheon-opencode@beta" : "pantheon-opencode"; } -function countTableRows(db, tableName) { - try { - const row = db.prepare(`SELECT count(*) AS cnt FROM "${tableName.replace(/"/g, "\"\"")}"`).get(); - return Number(row?.cnt ?? 0); - } catch { - return 0; - } +/** Format a bilingual toast title + message for a newly discovered update. */ +function formatUpdateToast(currentVersion, latestVersion, isPt = false) { + const spec = packageSpecForVersion(currentVersion); + if (isPt) return { + title: `Pantheon v${latestVersion} disponível`, + message: `Atualize em /pantheon-settings (Atualizações) ou \`opencode plugin update ${spec}\`` + }; + return { + title: `Pantheon v${latestVersion} available`, + message: `Update in /pantheon-settings (Updates) or \`opencode plugin update ${spec}\`` + }; } -function tableExists(db, name) { - try { - const row = db.prepare("SELECT name FROM sqlite_master WHERE type IN ('table','view') AND name = ?").get(name); - return Boolean(row?.name); - } catch { - return false; - } +/** Compact persistent badge rendered in Home footer and Sidebar header when an update exists. */ +function formatUpdateBadge(currentVersion, latestVersion, options = {}) { + if (!latestVersion || !isNewerUpdateAvailable(currentVersion, latestVersion)) return null; + const version = latestVersion.trim().replace(/^v/i, ""); + if (options.compact) return `↑ v${version} (/pantheon-settings)`; + return options.isPt ? `↑ v${version} disponível · /pantheon-settings` : `↑ v${version} available · /pantheon-settings`; } -function collectScopeAudit(scope, baseRoot, configRoot, options) { - const items = []; - const seen = /* @__PURE__ */ new Set(); - let unmigratedStores = 0; - const addItem = (filePath, category, reason) => { - const resolved = resolve(filePath); - if (seen.has(resolved) || !existsSync(resolved)) return; - seen.add(resolved); - items.push({ - path: resolved, - scope, - category, - reason, - bytes: measurePathBytes(resolved) - }); - }; - for (const hookName of [ - "pantheon-hooks.ts", - "pantheon-hooks.js", - "pantheon-hooks.mjs" - ]) addItem(join(configRoot, "plugins", hookName), "hooks", "Obsolete OpenCode V1 hook plugin"); - addItem(join(configRoot, "tiers.json"), "v1Obsolete", "Obsolete V1 model tiers registry"); - addItem(join(baseRoot, "tiers.json"), "v1Obsolete", "Obsolete V1 model tiers registry"); - const pantheonDir = join(baseRoot, ".pantheon"); - addItem(join(pantheonDir, "fastembed_cache"), "v1Obsolete", "Unused legacy fastembed cache"); - addItem(join(pantheonDir, ".fastembed"), "v1Obsolete", "Unused legacy fastembed cache"); - addItem(join(baseRoot, "fastembed_cache"), "v1Obsolete", "Unused legacy fastembed cache"); - addItem(join(pantheonDir, ".migration-checkpoint"), "v1Obsolete", "Stale migration checkpoint file"); - for (const bakDir of [configRoot, pantheonDir]) { - if (!existsSync(bakDir)) continue; - try { - for (const name of readdirSync(bakDir)) if (name.startsWith("opencode.json.bak") || name.startsWith("active-preset.json.bak")) addItem(join(bakDir, name), "backup", "Old configuration backup sidecar"); - } catch {} - } - const legacyFlatMemDb = join(pantheonDir, "memory.db"); - if (existsSync(legacyFlatMemDb)) { - unmigratedStores += 1; - addItem(legacyFlatMemDb, "legacyStore", "Unmigrated flat .pantheon/memory.db"); - } - const canonicalMemDb = join(pantheonDir, "memory", "memory.db"); - if (existsSync(canonicalMemDb)) try { - const db = new DatabaseSync(canonicalMemDb, { readOnly: true }); - const hasLegacyVec = [ - "memories_vec", - "vec_memories", - "memory_embeddings", - "memory_vectors" - ].some((t) => tableExists(db, t)); - db.close(); - if (hasLegacyVec) { - unmigratedStores += 1; - items.push({ - path: `${canonicalMemDb}#legacy-vec`, - scope, - category: "legacyStore", - reason: "Legacy vector tables pending cleanup in memory.db", - bytes: 0 - }); - } - } catch {} - for (const dbName of ["global.db", "project.db"]) { - const persDbPath = join(pantheonDir, "persistence", dbName); - if (existsSync(persDbPath)) { - unmigratedStores += 1; - addItem(persDbPath, "legacyStore", `Unmigrated persistence/${dbName}`); - } - } - const legacyGoalsJson = join(pantheonDir, "goals.json"); - if (existsSync(legacyGoalsJson)) { - unmigratedStores += 1; - addItem(legacyGoalsJson, "legacyStore", "Unmigrated legacy goals.json"); - } - if (options.includeRedundantCopiedAssets !== false) { - for (const agentFile of CANONICAL_AGENT_MD_FILES) { - addItem(join(configRoot, "agents", agentFile), "redundantAsset", "Canonical Pantheon agent copy shadowed by native plugin transform"); - addItem(join(configRoot, "agent", agentFile), "redundantAsset", "Legacy singular agent copy shadowed by native plugin transform"); - addItem(join(configRoot, "prompts", agentFile), "redundantAsset", "Legacy prompt template copy provided in package"); - } - for (const cmdFile of CANONICAL_COMMAND_MD_FILES) { - addItem(join(configRoot, "commands", cmdFile), "redundantAsset", "Canonical Pantheon command copy shadowed by native plugin transform"); - addItem(join(configRoot, "command", cmdFile), "redundantAsset", "Legacy singular command directory copy"); - } - for (const instr of LEGACY_INSTRUCTION_FILES) addItem(join(configRoot, "instructions", instr), "redundantAsset", "Legacy instruction file superseded by AGENTS.global.md"); - for (const skillId of CANONICAL_SKILL_IDS) addItem(join(configRoot, "skills", skillId), "redundantAsset", "Bundled Pantheon skill directory provided natively by plugin"); - const tuiCopyDir = join(configRoot, "plugins", "pantheon-tui"); - if (existsSync(tuiCopyDir)) { - let copiedVersion = ""; - try { - copiedVersion = String(JSON.parse(readFileSync(join(tuiCopyDir, "package.json"), "utf8")).version ?? ""); - } catch { - copiedVersion = ""; - } - const runningVersion = options.runningVersion ? String(options.runningVersion) : ""; - const drifted = Boolean(runningVersion && copiedVersion && copiedVersion !== runningVersion); - addItem(tuiCopyDir, drifted ? "drift" : "redundantAsset", drifted ? `Copied TUI plugin v${copiedVersion} drifts from v${runningVersion}` : "Copied TUI directory superseded by npm package export"); - } - } +/** Resolve cached newer version from persisted check state (no network call needed). */ +function resolveCachedAvailableUpdate(currentVersion, state) { + if (!state) return null; + const candidate = state.lastKnownLatestVersion ?? state.lastNotifiedVersion; + if (!candidate) return null; + return isNewerUpdateAvailable(currentVersion, candidate) ? candidate : null; +} +/** Stamp `lastKnownLatestVersion` onto an `UpdateCheckState` without altering TTL/notice fields. */ +function withKnownLatest(state, latestVersion) { + if (!latestVersion) return state; return { - items, - unmigratedStores + ...state, + lastKnownLatestVersion: latestVersion }; } -function ensureCanonicalMemoryDb(dbPath) { - mkdirSync(dirname(dbPath), { recursive: true }); - const db = new DatabaseSync(dbPath); - db.exec(` - PRAGMA busy_timeout = 3000; - PRAGMA journal_mode = WAL; - CREATE TABLE IF NOT EXISTS memories ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - namespace TEXT NOT NULL DEFAULT 'default', - key TEXT NOT NULL, - value TEXT NOT NULL, - importance REAL NOT NULL DEFAULT 0.5, - created_at TEXT NOT NULL, - expires_at TEXT, - UNIQUE(namespace, key) - ); - CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5( - key, value, namespace, - content='memories', - content_rowid='id' - ); - CREATE TRIGGER IF NOT EXISTS memories_ai AFTER INSERT ON memories BEGIN - INSERT INTO memories_fts(rowid, key, value, namespace) VALUES (new.id, new.key, new.value, new.namespace); - END; - CREATE TRIGGER IF NOT EXISTS memories_ad AFTER DELETE ON memories BEGIN - INSERT INTO memories_fts(memories_fts, rowid, key, value, namespace) VALUES('delete', old.id, old.key, old.value, old.namespace); - END; - CREATE TRIGGER IF NOT EXISTS memories_au AFTER UPDATE ON memories BEGIN - INSERT INTO memories_fts(memories_fts, rowid, key, value, namespace) VALUES('delete', old.id, old.key, old.value, old.namespace); - INSERT INTO memories_fts(rowid, key, value, namespace) VALUES (new.id, new.key, new.value, new.namespace); - END; - `); - return db; +let availableUpdateState = null; +const availableUpdateListeners = /* @__PURE__ */ new Set(); +function getAvailableUpdateVersion() { + return availableUpdateState; } -function migrateScopeBeforeDelete(baseRoot) { - const pantheonDir = join(baseRoot, ".pantheon"); - if (!existsSync(pantheonDir)) return 0; - let migrated = 0; - const nowIso = (/* @__PURE__ */ new Date()).toISOString(); - const flatMemDbPath = join(pantheonDir, "memory.db"); - const canonicalMemPath = join(pantheonDir, "memory", "memory.db"); - if (existsSync(flatMemDbPath)) try { - const src = new DatabaseSync(flatMemDbPath, { readOnly: true }); - const dst = ensureCanonicalMemoryDb(canonicalMemPath); - if (tableExists(src, "memories")) { - const rows = src.prepare("SELECT namespace, key, value, created_at FROM memories").all(); - const insert = dst.prepare("INSERT OR IGNORE INTO memories (namespace, key, value, importance, created_at) VALUES (?, ?, ?, ?, ?)"); - dst.exec("BEGIN IMMEDIATE"); - try { - for (const r of rows) { - insert.run(String(r.namespace ?? "default"), String(r.key ?? ""), String(r.value ?? ""), .5, String(r.created_at ?? nowIso)); - migrated += 1; - } - dst.exec("COMMIT"); - } catch (txErr) { - try { - dst.exec("ROLLBACK"); - } catch {} - throw txErr; - } - } - src.close(); - dst.close(); - } catch {} - if (existsSync(canonicalMemPath)) try { - const db = ensureCanonicalMemoryDb(canonicalMemPath); - for (const trig of [ - "memories_vec_ai", - "memories_vec_ad", - "memories_vec_au" - ]) db.exec(`DROP TRIGGER IF EXISTS ${trig}`); - for (const tbl of [ - "memories_vec", - "vec_memories", - "memory_embeddings", - "memory_vectors" - ]) if (tableExists(db, tbl)) { - db.exec(`DROP TABLE IF EXISTS ${tbl}`); - migrated += 1; - } - db.close(); - } catch {} - const persDir = join(pantheonDir, "persistence"); - for (const dbName of ["global.db", "project.db"]) { - const dbPath = join(persDir, dbName); - if (!existsSync(dbPath)) continue; - try { - const db = new DatabaseSync(dbPath, { readOnly: true }); - for (const tbl of [ - "kv", - "kv_store", - "context", - "checkpoints", - "sessions" - ]) { - if (!tableExists(db, tbl) || countTableRows(db, tbl) === 0) continue; - const cols = db.prepare(`PRAGMA table_info(${tbl})`).all(); - const colNames = new Set(cols.map((c) => c.name)); - const keyCol = colNames.has("key") ? "key" : colNames.has("id") ? "id" : colNames.has("session_id") ? "session_id" : null; - const valCol = colNames.has("value") ? "value" : colNames.has("data") ? "data" : colNames.has("content") ? "content" : null; - if (!keyCol || !valCol) continue; - const nsSelect = colNames.has("namespace") ? "namespace" : `'${tbl === "checkpoints" || tbl === "sessions" ? "checkpoints" : "default"}' AS namespace`; - const rows = db.prepare(`SELECT ${nsSelect}, ${keyCol} AS k, ${valCol} AS v FROM ${tbl}`).all(); - for (const r of rows) { - const ns = toSafeSegment(r.namespace, "default"); - const key = toSafeSegment(r.k, ""); - if (!key) continue; - const targetDir = join(persDir, ns); - const targetFile = join(targetDir, `${key}.json`); - if (!existsSync(targetFile)) { - mkdirSync(targetDir, { recursive: true }); - writeFileSync(targetFile, JSON.stringify({ - key, - namespace: ns, - value: String(r.v ?? ""), - updated_at: nowIso - }, null, 2), "utf8"); - migrated += 1; - } - } - } - db.close(); - } catch {} - } - const legacyGoalsPath = join(pantheonDir, "goals.json"); - if (existsSync(legacyGoalsPath)) try { - const parsed = JSON.parse(readFileSync(legacyGoalsPath, "utf8")); - const list = Array.isArray(parsed) ? parsed : parsed && typeof parsed === "object" && Array.isArray(parsed.goals) ? parsed.goals ?? [] : []; - const goalsDir = join(pantheonDir, "goals"); - for (const item of list) { - if (!item || typeof item !== "object") continue; - const rec = item; - const safeId = toSafeSegment(rec.id ?? rec.goal_id, ""); - if (!safeId) continue; - const target = join(goalsDir, `${safeId}.json`); - if (!existsSync(target)) { - mkdirSync(goalsDir, { recursive: true }); - writeFileSync(target, JSON.stringify({ - id: safeId, - title: String(rec.title ?? rec.description ?? ""), - criteria: Array.isArray(rec.criteria) ? rec.criteria.map(String) : [], - status: String(rec.status ?? "active"), - created_at: typeof rec.created_at === "string" ? rec.created_at : nowIso, - updated_at: typeof rec.updated_at === "string" ? rec.updated_at : nowIso - }, null, 2), "utf8"); - migrated += 1; - } - } +function setAvailableUpdateVersion(version) { + const normalized = version && version.trim() !== "" ? version.trim() : null; + if (normalized === availableUpdateState) return; + availableUpdateState = normalized; + for (const listener of availableUpdateListeners) try { + listener(availableUpdateState); } catch {} - return migrated; } -function scanLegacyArtifacts(options = {}) { - const workspaceDir = options.workspaceDir ? resolve(options.workspaceDir) : void 0; - const globalConfigDir = options.globalConfigDir ? resolve(options.globalConfigDir) : resolveAuditGlobalDir(options.env); - const items = []; - let unmigratedStores = 0; - if (globalConfigDir && existsSync(globalConfigDir) && globalConfigDir !== "/") { - const res = collectScopeAudit("global", globalConfigDir, globalConfigDir, options); - items.push(...res.items); - unmigratedStores += res.unmigratedStores; - } - if (workspaceDir && existsSync(workspaceDir) && workspaceDir !== "/" && (!globalConfigDir || !samePath(workspaceDir, globalConfigDir))) { - const res = collectScopeAudit("project", workspaceDir, join(workspaceDir, ".opencode"), options); - items.push(...res.items); - unmigratedStores += res.unmigratedStores; +function subscribeAvailableUpdate(listener) { + availableUpdateListeners.add(listener); + return () => { + availableUpdateListeners.delete(listener); + }; +} +/** Semver-ish compare for X.Y.Z[-(beta|rc).N]; prereleases sort before their release. */ +function comparePantheonVersions(left, right) { + const parse = (version) => { + const match = String(version).trim().match(/^(\d+)\.(\d+)\.(\d+)(?:-(beta|rc)\.(\d+))?$/); + if (!match) return null; + const [, major = "", minor = "", patch = "", stage = "", stageNum = ""] = match; + const stageRank = stage === "beta" ? 1 : stage === "rc" ? 2 : 3; + return { + core: [ + +major, + +minor, + +patch + ], + stageRank, + stageNum: stage !== "" ? +stageNum : Number.POSITIVE_INFINITY + }; + }; + const a = parse(left); + const b = parse(right); + if (!a || !b) return 0; + const [aMajor, aMinor, aPatch] = a.core; + const [bMajor, bMinor, bPatch] = b.core; + if (aMajor !== bMajor) return aMajor - bMajor; + if (aMinor !== bMinor) return aMinor - bMinor; + if (aPatch !== bPatch) return aPatch - bPatch; + if (a.stageRank !== b.stageRank) return a.stageRank - b.stageRank; + return a.stageNum - b.stageNum; +} +function pickUpdateNotice(input) { + const { currentVersion, latestVersion, state = {}, nowMs = Date.now(), isPt = false } = input; + const ttlMs = input.ttlMs ?? 216e5; + if (nowMs - (state.lastCheckMs ?? 0) < ttlMs) return null; + if (state.lastNotifiedVersion === latestVersion) return null; + if (!isNewerUpdateAvailable(currentVersion, latestVersion)) return null; + return { + version: latestVersion, + message: formatUpdateToast(currentVersion, latestVersion, isPt).message + }; +} +/** The state to persist after a check (notified or not) for the TTL. */ +function nextCheckState(previous, notice, nowMs) { + const lastNotifiedVersion = notice?.version ?? previous.lastNotifiedVersion; + return { + lastCheckMs: nowMs, + ...lastNotifiedVersion !== void 0 ? { lastNotifiedVersion } : {} + }; +} +//#endregion +//#region src/doctor-state.ts +/** +* doctor-state.ts — the Doctor section of the settings window (read-only). +* +* TUI-local replica (the bundle must stay self-contained — the installed copy +* physically lacks the repo tree, so doctor.mjs itself is unreachable). Only +* the FILE-DERIVABLE checks are mirrored here; everything that spawns +* processes, reads the network, or writes (MCP smoke, python validators, git, +* venv pins, --fix quarantines) stays in the CLI and the section says so. +* +* The install-state path mirrors doctor's checkInstallVersionDrift +* (`/opencode/.pantheon/install-state.json`); the Node floor is +* drift-pinned against scripts/node-engine-policy.mjs by +* tests/tui-doctor-state.test.mjs. +*/ +/** Drift-pinned against scripts/node-engine-policy.mjs MIN_SUPPORTED_NODE_VERSION. */ +const MIN_SUPPORTED_NODE_VERSION = "26.4.0"; +function opencodePantheonDir(env = process.env) { + const xdg = env.XDG_CONFIG_HOME; + const home = env.HOME ?? ""; + const root = xdg ?? join(home, ".config"); + return join(root, "opencode", ".pantheon"); +} +/** +* H2: the installed package version (install-state) vs the running one. +* Fail-open: a missing/unreadable state file means "unknown", not a failure — +* pre-2.0 installs may not have one. +*/ +function classifyInstallVersion(runningVersion, env = process.env) { + let installed = null; + try { + const path = join(opencodePantheonDir(env), "install-state.json"); + const raw = JSON.parse(readFileSync(path, "utf8")); + if (typeof raw?.pantheon_version === "string" && raw.pantheon_version !== "") installed = raw.pantheon_version; + } catch { + installed = null; } - const byScope = { - global: 0, - project: 0 + if (installed === null) return { + status: "unknown", + installed: null + }; + const compared = comparePantheonVersions(installed, runningVersion); + if (compared === 0) return { + status: "ok", + installed }; - const byCategory = {}; - let totalBytes = 0; - for (const item of items) { - byScope[item.scope] = (byScope[item.scope] ?? 0) + 1; - byCategory[item.category] = (byCategory[item.category] ?? 0) + 1; - totalBytes += item.bytes; - } return { - items, - summary: { - total: items.length, - totalBytes, - unmigratedStores, - byScope, - byCategory - } + status: compared < 0 ? "older" : "newer", + installed }; } -function cleanLegacyArtifacts(options = {}) { - const workspaceDir = options.workspaceDir ? resolve(options.workspaceDir) : void 0; - const globalConfigDir = options.globalConfigDir ? resolve(options.globalConfigDir) : resolveAuditGlobalDir(options.env); - const scopeFilter = options.scope && options.scope !== "all" ? options.scope : null; - const scan = scanLegacyArtifacts(options); - let migratedRecords = 0; - if (scopeFilter !== "project" && globalConfigDir && existsSync(globalConfigDir) && globalConfigDir !== "/") migratedRecords += migrateScopeBeforeDelete(globalConfigDir); - if (scopeFilter !== "global" && workspaceDir && existsSync(workspaceDir) && workspaceDir !== "/" && (!globalConfigDir || !samePath(workspaceDir, globalConfigDir))) migratedRecords += migrateScopeBeforeDelete(workspaceDir); - const removed = []; - const errors = []; - let reclaimedBytes = 0; - for (const item of scan.items) { - if (scopeFilter && item.scope !== scopeFilter) continue; - if (item.path.endsWith("#legacy-vec")) { - removed.push(item.path); - continue; - } - const scopeRoot = item.scope === "global" ? globalConfigDir : workspaceDir; - if (!scopeRoot || !isConfinedWithin(scopeRoot, item.path)) { - errors.push({ - path: item.path, - reason: "Path escapes target scope root" - }); - continue; - } - try { - if (existsSync(item.path)) { - rmSync(item.path, { - recursive: true, - force: true - }); - removed.push(item.path); - reclaimedBytes += item.bytes; - } - if (item.path.endsWith(".db")) for (const suffix of [ - "-wal", - "-shm", - "-journal" - ]) { - const sidecar = `${item.path}${suffix}`; - if (existsSync(sidecar) && isConfinedWithin(scopeRoot, sidecar)) { - const sidecarBytes = measurePathBytes(sidecar); - rmSync(sidecar, { force: true }); - removed.push(sidecar); - reclaimedBytes += sidecarBytes; - } - } - } catch (err) { - errors.push({ - path: item.path, - reason: err instanceof Error ? err.message : String(err) - }); - } +function isSupportedNodeFloor(version) { + const match = /^v?(\d+)\.(\d+)\.(\d+)(?:-([^+]+))?(?:\+([\w.-]+))?$/.exec(String(version)); + const minimum = /^v?(\d+)\.(\d+)\.(\d+)/.exec(MIN_SUPPORTED_NODE_VERSION); + if (!match || !minimum) return false; + const [, major = "", minor = "", patch = "", prerelease = ""] = match; + if (prerelease !== "") return false; + const [, minMajor = "0", minMinor = "0", minPatch = "0"] = minimum; + const currentParts = [ + +major, + +minor, + +patch + ]; + const minimumParts = [ + +minMajor, + +minMinor, + +minPatch + ]; + for (let index = 0; index < 3; index += 1) { + const currentPart = currentParts[index] ?? 0; + const minimumPart = minimumParts[index] ?? 0; + if (currentPart !== minimumPart) return currentPart > minimumPart; } + return true; +} +/** K: validate both overrides files against the window's registry. */ +function classifyOverridesHealth(load) { + if (load.corruptGlobal) return { + status: "corrupt", + unknownIds: [] + }; + const known = new Set(SETTINGS_BEHAVIORS.map((behavior) => behavior.id)); + const unknownIds = Object.keys({ + ...load.global, + ...load.project + }).filter((id) => !known.has(id)); return { - removed, - reclaimedBytes, - migratedRecords, - errors + status: unknownIds.length > 0 ? "unknown-ids" : "clean", + unknownIds + }; +} +function classifyDecisionConfigHealth(env = process.env) { + if (!existsSync(join(env.XDG_CONFIG_HOME ?? join(env.HOME ?? "", ".config"), "pantheon", "decision-router.json"))) return { status: "absent" }; + return readDecisionRouterConfig(env).corrupt ? { status: "corrupt" } : { status: "ok" }; +} +function buildDoctorTab(input) { + const env = input.env ?? process.env; + const rows = []; + const version = classifyInstallVersion(input.runningVersion, env); + rows.push({ + id: "doctor.version", + name: "Install version", + value: version.status === "ok" ? `v${version.installed} — matches` : version.status === "older" ? `v${version.installed} older` : version.status === "newer" ? `v${version.installed} newer` : "unknown", + note: version.status === "older" ? "refresh with `pantheon-opencode update`" : "read from /opencode/.pantheon/install-state.json" + }); + const nodeOk = isSupportedNodeFloor(input.nodeVersion); + rows.push({ + id: "doctor.node", + name: "Node runtime", + value: input.nodeVersion.replace(/^v/, ""), + note: nodeOk ? `meets the >= ${MIN_SUPPORTED_NODE_VERSION} floor` : `below the >= ${MIN_SUPPORTED_NODE_VERSION} floor — tooling may refuse` + }); + const overrides = classifyOverridesHealth(input.load); + rows.push({ + id: "doctor.overrides", + name: "Overrides", + value: overrides.status === "clean" ? "valid" : overrides.status === "corrupt" ? "unreadable" : `${overrides.unknownIds.length} unknown id(s)`, + note: overrides.status === "unknown-ids" ? `${overrides.unknownIds.join(", ")} — harmless; repair with doctor --fix` : overrides.status === "corrupt" ? "writes are refused until repaired (doctor --fix)" : "both files parse against the behavior registry" + }); + const decision = classifyDecisionConfigHealth(env); + rows.push({ + id: "doctor.decision", + name: "Decision config", + value: decision.status === "ok" ? "valid" : decision.status === "corrupt" ? "corrupt" : "absent", + note: decision.status === "corrupt" ? "runtime fail-closes to disabled · read from /pantheon/decision-router.json" : "read from /pantheon/decision-router.json" + }); + return { + id: "doctor", + title: "Doctor", + groups: [{ + title: "Health (file-derived)", + rows + }, { rows: [{ + id: "doctor.cli", + name: "Full check", + value: "`pantheon-opencode doctor`", + note: "MCP smoke, venv pins, git stay in the CLI" + }] }] }; } //#endregion -//#region src/preset-state.ts +//#region src/j1-gate-status.ts +const J1_FLAG_ENV = "PANTHEON_J1_RISK_SCORE"; +const J1_THRESHOLD_ENV = "PANTHEON_J1_ENFORCE_THRESHOLD"; +const J1_THRESHOLD_DEFAULT = .8; +/** `1`/`on`/`true` map to `shadow` for back-compatibility with the shipped setup. */ +const FLAG_ON = /* @__PURE__ */ new Set([ + "1", + "on", + "true", + "shadow" +]); +function j1ModeFromEnv(env = process.env) { + const raw = (env["PANTHEON_J1_RISK_SCORE"] ?? "").trim().toLowerCase(); + if (raw === "enforce") return "enforce"; + if (raw === "warn") return "warn"; + return FLAG_ON.has(raw) ? "shadow" : "off"; +} +/** Invalid or out-of-range values fall back to the default — a typo must not disable the gate. */ +function j1ThresholdFromEnv(env = process.env) { + const text = (env["PANTHEON_J1_ENFORCE_THRESHOLD"] ?? "").trim(); + if (text === "") return J1_THRESHOLD_DEFAULT; + const raw = Number(text); + if (!Number.isFinite(raw) || raw < 0 || raw > 1) return J1_THRESHOLD_DEFAULT; + return raw; +} +const MODE_DESCRIPTION_EN = { + off: "nothing fires (hard zero)", + shadow: "observe + record; invisible in the session", + warn: "RESERVED — behaves as shadow in this release", + enforce: "high-risk scores DENY the tool call (fail-open on gate unavailability)" +}; +const MODE_DESCRIPTION_PT = { + off: "desativado (hard zero)", + shadow: "observa + registra telemetria (modo silencioso)", + warn: "RESERVADO (RESERVED) — comporta-se como shadow nesta versão", + enforce: "alto risco bloqueia a ferramenta (fail-open se indisponível)" +}; +function buildJ1Tab(env, disabledByOverride, languagePref) { + const isPt = resolveLanguage(languagePref) === "pt-BR"; + const mode = j1ModeFromEnv(env); + const threshold = j1ThresholdFromEnv(env); + const gateState = disabledByOverride ? "disabled via overrides" : mode === "off" ? "off (env unset)" : "active"; + const desc = isPt ? MODE_DESCRIPTION_PT[mode] : MODE_DESCRIPTION_EN[mode]; + return { + id: "j1", + title: isPt ? "Segurança J1" : "J1 Safety", + groups: [{ + title: isPt ? "Portão de Segurança (J1)" : "Safety Risk Gate (J1)", + rows: [ + { + id: "j1.mode", + name: isPt ? "Modo de Operação" : "Operation Mode", + value: mode, + note: `${desc} · ${isPt ? "reinício necessário (restart applies)" : "restart applies"}` + }, + { + id: "j1.threshold", + name: isPt ? "Limiar de bloqueio" : "Enforce threshold", + value: String(threshold), + note: isPt ? "bloqueia em ou acima · 0..1 · padrão 0.8" : "deny at or above · 0..1 · default 0.8" + }, + { + id: "j1.gate", + name: isPt ? "Portão de Segurança" : "Safety Risk Gate", + value: gateState, + note: `${J1_FLAG_ENV} / ${J1_THRESHOLD_ENV} · ${isPt ? "lido na inicialização" : "read once at startup"}` + } + ] + }] + }; +} +//#endregion +//#region src/legacy-audit.ts /** -* preset-state.ts — the Model Preset section of the settings window. +* legacy-audit.ts — Self-contained Legacy & Drift Auditor for the TUI Settings panel. * -* TUI-local replica (the bundle must stay self-contained). The preset NAMES -* mirror routing.yml's `presets:` and are drift-pinned by -* tests/tui-preset-state.test.mjs against `loadPresetDefs()`. The marker file -* shape mirrors scripts/install/model-picker.mjs's `buildActivePresetFile` -* (version 1), and the readers (`resolveActivePreset`, vision.ts candidates) -* only consult `.preset`, so the window writes `source: 'tui-settings'`. +* Scans global (~/.config/opencode) and workspace () scopes for: +* - Dead V1 hooks/files (pantheon-hooks.*, tiers.json, fastembed_cache, .migration-checkpoint) +* - Unmigrated legacy stores (memory.db, persistence/{global,project}.db, goals.json) +* - Redundant copied canonical Pantheon assets shadowed by native plugin transforms +* - Drifted copied TUI plugins (plugins/pantheon-tui version != running plugin version) +* - Old configuration backup sidecars (opencode.json.bak*, active-preset.json.bak*) * -* Scope note: the window writes the GLOBAL marker only -* (`/opencode/.pantheon/active-preset.json`). A project marker -* wins (it precedes the global path in every runtime candidate list), so it -* is displayed read-only. `none` DELETES the marker with a .bak backup — the -* same contract as the CLI's `set-tier none`. +* Always migrates unmigrated legacy context/memory/goals BEFORE deleting obsolete stores, +* and NEVER touches user-created custom agents or custom user skills. */ -/** Mirrors routing.yml `presets:` — drift-pinned against loadPresetDefs(). */ -const PRESET_NAMES = Object.freeze([ - "go-free", - "go-fast", - "go-premium", - "go-hybrid", - "anthropic", - "openai" +const SAFE_SEGMENT_RE = /^[a-zA-Z0-9._:-]{1,128}$/; +const CANONICAL_AGENT_MD_FILES = Object.freeze([ + "aphrodite.md", + "apollo.md", + "artemis.md", + "athena.md", + "demeter.md", + "gaia.md", + "hephaestus.md", + "hermes.md", + "iris.md", + "mnemosyne.md", + "nyx.md", + "prometheus.md", + "talos.md", + "themis.md", + "zeus.md" ]); -function globalActivePresetPath(env = process.env) { - const xdg = env.XDG_CONFIG_HOME; - const home = env.HOME ?? ""; - const root = xdg ?? join(home, ".config"); - return join(root, "opencode", ".pantheon", "active-preset.json"); +const CANONICAL_COMMAND_MD_FILES = Object.freeze([ + "pantheon.md", + "pantheon-audit.md", + "pantheon-deepwork.md", + "pantheon-focus.md", + "pantheon-model.md", + "pantheon-optimize.md", + "pantheon-settings.md", + "pantheon-vision.md" +]); +const CANONICAL_SKILL_IDS = Object.freeze([ + "agent-coordination", + "agent-forge", + "artifact-management", + "auto-continue", + "clonedeps", + "code-review-checklist", + "codemap", + "context-compression", + "fast-path-execution", + "git-workflow-and-versioning", + "incremental-implementation", + "instruction-forge", + "loop-engineering", + "memory-bank", + "prompt-refinery", + "reflect", + "security-hardening", + "session-goal", + "simplify", + "spec-driven-development", + "tdd-with-agents", + "test-slicing", + "verification-planning", + "visual-review-pipeline", + "worktrees" +]); +const LEGACY_INSTRUCTION_FILES = Object.freeze([ + "zeus-execution-rules.instructions.md", + "zeus-orchestration.instructions.md", + "zeus-workflow.instructions.md" +]); +function resolveAuditCacheDir(env = process.env) { + if (env.NODE_TEST_CONTEXT) return void 0; + if (env.XDG_CACHE_HOME?.trim()) return join(resolve(env.XDG_CACHE_HOME.trim()), "opencode", "npm"); + const home = env.HOME?.trim(); + return home ? join(resolve(home), ".cache", "opencode", "npm") : void 0; } -function projectActivePresetPath() { - return join(process.cwd(), ".pantheon", "active-preset.json"); +function readCachedPackageVersion(candidateDir) { + for (const manifest of [join(candidateDir, "node_modules", "pantheon-opencode", "package.json"), join(candidateDir, "package.json")]) try { + if (!existsSync(manifest)) continue; + const parsed = JSON.parse(readFileSync(manifest, "utf8")); + if (typeof parsed.version === "string" && parsed.version.trim() !== "") return parsed.version.trim(); + } catch {} + return null; } -/** Fail-open read: missing/corrupt marker = no active preset. */ -function readActivePresetMarker(path) { +function isUnderPath(parentDir, targetPath) { try { - const raw = JSON.parse(readFileSync(path, "utf8")); - if (typeof raw?.preset !== "string" || raw.preset === "" || raw.preset === "none") return null; - return { - name: raw.preset, - updatedAt: typeof raw.updated_at === "string" ? raw.updated_at : "" - }; + const parentReal = realpathSync(parentDir); + const targetReal = realpathSync(targetPath); + return targetReal === parentReal || targetReal.startsWith(`${parentReal}/`); } catch { - return null; + return false; } } -function writeMarkerAtomically(path, content) { - mkdirSync(dirname(path), { recursive: true }); - const temp = `${path}.tui.tmp`; - writeFileSync(temp, content); - renameSync(temp, path); -} -/** Select a preset globally: .bak backup, atomic write, version-1 marker. */ -function writeActivePreset(path, name, nowIso = (/* @__PURE__ */ new Date()).toISOString()) { - if (!PRESET_NAMES.includes(name)) throw new TypeError(`Refusing to persist unknown preset "${name}"`); - backupMarker(path); - writeMarkerAtomically(path, `${JSON.stringify({ - version: 1, - preset: name, - source: "tui-settings", - updated_at: nowIso - }, null, 2)}\n`); -} -/** Clear the global marker (the `none` contract): .bak backup, then remove. */ -function clearActivePreset(path) { - backupMarker(path); - rmSync(path, { force: true }); +function collectCacheAudit(cacheNpmDir, options) { + const items = []; + if (!existsSync(cacheNpmDir) || cacheNpmDir === "/") return items; + const activeBundlePath = options.activeBundlePath ?? ""; + const runningVersion = options.runningVersion ? String(options.runningVersion).trim() : ""; + const runningIsStable = runningVersion !== "" && !/-(?:beta|rc)\./i.test(runningVersion); + const seen = /* @__PURE__ */ new Set(); + const pushCacheItem = (targetPath, reason) => { + const resolved = resolve(targetPath); + if (seen.has(resolved) || !existsSync(resolved)) return; + if (activeBundlePath && isUnderPath(resolved, activeBundlePath)) return; + seen.add(resolved); + items.push({ + path: resolved, + scope: "global", + category: "drift", + reason, + bytes: measurePathBytes(resolved) + }); + }; + let channelEntries = []; + try { + channelEntries = readdirSync(cacheNpmDir, { withFileTypes: true }); + } catch { + return items; + } + for (const entry of channelEntries) { + if (!entry.isDirectory()) continue; + if (entry.name !== "pantheon-opencode" && !entry.name.startsWith("pantheon-opencode@")) continue; + const channelDir = join(cacheNpmDir, entry.name); + if (runningIsStable && entry.name === "pantheon-opencode@beta") { + pushCacheItem(channelDir, "Stale @beta plugin cache coexisting with stable install"); + continue; + } + try { + const revisions = readdirSync(channelDir, { withFileTypes: true }).filter((sub) => sub.isDirectory() && sub.name !== "node_modules" && !sub.name.startsWith(".")).map((sub) => { + const full = join(channelDir, sub.name); + let mtime = 0; + try { + mtime = statSync(full).mtimeMs; + } catch {} + return { + path: full, + mtime, + active: Boolean(activeBundlePath && isUnderPath(full, activeBundlePath)) + }; + }); + if (revisions.length > 1) { + revisions.sort((a, b) => Number(b.active) - Number(a.active) || b.mtime - a.mtime); + for (const stale of revisions.slice(1)) { + const ver = readCachedPackageVersion(stale.path); + pushCacheItem(stale.path, ver ? `Stale cached Pantheon plugin revision (v${ver})` : "Stale cached Pantheon plugin revision"); + } + } + } catch {} + } + return items; } -function backupMarker(path) { - if (!existsSync(path)) return; - mkdirSync(dirname(path), { recursive: true }); - copyFileSync(path, `${path}.bak`); +function resolveAuditGlobalDir(env = process.env) { + if (env.PANTHEON_HOME?.trim()) return resolve(env.PANTHEON_HOME.trim()); + if (env.XDG_CONFIG_HOME?.trim()) return join(resolve(env.XDG_CONFIG_HOME.trim()), "opencode"); + if (env.NODE_TEST_CONTEXT) return void 0; + const home = env.HOME?.trim(); + return home ? join(resolve(home), ".config", "opencode") : void 0; } -const VISION_MODEL_OPTIONS = Object.freeze([ - "auto", - "opencode-go/mimo-v2.6-flash", - "google/gemini-2.5-flash", - "openai/gpt-5-mini", - "anthropic/claude-3-5-haiku", - "opencode-go/mimo-v2.5" -]); -function visionConfigPaths(cwd = process.cwd(), env = process.env) { - const home = env.HOME ?? ""; - const xdg = env.XDG_CONFIG_HOME ?? join(home, ".config"); - return [join(cwd, ".opencode", "opencode-vision.json"), join(xdg, "opencode", "opencode-vision.json")]; +function formatBytes(bytes) { + if (bytes < 1024) return `${bytes} B`; + if (bytes < 1048576) return `${(bytes / 1024).toFixed(1)} KB`; + return `${(bytes / 1048576).toFixed(2)} MB`; } -function readConfiguredVisionModel(cwd = process.cwd(), env = process.env) { - for (const path of visionConfigPaths(cwd, env)) try { - if (existsSync(path)) { - const parsed = JSON.parse(readFileSync(path, "utf8")); - if (typeof parsed?.visionModel === "string" && parsed.visionModel.trim()) return parsed.visionModel.trim(); - } - } catch {} - return "auto"; +function toSafeSegment(raw, fallback = "default") { + const str = String(raw ?? "").trim().replace(/[^a-zA-Z0-9._:-]/g, "_").slice(0, 128); + if (!str || str === "." || str === ".." || !SAFE_SEGMENT_RE.test(str)) return fallback; + return str; } -function writeConfiguredVisionModel(model, cwd = process.cwd(), env = process.env) { - const home = env.HOME ?? ""; - const xdg = env.XDG_CONFIG_HOME ?? join(home, ".config"); - const projectDir = join(cwd, ".opencode"); - const targetPath = existsSync(projectDir) ? join(projectDir, "opencode-vision.json") : join(xdg, "opencode", "opencode-vision.json"); - let current = {}; +function measurePathBytes(targetPath, depth = 0) { + if (depth > 8) return 0; try { - if (existsSync(targetPath)) current = JSON.parse(readFileSync(targetPath, "utf8")); + const st = statSync(targetPath); + if (st.isFile()) return st.size; + if (!st.isDirectory()) return 0; + let total = 0; + for (const entry of readdirSync(targetPath, { withFileTypes: true })) total += measurePathBytes(join(targetPath, entry.name), depth + 1); + return total; } catch { - current = {}; + return 0; } - if (model === "auto" || !model.trim()) delete current.visionModel; - else current.visionModel = model.trim(); - mkdirSync(dirname(targetPath), { recursive: true }); - const temp = `${targetPath}.tui.tmp`; - writeFileSync(temp, `${JSON.stringify(current, null, 2)}\n`, "utf8"); - renameSync(temp, targetPath); } -const PRESET_CYCLE = Object.freeze(["none", ...PRESET_NAMES]); -function buildPresetTab(input, languagePref) { - const isPt = languagePref === "pt-BR"; - const rows = [{ - id: "preset", - name: isPt ? "Predefinição" : "Preset", - value: input.globalName ?? "none", - cycle: PRESET_CYCLE, - note: isPt ? "marcador global · gravação atômica, backup .bak · none = padrão OpenCode" : "global marker · atomic write, .bak backup · none = opencode defaults" - }]; - if (input.projectName !== null) rows.push({ - id: "preset.project", - name: isPt ? "Projeto" : "Project", - value: input.projectName, - note: isPt ? `${projectActivePresetPath()} tem precedência sobre o global — somente leitura aqui` : `${projectActivePresetPath()} wins over the global marker — read-only here` - }); - if (input.visionModel !== void 0) rows.push({ - id: "preset.vision_model", - name: isPt ? "Modelo de Visão" : "Vision Model", - value: input.visionModel || "auto", - cycle: VISION_MODEL_OPTIONS, - note: isPt ? "modelo para inspeção de imagens (vision_describe) · salvo em opencode-vision.json" : "model for image inspection (vision_describe) · saved in opencode-vision.json" - }); - return { - id: "preset", - title: "Preset", - groups: [{ - title: isPt ? "Predefinição de modelo" : "Model preset", - rows - }] - }; +function samePath(a, b) { + if (resolve(a) === resolve(b)) return true; + if (!existsSync(a) || !existsSync(b)) return false; + try { + return realpathSync(a) === realpathSync(b); + } catch { + return false; + } } -//#endregion -//#region src/quota-state.ts -/** -* quota-state.ts — the Quotas & Spend tab (inspired by opencode-quota). -* -* Exposes live model token spending, daily budgets, rate-limits per provider, -* and context token telemetry in a dedicated tab in the Pantheon Settings window. -*/ -const DEFAULT_QUOTA_PREFS = { - sessionCap: "$5.00", - alertThreshold: "enabled", - autoCompact: "enabled" -}; -function resolveQuotaPrefsPath() { - const xdg = process.env.XDG_CONFIG_HOME; - const base = xdg?.startsWith("/") ? xdg : join(homedir(), ".config"); - return join(base, "opencode", "pantheon-quota.json"); +function isConfinedWithin(rootDir, targetPath) { + try { + const realRoot = realpathSync(rootDir); + const parentReal = realpathSync(dirname(targetPath)); + return parentReal === realRoot || parentReal.startsWith(`${realRoot}/`); + } catch { + return false; + } } -function readQuotaPrefs(filePath = resolveQuotaPrefsPath()) { +function countTableRows(db, tableName) { try { - if (!existsSync(filePath)) return { ...DEFAULT_QUOTA_PREFS }; - const raw = JSON.parse(readFileSync(filePath, "utf8")); - return { - sessionCap: typeof raw.sessionCap === "string" && [ - "$1.00", - "$2.00", - "$5.00", - "$10.00", - "unlimited" - ].includes(raw.sessionCap) ? raw.sessionCap : DEFAULT_QUOTA_PREFS.sessionCap, - alertThreshold: raw.alertThreshold === "disabled" ? "disabled" : "enabled", - autoCompact: raw.autoCompact === "disabled" ? "disabled" : "enabled" - }; + const row = db.prepare(`SELECT count(*) AS cnt FROM "${tableName.replace(/"/g, "\"\"")}"`).get(); + return Number(row?.cnt ?? 0); } catch { - return { ...DEFAULT_QUOTA_PREFS }; - } -} -function writeQuotaPrefs(prefs, filePath = resolveQuotaPrefsPath()) { - mkdirSync(dirname(filePath), { recursive: true }); - writeFileSync(filePath, `${JSON.stringify(prefs, null, 2)}\n`, "utf8"); -} -function applyQuotaRow(prefs, id, value) { - const next = { ...prefs }; - if (id === "quota.budget.sessionCap") { - if ([ - "$1.00", - "$2.00", - "$5.00", - "$10.00", - "unlimited" - ].includes(value)) next.sessionCap = value; - } else if (id === "quota.budget.alertThreshold") next.alertThreshold = value === "disabled" ? "disabled" : "enabled"; - else if (id === "quota.compaction.auto") next.autoCompact = value === "disabled" ? "disabled" : "enabled"; - return next; + return 0; + } } -function buildQuotaTab(snapshot, languagePref, prefs = readQuotaPrefs()) { - const isPt = resolveLanguage(languagePref) === "pt-BR"; - return { - id: "quota", - title: isPt ? "Cotas & Gastos" : "Quotas & Spend", - groups: [ - { - title: isPt ? "Consumo & Gastos de Sessão" : "Session Spend & Tokens", - rows: [ - { - id: "quota.spend.today", - name: isPt ? "Gasto hoje (00h-agora)" : "Spend today (00h-now)", - value: snapshot?.todaySpend ?? "—", - note: isPt ? "Calculado a partir de opencode.db" : "Derived from opencode.db ledger" - }, - { - id: "quota.spend.month", - name: isPt ? "Gasto acumulado (30d)" : "Spend last 30 days", - value: snapshot?.monthSpend ?? "—", - note: isPt ? "Janela móvel de 30 dias" : "Rolling 30-day window" - }, - { - id: "quota.spend.session", - name: isPt ? "Gasto na sessão ativa" : "Active session spend", - value: snapshot?.sessionSpend ?? "—", - note: isPt ? "Custo de todas as mensagens do turno" : "Sum of turn assistant messages" - }, - { - id: "quota.tokens.context", - name: isPt ? "Tokens de contexto" : "Context tokens", - value: snapshot?.sessionTokens ?? "—", - note: isPt ? "Tokens consumidos vs janela do modelo" : "Tokens used vs model context limit" - }, - { - id: "quota.tokens.cache", - name: isPt ? "Eficiência de cache" : "Prompt cache hit", - value: snapshot?.cacheHit ?? "—", - note: isPt ? "Desconto de leitura em cache aplicado" : "Cache read discount applied" - } - ] - }, - { - title: isPt ? "Limites & Teto de Orçamento" : "Rate Limits & Budget Caps", - rows: [ - { - id: "quota.budget.sessionCap", - name: isPt ? "Teto por sessão" : "Session budget cap", - value: prefs.sessionCap, - cycle: [ - "$1.00", - "$2.00", - "$5.00", - "$10.00", - "unlimited" - ], - note: isPt ? "Avisa ou pausa ao atingir o teto" : "Warns or pauses when session spend reaches cap" - }, - { - id: "quota.budget.alertThreshold", - name: isPt ? "Alerta em 80% do teto" : "Alert at 80% of cap", - value: prefs.alertThreshold, - cycle: ["enabled", "disabled"], - note: isPt ? "Emite aviso visual no footer da TUI" : "Shows visual notice in TUI footer" - }, - { - id: "quota.compaction.auto", - name: isPt ? "Auto-compactar em 80% do contexto" : "Auto-compact at 80% context", - value: prefs.autoCompact, - cycle: ["enabled", "disabled"], - note: isPt ? "Aciona compressão automática de histórico" : "Triggers automatic context compaction" - } - ] - }, - { - title: isPt ? "Provedores & Janelas de Cota (Referência)" : "Providers & Quota Windows (Reference)", - rows: [ - { - id: "quota.ref.anthropic", - name: "Anthropic (Claude 3.7)", - value: "Tier 4", - note: isPt ? "400k TPM · Reset diário às 00:00 UTC" : "400k TPM · Daily reset at 00:00 UTC" - }, - { - id: "quota.ref.openai", - name: "OpenAI (GPT-4o)", - value: "Tier 4", - note: isPt ? "800k TPM · Reset por janela móvel de 1 min" : "800k TPM · 1-minute rolling window" - }, - { - id: "quota.ref.google", - name: "Google (Gemini 2.5)", - value: "Pay-as-you-go", - note: isPt ? "4M TPM · Alta capacidade com cota flexível" : "4M TPM · High capacity with flexible quota" - } - ] +function tableExists(db, name) { + try { + const row = db.prepare("SELECT name FROM sqlite_master WHERE type IN ('table','view') AND name = ?").get(name); + return Boolean(row?.name); + } catch { + return false; + } +} +function collectScopeAudit(scope, baseRoot, configRoot, options) { + const items = []; + const seen = /* @__PURE__ */ new Set(); + let unmigratedStores = 0; + const addItem = (filePath, category, reason) => { + const resolved = resolve(filePath); + if (seen.has(resolved) || !existsSync(resolved)) return; + seen.add(resolved); + items.push({ + path: resolved, + scope, + category, + reason, + bytes: measurePathBytes(resolved) + }); + }; + for (const hookName of [ + "pantheon-hooks.ts", + "pantheon-hooks.js", + "pantheon-hooks.mjs" + ]) addItem(join(configRoot, "plugins", hookName), "hooks", "Obsolete OpenCode V1 hook plugin"); + addItem(join(configRoot, "tiers.json"), "v1Obsolete", "Obsolete V1 model tiers registry"); + addItem(join(baseRoot, "tiers.json"), "v1Obsolete", "Obsolete V1 model tiers registry"); + const pantheonDir = join(baseRoot, ".pantheon"); + addItem(join(pantheonDir, "fastembed_cache"), "v1Obsolete", "Unused legacy fastembed cache"); + addItem(join(pantheonDir, ".fastembed"), "v1Obsolete", "Unused legacy fastembed cache"); + addItem(join(baseRoot, "fastembed_cache"), "v1Obsolete", "Unused legacy fastembed cache"); + addItem(join(pantheonDir, ".migration-checkpoint"), "v1Obsolete", "Stale migration checkpoint file"); + for (const bakDir of [configRoot, pantheonDir]) { + if (!existsSync(bakDir)) continue; + try { + for (const name of readdirSync(bakDir)) if (name.startsWith("opencode.json.bak") || name.startsWith("active-preset.json.bak")) addItem(join(bakDir, name), "backup", "Old configuration backup sidecar"); + } catch {} + } + const legacyFlatMemDb = join(pantheonDir, "memory.db"); + if (existsSync(legacyFlatMemDb)) { + unmigratedStores += 1; + addItem(legacyFlatMemDb, "legacyStore", "Unmigrated flat .pantheon/memory.db"); + } + const canonicalMemDb = join(pantheonDir, "memory", "memory.db"); + if (existsSync(canonicalMemDb)) try { + const db = new DatabaseSync(canonicalMemDb, { readOnly: true }); + const hasLegacyVec = [ + "memories_vec", + "vec_memories", + "memory_embeddings", + "memory_vectors" + ].some((t) => tableExists(db, t)); + db.close(); + if (hasLegacyVec) { + unmigratedStores += 1; + items.push({ + path: `${canonicalMemDb}#legacy-vec`, + scope, + category: "legacyStore", + reason: "Legacy vector tables pending cleanup in memory.db", + bytes: 0 + }); + } + } catch {} + for (const dbName of ["global.db", "project.db"]) { + const persDbPath = join(pantheonDir, "persistence", dbName); + if (existsSync(persDbPath)) { + unmigratedStores += 1; + addItem(persDbPath, "legacyStore", `Unmigrated persistence/${dbName}`); + } + } + const legacyGoalsJson = join(pantheonDir, "goals.json"); + if (existsSync(legacyGoalsJson)) { + unmigratedStores += 1; + addItem(legacyGoalsJson, "legacyStore", "Unmigrated legacy goals.json"); + } + if (options.includeRedundantCopiedAssets !== false) { + for (const agentFile of CANONICAL_AGENT_MD_FILES) { + addItem(join(configRoot, "agents", agentFile), "redundantAsset", "Canonical Pantheon agent copy shadowed by native plugin transform"); + addItem(join(configRoot, "agent", agentFile), "redundantAsset", "Legacy singular agent copy shadowed by native plugin transform"); + addItem(join(configRoot, "prompts", agentFile), "redundantAsset", "Legacy prompt template copy provided in package"); + } + for (const cmdFile of CANONICAL_COMMAND_MD_FILES) { + addItem(join(configRoot, "commands", cmdFile), "redundantAsset", "Canonical Pantheon command copy shadowed by native plugin transform"); + addItem(join(configRoot, "command", cmdFile), "redundantAsset", "Legacy singular command directory copy"); + } + for (const instr of LEGACY_INSTRUCTION_FILES) addItem(join(configRoot, "instructions", instr), "redundantAsset", "Legacy instruction file superseded by AGENTS.global.md"); + for (const skillId of CANONICAL_SKILL_IDS) addItem(join(configRoot, "skills", skillId), "redundantAsset", "Bundled Pantheon skill directory provided natively by plugin"); + const tuiCopyDir = join(configRoot, "plugins", "pantheon-tui"); + if (existsSync(tuiCopyDir)) { + let copiedVersion = ""; + try { + copiedVersion = String(JSON.parse(readFileSync(join(tuiCopyDir, "package.json"), "utf8")).version ?? ""); + } catch { + copiedVersion = ""; } - ] + const runningVersion = options.runningVersion ? String(options.runningVersion) : ""; + const drifted = Boolean(runningVersion && copiedVersion && copiedVersion !== runningVersion); + addItem(tuiCopyDir, drifted ? "drift" : "redundantAsset", drifted ? `Copied TUI plugin v${copiedVersion} drifts from v${runningVersion}` : "Copied TUI directory superseded by npm package export"); + } + } + return { + items, + unmigratedStores }; } -//#endregion -//#region src/tui-prefs.ts -const PREFS_SYMBOL = Symbol.for("pantheon.tui.prefs.v1"); -const DRAFT_PREVIEW_SYMBOL = Symbol.for("pantheon.tui.draft_preview.v1"); -function stash() { - return globalThis[PREFS_SYMBOL]; -} -function getDraftPreviewSignal() { - const g = globalThis; - if (!g[DRAFT_PREVIEW_SYMBOL]) g[DRAFT_PREVIEW_SYMBOL] = createSignal(void 0); - return g[DRAFT_PREVIEW_SYMBOL]; -} -/** Set the active draft preview overlay (used by settings window to provide live preview). */ -function setTuiDraftPreview(draft) { - const [, setDraft] = getDraftPreviewSignal(); - setDraft(draft && Object.keys(draft).length > 0 ? { ...draft } : void 0); -} -/** Clear the active draft preview overlay. */ -function clearTuiDraftPreview() { - const [, setDraft] = getDraftPreviewSignal(); - setDraft(void 0); -} -/** The active draft preview accessor. */ -function tuiDraftPreview() { - const [draft] = getDraftPreviewSignal(); - return draft(); +function ensureCanonicalMemoryDb(dbPath) { + mkdirSync(dirname(dbPath), { recursive: true }); + const db = new DatabaseSync(dbPath); + db.exec(` + PRAGMA busy_timeout = 3000; + PRAGMA journal_mode = WAL; + CREATE TABLE IF NOT EXISTS memories ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + namespace TEXT NOT NULL DEFAULT 'default', + key TEXT NOT NULL, + value TEXT NOT NULL, + importance REAL NOT NULL DEFAULT 0.5, + created_at TEXT NOT NULL, + expires_at TEXT, + UNIQUE(namespace, key) + ); + CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5( + key, value, namespace, + content='memories', + content_rowid='id' + ); + CREATE TRIGGER IF NOT EXISTS memories_ai AFTER INSERT ON memories BEGIN + INSERT INTO memories_fts(rowid, key, value, namespace) VALUES (new.id, new.key, new.value, new.namespace); + END; + CREATE TRIGGER IF NOT EXISTS memories_ad AFTER DELETE ON memories BEGIN + INSERT INTO memories_fts(memories_fts, rowid, key, value, namespace) VALUES('delete', old.id, old.key, old.value, old.namespace); + END; + CREATE TRIGGER IF NOT EXISTS memories_au AFTER UPDATE ON memories BEGIN + INSERT INTO memories_fts(memories_fts, rowid, key, value, namespace) VALUES('delete', old.id, old.key, old.value, old.namespace); + INSERT INTO memories_fts(rowid, key, value, namespace) VALUES (new.id, new.key, new.value, new.namespace); + END; + `); + return db; } -/** Create (or reuse) the durable prefs store. Fail-open: without host -* storage the consumers fall back to DEFAULT_TUI_PREFS (read-only). */ -function initTuiPrefs(context) { - if (stash() !== void 0) return; - try { - const handle = context.storage?.store?.("tui-prefs", { initial: DEFAULT_TUI_PREFS }); - if (handle !== void 0) { - globalThis[PREFS_SYMBOL] = handle; - if (!handle[0]?.layout || typeof handle[0]?.sidebar?.context?.turnCost !== "boolean" || typeof handle[0]?.sidebar?.context?.tokenAnatomy !== "boolean") handle[1]((draft) => { - if (!draft.layout) draft.layout = { ...DEFAULT_TUI_PREFS.layout }; - if (draft.sidebar?.context) { - if (typeof draft.sidebar.context.turnCost !== "boolean") draft.sidebar.context.turnCost = true; - if (typeof draft.sidebar.context.tokenAnatomy !== "boolean") draft.sidebar.context.tokenAnatomy = true; +function migrateScopeBeforeDelete(baseRoot) { + const pantheonDir = join(baseRoot, ".pantheon"); + if (!existsSync(pantheonDir)) return 0; + let migrated = 0; + const nowIso = (/* @__PURE__ */ new Date()).toISOString(); + const flatMemDbPath = join(pantheonDir, "memory.db"); + const canonicalMemPath = join(pantheonDir, "memory", "memory.db"); + if (existsSync(flatMemDbPath)) try { + const src = new DatabaseSync(flatMemDbPath, { readOnly: true }); + const dst = ensureCanonicalMemoryDb(canonicalMemPath); + if (tableExists(src, "memories")) { + const rows = src.prepare("SELECT namespace, key, value, created_at FROM memories").all(); + const insert = dst.prepare("INSERT OR IGNORE INTO memories (namespace, key, value, importance, created_at) VALUES (?, ?, ?, ?, ?)"); + dst.exec("BEGIN IMMEDIATE"); + try { + for (const r of rows) { + insert.run(String(r.namespace ?? "default"), String(r.key ?? ""), String(r.value ?? ""), .5, String(r.created_at ?? nowIso)); + migrated += 1; } - }).catch(() => {}); + dst.exec("COMMIT"); + } catch (txErr) { + try { + dst.exec("ROLLBACK"); + } catch {} + throw txErr; + } } + src.close(); + dst.close(); } catch {} -} -/** Deep clone and overlay staged settings draft onto base TuiPrefs. */ -function previewTuiPrefs(base, draft) { - if (!draft || Object.keys(draft).length === 0) return base; - let hasTui = false; - for (const k of Object.keys(draft)) if (k.startsWith("tui.")) { - hasTui = true; - break; - } - if (!hasTui) return base; - const normalized = normalizeTuiPrefs(base); - const effective = { - version: 1, - layout: { ...normalized.layout }, - ...normalized.theme ? { theme: { ...normalized.theme } } : {}, - sidebar: { - header: { ...normalized.sidebar.header }, - ...normalized.sidebar.pinnedSessions ? { pinnedSessions: [...normalized.sidebar.pinnedSessions] } : {}, - blocks: { ...normalized.sidebar.blocks }, - context: { ...normalized.sidebar.context } - }, - footer: { ...normalized.footer } - }; - for (const [id, value] of Object.entries(draft)) if (id.startsWith("tui.")) applyTuiRow(effective, id, value); - return effective; -} -/** The raw persisted prefs from host storage (no draft overlay). */ -function savedTuiPrefs() { - const s = stash()?.[0]; - if (!s) return DEFAULT_TUI_PREFS; - return normalizeTuiPrefs(s); -} -/** The live reactive prefs (read properties inside memos/JSX — tracked). -* When a settings window has an active draft, preview overlays on top -* of durable storage in real time. */ -function tuiPrefs() { - const base = savedTuiPrefs(); - const preview = tuiDraftPreview(); - if (!preview) return base; - return previewTuiPrefs(base, preview); -} -/** Stage a mutation against the durable store; resolves when persisted. */ -function mutateTuiPrefs(mutation) { - const handle = stash(); - if (handle === void 0) return Promise.resolve(); - return handle[1](mutation); -} -const GAUGE_STYLES = Object.freeze([ - "both", - "bar", - "percent", - "off" -]); -const ENABLED_CYCLE = Object.freeze(["enabled", "disabled"]); -const BAR_SHAPES_CYCLE = Object.freeze([ - "smooth", - "line", - "block", - "ascii", - "dots", - "braille" -]); -const BAR_WIDTHS_CYCLE = Object.freeze([ - "standard", - "compact", - "wide", - "full" -]); -const LAYOUT_PRESETS_CYCLE = Object.freeze(["comfortable", "compact"]); -const SEPARATOR_STYLES_CYCLE = Object.freeze([ - "spaces", - "pipes", - "dots", - "slashes" -]); -const SETTINGS_VIEW_MODES = Object.freeze([ - "docked", - "fullscreen", - "dialog" -]); -const LANGUAGE_CYCLE = Object.freeze([ - "auto", - "pt-BR", - "en" -]); -const THEME_MODES_CYCLE = Object.freeze([ - "auto", - "dark", - "light" -]); -const ACCENT_COLORS_CYCLE = Object.freeze([ - "host", - "pantheon", - "emerald", - "cyan", - "amber", - "purple", - "rose" -]); -const ACCENT_PALETTE = { - host: { - primary: "#fba970", - hover: "#fdba74", - muted: "#a1a1aa" - }, - pantheon: { - primary: "#fba970", - hover: "#fdba74", - muted: "#a1a1aa" - }, - emerald: { - primary: "#10b981", - hover: "#34d399", - muted: "#059669" - }, - cyan: { - primary: "#06b6d4", - hover: "#22d3ee", - muted: "#0891b2" - }, - amber: { - primary: "#f59e0b", - hover: "#fbbf24", - muted: "#d97706" - }, - purple: { - primary: "#a855f7", - hover: "#c084fc", - muted: "#9333ea" - }, - rose: { - primary: "#f43f5e", - hover: "#fb7185", - muted: "#e11d48" + if (existsSync(canonicalMemPath)) try { + const db = ensureCanonicalMemoryDb(canonicalMemPath); + for (const trig of [ + "memories_vec_ai", + "memories_vec_ad", + "memories_vec_au" + ]) db.exec(`DROP TRIGGER IF EXISTS ${trig}`); + for (const tbl of [ + "memories_vec", + "vec_memories", + "memory_embeddings", + "memory_vectors" + ]) if (tableExists(db, tbl)) { + db.exec(`DROP TABLE IF EXISTS ${tbl}`); + migrated += 1; + } + db.close(); + } catch {} + const persDir = join(pantheonDir, "persistence"); + for (const dbName of ["global.db", "project.db"]) { + const dbPath = join(persDir, dbName); + if (!existsSync(dbPath)) continue; + try { + const db = new DatabaseSync(dbPath, { readOnly: true }); + for (const tbl of [ + "kv", + "kv_store", + "context", + "checkpoints", + "sessions" + ]) { + if (!tableExists(db, tbl) || countTableRows(db, tbl) === 0) continue; + const cols = db.prepare(`PRAGMA table_info(${tbl})`).all(); + const colNames = new Set(cols.map((c) => c.name)); + const keyCol = colNames.has("key") ? "key" : colNames.has("id") ? "id" : colNames.has("session_id") ? "session_id" : null; + const valCol = colNames.has("value") ? "value" : colNames.has("data") ? "data" : colNames.has("content") ? "content" : null; + if (!keyCol || !valCol) continue; + const nsSelect = colNames.has("namespace") ? "namespace" : `'${tbl === "checkpoints" || tbl === "sessions" ? "checkpoints" : "default"}' AS namespace`; + const rows = db.prepare(`SELECT ${nsSelect}, ${keyCol} AS k, ${valCol} AS v FROM ${tbl}`).all(); + for (const r of rows) { + const ns = toSafeSegment(r.namespace, "default"); + const key = toSafeSegment(r.k, ""); + if (!key) continue; + const targetDir = join(persDir, ns); + const targetFile = join(targetDir, `${key}.json`); + if (!existsSync(targetFile)) { + mkdirSync(targetDir, { recursive: true }); + writeFileSync(targetFile, JSON.stringify({ + key, + namespace: ns, + value: String(r.v ?? ""), + updated_at: nowIso + }, null, 2), "utf8"); + migrated += 1; + } + } + } + db.close(); + } catch {} } -}; -function resolveAccentColor(accent, contextTheme) { - if (!accent || accent === "host") return contextTheme?.text?.feedback?.warning?.base ?? contextTheme?.text?.base ?? "#fba970"; - return ACCENT_PALETTE[accent]?.primary ?? "#fba970"; -} -const DEFAULT_TUI_PREFS = { - version: 1, - layout: { - preset: "comfortable", - separator: "spaces", - settingsView: "docked", - language: "auto" - }, - theme: { - mode: "auto", - accent: "host" - }, - sidebar: { - header: { - version: true, - preset: true, - session: true - }, - pinnedSessions: [], - blocks: { - context: true, - git: true, - todo: false, - dispatch: true - }, - context: { - gauge: "both", - barShape: "smooth", - barWidth: "standard", - evenMark: false, - tokens: true, - spent: true, - modelUsage: true, - performance: true, - localSpend: true, - turnCost: true, - tokenAnatomy: true + const legacyGoalsPath = join(pantheonDir, "goals.json"); + if (existsSync(legacyGoalsPath)) try { + const parsed = JSON.parse(readFileSync(legacyGoalsPath, "utf8")); + const list = Array.isArray(parsed) ? parsed : parsed && typeof parsed === "object" && Array.isArray(parsed.goals) ? parsed.goals ?? [] : []; + const goalsDir = join(pantheonDir, "goals"); + for (const item of list) { + if (!item || typeof item !== "object") continue; + const rec = item; + const safeId = toSafeSegment(rec.id ?? rec.goal_id, ""); + if (!safeId) continue; + const target = join(goalsDir, `${safeId}.json`); + if (!existsSync(target)) { + mkdirSync(goalsDir, { recursive: true }); + writeFileSync(target, JSON.stringify({ + id: safeId, + title: String(rec.title ?? rec.description ?? ""), + criteria: Array.isArray(rec.criteria) ? rec.criteria.map(String) : [], + status: String(rec.status ?? "active"), + created_at: typeof rec.created_at === "string" ? rec.created_at : nowIso, + updated_at: typeof rec.updated_at === "string" ? rec.updated_at : nowIso + }, null, 2), "utf8"); + migrated += 1; + } } - }, - footer: { - prompt: true, - home: true - } -}; -function asBool(value, fallback) { - return typeof value === "boolean" ? value : fallback; + } catch {} + return migrated; } -/** Deep-merge stored JSON over the defaults; unknown keys and junk are ignored. */ -function normalizeTuiPrefs(raw) { - const stored = typeof raw === "object" && raw !== null ? raw : {}; - const layout = typeof stored.layout === "object" && stored.layout !== null ? stored.layout : {}; - const sidebar = typeof stored.sidebar === "object" && stored.sidebar !== null ? stored.sidebar : {}; - const header = typeof sidebar.header === "object" && sidebar.header !== null ? sidebar.header : {}; - const blocks = typeof sidebar.blocks === "object" && sidebar.blocks !== null ? sidebar.blocks : {}; - const context = typeof sidebar.context === "object" && sidebar.context !== null ? sidebar.context : {}; - const footer = typeof stored.footer === "object" && stored.footer !== null ? stored.footer : {}; - const rawTheme = typeof stored.theme === "object" && stored.theme !== null ? stored.theme : {}; - const themeMode = THEME_MODES_CYCLE.includes(rawTheme.mode) ? rawTheme.mode : DEFAULT_TUI_PREFS.theme?.mode ?? "auto"; - const themeAccent = ACCENT_COLORS_CYCLE.includes(rawTheme.accent) ? rawTheme.accent : DEFAULT_TUI_PREFS.theme?.accent ?? "host"; - const preset = LAYOUT_PRESETS_CYCLE.includes(layout.preset) ? layout.preset : DEFAULT_TUI_PREFS.layout.preset; - const separator = SEPARATOR_STYLES_CYCLE.includes(layout.separator) ? layout.separator : DEFAULT_TUI_PREFS.layout.separator; - const settingsView = SETTINGS_VIEW_MODES.includes(layout.settingsView) ? layout.settingsView : DEFAULT_TUI_PREFS.layout.settingsView; - const language = LANGUAGE_CYCLE.includes(layout.language) ? layout.language : DEFAULT_TUI_PREFS.layout.language; - const gauge = GAUGE_STYLES.includes(context.gauge) ? context.gauge : DEFAULT_TUI_PREFS.sidebar.context.gauge; - const barShape = BAR_SHAPES_CYCLE.includes(context.barShape) ? context.barShape : DEFAULT_TUI_PREFS.sidebar.context.barShape; - const barWidth = BAR_WIDTHS_CYCLE.includes(context.barWidth) ? context.barWidth : DEFAULT_TUI_PREFS.sidebar.context.barWidth; - const evenMark = asBool(context.evenMark, DEFAULT_TUI_PREFS.sidebar.context.evenMark); +function scanLegacyArtifacts(options = {}) { + const workspaceDir = options.workspaceDir ? resolve(options.workspaceDir) : void 0; + const globalConfigDir = options.globalConfigDir ? resolve(options.globalConfigDir) : resolveAuditGlobalDir(options.env); + const cacheNpmDir = options.cacheDir ? resolve(options.cacheDir) : resolveAuditCacheDir(options.env); + const items = []; + let unmigratedStores = 0; + if (globalConfigDir && existsSync(globalConfigDir) && globalConfigDir !== "/") { + const res = collectScopeAudit("global", globalConfigDir, globalConfigDir, options); + items.push(...res.items); + unmigratedStores += res.unmigratedStores; + } + if (cacheNpmDir && existsSync(cacheNpmDir) && cacheNpmDir !== "/") items.push(...collectCacheAudit(cacheNpmDir, options)); + if (workspaceDir && existsSync(workspaceDir) && workspaceDir !== "/" && (!globalConfigDir || !samePath(workspaceDir, globalConfigDir))) { + const res = collectScopeAudit("project", workspaceDir, join(workspaceDir, ".opencode"), options); + items.push(...res.items); + unmigratedStores += res.unmigratedStores; + } + const byScope = { + global: 0, + project: 0 + }; + const byCategory = {}; + let totalBytes = 0; + for (const item of items) { + byScope[item.scope] = (byScope[item.scope] ?? 0) + 1; + byCategory[item.category] = (byCategory[item.category] ?? 0) + 1; + totalBytes += item.bytes; + } return { - version: 1, - layout: { - preset, - separator, - settingsView, - language - }, - theme: { - mode: themeMode, - accent: themeAccent - }, - sidebar: { - header: { - version: asBool(header.version, true), - preset: asBool(header.preset, true), - session: asBool(header.session, true) - }, - pinnedSessions: Array.isArray(sidebar.pinnedSessions) ? sidebar.pinnedSessions.filter((s) => typeof s === "string") : [], - blocks: { - context: asBool(blocks.context, true), - git: asBool(blocks.git, true), - todo: asBool(blocks.todo, false), - dispatch: asBool(blocks.dispatch, true) - }, - context: { - gauge, - barShape, - barWidth, - evenMark, - tokens: asBool(context.tokens, true), - spent: asBool(context.spent, true), - modelUsage: asBool(context.modelUsage, true), - performance: asBool(context.performance, true), - localSpend: asBool(context.localSpend, true), - turnCost: asBool(context.turnCost, true), - tokenAnatomy: asBool(context.tokenAnatomy, true) - } - }, - footer: { - prompt: asBool(footer.prompt, true), - home: asBool(footer.home, true) + items, + summary: { + total: items.length, + totalBytes, + unmigratedStores, + byScope, + byCategory } }; } -const onOff = ENABLED_CYCLE; -const row = (id, name, value, note) => ({ - id, - name, - value: value ? "enabled" : "disabled", - cycle: onOff, - note -}); -function buildTuiTab(prefs, languagePref) { - const isPt = resolveLanguage(languagePref ?? prefs.layout?.language) === "pt-BR"; - return { - id: "tui", - title: "TUI", - groups: [ - { - title: isPt ? "Predefinição & Layout" : "Preset & Layout", - rows: [ - { - id: "tui.layout.preset", - name: isPt ? "Predefinição de layout" : "Layout preset", - value: prefs.layout?.preset ?? DEFAULT_TUI_PREFS.layout.preset, - cycle: LAYOUT_PRESETS_CYCLE, - note: isPt ? "comfortable | compact — define espaçamento e bordas" : "comfortable | compact — sets spacing & borders" - }, - { - id: "tui.layout.separator", - name: isPt ? "Separador" : "Separator", - value: prefs.layout?.separator ?? DEFAULT_TUI_PREFS.layout.separator, - cycle: SEPARATOR_STYLES_CYCLE, - note: isPt ? "spaces | pipes | dots | slashes — glifos na linha de status" : "spaces | pipes | dots | slashes — status line glyphs" - }, - { - id: "tui.layout.settingsView", - name: isPt ? "Superfície de configurações" : "Settings surface", - value: tuiRowValue(prefs, "tui.layout.settingsView") ?? "docked", - cycle: SETTINGS_VIEW_MODES, - note: isPt ? "docked (acima do prompt) | fullscreen | dialog" : "docked (above prompt) | fullscreen router page | dialog overlay" - }, - { - id: "tui.layout.language", - name: isPt ? "Idioma / Language" : "Language / Idioma", - value: tuiRowValue(prefs, "tui.layout.language") ?? "auto", - cycle: LANGUAGE_CYCLE, - note: isPt ? "auto (detecta via fuso/locale) | pt-BR (Português) | en (English)" : "auto (detect via timezone/locale) | pt-BR (Português) | en (English)" - } - ] - }, - { - title: isPt ? "Cores & Tema" : "Colors & Theme", - rows: [{ - id: "tui.theme.mode", - name: isPt ? "Modo do tema" : "Theme mode", - value: tuiRowValue(prefs, "tui.theme.mode") ?? "auto", - cycle: THEME_MODES_CYCLE, - note: isPt ? "auto (segue o OpenCode) | dark | light" : "auto (follow OpenCode theme) | dark | light" - }, { - id: "tui.theme.accent", - name: isPt ? "Cor de destaque" : "Accent color", - value: tuiRowValue(prefs, "tui.theme.accent") ?? "host", - cycle: ACCENT_COLORS_CYCLE, - note: isPt ? "host (segue tema) | pantheon | emerald | cyan | amber | purple | rose" : "host (follow theme) | pantheon | emerald | cyan | amber | purple | rose" - }] - }, - { - title: isPt ? "Barras & Medidores" : "Bars & Gauges", - rows: [ - { - id: "tui.sidebar.context.barShape", - name: isPt ? "Formato da barra" : "Bar shape", - value: prefs.sidebar.context.barShape, - cycle: BAR_SHAPES_CYCLE, - note: "line (━─) | block (▰▱) | smooth (█░) | ascii (=) | dots (●○) | braille" - }, - { - id: "tui.sidebar.context.barWidth", - name: isPt ? "Largura da barra" : "Bar width", - value: prefs.sidebar.context.barWidth, - cycle: BAR_WIDTHS_CYCLE, - note: isPt ? "standard (12) | compact (8) | wide (16) | full (20 células)" : "standard (12) | compact (8) | wide (16) | full (20 cells)" - }, - row("tui.sidebar.context.evenMark", isPt ? "Marca central (50%)" : "Even-use mark", prefs.sidebar.context.evenMark, isPt ? "| indicador aos 50% nas barras de medição" : "| indicator at 50% midpoint in gauge bars"), - { - id: "tui.sidebar.context.gauge", - name: isPt ? "Estilo do medidor" : "Gauge style", - value: prefs.sidebar.context.gauge, - cycle: GAUGE_STYLES, - note: "both | bar | percent | off — `▰▱ 42% of 200k`" - } - ] - }, - { - title: isPt ? "Cabeçalho da barra lateral" : "Sidebar header", - rows: [ - row("tui.sidebar.header.version", isPt ? "Linha de versão" : "Version line", prefs.sidebar.header.version, isPt ? "linha `Pantheon v…`" : "the `Pantheon v…` line"), - row("tui.sidebar.header.preset", isPt ? "Linha de preset" : "Preset line", prefs.sidebar.header.preset, isPt ? "linha `▸ preset · provider`" : "the `▸ preset · provider` line"), - row("tui.sidebar.header.session", isPt ? "Linha de sessão" : "Session line", prefs.sidebar.header.session, isPt ? "título da sessão ativa" : "the active session title") - ] - }, - { - title: isPt ? "Blocos da barra lateral" : "Sidebar blocks", - rows: [ - row("tui.sidebar.block.context", isPt ? "Bloco de contexto" : "Context block", prefs.sidebar.blocks.context, isPt ? "tokens, medidor, custo, uso de modelos" : "tokens, gauge, spend, model usage"), - row("tui.sidebar.block.git", isPt ? "Bloco do Git" : "Git block", prefs.sidebar.blocks.git, isPt ? "branch + contagem de alterações" : "branch + working-tree counts"), - row("tui.sidebar.block.dispatch", isPt ? "Bloco Dispatch" : "Dispatch block", prefs.sidebar.blocks.dispatch, isPt ? "delegações em tempo real" : "live delegations + rollup") - ] - }, - { - title: isPt ? "Detalhe do bloco de contexto" : "Context block detail", - rows: [ - row("tui.sidebar.context.tokens", isPt ? "Linha de tokens" : "Tokens row", prefs.sidebar.context.tokens, isPt ? "contagem bruta de tokens" : "the raw token count line"), - row("tui.sidebar.context.spent", isPt ? "Linha de custo" : "Spent row", prefs.sidebar.context.spent, isPt ? "linha `$… gastos na sessão`" : "the `$… spent in session` line"), - row("tui.sidebar.context.modelUsage", isPt ? "Tabela de uso de modelos" : "Model usage table", prefs.sidebar.context.modelUsage, isPt ? "resumo de chamadas por modelo" : "per-model tokens/USD"), - row("tui.sidebar.context.performance", isPt ? "Linha de desempenho" : "Performance row", prefs.sidebar.context.performance, isPt ? "tokens/segundo e latência" : "cache % + tok/s"), - row("tui.sidebar.context.turnCost", isPt ? "Custo do turno" : "Turn cost", prefs.sidebar.context.turnCost, isPt ? "linha `Turn: $… (prev: $…)`" : "the `Turn: $… (prev: $…)` line"), - row("tui.sidebar.context.tokenAnatomy", isPt ? "Anatomia de tokens" : "Token anatomy", prefs.sidebar.context.tokenAnatomy, isPt ? "linha `↑in ↓out ✦think`" : "the `↑in ↓out ✦think` line"), - row("tui.sidebar.context.localSpend", isPt ? "Linha de custo local" : "Local spend row", prefs.sidebar.context.localSpend, isPt ? "totais de hoje / 30 dias" : "hoje / 30d totals") - ] - }, - { - title: isPt ? "Rodapés" : "Footers", - rows: [row("tui.footer.prompt", isPt ? "Prompt inferior" : "Prompt footer", prefs.footer.prompt, isPt ? "linha `▸preset · ✦n ativos` durante delegações" : "the `▸preset · ✦n ativos` line while delegations run"), row("tui.footer.home", isPt ? "Status inicial" : "Home status", prefs.footer.home, isPt ? "linha `Pantheon v…` sob o prompt inicial" : "the `Pantheon v…` line under the home prompt")] +function cleanLegacyArtifacts(options = {}) { + const workspaceDir = options.workspaceDir ? resolve(options.workspaceDir) : void 0; + const globalConfigDir = options.globalConfigDir ? resolve(options.globalConfigDir) : resolveAuditGlobalDir(options.env); + const cacheNpmDir = options.cacheDir ? resolve(options.cacheDir) : resolveAuditCacheDir(options.env); + const scopeFilter = options.scope && options.scope !== "all" ? options.scope : null; + const scan = scanLegacyArtifacts(options); + let migratedRecords = 0; + if (scopeFilter !== "project" && globalConfigDir && existsSync(globalConfigDir) && globalConfigDir !== "/") migratedRecords += migrateScopeBeforeDelete(globalConfigDir); + if (scopeFilter !== "global" && workspaceDir && existsSync(workspaceDir) && workspaceDir !== "/" && (!globalConfigDir || !samePath(workspaceDir, globalConfigDir))) migratedRecords += migrateScopeBeforeDelete(workspaceDir); + const removed = []; + const errors = []; + let reclaimedBytes = 0; + for (const item of scan.items) { + if (scopeFilter && item.scope !== scopeFilter) continue; + if (item.path.endsWith("#legacy-vec")) { + removed.push(item.path); + continue; + } + const scopeRoot = item.scope === "global" ? globalConfigDir : workspaceDir; + const confineRoot = item.scope === "global" && cacheNpmDir && isConfinedWithin(cacheNpmDir, item.path) ? cacheNpmDir : scopeRoot; + if (!confineRoot || !isConfinedWithin(confineRoot, item.path)) { + errors.push({ + path: item.path, + reason: "Path escapes target scope root" + }); + continue; + } + try { + if (existsSync(item.path)) { + rmSync(item.path, { + recursive: true, + force: true + }); + removed.push(item.path); + reclaimedBytes += item.bytes; } - ] + if (item.path.endsWith(".db")) for (const suffix of [ + "-wal", + "-shm", + "-journal" + ]) { + const sidecar = `${item.path}${suffix}`; + if (existsSync(sidecar) && isConfinedWithin(confineRoot, sidecar)) { + const sidecarBytes = measurePathBytes(sidecar); + rmSync(sidecar, { force: true }); + removed.push(sidecar); + reclaimedBytes += sidecarBytes; + } + } + } catch (err) { + errors.push({ + path: item.path, + reason: err instanceof Error ? err.message : String(err) + }); + } + } + return { + removed, + reclaimedBytes, + migratedRecords, + errors }; } +//#endregion +//#region src/preset-state.ts /** -* Apply one staged row INTO a prefs draft (in place — the storage mutate -* callback hands an immer-style draft). Unknown ids or junk values are no-ops. +* preset-state.ts — the Model Preset section of the settings window. +* +* TUI-local replica (the bundle must stay self-contained). The preset NAMES +* mirror routing.yml's `presets:` and are drift-pinned by +* tests/tui-preset-state.test.mjs against `loadPresetDefs()`. The marker file +* shape mirrors scripts/install/model-picker.mjs's `buildActivePresetFile` +* (version 1), and the readers (`resolveActivePreset`, vision.ts candidates) +* only consult `.preset`, so the window writes `source: 'tui-settings'`. +* +* Scope note: the window writes the GLOBAL marker only +* (`/opencode/.pantheon/active-preset.json`). A project marker +* wins (it precedes the global path in every runtime candidate list), so it +* is displayed read-only. `none` DELETES the marker with a .bak backup — the +* same contract as the CLI's `set-tier none`. */ -function applyTuiRow(draft, id, value) { - const enabled = value === "enabled"; - switch (id) { - case "tui.layout.preset": - if (LAYOUT_PRESETS_CYCLE.includes(value)) { - if (!draft.layout) draft.layout = { ...DEFAULT_TUI_PREFS.layout }; - draft.layout.preset = value; - } - return; - case "tui.layout.separator": - if (SEPARATOR_STYLES_CYCLE.includes(value)) { - if (!draft.layout) draft.layout = { ...DEFAULT_TUI_PREFS.layout }; - draft.layout.separator = value; - } - return; - case "tui.layout.settingsView": - if (SETTINGS_VIEW_MODES.includes(value)) { - if (!draft.layout) draft.layout = { ...DEFAULT_TUI_PREFS.layout }; - draft.layout.settingsView = value; - } - return; - case "tui.layout.language": - if (LANGUAGE_CYCLE.includes(value)) { - if (!draft.layout) draft.layout = { ...DEFAULT_TUI_PREFS.layout }; - draft.layout.language = value; - } - return; - case "tui.theme.mode": - if (THEME_MODES_CYCLE.includes(value)) { - if (!draft.theme) draft.theme = { ...DEFAULT_TUI_PREFS.theme }; - draft.theme.mode = value; - } - return; - case "tui.theme.accent": - if (ACCENT_COLORS_CYCLE.includes(value)) { - if (!draft.theme) draft.theme = { ...DEFAULT_TUI_PREFS.theme }; - draft.theme.accent = value; - } - return; - case "tui.sidebar.context.barShape": - if (BAR_SHAPES_CYCLE.includes(value)) draft.sidebar.context.barShape = value; - return; - case "tui.sidebar.context.barWidth": - if (BAR_WIDTHS_CYCLE.includes(value)) draft.sidebar.context.barWidth = value; - return; - case "tui.sidebar.context.evenMark": - draft.sidebar.context.evenMark = enabled; - return; - case "tui.sidebar.header.version": - draft.sidebar.header.version = enabled; - return; - case "tui.sidebar.header.preset": - draft.sidebar.header.preset = enabled; - return; - case "tui.sidebar.header.session": - draft.sidebar.header.session = enabled; - return; - case "tui.sidebar.block.context": - draft.sidebar.blocks.context = enabled; - return; - case "tui.sidebar.block.git": - draft.sidebar.blocks.git = enabled; - return; - case "tui.sidebar.block.todo": - draft.sidebar.blocks.todo = enabled; - return; - case "tui.sidebar.block.dispatch": - draft.sidebar.blocks.dispatch = enabled; - return; - case "tui.sidebar.context.gauge": - if (GAUGE_STYLES.includes(value)) draft.sidebar.context.gauge = value; - return; - case "tui.sidebar.context.tokens": - draft.sidebar.context.tokens = enabled; - return; - case "tui.sidebar.context.spent": - draft.sidebar.context.spent = enabled; - return; - case "tui.sidebar.context.modelUsage": - draft.sidebar.context.modelUsage = enabled; - return; - case "tui.sidebar.context.performance": - draft.sidebar.context.performance = enabled; - return; - case "tui.sidebar.context.localSpend": - draft.sidebar.context.localSpend = enabled; - return; - case "tui.sidebar.context.turnCost": - draft.sidebar.context.turnCost = enabled; - return; - case "tui.sidebar.context.tokenAnatomy": - draft.sidebar.context.tokenAnatomy = enabled; - return; - case "tui.footer.prompt": - draft.footer.prompt = enabled; - return; - case "tui.footer.home": - draft.footer.home = enabled; - return; - default: return; +/** Mirrors routing.yml `presets:` — drift-pinned against loadPresetDefs(). */ +const PRESET_NAMES = Object.freeze([ + "go-free", + "go-fast", + "go-premium", + "go-hybrid", + "anthropic", + "openai" +]); +function globalActivePresetPath(env = process.env) { + const xdg = env.XDG_CONFIG_HOME; + const home = env.HOME ?? ""; + const root = xdg ?? join(home, ".config"); + return join(root, "opencode", ".pantheon", "active-preset.json"); +} +function projectActivePresetPath() { + return join(process.cwd(), ".pantheon", "active-preset.json"); +} +/** Fail-open read: missing/corrupt marker = no active preset. */ +function readActivePresetMarker(path) { + try { + const raw = JSON.parse(readFileSync(path, "utf8")); + if (typeof raw?.preset !== "string" || raw.preset === "" || raw.preset === "none") return null; + return { + name: raw.preset, + updatedAt: typeof raw.updated_at === "string" ? raw.updated_at : "" + }; + } catch { + return null; } } -/** Read the current pref value for a row id ('enabled'/'disabled'/gauge/custom). */ -function tuiRowValue(prefs, id) { - if (id === "tui.layout.preset") return prefs.layout?.preset ?? DEFAULT_TUI_PREFS.layout.preset; - if (id === "tui.layout.separator") return prefs.layout?.separator ?? DEFAULT_TUI_PREFS.layout.separator; - if (id === "tui.layout.settingsView") return prefs.layout?.settingsView ?? DEFAULT_TUI_PREFS.layout.settingsView ?? "docked"; - if (id === "tui.layout.language") return prefs.layout?.language ?? "auto"; - if (id === "tui.theme.mode") return prefs.theme?.mode ?? DEFAULT_TUI_PREFS.theme?.mode ?? "auto"; - if (id === "tui.theme.accent") return prefs.theme?.accent ?? DEFAULT_TUI_PREFS.theme?.accent ?? "host"; - if (id === "tui.sidebar.context.barShape") return prefs.sidebar.context.barShape; - if (id === "tui.sidebar.context.barWidth") return prefs.sidebar.context.barWidth; - if (id === "tui.sidebar.context.gauge") return prefs.sidebar.context.gauge; - if (id === "tui.sidebar.context.evenMark") return prefs.sidebar.context.evenMark ? "enabled" : "disabled"; - const enabled = (() => { - switch (id) { - case "tui.sidebar.header.version": return prefs.sidebar.header.version; - case "tui.sidebar.header.preset": return prefs.sidebar.header.preset; - case "tui.sidebar.header.session": return prefs.sidebar.header.session; - case "tui.sidebar.block.context": return prefs.sidebar.blocks.context; - case "tui.sidebar.block.git": return prefs.sidebar.blocks.git; - case "tui.sidebar.block.todo": return prefs.sidebar.blocks.todo; - case "tui.sidebar.block.dispatch": return prefs.sidebar.blocks.dispatch; - case "tui.sidebar.context.tokens": return prefs.sidebar.context.tokens; - case "tui.sidebar.context.spent": return prefs.sidebar.context.spent; - case "tui.sidebar.context.modelUsage": return prefs.sidebar.context.modelUsage; - case "tui.sidebar.context.performance": return prefs.sidebar.context.performance; - case "tui.sidebar.context.localSpend": return prefs.sidebar.context.localSpend; - case "tui.sidebar.context.turnCost": return prefs.sidebar.context.turnCost; - case "tui.sidebar.context.tokenAnatomy": return prefs.sidebar.context.tokenAnatomy; - case "tui.footer.prompt": return prefs.footer.prompt; - case "tui.footer.home": return prefs.footer.home; - default: return; +function writeMarkerAtomically(path, content) { + mkdirSync(dirname(path), { recursive: true }); + const temp = `${path}.tui.tmp`; + writeFileSync(temp, content); + renameSync(temp, path); +} +/** Select a preset globally: .bak backup, atomic write, version-1 marker. */ +function writeActivePreset(path, name, nowIso = (/* @__PURE__ */ new Date()).toISOString()) { + if (!PRESET_NAMES.includes(name)) throw new TypeError(`Refusing to persist unknown preset "${name}"`); + backupMarker(path); + writeMarkerAtomically(path, `${JSON.stringify({ + version: 1, + preset: name, + source: "tui-settings", + updated_at: nowIso + }, null, 2)}\n`); +} +/** Clear the global marker (the `none` contract): .bak backup, then remove. */ +function clearActivePreset(path) { + backupMarker(path); + rmSync(path, { force: true }); +} +function backupMarker(path) { + if (!existsSync(path)) return; + mkdirSync(dirname(path), { recursive: true }); + copyFileSync(path, `${path}.bak`); +} +const VISION_MODEL_OPTIONS = Object.freeze([ + "auto", + "opencode-go/mimo-v2.6-flash", + "google/gemini-2.5-flash", + "openai/gpt-5-mini", + "anthropic/claude-3-5-haiku", + "opencode-go/mimo-v2.5" +]); +function visionConfigPaths(cwd = process.cwd(), env = process.env) { + const home = env.HOME ?? ""; + const xdg = env.XDG_CONFIG_HOME ?? join(home, ".config"); + return [join(cwd, ".opencode", "opencode-vision.json"), join(xdg, "opencode", "opencode-vision.json")]; +} +function readConfiguredVisionModel(cwd = process.cwd(), env = process.env) { + for (const path of visionConfigPaths(cwd, env)) try { + if (existsSync(path)) { + const parsed = JSON.parse(readFileSync(path, "utf8")); + if (typeof parsed?.visionModel === "string" && parsed.visionModel.trim()) return parsed.visionModel.trim(); } - })(); - return enabled === void 0 ? void 0 : enabled ? "enabled" : "disabled"; + } catch {} + return "auto"; } -function isSessionPinned(sessionID) { - if (!sessionID) return false; - const list = tuiPrefs().sidebar.pinnedSessions; - return Array.isArray(list) && list.includes(sessionID); +function writeConfiguredVisionModel(model, cwd = process.cwd(), env = process.env) { + const home = env.HOME ?? ""; + const xdg = env.XDG_CONFIG_HOME ?? join(home, ".config"); + const projectDir = join(cwd, ".opencode"); + const targetPath = existsSync(projectDir) ? join(projectDir, "opencode-vision.json") : join(xdg, "opencode", "opencode-vision.json"); + let current = {}; + try { + if (existsSync(targetPath)) current = JSON.parse(readFileSync(targetPath, "utf8")); + } catch { + current = {}; + } + if (model === "auto" || !model.trim()) delete current.visionModel; + else current.visionModel = model.trim(); + mkdirSync(dirname(targetPath), { recursive: true }); + const temp = `${targetPath}.tui.tmp`; + writeFileSync(temp, `${JSON.stringify(current, null, 2)}\n`, "utf8"); + renameSync(temp, targetPath); +} +const PRESET_CYCLE = Object.freeze(["none", ...PRESET_NAMES]); +function buildPresetTab(input, languagePref) { + const isPt = languagePref === "pt-BR"; + const rows = [{ + id: "preset", + name: isPt ? "Predefinição" : "Preset", + value: input.globalName ?? "none", + cycle: PRESET_CYCLE, + note: isPt ? "marcador global · gravação atômica, backup .bak · none = padrão OpenCode" : "global marker · atomic write, .bak backup · none = opencode defaults" + }]; + if (input.projectName !== null) rows.push({ + id: "preset.project", + name: isPt ? "Projeto" : "Project", + value: input.projectName, + note: isPt ? `${projectActivePresetPath()} tem precedência sobre o global — somente leitura aqui` : `${projectActivePresetPath()} wins over the global marker — read-only here` + }); + if (input.visionModel !== void 0) rows.push({ + id: "preset.vision_model", + name: isPt ? "Modelo de Visão" : "Vision Model", + value: input.visionModel || "auto", + cycle: VISION_MODEL_OPTIONS, + note: isPt ? "modelo para inspeção de imagens (vision_describe) · salvo em opencode-vision.json" : "model for image inspection (vision_describe) · saved in opencode-vision.json" + }); + return { + id: "preset", + title: "Preset", + groups: [{ + title: isPt ? "Predefinição de modelo" : "Model preset", + rows + }] + }; } //#endregion //#region src/update-status.ts @@ -2730,29 +4774,29 @@ function buildUpdatesTab(input) { id: "update.command", name: isPt ? "Comando no terminal" : "CLI Command", value: "opencode plugin update", - note: isPt ? `sem npx: \`${pluginCommand} && opencode reload\`` : `native CLI (no npx): \`${pluginCommand} && opencode reload\`` + note: isPt ? `rode \`${pluginCommand} && opencode reload\` (sem npx)` : `run \`${pluginCommand} && opencode reload\` (no npx)` }); const audit = input.legacyAudit; const legacyRows = [ { id: "legacy.status", name: isPt ? "Auditoria legada" : "Legacy & Drift", - value: input.legacyScanning ? isPt ? "escaneando…" : "scanning…" : audit === void 0 || audit === null ? isPt ? "não escaneado" : "not scanned" : audit.total === 0 ? isPt ? "limpo (0 obsoletos)" : "clean (0 obsolete)" : isPt ? `${audit.total} arquivo(s) (${formatBytes(audit.totalBytes)})` : `${audit.total} file(s) (${formatBytes(audit.totalBytes)})`, - note: input.legacyNotice ? input.legacyNotice : audit && audit.total > 0 ? isPt ? `global: ${audit.byScope.global} · projeto: ${audit.byScope.project}${audit.unmigratedStores > 0 ? ` · ${audit.unmigratedStores} store(s) p/ migrar` : ""}` : `global: ${audit.byScope.global} · project: ${audit.byScope.project}${audit.unmigratedStores > 0 ? ` · ${audit.unmigratedStores} store(s) to migrate` : ""}` : isPt ? "verifica hooks V1, bancos não migrados e cópias redundantes" : "checks V1 hooks, unmigrated stores & redundant plugin copies" + value: input.legacyScanning ? isPt ? "escaneando…" : "scanning…" : audit === void 0 || audit === null ? isPt ? "não escaneado" : "not scanned" : audit.total === 0 ? isPt ? "limpo (0 obsoletos)" : "clean (0 obsolete)" : isPt ? `${audit.total} item(ns) (${formatBytes(audit.totalBytes)})` : `${audit.total} item(s) (${formatBytes(audit.totalBytes)})`, + note: input.legacyNotice ? input.legacyNotice : audit && audit.total > 0 ? isPt ? `global: ${audit.byScope.global} · projeto: ${audit.byScope.project}${audit.unmigratedStores > 0 ? ` · ${audit.unmigratedStores} store(s) p/ migrar` : ""}` : `global: ${audit.byScope.global} · project: ${audit.byScope.project}${audit.unmigratedStores > 0 ? ` · ${audit.unmigratedStores} store(s) to migrate` : ""}` : isPt ? "verifica caches npm antigos, hooks V1, bancos e cópias redundantes" : "checks stale npm caches, V1 hooks, unmigrated stores & copied files" }, { id: "legacy.scan", name: isPt ? "Escanear obsoletos" : "Scan legacy & drift", value: input.legacyScanning ? isPt ? "escaneando…" : "scanning…" : isPt ? "escanear agora" : "scan global + project", action: "legacy-scan", - note: isPt ? "enter escaneia sem modificar ou apagar nenhum arquivo" : "enter scans read-only without deleting anything" + note: isPt ? "enter verifica global, projeto e cache npm sem apagar nada" : "enter scans global, project & npm cache read-only" }, { id: "legacy.clean", name: isPt ? "Migrar & limpar" : "Migrate & clean obsolete", - value: input.legacyCleaning ? isPt ? "limpando…" : "cleaning…" : audit && audit.total > 0 ? isPt ? `remover ${audit.total} (${formatBytes(audit.totalBytes)})` : `remove ${audit.total} (${formatBytes(audit.totalBytes)})` : isPt ? "nada para remover" : "nothing to remove", + value: input.legacyCleaning ? isPt ? "limpando…" : "cleaning…" : audit && audit.total > 0 ? isPt ? `limpar ${audit.total} (${formatBytes(audit.totalBytes)})` : `remove ${audit.total} (${formatBytes(audit.totalBytes)})` : isPt ? "nada a remover" : "nothing to remove", action: "legacy-clean", - note: isPt ? "migra memória/contexto/goals antes e preserva agentes/skills custom" : "migrates memory/context/goals first · preserves custom agents/skills" + note: isPt ? "migra memória/contexto/goals antes; preserva agentes/skills custom" : "migrates memory/context/goals first · preserves custom agents/skills" } ]; return { @@ -2954,7 +4998,7 @@ async function readChangelogForBundle(bundleUrl) { } /** The ambient build-time version, or null outside a tsdown build. */ function embeddedVersion() { - return "2.2.0-beta.11"; + return "2.2.0"; } /** * Resolve the running Pantheon version for the what's-new window: the plugin @@ -3196,9 +5240,9 @@ function persistUpdateCheckState(previous, latest) { } catch {} } function resolveRunningVersion() { - return "2.2.0-beta.11"; + return "2.2.0"; } -const VALUE_WIDTH = 30; +const VALUE_WIDTH = 32; function SettingsWindow(props) { const isPt = () => resolveLanguage(tuiPrefs().layout?.language) === "pt-BR"; const formatValueDisplay = (val) => { @@ -3232,8 +5276,9 @@ function SettingsWindow(props) { insertNode(_el$, _el$10); spread(_el$, mergeProps(() => props.boxRef !== void 0 ? { ref: props.boxRef } : {}, { "focusable": true, - "flexDirection": "column" - }, () => props.height !== void 0 ? { height: props.height } : { + "flexDirection": "column", + "width": "100%" + }, () => props.isDialog ? { minWidth: 80 } : {}, () => props.height !== void 0 ? { height: props.height } : { flexGrow: 1, flexBasis: 0 }, { @@ -3270,7 +5315,8 @@ function SettingsWindow(props) { setProp(_el$8, "flexDirection", "row"); setProp(_el$8, "flexWrap", "wrap"); setProp(_el$8, "flexGrow", 1); - setProp(_el$8, "flexShrink", 0); + setProp(_el$8, "flexShrink", 1); + setProp(_el$8, "minWidth", 0); setProp(_el$8, "columnGap", 1); setProp(_el$8, "rowGap", 1); insert(_el$8, createComponent(For, { @@ -3343,41 +5389,54 @@ function SettingsWindow(props) { const gutter = () => isSelected() ? "▸ " : " "; const valueCell = () => { const formatted = formatValueDisplay(display()); - if (row.cycle !== void 0) return `< ${formatted} >`; - if (row.action !== void 0) return `[ ${formatted} ]`; - if (row.id.startsWith("autonomy.gradient.")) return `[ref] ${formatted}`; - return formatted; + const raw = row.cycle !== void 0 ? `< ${formatted} >` : row.action !== void 0 ? `[ ${formatted} ]` : row.id.startsWith("autonomy.gradient.") ? `[ref] ${formatted}` : formatted; + const maxLen = VALUE_WIDTH - (staged() ? 2 : 0); + return raw.length > maxLen ? `${raw.slice(0, maxLen - 1)}…` : raw; }; return (() => { - var _el$31 = createElement("box"), _el$32 = createElement("box"), _el$33 = createElement("text"); + var _el$31 = createElement("box"), _el$32 = createElement("box"), _el$33 = createElement("text"), _el$34 = createElement("box"); insertNode(_el$31, _el$32); + insertNode(_el$31, _el$34); setProp(_el$31, "flexDirection", "row"); spread(_el$31, mergeProps(() => isSelected() ? { backgroundColor: "#262626" } : {}, { "onMouseDown": () => { props.onSelectRow?.(row.id); } }), true); insertNode(_el$32, _el$33); setProp(_el$32, "width", 26); + setProp(_el$32, "flexShrink", 0); + setProp(_el$33, "wrapMode", "none"); spread(_el$33, mergeProps({ get fg() { return memo(() => !!isSelected())() ? props.warn ?? "#fba970" : props.fg; } }, () => isSelected() ? { attributes: 1 } : {}), true); insert(_el$33, () => `${gutter()}${row.name}`.padEnd(26)); + setProp(_el$34, "width", 2); + setProp(_el$34, "flexShrink", 0); insert(_el$31, createComponent(Show, { get when() { return memo(() => row.value !== "")() && row.value !== void 0; }, get children() { - var _el$34 = createElement("box"), _el$35 = createElement("text"); - insertNode(_el$34, _el$35); - setProp(_el$34, "width", 30); - setProp(_el$34, "onMouseDown", () => { - props.onSelectRow?.(row.id); - props.onCycleValue?.(row.id, 1); - }); - spread(_el$35, mergeProps({ get fg() { - return memo(() => !!isSelected())() ? "#ffffff" : memo(() => !!staged())() ? props.warn ?? props.fg : props.muted; - } }, () => isSelected() || staged() ? { attributes: 1 } : {}), true); - insert(_el$35, () => `${valueCell()}${staged() ? " ●" : ""}`.padEnd(VALUE_WIDTH)); - return _el$34; + return [(() => { + var _el$35 = createElement("box"), _el$36 = createElement("text"); + insertNode(_el$35, _el$36); + setProp(_el$35, "width", 32); + setProp(_el$35, "flexShrink", 0); + setProp(_el$35, "onMouseDown", () => { + props.onSelectRow?.(row.id); + props.onCycleValue?.(row.id, 1); + }); + setProp(_el$36, "wrapMode", "none"); + spread(_el$36, mergeProps({ get fg() { + return memo(() => !!isSelected())() ? "#ffffff" : memo(() => !!staged())() ? props.warn ?? props.fg : props.muted; + } }, () => isSelected() || staged() ? { attributes: 1 } : {}), true); + insert(_el$36, () => `${valueCell()}${staged() ? " ●" : ""}`.padEnd(VALUE_WIDTH)); + return _el$35; + })(), (() => { + var _el$37 = createElement("box"); + setProp(_el$37, "width", 2); + setProp(_el$37, "flexShrink", 0); + return _el$37; + })()]; } }), null); insert(_el$31, createComponent(Show, { @@ -3385,13 +5444,13 @@ function SettingsWindow(props) { return row.note !== void 0; }, get children() { - var _el$36 = createElement("box"), _el$37 = createElement("text"); - insertNode(_el$36, _el$37); - setProp(_el$36, "flexGrow", 1); - setProp(_el$36, "flexShrink", 1); - insert(_el$37, () => row.note); - effect((_$p) => setProp(_el$37, "fg", isSelected() ? "#e5e7eb" : props.muted, _$p)); - return _el$36; + var _el$38 = createElement("box"), _el$39 = createElement("text"); + insertNode(_el$38, _el$39); + setProp(_el$38, "flexGrow", 1); + setProp(_el$38, "flexShrink", 1); + insert(_el$39, () => row.note); + effect((_$p) => setProp(_el$39, "fg", isSelected() ? "#e5e7eb" : props.muted, _$p)); + return _el$38; } }), null); return _el$31; @@ -3421,113 +5480,113 @@ function SettingsWindow(props) { }, get fallback() { return (() => { - var _el$38 = createElement("box"), _el$52 = createElement("text"); - insertNode(_el$38, _el$52); - setProp(_el$38, "flexDirection", "column"); - insert(_el$38, createComponent(Show, { + var _el$40 = createElement("box"), _el$54 = createElement("text"); + insertNode(_el$40, _el$54); + setProp(_el$40, "flexDirection", "column"); + insert(_el$40, createComponent(Show, { get when() { return draftDirty(props.draft()); }, get fallback() { return (() => { - var _el$53 = createElement("box"), _el$54 = createElement("box"), _el$55 = createElement("text"), _el$57 = createElement("text"), _el$59 = createElement("box"), _el$60 = createElement("text"), _el$62 = createElement("text"), _el$64 = createElement("box"), _el$65 = createElement("text"), _el$67 = createElement("box"), _el$68 = createElement("text"); - insertNode(_el$53, _el$54); - insertNode(_el$53, _el$57); - insertNode(_el$53, _el$59); - insertNode(_el$53, _el$62); - insertNode(_el$53, _el$64); - insertNode(_el$53, _el$67); - insertNode(_el$53, _el$68); - setProp(_el$53, "flexDirection", "row"); - setProp(_el$53, "flexWrap", "wrap"); - setProp(_el$53, "alignItems", "center"); - setProp(_el$53, "flexShrink", 0); - setProp(_el$53, "rowGap", 1); - insertNode(_el$54, _el$55); - setProp(_el$54, "backgroundColor", "#262626"); - setProp(_el$54, "flexShrink", 0); - setProp(_el$54, "onMouseDown", () => props.onClose?.()); - insertNode(_el$55, createTextNode(` Close `)); - setProp(_el$55, "fg", "#ffffff"); - insertNode(_el$57, createTextNode(` `)); - setProp(_el$57, "flexShrink", 0); - insertNode(_el$59, _el$60); - setProp(_el$59, "backgroundColor", "#262626"); + var _el$55 = createElement("box"), _el$56 = createElement("box"), _el$57 = createElement("text"), _el$59 = createElement("text"), _el$61 = createElement("box"), _el$62 = createElement("text"), _el$64 = createElement("text"), _el$66 = createElement("box"), _el$67 = createElement("text"), _el$69 = createElement("box"), _el$70 = createElement("text"); + insertNode(_el$55, _el$56); + insertNode(_el$55, _el$59); + insertNode(_el$55, _el$61); + insertNode(_el$55, _el$64); + insertNode(_el$55, _el$66); + insertNode(_el$55, _el$69); + insertNode(_el$55, _el$70); + setProp(_el$55, "flexDirection", "row"); + setProp(_el$55, "flexWrap", "wrap"); + setProp(_el$55, "alignItems", "center"); + setProp(_el$55, "flexShrink", 0); + setProp(_el$55, "rowGap", 1); + insertNode(_el$56, _el$57); + setProp(_el$56, "backgroundColor", "#262626"); + setProp(_el$56, "flexShrink", 0); + setProp(_el$56, "onMouseDown", () => props.onClose?.()); + insertNode(_el$57, createTextNode(` Close `)); + setProp(_el$57, "fg", "#ffffff"); + insertNode(_el$59, createTextNode(` `)); setProp(_el$59, "flexShrink", 0); - setProp(_el$59, "onMouseDown", () => props.onResetPage?.()); - insertNode(_el$60, createTextNode(` Reset page `)); - setProp(_el$60, "fg", "#ffffff"); - insertNode(_el$62, createTextNode(` `)); - setProp(_el$62, "flexShrink", 0); - insertNode(_el$64, _el$65); - setProp(_el$64, "backgroundColor", "#262626"); + insertNode(_el$61, _el$62); + setProp(_el$61, "backgroundColor", "#262626"); + setProp(_el$61, "flexShrink", 0); + setProp(_el$61, "onMouseDown", () => props.onResetPage?.()); + insertNode(_el$62, createTextNode(` Reset page `)); + setProp(_el$62, "fg", "#ffffff"); + insertNode(_el$64, createTextNode(` `)); setProp(_el$64, "flexShrink", 0); - setProp(_el$64, "onMouseDown", () => props.onStageDefaults?.()); - insertNode(_el$65, createTextNode(` Defaults `)); - setProp(_el$65, "fg", "#ffffff"); - setProp(_el$67, "flexGrow", 1); - setProp(_el$67, "minWidth", 1); - setProp(_el$68, "flexShrink", 0); - insert(_el$68, () => isPt() ? "sem alterações pendentes" : "no staged changes"); + insertNode(_el$66, _el$67); + setProp(_el$66, "backgroundColor", "#262626"); + setProp(_el$66, "flexShrink", 0); + setProp(_el$66, "onMouseDown", () => props.onStageDefaults?.()); + insertNode(_el$67, createTextNode(` Defaults `)); + setProp(_el$67, "fg", "#ffffff"); + setProp(_el$69, "flexGrow", 1); + setProp(_el$69, "minWidth", 1); + setProp(_el$70, "flexShrink", 0); + insert(_el$70, () => isPt() ? "sem alterações pendentes" : "no staged changes"); effect((_p$) => { var _v$11 = props.muted, _v$12 = props.muted, _v$13 = props.muted; - _v$11 !== _p$.e && (_p$.e = setProp(_el$57, "fg", _v$11, _p$.e)); - _v$12 !== _p$.t && (_p$.t = setProp(_el$62, "fg", _v$12, _p$.t)); - _v$13 !== _p$.a && (_p$.a = setProp(_el$68, "fg", _v$13, _p$.a)); + _v$11 !== _p$.e && (_p$.e = setProp(_el$59, "fg", _v$11, _p$.e)); + _v$12 !== _p$.t && (_p$.t = setProp(_el$64, "fg", _v$12, _p$.t)); + _v$13 !== _p$.a && (_p$.a = setProp(_el$70, "fg", _v$13, _p$.a)); return _p$; }, { e: void 0, t: void 0, a: void 0 }); - return _el$53; + return _el$55; })(); }, get children() { - var _el$39 = createElement("box"), _el$40 = createElement("box"), _el$41 = createElement("text"), _el$42 = createElement("text"), _el$44 = createElement("box"), _el$45 = createElement("text"), _el$46 = createElement("text"), _el$48 = createElement("box"), _el$49 = createElement("text"), _el$50 = createElement("box"), _el$51 = createElement("text"); - insertNode(_el$39, _el$40); - insertNode(_el$39, _el$42); - insertNode(_el$39, _el$44); - insertNode(_el$39, _el$46); - insertNode(_el$39, _el$48); - insertNode(_el$39, _el$50); - insertNode(_el$39, _el$51); - setProp(_el$39, "flexDirection", "row"); - setProp(_el$39, "flexWrap", "wrap"); - setProp(_el$39, "alignItems", "center"); - setProp(_el$39, "flexShrink", 0); - setProp(_el$39, "rowGap", 1); - insertNode(_el$40, _el$41); - setProp(_el$40, "flexShrink", 0); - setProp(_el$40, "onMouseDown", () => props.onSave?.()); - setProp(_el$41, "fg", "#000000"); - insert(_el$41, () => isPt() ? " Salvar " : " Save "); - insertNode(_el$42, createTextNode(` `)); + var _el$41 = createElement("box"), _el$42 = createElement("box"), _el$43 = createElement("text"), _el$44 = createElement("text"), _el$46 = createElement("box"), _el$47 = createElement("text"), _el$48 = createElement("text"), _el$50 = createElement("box"), _el$51 = createElement("text"), _el$52 = createElement("box"), _el$53 = createElement("text"); + insertNode(_el$41, _el$42); + insertNode(_el$41, _el$44); + insertNode(_el$41, _el$46); + insertNode(_el$41, _el$48); + insertNode(_el$41, _el$50); + insertNode(_el$41, _el$52); + insertNode(_el$41, _el$53); + setProp(_el$41, "flexDirection", "row"); + setProp(_el$41, "flexWrap", "wrap"); + setProp(_el$41, "alignItems", "center"); + setProp(_el$41, "flexShrink", 0); + setProp(_el$41, "rowGap", 1); + insertNode(_el$42, _el$43); setProp(_el$42, "flexShrink", 0); - insertNode(_el$44, _el$45); - setProp(_el$44, "backgroundColor", "#262626"); + setProp(_el$42, "onMouseDown", () => props.onSave?.()); + setProp(_el$43, "fg", "#000000"); + insert(_el$43, () => isPt() ? " Salvar " : " Save "); + insertNode(_el$44, createTextNode(` `)); setProp(_el$44, "flexShrink", 0); - setProp(_el$44, "onMouseDown", () => props.onDiscard?.()); - setProp(_el$45, "fg", "#ffffff"); - insert(_el$45, () => isPt() ? " Descartar " : " Discard "); - insertNode(_el$46, createTextNode(` `)); + insertNode(_el$46, _el$47); + setProp(_el$46, "backgroundColor", "#262626"); setProp(_el$46, "flexShrink", 0); - insertNode(_el$48, _el$49); - setProp(_el$48, "backgroundColor", "#262626"); + setProp(_el$46, "onMouseDown", () => props.onDiscard?.()); + setProp(_el$47, "fg", "#ffffff"); + insert(_el$47, () => isPt() ? " Descartar " : " Discard "); + insertNode(_el$48, createTextNode(` `)); setProp(_el$48, "flexShrink", 0); - setProp(_el$48, "onMouseDown", () => props.onResetPage?.()); - setProp(_el$49, "fg", "#ffffff"); - insert(_el$49, () => isPt() ? " Redefinir página " : " Reset page "); - setProp(_el$50, "flexGrow", 1); - setProp(_el$50, "minWidth", 1); - setProp(_el$51, "flexShrink", 0); - insert(_el$51, () => isPt() ? "alterações não salvas" : "unsaved changes"); + insertNode(_el$50, _el$51); + setProp(_el$50, "backgroundColor", "#262626"); + setProp(_el$50, "flexShrink", 0); + setProp(_el$50, "onMouseDown", () => props.onResetPage?.()); + setProp(_el$51, "fg", "#ffffff"); + insert(_el$51, () => isPt() ? " Redefinir página " : " Reset page "); + setProp(_el$52, "flexGrow", 1); + setProp(_el$52, "minWidth", 1); + setProp(_el$53, "flexShrink", 0); + insert(_el$53, () => isPt() ? "alterações não salvas" : "unsaved changes"); effect((_p$) => { var _v$9 = props.warn ?? "#fba970", _v$0 = props.muted, _v$1 = props.muted, _v$10 = props.warn ?? "#f59e0b"; - _v$9 !== _p$.e && (_p$.e = setProp(_el$40, "backgroundColor", _v$9, _p$.e)); - _v$0 !== _p$.t && (_p$.t = setProp(_el$42, "fg", _v$0, _p$.t)); - _v$1 !== _p$.a && (_p$.a = setProp(_el$46, "fg", _v$1, _p$.a)); - _v$10 !== _p$.o && (_p$.o = setProp(_el$51, "fg", _v$10, _p$.o)); + _v$9 !== _p$.e && (_p$.e = setProp(_el$42, "backgroundColor", _v$9, _p$.e)); + _v$0 !== _p$.t && (_p$.t = setProp(_el$44, "fg", _v$0, _p$.t)); + _v$1 !== _p$.a && (_p$.a = setProp(_el$48, "fg", _v$1, _p$.a)); + _v$10 !== _p$.o && (_p$.o = setProp(_el$53, "fg", _v$10, _p$.o)); return _p$; }, { e: void 0, @@ -3535,17 +5594,17 @@ function SettingsWindow(props) { a: void 0, o: void 0 }); - return _el$39; + return _el$41; } - }), _el$52); - insert(_el$52, () => { + }), _el$54); + insert(_el$54, () => { const currentRow = findRow(tab(), props.selectedId() ?? ""); if (currentRow?.cycle !== void 0) return isPt() ? "clique ou ›/←/→ alterar · ↑↓ selecionar · tab próxima aba · ctrl+s salvar · ctrl+r redefinir · esc fechar" : "click or ›/←/→ change · ↑↓ select · tab next tab · ctrl+s save · ctrl+r reset page · esc close"; if (currentRow?.action !== void 0) return isPt() ? "enter ou espaço executar · ↑↓ selecionar · tab próxima aba · ctrl+s salvar · ctrl+r redefinir · esc fechar" : "enter or space run action · ↑↓ select · tab next tab · ctrl+s save · ctrl+r reset page · esc close"; return isPt() ? "[ref] política de referência (somente leitura) · ↑↓ selecionar · tab próxima aba · esc fechar" : "[ref] documented reference (read-only) · ↑↓ select · tab next tab · esc close"; }); - effect((_$p) => setProp(_el$52, "fg", props.muted, _$p)); - return _el$38; + effect((_$p) => setProp(_el$54, "fg", props.muted, _$p)); + return _el$40; })(); }, get children() { @@ -3612,6 +5671,7 @@ function SettingsWindow(props) { })(); } let pageApi; +let pendingInitialTabId; function createWindowController(context, exit) { const currentVersion = resolveRunningVersion(); const workspaceDir = resolveWorkspaceDir(context); @@ -3637,11 +5697,19 @@ function createWindowController(context, exit) { const [draft, setDraft] = createSignal({}); const [notice, setNotice] = createSignal(void 0); const [confirmExit, setConfirmExit] = createSignal(false); + const activeBundlePath = (() => { + try { + return fileURLToPath(import.meta.url); + } catch { + return; + } + })(); queueMicrotask(() => { try { const scan = scanLegacyArtifacts({ workspaceDir, - runningVersion: currentVersion + runningVersion: currentVersion, + ...activeBundlePath ? { activeBundlePath } : {} }); setLegacyAudit(scan.summary); } catch {} @@ -3703,7 +5771,6 @@ function createWindowController(context, exit) { buildGatesTab(load(), lang, activeScope), buildDecisionTab(decision(), process.env, readAuthProviders(), readConfigProviders(), lang), buildPresetTab(presetInput(), lang), - buildQuotaTab(void 0, lang, readQuotaPrefs()), buildTuiTab(tuiPrefs(), lang), buildAutonomyTab({ goalLoop: goalLoop(), @@ -3732,6 +5799,12 @@ function createWindowController(context, exit) { }) ]; }; + if (pendingInitialTabId !== void 0) { + const requestedTab = pendingInitialTabId; + pendingInitialTabId = void 0; + const targetIdx = tabs().findIndex((tab) => tab.id === requestedTab); + if (targetIdx >= 0) setPage(targetIdx); + } const rows = () => tabRows(tabs()[page()] ?? tabs()[0] ?? EMPTY_TAB); const move = (delta) => { if (confirmExit()) setConfirmExit(false); @@ -3837,7 +5910,8 @@ function createWindowController(context, exit) { try { const scan = scanLegacyArtifacts({ workspaceDir, - runningVersion: currentVersion + runningVersion: currentVersion, + ...activeBundlePath ? { activeBundlePath } : {} }); setLegacyAudit(scan.summary); const isPt = resolveLanguage(tuiPrefs().layout?.language) === "pt-BR"; @@ -3853,14 +5927,13 @@ function createWindowController(context, exit) { setLegacyCleaning(true); const isPt = resolveLanguage(tuiPrefs().layout?.language) === "pt-BR"; try { - const res = cleanLegacyArtifacts({ - workspaceDir, - runningVersion: currentVersion - }); - const after = scanLegacyArtifacts({ + const auditOpts = { workspaceDir, - runningVersion: currentVersion - }); + runningVersion: currentVersion, + ...activeBundlePath ? { activeBundlePath } : {} + }; + const res = cleanLegacyArtifacts(auditOpts); + const after = scanLegacyArtifacts(auditOpts); setLegacyAudit(after.summary); setLoad(readOverridesLoad(workspaceDir)); const summaryMsg = isPt ? `limpos ${res.removed.length} item(ns) (${formatBytes(res.reclaimedBytes)}), ${res.migratedRecords} registro(s) migrado(s)` : `removed ${res.removed.length} item(s) (${formatBytes(res.reclaimedBytes)}), ${res.migratedRecords} record(s) migrated`; @@ -4072,15 +6145,6 @@ function createWindowController(context, exit) { reason: "tui prefs storage unavailable" }; } - if (id.startsWith("quota.")) try { - writeQuotaPrefs(applyQuotaRow(readQuotaPrefs(), id, value)); - return { ok: true }; - } catch { - return { - ok: false, - reason: "quota prefs disk write failed" - }; - } return { ok: false, reason: "unknown staged row" @@ -4298,27 +6362,27 @@ function SettingsPage(props) { return window(); }, get children() { - var _el$69 = createElement("box"), _el$70 = createElement("box"), _el$71 = createElement("box"); - insertNode(_el$69, _el$70); - insertNode(_el$69, _el$71); - setProp(_el$69, "flexDirection", "row"); - setProp(_el$69, "flexGrow", 1); - setProp(_el$69, "flexBasis", 0); - setProp(_el$69, "minHeight", 0); - setProp(_el$69, "width", "100%"); - setProp(_el$70, "flexDirection", "column"); - setProp(_el$70, "flexGrow", 1); - setProp(_el$70, "flexBasis", 0); - setProp(_el$70, "minHeight", 0); - setProp(_el$70, "minWidth", 0); - insert(_el$70, window); - setProp(_el$71, "width", 32); - setProp(_el$71, "flexShrink", 0); - setProp(_el$71, "border", true); - setProp(_el$71, "borderStyle", "single"); - insert(_el$71, sidebar); - effect((_$p) => setProp(_el$71, "borderColor", theme.muted ?? "#333333", _$p)); - return _el$69; + var _el$71 = createElement("box"), _el$72 = createElement("box"), _el$73 = createElement("box"); + insertNode(_el$71, _el$72); + insertNode(_el$71, _el$73); + setProp(_el$71, "flexDirection", "row"); + setProp(_el$71, "flexGrow", 1); + setProp(_el$71, "flexBasis", 0); + setProp(_el$71, "minHeight", 0); + setProp(_el$71, "width", "100%"); + setProp(_el$72, "flexDirection", "column"); + setProp(_el$72, "flexGrow", 1); + setProp(_el$72, "flexBasis", 0); + setProp(_el$72, "minHeight", 0); + setProp(_el$72, "minWidth", 0); + insert(_el$72, window); + setProp(_el$73, "width", 32); + setProp(_el$73, "flexShrink", 0); + setProp(_el$73, "border", true); + setProp(_el$73, "borderStyle", "single"); + insert(_el$73, sidebar); + effect((_$p) => setProp(_el$73, "borderColor", theme.muted ?? "#333333", _$p)); + return _el$71; } }); } @@ -4352,7 +6416,7 @@ function openSettingsDialog(context) { setDialogOpen(true); pageApi = controller.api; const rendererHeight = () => context.renderer?.height ?? 30; - const maxHeight = () => Math.min(16, Math.max(8, Math.floor(rendererHeight() * .55))); + const maxHeight = () => Math.min(28, Math.max(14, Math.floor(rendererHeight() * .78))); try { context.ui.dialog.show(() => createComponent(SettingsWindow, { get version() { @@ -4400,7 +6464,7 @@ function openSettingsDialog(context) { onCancelExit: () => controller.api.cancelExit?.() }), close); context.ui.dialog.set({ - size: "medium", + size: "large", centered: true }); } catch {} @@ -4649,7 +6713,7 @@ function setupPantheonSettings(context, options) { { id: "pantheon.settings.next.tab", title: "Next settings tab", - bind: "tab", + bind: "tab,]", run: () => { pageApi?.nextTab(); } @@ -4657,7 +6721,7 @@ function setupPantheonSettings(context, options) { { id: "pantheon.settings.prev.tab", title: "Previous settings tab", - bind: "shift+tab", + bind: "shift+tab,[", run: () => { pageApi?.prevTab?.(); } @@ -4712,10 +6776,12 @@ function setupPantheonSettings(context, options) { })); } catch {} } -async function openPantheonSettings(context) { +async function openPantheonSettings(context, options = {}) { + if (options.initialTab) pendingInitialTabId = options.initialTab; + const sessionID = context?.sessionID ?? routeSessionID(context) ?? activeSessionId(); try { const viewMode = tuiPrefs().layout?.settingsView ?? "docked"; - if (viewMode === "fullscreen" && routerAvailable && context.ui?.router?.navigate) { + if (viewMode !== "dialog" && (viewMode === "fullscreen" || !sessionID) && routerAvailable && context.ui?.router?.navigate) { let returnRoute; try { const current = context.ui.router.current(); @@ -4735,17 +6801,30 @@ async function openPantheonSettings(context) { return; } } catch {} - if (!(context?.sessionID ?? routeSessionID(context) ?? activeSessionId())) { - try { - context.ui?.toast?.show?.({ - variant: "info", - title: "Pantheon", - message: "Open a session first: Pantheon settings opens above the prompt box." - }); - } catch {} + if (!sessionID) { + openSettingsDialog(context); return; } if (settingsOpen()) { + if (options.initialTab && pageApi) { + const targetIdx = [ + "gates", + "decision", + "preset", + "tui", + "autonomy", + "j1", + "updates", + "changelog", + "doctor", + "about" + ].indexOf(options.initialTab); + if (targetIdx >= 0) { + pendingInitialTabId = void 0; + pageApi.jumpTab(targetIdx); + return; + } + } closePantheonSettings(); return; } @@ -5032,9 +7111,9 @@ function paginateWhatsNewLines(lines, pageSize = 14) { * (both host-initiated and local close binds) must funnel into marking seen. */ async function openWhatsNew(input) { - const { version, statePath, changelogText, show } = input; + const { version, statePath, changelogText, show, force = false } = input; if (typeof version !== "string" || version.trim() === "") return false; - if (!await shouldShowWhatsNew(version, statePath)) return false; + if (!force && !await shouldShowWhatsNew(version, statePath)) return false; const lines = whatsNewLines(changelogText ? extractHighlights(changelogText, version) : { ...EMPTY_HIGHLIGHTS }); if (lines.length === 0) return false; const pages = paginateWhatsNewLines(lines); @@ -5084,6 +7163,7 @@ async function openWhatsNew(input) { */ /** Window body: title, rule, the current page (wrapped), footer action bar with OK button. */ function WhatsNewContent(props) { + const isPt = () => props.isPt ?? resolveLanguage(tuiPrefs().layout?.language) === "pt-BR"; const rows = () => { const current = props.data.pages[Math.min(props.page(), props.pageCount() - 1)] ?? []; const wrapped = []; @@ -5091,7 +7171,7 @@ function WhatsNewContent(props) { return wrapped; }; return (() => { - var _el$ = createElement("box"), _el$2 = createElement("box"), _el$3 = createElement("box"), _el$4 = createElement("box"), _el$5 = createElement("text"), _el$7 = createElement("text"), _el$8 = createElement("box"), _el$9 = createElement("text"), _el$1 = createElement("box"), _el$10 = createElement("text"), _el$12 = createElement("box"), _el$13 = createElement("box"), _el$14 = createElement("text"), _el$16 = createElement("box"), _el$17 = createElement("box"), _el$25 = createElement("text"), _el$27 = createElement("box"), _el$28 = createElement("text"); + var _el$ = createElement("box"), _el$2 = createElement("box"), _el$3 = createElement("box"), _el$4 = createElement("box"), _el$5 = createElement("text"), _el$7 = createElement("text"), _el$8 = createElement("box"), _el$9 = createElement("text"), _el$1 = createElement("box"), _el$10 = createElement("text"), _el$12 = createElement("box"), _el$13 = createElement("box"), _el$14 = createElement("text"), _el$16 = createElement("box"), _el$17 = createElement("box"), _el$23 = createElement("text"), _el$24 = createElement("box"), _el$25 = createElement("text"); insertNode(_el$, _el$2); insertNode(_el$, _el$1); insertNode(_el$, _el$12); @@ -5116,14 +7196,19 @@ function WhatsNewContent(props) { setProp(_el$4, "paddingLeft", 1); setProp(_el$4, "paddingRight", 1); setProp(_el$4, "marginRight", 1); + setProp(_el$4, "flexShrink", 0); insertNode(_el$5, createTextNode(`NOVIDADES`)); setProp(_el$5, "fg", "#000000"); setProp(_el$5, "attributes", 1); + setProp(_el$5, "wrapMode", "none"); setProp(_el$7, "attributes", 1); + setProp(_el$7, "wrapMode", "none"); insert(_el$7, () => props.data.title); insertNode(_el$8, _el$9); + setProp(_el$8, "flexShrink", 0); setProp(_el$8, "onMouseDown", () => props.onClose?.()); insertNode(_el$9, createTextNode(`[ Esc / Q ]`)); + setProp(_el$9, "wrapMode", "none"); insertNode(_el$1, _el$10); setProp(_el$1, "flexDirection", "row"); setProp(_el$1, "height", 1); @@ -5139,12 +7224,12 @@ function WhatsNewContent(props) { children: (line) => { const isBullet = line.startsWith("• "); return (() => { - var _el$30 = createElement("text"); - spread(_el$30, mergeProps({ get fg() { + var _el$26 = createElement("text"); + spread(_el$26, mergeProps({ get fg() { return isBullet ? props.fg : props.muted; } }, isBullet ? { attributes: 1 } : {}), true); - insert(_el$30, line); - return _el$30; + insert(_el$26, line); + return _el$26; })(); } })); @@ -5154,12 +7239,12 @@ function WhatsNewContent(props) { setProp(_el$13, "marginTop", 1); insertNode(_el$14, createTextNode(`────────────────────────────────────────────────────────────────────────`)); insertNode(_el$16, _el$17); - insertNode(_el$16, _el$27); + insertNode(_el$16, _el$24); setProp(_el$16, "flexDirection", "row"); setProp(_el$16, "alignItems", "center"); setProp(_el$16, "justifyContent", "space-between"); setProp(_el$16, "marginTop", 1); - insertNode(_el$17, _el$25); + insertNode(_el$17, _el$23); setProp(_el$17, "flexDirection", "row"); setProp(_el$17, "alignItems", "center"); insert(_el$17, createComponent(Show, { @@ -5176,40 +7261,40 @@ function WhatsNewContent(props) { setProp(_el$18, "paddingRight", 1); setProp(_el$18, "marginRight", 1); setProp(_el$18, "onMouseDown", () => props.onPrev?.()); - insertNode(_el$19, createTextNode(`‹ Prev`)); setProp(_el$19, "fg", "#ffffff"); + insert(_el$19, () => isPt() ? "‹ Anterior" : "‹ Prev"); return _el$18; })(), (() => { - var _el$21 = createElement("text"); - setProp(_el$21, "marginRight", 1); - insert(_el$21, () => `${props.page() + 1} / ${props.pageCount()}`); - effect((_$p) => setProp(_el$21, "fg", props.muted, _$p)); - return _el$21; + var _el$20 = createElement("text"); + setProp(_el$20, "marginRight", 1); + insert(_el$20, () => `${props.page() + 1} / ${props.pageCount()}`); + effect((_$p) => setProp(_el$20, "fg", props.muted, _$p)); + return _el$20; })(), (() => { - var _el$22 = createElement("box"), _el$23 = createElement("text"); - insertNode(_el$22, _el$23); - setProp(_el$22, "backgroundColor", "#262626"); - setProp(_el$22, "paddingLeft", 1); - setProp(_el$22, "paddingRight", 1); - setProp(_el$22, "marginRight", 1); - setProp(_el$22, "onMouseDown", () => props.onNext?.()); - insertNode(_el$23, createTextNode(`Next ›`)); - setProp(_el$23, "fg", "#ffffff"); - return _el$22; + var _el$21 = createElement("box"), _el$22 = createElement("text"); + insertNode(_el$21, _el$22); + setProp(_el$21, "backgroundColor", "#262626"); + setProp(_el$21, "paddingLeft", 1); + setProp(_el$21, "paddingRight", 1); + setProp(_el$21, "marginRight", 1); + setProp(_el$21, "onMouseDown", () => props.onNext?.()); + setProp(_el$22, "fg", "#ffffff"); + insert(_el$22, () => isPt() ? "Próxima ›" : "Next ›"); + return _el$21; })() ]; } - }), _el$25); - insertNode(_el$25, createTextNode(`Enter / Esc / Q close`)); - insertNode(_el$27, _el$28); - setProp(_el$27, "paddingLeft", 2); - setProp(_el$27, "paddingRight", 2); - setProp(_el$27, "onMouseDown", () => props.onClose?.()); - insertNode(_el$28, createTextNode(`OK, Got it`)); - setProp(_el$28, "fg", "#000000"); - setProp(_el$28, "attributes", 1); + }), _el$23); + insert(_el$23, () => isPt() ? "Enter / Esc / Q fechar" : "Enter / Esc / Q close"); + insertNode(_el$24, _el$25); + setProp(_el$24, "paddingLeft", 2); + setProp(_el$24, "paddingRight", 2); + setProp(_el$24, "onMouseDown", () => props.onClose?.()); + setProp(_el$25, "fg", "#000000"); + setProp(_el$25, "attributes", 1); + insert(_el$25, () => isPt() ? "OK, Entendido" : "OK, Got it"); effect((_p$) => { var _v$ = props.warn ?? "#fba970", _v$2 = props.warn ?? "#fba970", _v$3 = props.fg, _v$4 = props.muted, _v$5 = props.muted, _v$6 = props.muted, _v$7 = props.muted, _v$8 = props.warn ?? "#fba970"; _v$ !== _p$.e && (_p$.e = setProp(_el$, "borderColor", _v$, _p$.e)); @@ -5218,8 +7303,8 @@ function WhatsNewContent(props) { _v$4 !== _p$.o && (_p$.o = setProp(_el$9, "fg", _v$4, _p$.o)); _v$5 !== _p$.i && (_p$.i = setProp(_el$10, "fg", _v$5, _p$.i)); _v$6 !== _p$.n && (_p$.n = setProp(_el$14, "fg", _v$6, _p$.n)); - _v$7 !== _p$.s && (_p$.s = setProp(_el$25, "fg", _v$7, _p$.s)); - _v$8 !== _p$.h && (_p$.h = setProp(_el$27, "backgroundColor", _v$8, _p$.h)); + _v$7 !== _p$.s && (_p$.s = setProp(_el$23, "fg", _v$7, _p$.s)); + _v$8 !== _p$.h && (_p$.h = setProp(_el$24, "backgroundColor", _v$8, _p$.h)); return _p$; }, { e: void 0, @@ -5236,9 +7321,10 @@ function WhatsNewContent(props) { } /** * Entry glue: resolve version + shipped CHANGELOG.md, then show the window -* through the host dialog stack once. Never throws. +* through the host dialog stack once (or on demand when `options.force` is set). +* Never throws. */ -async function maybeShowWhatsNew(context) { +async function maybeShowWhatsNew(context, options = {}) { try { const version = await resolveRunningVersion$1(import.meta.url); if (!version) return; @@ -5297,6 +7383,7 @@ async function maybeShowWhatsNew(context) { version, statePath, changelogText, + force: options.force === true, show: (render, onClose) => { const close = () => { setOpen(false); @@ -5329,6 +7416,10 @@ async function maybeShowWhatsNew(context) { onNext: () => setPage((current) => Math.min(current + 1, pageCount() - 1)), onPrev: () => setPage((current) => Math.max(current - 1, 0)) }), close); + context.ui.dialog.set({ + size: "large", + centered: true + }); } catch {} } }); @@ -5374,7 +7465,19 @@ const SIDEBAR_REFRESH_EVENTS = [ "session.moved", "session.idle", "session.status", - "session.deleted" + "session.deleted", + "session.execution.started", + "session.execution.succeeded", + "session.execution.failed", + "session.execution.interrupted", + "session.message.content.updated", + "session.tool.input.started", + "session.tool.called", + "session.tool.success", + "session.tool.failed", + "session.step.ended", + "session.usage.updated", + "session.permissions" ]; /** One `overrides.agents[]` entry from active-preset.json. */ /** The override map the CLI wrote into active-preset.json. */ @@ -5959,28 +8062,176 @@ function formatTokenAnatomySplit(anatomy) { think }; } -/** Conta chamadas de ferramentas e eventuais falhas/erros. Pure. */ -function countToolCalls(messages) { +const TOOL_DOMAIN_ORDER = [ + "mem", + "ctx", + "code", + "edit", + "read", + "shell", + "agent", + "mcp" +]; +function normalizeToolName(part) { + return (typeof part?.name === "string" ? part.name : typeof part?.tool === "string" ? part.tool : "").trim(); +} +/** Extrai chamadas `tools.(...)` de dentro do Code Mode (`execute` / `search`) +* para revelar a tool real do Pantheon/OpenCode usada. Pure. */ +function resolveEffectiveToolNames(part) { + const outer = normalizeToolName(part); + if (outer === "") return []; + if (outer.toLowerCase() === "execute") { + const code = part?.state?.input?.code; + if (typeof code === "string" && code !== "") { + const inner = []; + for (const match of code.matchAll(/\btools\.([a-zA-Z0-9_]+)\s*\(/g)) if (match[1]) inner.push(match[1]); + if (inner.length > 0) return inner; + } + } + return [outer]; +} +function extractToolFilePaths(part) { + const found = []; + const input = part?.state?.input && typeof part.state.input === "object" ? part.state.input : null; + if (!input) return found; + for (const candidate of [ + input.file, + input.path, + input.filePath, + input.target + ]) { + const base = fileBasename(candidate); + if (base && !found.includes(base)) found.push(base); + } + if (typeof input.code === "string" && input.code !== "") for (const match of input.code.matchAll(/\b(?:file|path|filePath|target)\s*:\s*["']([^"']+)["']/g)) { + const base = fileBasename(match[1]); + if (base && !found.includes(base)) found.push(base); + } + return found; +} +function isToolFailureState(state) { + return state?.status === "error" || state?.status === "failed" || state?.error !== void 0 || typeof state?.exitCode === "number" && state.exitCode !== 0; +} +function isToolActiveState(state) { + return state?.status === "running" || state?.status === "pending" || state?.status === "streaming"; +} +/** Classifica uma tool (nativa, OpenCode ou MCP externa) em domínio curto e +* verbo de 3–4 caracteres para Sidebar/Dispatch. Pure. */ +function classifyToolPart(rawName) { + const name = typeof rawName === "string" ? rawName.trim().toLowerCase() : ""; + if (name === "") return { + domain: "agent", + verb: "tool" + }; + if (name === "question") return { + domain: "agent", + verb: "ask" + }; + if (name.startsWith("memory_")) return { + domain: "mem", + verb: "mem" + }; + if (name.startsWith("context_") || name.startsWith("goal_") || name === "pantheon_step_ledger" || name === "todowrite" || name === "todoread") return { + domain: "ctx", + verb: name.startsWith("todo") ? "todo" : "ctx" + }; + if (name.startsWith("code_")) return { + domain: "code", + verb: "code" + }; + if (name === "hashline_edit" || name === "edit" || name === "edit_file" || name === "write" || name === "write_file" || name === "patch") return { + domain: "edit", + verb: "edit" + }; + if (name === "read" || name === "read_file" || name === "glob" || name === "grep" || name === "list") return { + domain: "read", + verb: "read" + }; + if (name === "shell" || name === "bash" || name === "run_command" || name === "execute") return { + domain: "shell", + verb: name === "execute" ? "exec" : "bash" + }; + if (name === "pantheon_deepwork") return { + domain: "agent", + verb: "plan" + }; + if (name === "subagent" || name.startsWith("pantheon_") || name === "vision" || name === "webfetch" || name === "websearch" || name === "search") return { + domain: "agent", + verb: name.startsWith("web") ? "web" : "agnt" + }; + if (name.includes("_") && !name.startsWith("pantheon_")) return { + domain: "mcp", + verb: "mcp" + }; + return { + domain: "agent", + verb: "tool" + }; +} +/** Resume chamadas de ferramentas por domínio nativo + tool em execução. Pure. */ +function summarizeToolDomains(messages) { + const byDomain = {}; if (!Array.isArray(messages)) return { total: 0, - failures: 0 + failures: 0, + byDomain, + activeTool: null }; let total = 0; let failures = 0; + let activeTool = null; for (const message of messages) { if (message?.type !== "assistant" || !Array.isArray(message.content)) continue; for (const part of message.content) { if (part?.type !== "tool") continue; total++; const state = part.state; - if (state?.status === "error" || state?.status === "failed" || state?.error !== void 0 || typeof state?.exitCode === "number" && state.exitCode !== 0) failures++; + if (isToolFailureState(state)) failures++; + const effectiveNames = resolveEffectiveToolNames(part); + for (const toolName of effectiveNames) { + const { domain } = classifyToolPart(toolName); + byDomain[domain] = (byDomain[domain] ?? 0) + 1; + } + if (isToolActiveState(state) && effectiveNames.length > 0) activeTool = effectiveNames[effectiveNames.length - 1] ?? null; } } + return { + total, + failures, + byDomain, + activeTool + }; +} +/** Conta chamadas de ferramentas e eventuais falhas/erros. Pure. */ +function countToolCalls(messages) { + const { total, failures } = summarizeToolDomains(messages); return { total, failures }; } +/** Formata a quebra compacta por domínio (`mem:2 ctx:1 code:1 · ✦ memory_search`) +* para caber na largura da sidebar. Retorna null sem dados. Pure. */ +function formatToolDomainLine(summary, max = 34) { + if (!summary) return null; + const chunks = []; + for (const domain of TOOL_DOMAIN_ORDER) { + const count = summary.byDomain?.[domain] ?? 0; + if (count > 0) chunks.push(`${domain}:${count}`); + } + const active = typeof summary.activeTool === "string" && summary.activeTool.trim() !== "" ? `\u2726 ${summary.activeTool.trim()}` : null; + if (chunks.length === 0 && !active) return null; + const joined = chunks.join(" "); + const raw = active ? joined ? `${joined} \u00B7 ${active}` : active : joined; + if (cellWidth(raw) <= max) return raw; + if (active) { + const activeFit = truncateLabel(active, max); + const remaining = max - cellWidth(activeFit) - 3; + if (remaining >= 5 && joined !== "") return `${truncateLabel(joined, remaining)} \u00B7 ${activeFit}`; + return activeFit; + } + return truncateLabel(raw, max); +} function formatToolCallLine(summary, locale = "en") { if (!summary || summary.total === 0) return null; const isPt = locale === "pt-BR" || locale === "pt"; @@ -6266,10 +8517,16 @@ function latestTodoItems(messages) { const parts = message.content; for (let position = parts.length - 1; position >= 0; position--) { const part = parts[position]; - if (part?.type !== "tool" || part?.name !== "todowrite") continue; + if (part?.type !== "tool") continue; if (part?.state?.status !== "completed") continue; - const items = parseTodoItems(part.state.input); - return items.length === 0 ? null : items; + if (part?.name === "todowrite") { + const items = parseTodoItems(part.state.input); + return items.length === 0 ? null : items; + } + if (part?.name === "execute" && resolveEffectiveToolNames(part).includes("todowrite")) { + const fromOutput = parseTodoItems(part.state.output); + if (fromOutput.length > 0) return fromOutput; + } } } return null; @@ -6723,6 +8980,74 @@ function collectSubagentCalls(messages) { } return calls; } +/** Atividade em tempo real extraída das mensagens em cache de um subagente. */ +function fileBasename(raw) { + if (typeof raw !== "string") return null; + const trimmed = raw.trim(); + if (trimmed === "") return null; + const parts = trimmed.replaceAll("\\", "/").split("/").filter(Boolean); + return parts.length > 0 ? parts[parts.length - 1] ?? null : null; +} +/** Extrai atividade ao vivo, alertas de bloqueio e histórico recente de um filho +* a partir de suas mensagens em cache. Pure, fail-open. */ +function extractChildActivity(messages, status, hostAttention) { + let activeTool = null; + let activeVerb = null; + let latestTool = null; + let latestVerb = null; + let attention = hostAttention?.permission ? "permission" : hostAttention?.question ? "question" : status === "error" || status === "failed" ? "error" : null; + const recentTools = []; + const filesTouched = []; + let lastSnippet = null; + if (Array.isArray(messages)) for (const message of messages) { + if (message?.type !== "assistant" || !Array.isArray(message.content)) continue; + for (const part of message.content) { + if (part?.type === "text" && typeof part.text === "string") { + const clean = part.text.replace(/\s+/g, " ").trim(); + if (clean !== "") lastSnippet = clean; + continue; + } + if (part?.type !== "tool") continue; + const effectiveNames = resolveEffectiveToolNames(part); + if (effectiveNames.length === 0) continue; + const name = effectiveNames[effectiveNames.length - 1] ?? ""; + const state = part.state; + const { verb } = classifyToolPart(name); + latestTool = name; + latestVerb = verb; + for (const toolName of effectiveNames) { + const existingIdx = recentTools.indexOf(toolName); + if (existingIdx !== -1) recentTools.splice(existingIdx, 1); + recentTools.unshift(toolName); + if (recentTools.length > 4) recentTools.pop(); + } + for (const base of extractToolFilePaths(part)) if (!filesTouched.includes(base)) { + filesTouched.unshift(base); + if (filesTouched.length > 3) filesTouched.pop(); + } + if (isToolActiveState(state)) { + activeTool = name; + activeVerb = verb; + if (name.toLowerCase() === "question") attention = "question"; + } else if (attention === null && isToolFailureState(state) && (status === "error" || status === "failed" || status === "retry")) attention = "error"; + } + } + if (attention === "question" || attention === "permission") activeVerb = "ask"; + else if (attention === "error") activeVerb = "err"; + else if (activeVerb === null && (status === "running" || status === "busy")) { + activeVerb = latestVerb; + activeTool = latestTool; + } + if (activeVerb === null && activeTool === null && attention === null && recentTools.length === 0 && filesTouched.length === 0 && lastSnippet === null) return null; + return { + activeVerb, + activeTool, + attention, + recentTools, + filesTouched, + lastSnippet + }; +} /** Grace window for a child that has not started yet. V2's `session.status()` * returns `idle` both for "created but not started" and for "finished", so an * idle/unknown/absent child whose own last activity (`time.updated`, falling @@ -6861,12 +9186,16 @@ function dispatchTokens(tokens) { /** One child `SessionInfo` + its live status → `DispatchEntry`. The call only * ever adds the kind and the description; an absent one leaves the entry fully * renderable. Pure. */ -function toDispatchEntry(child, status, now = Date.now(), call) { +function toDispatchEntry(child, status, now = Date.now(), call, activity) { const title = typeof child?.title === "string" && child.title !== "" ? child.title : null; const parentID = typeof child?.parentID === "string" && child.parentID !== "" ? child.parentID : null; const description = typeof call?.description === "string" && call.description !== "" ? call.description : null; + const baseView = toDelegationView(child, status, now, call); return { - view: toDelegationView(child, status, now, call), + view: activity ? { + ...baseView, + activity + } : baseView, title, description, parentID, @@ -6905,10 +9234,45 @@ function collectDispatch(context, sessionID, options = {}) { continue; } if (!child) continue; - entries.push(toDispatchEntry(child, sessionStatusOf(context, childID), now, calls.get(childID) ?? null)); + const status = sessionStatusOf(context, childID); + let hasPerm = false; + let hasQuest = false; + try { + const perms = context?.data?.session?.permission?.(childID); + if (Array.isArray(perms) && perms.length > 0) hasPerm = true; + } catch {} + try { + const quests = context?.data?.session?.question?.(childID); + if (Array.isArray(quests) && quests.length > 0) hasQuest = true; + } catch {} + let activity = options.activities?.get(childID) ?? null; + if (activity === null && options.includeChildActivity === true) activity = extractChildActivity(readSessionMessages(context, childID), status, { + permission: hasPerm, + question: hasQuest + }); + else if (hasPerm || hasQuest) activity = extractChildActivity(void 0, status, { + permission: hasPerm, + question: hasQuest + }) ?? activity; + entries.push(toDispatchEntry(child, status, now, calls.get(childID) ?? null, activity)); } return entries.sort((a, b) => compareDelegations(a.view, b.view)); } +/** Enrich pre-collected dispatch entries with live child activity from cached +* child transcripts (used by the full-width dispatch panel). */ +function enrichDispatchEntries(context, entries) { + return entries.map((entry) => { + if (entry.view.activity) return entry; + const activity = extractChildActivity(readSessionMessages(context, entry.view.id), sessionStatusOf(context, entry.view.id)); + return activity ? { + ...entry, + view: { + ...entry.view, + activity + } + } : entry; + }); +} /** Sidebar blocks in render order. Spacing is derived from this list instead of * from the view, so a hidden block can never leave an empty gap behind. * Note: The custom Todo block was removed from the sidebar composition because @@ -7052,6 +9416,21 @@ function dispatchTotalCost(views) { } return total; } +function effectiveChildPresentation(view, frame = 0) { + const act = view.activity; + const attention = act?.attention ?? null; + const tone = attention === "error" ? "error" : attention === "question" || attention === "permission" ? "warning" : "success"; + const marker = attention === "error" ? "! " : attention === "question" || attention === "permission" ? "? " : `${spinnerFrame(frame)} `; + let suffix = dispatchKindSuffix(view.kind, view.background); + if (attention === "question" || attention === "permission") suffix = `${DISPATCH_KIND_SEPARATOR}ask${view.background === true ? DISPATCH_BACKGROUND_MARKER : ""}`; + else if (attention === "error") suffix = `${DISPATCH_KIND_SEPARATOR}err${view.background === true ? DISPATCH_BACKGROUND_MARKER : ""}`; + else if ((view.kind === null || view.kind === "oth") && act?.activeVerb) suffix = `${DISPATCH_KIND_SEPARATOR}${act.activeVerb}${view.background === true ? DISPATCH_BACKGROUND_MARKER : ""}`; + return { + marker, + suffix, + tone + }; +} /** One live child: `⠸ · `, with the model as a * fourth column only when the row still fits and the child is unclassified — * the kind is the stronger evidence at this width, so it takes the model's @@ -7060,11 +9439,10 @@ function dispatchTotalCost(views) { * below `DISPATCH_MIN_AGENT_WIDTH`); the cost is always present — `$0.00` for a * zero cost, an em dash for a missing one. Pure. */ function runningChildRowText(view, now = Date.now(), frame = 0, max = 34) { - const marker = `${spinnerFrame(frame)} `; + const { marker, suffix } = effectiveChildPresentation(view, frame); const duration = dispatchElapsed(view, now).padStart(5); const cost = formatDispatchCost(view.cost).padStart(5); const model = dispatchModelText(view); - const suffix = dispatchKindSuffix(view.kind, view.background); const limit = Math.max(1, max); const row = (agentWidth, withModel, withSuffix = true) => { const kind = withSuffix ? suffix : ""; @@ -7180,7 +9558,7 @@ function failedSuffixText(failures) { const rounded = Math.round(count); return `${rounded} ${rounded === 1 ? "falha" : "falhas"}`; } -/** One rendered live row: its text plus the session it navigates to. */ +/** One rendered live row: its text, attention tone and session id. */ /** Everything the `Dispatch` block renders, already joined and capped. */ /** Newest activity first, so the live rows that just moved lead the section. * Pure. */ @@ -7205,7 +9583,8 @@ function buildDispatchBlock(views, now = Date.now(), frame = 0, max = 34) { const runningHidden = running.length - runningSlots; const runningLines = running.map((view) => ({ id: view.id, - text: runningChildRowText(view, now, frame, max) + text: runningChildRowText(view, now, frame, max), + tone: effectiveChildPresentation(view, frame).tone })); const summary = completedSummaryText(finished.length, finishedCost, groups.length); const runningRows = runningSlots + (runningHidden > 0 ? 1 : 0); @@ -7353,7 +9732,7 @@ function dispatchPanelRowText(entry, options = {}) { const costText = formatDispatchCost(view.cost); const costWidth = Math.max(7, cellWidth(costText)); const agentWidth = Math.max(6, Math.min(12, width - (DISPATCH_PANEL_ROW_FIXED_WIDTH + costWidth))); - return `${dispatchPanelMarker(view.state, frame)}${dispatchPanelCell(dispatchAgentText(view, 12), agentWidth)} ${dispatchPanelCell(view.kind, 4)} ${costText.padStart(costWidth)}${truncateLabel(dispatchElapsed(view, now), 8).padStart(8)}`; + return `${view.activity?.attention === "error" ? "! " : view.activity?.attention === "question" || view.activity?.attention === "permission" ? "? " : dispatchPanelMarker(view.state, frame)}${dispatchPanelCell(dispatchAgentText(view, 12), agentWidth)} ${dispatchPanelCell(view.activity?.attention === "question" || view.activity?.attention === "permission" ? "ask" : view.activity?.attention === "error" ? "err" : (view.kind === null || view.kind === "oth") && view.activity?.activeVerb ? view.activity.activeVerb : view.kind, 4)} ${costText.padStart(costWidth)}${truncateLabel(dispatchElapsed(view, now), 8).padStart(8)}`; } /** `ses_ab12cd`, short enough for a detail line. Full id when it already fits. */ function shortSessionID(id, max = 10) { @@ -7387,6 +9766,20 @@ function dispatchPanelDetail(entry, options = {}) { lines.push(truncateLabel(dispatchTokenLine(entry.tokens), max)); const origin = DISPATCH_KIND_ORIGIN_LABELS[view.kindOrigin] ?? DISPATCH_KIND_ORIGIN_LABELS.unavailable; lines.push(truncateLabel(`kind ${view.kind ?? "—"} (${origin})${SPEND_LINE_SEPARATOR}parent ${entry.parentID ?? "—"}`, max)); + const activity = view.activity; + if (activity) { + if (activity.attention === "question") lines.push(truncateLabel("status ? aguardando resposta do usuário", max)); + else if (activity.attention === "permission") lines.push(truncateLabel("status ? aguardando permissão", max)); + else if (activity.attention === "error") lines.push(truncateLabel("status ! erro na execução", max)); + else if (activity.activeTool) lines.push(truncateLabel(`status \u2726 ${activity.activeTool}`, max)); + const toolsText = activity.recentTools.length > 0 ? activity.recentTools.join(", ") : ""; + const filesText = activity.filesTouched.length > 0 ? activity.filesTouched.join(", ") : ""; + if (toolsText || filesText) { + const joined = [toolsText, filesText].filter(Boolean).join(SPEND_LINE_SEPARATOR); + lines.push(truncateLabel(`tools ${joined}`, max)); + } + if (activity.lastSnippet) lines.push(truncateLabel(`\u21B3 ${activity.lastSnippet}`, max)); + } return lines; } /** Panel geometry for its input width: wide (≥72) puts the detail in a second @@ -7618,7 +10011,7 @@ function createDispatchPanelModel(context, panel) { const entries = createMemo(() => { revision(); if (!isOpen()) return []; - return collectDispatch(context, activeSessionID()); + return enrichDispatchEntries(context, collectDispatch(context, activeSessionID())); }); const layout = createMemo(() => dispatchPanelLayout(panel().width)); const rows = createMemo(() => { @@ -7826,7 +10219,7 @@ function updateCheckStateFile() { * version via toast, and keeps the persistent Home/Sidebar badge updated. */ async function checkForPantheonUpdate(context) { const { statePath, readState } = updateCheckStateFile(); - const currentVersion = "2.2.0-beta.11"; + const currentVersion = "2.2.0"; const initialState = readState(); setAvailableUpdateVersion(resolveCachedAvailableUpdate(currentVersion, initialState)); const nowMs = Date.now(); @@ -8228,6 +10621,7 @@ function createSidebarModel(context, sessionID, gitExec = defaultGitExec) { const rootID = activeSessionID(); const collected = []; let todo = []; + const activities = /* @__PURE__ */ new Map(); for (const id of familySessionIDs()) { let list = []; try { @@ -8236,10 +10630,15 @@ function createSidebarModel(context, sessionID, gitExec = defaultGitExec) { } catch {} collected.push(...list.slice(-400)); if (id === rootID) todo = latestTodoItems(list) ?? []; + else { + const activity = extractChildActivity(list, sessionStatusOf(context, id)); + if (activity) activities.set(id, activity); + } } return { messages: collected, - todo + todo, + activities }; }); const usageMessages = createMemo(() => transcript().messages); @@ -8374,7 +10773,8 @@ function createSidebarModel(context, sessionID, gitExec = defaultGitExec) { if (id === "") return []; return collectDispatch(context, id, { now: Date.now(), - calls: subagentCalls() + calls: subagentCalls(), + activities: transcript().activities }); }); /** What the sidebar block renders: the collector's rows, nothing else. */ @@ -8392,8 +10792,9 @@ function createSidebarModel(context, sessionID, gitExec = defaultGitExec) { }); const tokenAnatomyLine = createMemo(() => formatTokenAnatomyLine(tokenAnatomy())); const tokenAnatomySplit = createMemo(() => formatTokenAnatomySplit(tokenAnatomy())); - const toolCalls = createMemo(() => countToolCalls(messages())); + const toolCalls = createMemo(() => summarizeToolDomains(messages())); const toolCallsLine = createMemo(() => formatToolCallLine(toolCalls(), tuiPrefs().layout.language)); + const toolCallsDetailLine = createMemo(() => formatToolDomainLine(toolCalls(), 34)); const compactions = createMemo(() => extractCompactionInfo(messages())); const compactionBadge = createMemo(() => { const badge = formatCompactionBadge(compactions()); @@ -8510,6 +10911,7 @@ function createSidebarModel(context, sessionID, gitExec = defaultGitExec) { turnCostLine, tokenAnatomyLine, toolCallsLine, + toolCallsDetailLine, compactionBadge, turnsBadge, tokenAnatomySplit, @@ -8674,7 +11076,7 @@ function Sidebar(props) { setProp(_el$13, "paddingLeft", 1); setProp(_el$13, "paddingRight", 1); setProp(_el$14, "attributes", 1); - insert(_el$14, `Pantheon v2.2.0-beta.11`); + insert(_el$14, `Pantheon v2.2.0`); insert(_el$15, () => `Erro no painel: ${err?.message ?? "desconhecido"}`); effect((_p$) => { var _v$3 = text(), _v$4 = muted(); @@ -8728,8 +11130,11 @@ function SidebarInner(props) { }; const failedSuffix = () => failedSuffixText(dispatchView()?.failures); const header = () => tuiPrefs().sidebar.header; - const availableUpdate = useAvailableUpdate("2.2.0-beta.11"); - const updateBadge = () => formatUpdateBadge("2.2.0-beta.11", availableUpdate(), { isPt: resolveLanguage(tuiPrefs().layout?.language) === "pt-BR" }); + const availableUpdate = useAvailableUpdate("2.2.0"); + const isPt = () => resolveLanguage(tuiPrefs().layout?.language) === "pt-BR"; + const updateBadge = () => formatUpdateBadge("2.2.0", availableUpdate(), { isPt: isPt() }); + const artifacts = useWorkspaceArtifacts(context); + const activePlan = () => artifacts().find((entry) => entry.kind === "plan"); return (() => { var _el$16 = createElement("box"), _el$17 = createElement("box"), _el$19 = createElement("box"); insertNode(_el$16, _el$17); @@ -8747,7 +11152,7 @@ function SidebarInner(props) { get children() { var _el$18 = createElement("text"); setProp(_el$18, "attributes", 1); - insert(_el$18, `Pantheon v2.2.0-beta.11`); + insert(_el$18, `Pantheon v2.2.0`); effect((_$p) => setProp(_el$18, "fg", text(), _$p)); return _el$18; } @@ -8758,10 +11163,10 @@ function SidebarInner(props) { return model.turnsBadge(); }, children: (turns) => (() => { - var _el$38 = createElement("text"); - insert(_el$38, turns); - effect((_$p) => setProp(_el$38, "fg", muted(), _$p)); - return _el$38; + var _el$41 = createElement("text"); + insert(_el$41, turns); + effect((_$p) => setProp(_el$41, "fg", muted(), _$p)); + return _el$41; })() }), null); insert(_el$19, createComponent(Show, { @@ -8780,10 +11185,14 @@ function SidebarInner(props) { return memo(() => !!header().version)() && updateBadge(); }, children: (badge) => (() => { - var _el$39 = createElement("text"); - insert(_el$39, badge); - effect((_$p) => setProp(_el$39, "fg", accent(), _$p)); - return _el$39; + var _el$42 = createElement("box"), _el$43 = createElement("text"); + insertNode(_el$42, _el$43); + setProp(_el$42, "onMouseDown", () => { + openPantheonSettings(context, { initialTab: "updates" }); + }); + insert(_el$43, badge); + effect((_$p) => setProp(_el$43, "fg", accent(), _$p)); + return _el$42; })() }), null); insert(_el$16, createComponent(Show, { @@ -8837,28 +11246,28 @@ function SidebarInner(props) { } }; return (() => { - var _el$40 = createElement("box"), _el$41 = createElement("text"); - insertNode(_el$40, _el$41); - setProp(_el$40, "flexDirection", "row"); - setProp(_el$40, "justifyContent", "space-between"); - insert(_el$41, leftPreset); - insert(_el$40, createComponent(Show, { + var _el$44 = createElement("box"), _el$45 = createElement("text"); + insertNode(_el$44, _el$45); + setProp(_el$44, "flexDirection", "row"); + setProp(_el$44, "justifyContent", "space-between"); + insert(_el$45, leftPreset); + insert(_el$44, createComponent(Show, { get when() { return badge(); }, children: (b) => (() => { - var _el$42 = createElement("box"), _el$43 = createElement("text"); - insertNode(_el$42, _el$43); - setProp(_el$42, "onMouseDown", triggerCompaction); - setProp(_el$42, "flexShrink", 0); - setProp(_el$43, "attributes", 1); - insert(_el$43, b); - effect((_$p) => setProp(_el$43, "fg", accent(), _$p)); - return _el$42; + var _el$46 = createElement("box"), _el$47 = createElement("text"); + insertNode(_el$46, _el$47); + setProp(_el$46, "onMouseDown", triggerCompaction); + setProp(_el$46, "flexShrink", 0); + setProp(_el$47, "attributes", 1); + insert(_el$47, b); + effect((_$p) => setProp(_el$47, "fg", accent(), _$p)); + return _el$46; })() }), null); - effect((_$p) => setProp(_el$41, "fg", muted(), _$p)); - return _el$40; + effect((_$p) => setProp(_el$45, "fg", muted(), _$p)); + return _el$44; })(); } }), null); @@ -8873,40 +11282,40 @@ function SidebarInner(props) { }, get fallback() { return (() => { - var _el$45 = createElement("box"); - setProp(_el$45, "height", 0); - return _el$45; + var _el$49 = createElement("box"); + setProp(_el$49, "height", 0); + return _el$49; })(); }, get children() { - var _el$44 = createElement("text"); - insert(_el$44, () => sidebarPlaceholder(props.sessionID)); - effect((_$p) => setProp(_el$44, "fg", muted(), _$p)); - return _el$44; + var _el$48 = createElement("text"); + insert(_el$48, () => sidebarPlaceholder(props.sessionID)); + effect((_$p) => setProp(_el$48, "fg", muted(), _$p)); + return _el$48; } }); }, children: (current) => (() => { - var _el$46 = createElement("box"), _el$47 = createElement("text"), _el$49 = createElement("text"), _el$51 = createElement("text"); - insertNode(_el$46, _el$47); - insertNode(_el$46, _el$49); - insertNode(_el$46, _el$51); - setProp(_el$46, "flexDirection", "row"); - insertNode(_el$47, createTextNode(`● `)); - setProp(_el$47, "fg", "#22c55e"); - insertNode(_el$49, createTextNode(`Session: `)); - setProp(_el$51, "attributes", 1); - insert(_el$51, () => truncateLabel(current().title || current().id, 18)); + var _el$50 = createElement("box"), _el$51 = createElement("text"), _el$53 = createElement("text"), _el$55 = createElement("text"); + insertNode(_el$50, _el$51); + insertNode(_el$50, _el$53); + insertNode(_el$50, _el$55); + setProp(_el$50, "flexDirection", "row"); + insertNode(_el$51, createTextNode(`● `)); + setProp(_el$51, "fg", "#22c55e"); + insertNode(_el$53, createTextNode(`Session: `)); + setProp(_el$55, "attributes", 1); + insert(_el$55, () => truncateLabel(current().title || current().id, 18)); effect((_p$) => { var _v$7 = muted(), _v$8 = text(); - _v$7 !== _p$.e && (_p$.e = setProp(_el$49, "fg", _v$7, _p$.e)); - _v$8 !== _p$.t && (_p$.t = setProp(_el$51, "fg", _v$8, _p$.t)); + _v$7 !== _p$.e && (_p$.e = setProp(_el$53, "fg", _v$7, _p$.e)); + _v$8 !== _p$.t && (_p$.t = setProp(_el$55, "fg", _v$8, _p$.t)); return _p$; }, { e: void 0, t: void 0 }); - return _el$46; + return _el$50; })() }), null); insert(_el$16, createComponent(Show, { @@ -8965,16 +11374,16 @@ function SidebarInner(props) { return l; }; return (() => { - var _el$52 = createElement("box"), _el$53 = createElement("text"), _el$55 = createElement("text"); - insertNode(_el$52, _el$53); - insertNode(_el$52, _el$55); - setProp(_el$52, "flexDirection", "row"); - insertNode(_el$53, createTextNode(`Turn: `)); - setProp(_el$55, "fg", "#34d399"); - setProp(_el$55, "attributes", 1); - insert(_el$55, () => display().replace(/^Turn:\s*/, "")); - effect((_$p) => setProp(_el$53, "fg", muted(), _$p)); - return _el$52; + var _el$56 = createElement("box"), _el$57 = createElement("text"), _el$59 = createElement("text"); + insertNode(_el$56, _el$57); + insertNode(_el$56, _el$59); + setProp(_el$56, "flexDirection", "row"); + insertNode(_el$57, createTextNode(`Turn: `)); + setProp(_el$59, "fg", "#34d399"); + setProp(_el$59, "attributes", 1); + insert(_el$59, () => display().replace(/^Turn:\s*/, "")); + effect((_$p) => setProp(_el$57, "fg", muted(), _$p)); + return _el$56; })(); } }); @@ -8985,17 +11394,17 @@ function SidebarInner(props) { return contextRows(); }, children: (rows) => (() => { - var _el$56 = createElement("box"); - setProp(_el$56, "flexDirection", "column"); - insert(_el$56, createComponent(Show, { + var _el$60 = createElement("box"); + setProp(_el$60, "flexDirection", "column"); + insert(_el$60, createComponent(Show, { get when() { return rows().percent; }, children: (row) => (() => { - var _el$57 = createElement("box"); - setProp(_el$57, "flexDirection", "row"); - setProp(_el$57, "justifyContent", "space-between"); - insert(_el$57, createComponent(ContextRowView, { + var _el$61 = createElement("box"); + setProp(_el$61, "flexDirection", "row"); + setProp(_el$61, "justifyContent", "space-between"); + insert(_el$61, createComponent(ContextRowView, { get row() { return memo(() => !!model.contextRatioLine())() ? { ...row(), @@ -9009,30 +11418,30 @@ function SidebarInner(props) { return muted(); } }), null); - insert(_el$57, createComponent(Show, { + insert(_el$61, createComponent(Show, { get when() { return model.contextRatioLine(); }, children: (ratio) => { const parts = ratio().split(" / "); return (() => { - var _el$58 = createElement("box"), _el$59 = createElement("text"), _el$60 = createElement("text"); - insertNode(_el$58, _el$59); - insertNode(_el$58, _el$60); - setProp(_el$58, "flexDirection", "row"); - setProp(_el$59, "fg", "#f1f5f9"); - setProp(_el$59, "attributes", 1); - insert(_el$59, () => parts[0]); - insert(_el$60, () => ` / ${parts[1] ?? ""}`); - effect((_$p) => setProp(_el$60, "fg", muted(), _$p)); - return _el$58; + var _el$62 = createElement("box"), _el$63 = createElement("text"), _el$64 = createElement("text"); + insertNode(_el$62, _el$63); + insertNode(_el$62, _el$64); + setProp(_el$62, "flexDirection", "row"); + setProp(_el$63, "fg", "#f1f5f9"); + setProp(_el$63, "attributes", 1); + insert(_el$63, () => parts[0]); + insert(_el$64, () => ` / ${parts[1] ?? ""}`); + effect((_$p) => setProp(_el$64, "fg", muted(), _$p)); + return _el$62; })(); } }), null); - return _el$57; + return _el$61; })() }), null); - insert(_el$56, createComponent(Show, { + insert(_el$60, createComponent(Show, { get when() { return memo(() => !!rows().tokens)() && !rows().percent; }, @@ -9048,7 +11457,7 @@ function SidebarInner(props) { } }) }), null); - insert(_el$56, createComponent(Show, { + insert(_el$60, createComponent(Show, { get when() { return rows().spent; }, @@ -9064,7 +11473,7 @@ function SidebarInner(props) { } }) }), null); - return _el$56; + return _el$60; })() }), _el$25); insert(_el$23, createComponent(Show, { @@ -9072,57 +11481,57 @@ function SidebarInner(props) { return memo(() => !!tuiPrefs().sidebar.context.tokenAnatomy)() && model.tokenAnatomySplit(); }, children: (anatomy) => (() => { - var _el$61 = createElement("box"), _el$62 = createElement("box"), _el$63 = createElement("text"), _el$65 = createElement("text"); - insertNode(_el$61, _el$62); - setProp(_el$61, "flexDirection", "row"); - setProp(_el$61, "justifyContent", "space-between"); - insertNode(_el$62, _el$63); - insertNode(_el$62, _el$65); - setProp(_el$62, "flexDirection", "row"); - insertNode(_el$63, createTextNode(`↑`)); - setProp(_el$63, "fg", "#60a5fa"); - insert(_el$65, () => anatomy().inOut?.split(" · ")[0]?.replace(/^↑\s*/, "") ?? ""); - insert(_el$62, createComponent(Show, { + var _el$65 = createElement("box"), _el$66 = createElement("box"), _el$67 = createElement("text"), _el$69 = createElement("text"); + insertNode(_el$65, _el$66); + setProp(_el$65, "flexDirection", "row"); + setProp(_el$65, "justifyContent", "space-between"); + insertNode(_el$66, _el$67); + insertNode(_el$66, _el$69); + setProp(_el$66, "flexDirection", "row"); + insertNode(_el$67, createTextNode(`↑`)); + setProp(_el$67, "fg", "#60a5fa"); + insert(_el$69, () => anatomy().inOut?.split(" · ")[0]?.replace(/^↑\s*/, "") ?? ""); + insert(_el$66, createComponent(Show, { get when() { return anatomy().inOut?.includes(" · "); }, get children() { return [ (() => { - var _el$66 = createElement("text"); - insertNode(_el$66, createTextNode(` · `)); - effect((_$p) => setProp(_el$66, "fg", muted(), _$p)); - return _el$66; + var _el$70 = createElement("text"); + insertNode(_el$70, createTextNode(` · `)); + effect((_$p) => setProp(_el$70, "fg", muted(), _$p)); + return _el$70; })(), (() => { - var _el$68 = createElement("text"); - insertNode(_el$68, createTextNode(`↓`)); - setProp(_el$68, "fg", "#4ade80"); - return _el$68; + var _el$72 = createElement("text"); + insertNode(_el$72, createTextNode(`↓`)); + setProp(_el$72, "fg", "#4ade80"); + return _el$72; })(), (() => { - var _el$70 = createElement("text"); - insert(_el$70, () => anatomy().inOut?.split(" · ")[1]?.replace(/^↓\s*/, "") ?? ""); - effect((_$p) => setProp(_el$70, "fg", muted(), _$p)); - return _el$70; + var _el$74 = createElement("text"); + insert(_el$74, () => anatomy().inOut?.split(" · ")[1]?.replace(/^↓\s*/, "") ?? ""); + effect((_$p) => setProp(_el$74, "fg", muted(), _$p)); + return _el$74; })() ]; } }), null); - insert(_el$61, createComponent(Show, { + insert(_el$65, createComponent(Show, { get when() { return anatomy().think; }, children: (think) => (() => { - var _el$71 = createElement("text"); - setProp(_el$71, "fg", "#c084fc"); - setProp(_el$71, "attributes", 1); - insert(_el$71, think); - return _el$71; + var _el$75 = createElement("text"); + setProp(_el$75, "fg", "#c084fc"); + setProp(_el$75, "attributes", 1); + insert(_el$75, think); + return _el$75; })() }), null); - effect((_$p) => setProp(_el$65, "fg", muted(), _$p)); - return _el$61; + effect((_$p) => setProp(_el$69, "fg", muted(), _$p)); + return _el$65; })() }), _el$25); insert(_el$23, createComponent(Show, { @@ -9130,33 +11539,33 @@ function SidebarInner(props) { return memo(() => !!tuiPrefs().sidebar.context.performance)() && model.performanceSplit(); }, children: (perf) => (() => { - var _el$72 = createElement("box"), _el$73 = createElement("box"), _el$74 = createElement("text"), _el$76 = createElement("text"), _el$77 = createElement("box"), _el$78 = createElement("text"), _el$80 = createElement("text"); - insertNode(_el$72, _el$73); - insertNode(_el$72, _el$77); - setProp(_el$72, "flexDirection", "row"); - setProp(_el$72, "justifyContent", "space-between"); - insertNode(_el$73, _el$74); - insertNode(_el$73, _el$76); - setProp(_el$73, "flexDirection", "row"); - insertNode(_el$74, createTextNode(`Cache: `)); - setProp(_el$76, "fg", "#34d399"); - insert(_el$76, () => perf().cache?.replace(/^Cache:\s*/, "") ?? ""); + var _el$76 = createElement("box"), _el$77 = createElement("box"), _el$78 = createElement("text"), _el$80 = createElement("text"), _el$81 = createElement("box"), _el$82 = createElement("text"), _el$84 = createElement("text"); + insertNode(_el$76, _el$77); + insertNode(_el$76, _el$81); + setProp(_el$76, "flexDirection", "row"); + setProp(_el$76, "justifyContent", "space-between"); insertNode(_el$77, _el$78); insertNode(_el$77, _el$80); setProp(_el$77, "flexDirection", "row"); - insertNode(_el$78, createTextNode(`Speed: `)); - setProp(_el$80, "fg", "#38bdf8"); - insert(_el$80, () => perf().speed?.replace(/^Speed:\s*/, "") ?? ""); + insertNode(_el$78, createTextNode(`Cache: `)); + setProp(_el$80, "fg", "#34d399"); + insert(_el$80, () => perf().cache?.replace(/^Cache:\s*/, "") ?? ""); + insertNode(_el$81, _el$82); + insertNode(_el$81, _el$84); + setProp(_el$81, "flexDirection", "row"); + insertNode(_el$82, createTextNode(`Speed: `)); + setProp(_el$84, "fg", "#38bdf8"); + insert(_el$84, () => perf().speed?.replace(/^Speed:\s*/, "") ?? ""); effect((_p$) => { var _v$9 = muted(), _v$0 = muted(); - _v$9 !== _p$.e && (_p$.e = setProp(_el$74, "fg", _v$9, _p$.e)); - _v$0 !== _p$.t && (_p$.t = setProp(_el$78, "fg", _v$0, _p$.t)); + _v$9 !== _p$.e && (_p$.e = setProp(_el$78, "fg", _v$9, _p$.e)); + _v$0 !== _p$.t && (_p$.t = setProp(_el$82, "fg", _v$0, _p$.t)); return _p$; }, { e: void 0, t: void 0 }); - return _el$72; + return _el$76; })() }), _el$25); insertNode(_el$25, createTextNode(`──────────────────────────────`)); @@ -9170,22 +11579,33 @@ function SidebarInner(props) { }, get fallback() { return (() => { - var _el$81 = createElement("text"); - insertNode(_el$81, createTextNode(`tools: 0 (0 err)`)); - effect((_$p) => setProp(_el$81, "fg", muted(), _$p)); - return _el$81; + var _el$85 = createElement("text"); + insertNode(_el$85, createTextNode(`tools: 0 (0 err)`)); + effect((_$p) => setProp(_el$85, "fg", muted(), _$p)); + return _el$85; })(); }, children: (line) => (() => { - var _el$83 = createElement("text"); - insert(_el$83, line); - effect((_$p) => setProp(_el$83, "fg", muted(), _$p)); - return _el$83; + var _el$87 = createElement("text"); + insert(_el$87, line); + effect((_$p) => setProp(_el$87, "fg", muted(), _$p)); + return _el$87; })() }), _el$28); setProp(_el$28, "fg", "#22c55e"); setProp(_el$28, "attributes", 1); insert(_el$28, () => model.gateStatus()); + insert(_el$23, createComponent(Show, { + get when() { + return model.toolCallsDetailLine(); + }, + children: (line) => (() => { + var _el$88 = createElement("text"); + insert(_el$88, line); + effect((_$p) => setProp(_el$88, "fg", muted(), _$p)); + return _el$88; + })() + }), null); insert(_el$23, createComponent(Show, { get when() { return memo(() => !!tuiPrefs().sidebar.context.modelUsage)() && usageRows().length > 0; @@ -9209,20 +11629,20 @@ function SidebarInner(props) { return usageRows(); }, children: (row) => (() => { - var _el$84 = createElement("box"); - setProp(_el$84, "flexDirection", "column"); - insert(_el$84, createComponent(For, { + var _el$89 = createElement("box"); + setProp(_el$89, "flexDirection", "column"); + insert(_el$89, createComponent(For, { get each() { return modelUsageRowLines(row); }, children: (line) => (() => { - var _el$85 = createElement("text"); - insert(_el$85, line); - effect((_$p) => setProp(_el$85, "fg", text(), _$p)); - return _el$85; + var _el$90 = createElement("text"); + insert(_el$90, line); + effect((_$p) => setProp(_el$90, "fg", text(), _$p)); + return _el$90; })() })); - return _el$84; + return _el$89; })() }), createComponent(Show, { @@ -9234,10 +11654,10 @@ function SidebarInner(props) { return sidebarTextLines(line()); }, children: (part) => (() => { - var _el$86 = createElement("text"); - insert(_el$86, part); - effect((_$p) => setProp(_el$86, "fg", muted(), _$p)); - return _el$86; + var _el$91 = createElement("text"); + insert(_el$91, part); + effect((_$p) => setProp(_el$91, "fg", muted(), _$p)); + return _el$91; })() }) }) @@ -9253,10 +11673,10 @@ function SidebarInner(props) { return contextSpendLines(line()); }, children: (part) => (() => { - var _el$87 = createElement("text"); - insert(_el$87, part); - effect((_$p) => setProp(_el$87, "fg", muted(), _$p)); - return _el$87; + var _el$92 = createElement("text"); + insert(_el$92, part); + effect((_$p) => setProp(_el$92, "fg", muted(), _$p)); + return _el$92; })() }) }), null); @@ -9301,16 +11721,16 @@ function SidebarInner(props) { return model.branch(); }, children: (value) => (() => { - var _el$88 = createElement("box"), _el$89 = createElement("text"), _el$91 = createElement("text"); - insertNode(_el$88, _el$89); - insertNode(_el$88, _el$91); - setProp(_el$88, "flexDirection", "row"); - insertNode(_el$89, createTextNode(`⎇ `)); - setProp(_el$89, "fg", "#38bdf8"); - setProp(_el$91, "attributes", 1); - insert(_el$91, () => truncateLabel(value(), 24)); - effect((_$p) => setProp(_el$91, "fg", text(), _$p)); - return _el$88; + var _el$93 = createElement("box"), _el$94 = createElement("text"), _el$96 = createElement("text"); + insertNode(_el$93, _el$94); + insertNode(_el$93, _el$96); + setProp(_el$93, "flexDirection", "row"); + insertNode(_el$94, createTextNode(`⎇ `)); + setProp(_el$94, "fg", "#38bdf8"); + setProp(_el$96, "attributes", 1); + insert(_el$96, () => truncateLabel(value(), 24)); + effect((_$p) => setProp(_el$96, "fg", text(), _$p)); + return _el$93; })() }), null); insert(_el$35, createComponent(Show, { @@ -9318,10 +11738,10 @@ function SidebarInner(props) { return model.gitLine(); }, children: (line) => (() => { - var _el$92 = createElement("text"); - setProp(_el$92, "fg", "#f59e0b"); - insert(_el$92, line); - return _el$92; + var _el$97 = createElement("text"); + setProp(_el$97, "fg", "#f59e0b"); + insert(_el$97, line); + return _el$97; })() }), null); return _el$33; @@ -9349,9 +11769,9 @@ function SidebarInner(props) { return dispatchView(); }, children: (view) => (() => { - var _el$93 = createElement("box"); - setProp(_el$93, "flexDirection", "column"); - insert(_el$93, createComponent(BlockHeader, { + var _el$98 = createElement("box"); + setProp(_el$98, "flexDirection", "column"); + insert(_el$98, createComponent(BlockHeader, { get icon() { return BLOCK_ICONS.dispatch; }, @@ -9367,91 +11787,129 @@ function SidebarInner(props) { return dispatchSummary(); } }), null); - insert(_el$93, createComponent(For, { + insert(_el$98, createComponent(For, { get each() { return view().running; }, children: (row) => (() => { - var _el$95 = createElement("box"), _el$96 = createElement("text"); - insertNode(_el$95, _el$96); - setProp(_el$95, "flexShrink", 0); - insert(_el$96, () => row.text); + var _el$100 = createElement("box"), _el$101 = createElement("text"); + insertNode(_el$100, _el$101); + setProp(_el$100, "flexShrink", 0); + insert(_el$101, () => row.text); effect((_p$) => { - var _v$1 = open(row.id), _v$10 = tone("success"); - _v$1 !== _p$.e && (_p$.e = setProp(_el$95, "onMouseDown", _v$1, _p$.e)); - _v$10 !== _p$.t && (_p$.t = setProp(_el$96, "fg", _v$10, _p$.t)); + var _v$1 = open(row.id), _v$10 = tone(row.tone ?? "success"); + _v$1 !== _p$.e && (_p$.e = setProp(_el$100, "onMouseDown", _v$1, _p$.e)); + _v$10 !== _p$.t && (_p$.t = setProp(_el$101, "fg", _v$10, _p$.t)); return _p$; }, { e: void 0, t: void 0 }); - return _el$95; + return _el$100; })() }), null); - insert(_el$93, createComponent(Show, { + insert(_el$98, createComponent(Show, { get when() { return view().runningHidden > 0; }, get children() { - var _el$94 = createElement("text"); - insert(_el$94, () => `\u2026 +${view().runningHidden} rodando`); - effect((_$p) => setProp(_el$94, "fg", muted(), _$p)); - return _el$94; + var _el$99 = createElement("text"); + insert(_el$99, () => `\u2026 +${view().runningHidden} rodando`); + effect((_$p) => setProp(_el$99, "fg", muted(), _$p)); + return _el$99; } }), null); - insert(_el$93, createComponent(Show, { + insert(_el$98, createComponent(Show, { get when() { return view().summary; }, children: (line) => (() => { - var _el$97 = createElement("box"), _el$98 = createElement("text"); - insertNode(_el$97, _el$98); - setProp(_el$97, "flexDirection", "row"); - setProp(_el$97, "flexShrink", 0); - insert(_el$98, line); - insert(_el$97, createComponent(Show, { + var _el$102 = createElement("box"), _el$103 = createElement("text"); + insertNode(_el$102, _el$103); + setProp(_el$102, "flexDirection", "row"); + setProp(_el$102, "flexShrink", 0); + insert(_el$103, line); + insert(_el$102, createComponent(Show, { get when() { return failedSuffix(); }, children: (suffix) => (() => { - var _el$99 = createElement("text"); - insert(_el$99, () => `${SPEND_LINE_SEPARATOR}${suffix()}`); - effect((_$p) => setProp(_el$99, "fg", tone("error"), _$p)); - return _el$99; + var _el$104 = createElement("text"); + insert(_el$104, () => `${SPEND_LINE_SEPARATOR}${suffix()}`); + effect((_$p) => setProp(_el$104, "fg", tone("error"), _$p)); + return _el$104; })() }), null); - effect((_$p) => setProp(_el$98, "fg", muted(), _$p)); - return _el$97; + effect((_$p) => setProp(_el$103, "fg", muted(), _$p)); + return _el$102; })() }), null); - insert(_el$93, createComponent(For, { + insert(_el$98, createComponent(For, { get each() { return view().agents; }, children: (row) => (() => { - var _el$100 = createElement("text"); - insert(_el$100, () => childAgentRowText(row)); - effect((_$p) => setProp(_el$100, "fg", muted(), _$p)); - return _el$100; + var _el$105 = createElement("text"); + insert(_el$105, () => childAgentRowText(row)); + effect((_$p) => setProp(_el$105, "fg", muted(), _$p)); + return _el$105; })() }), null); - insert(_el$93, createComponent(Show, { + insert(_el$98, createComponent(Show, { get when() { return hiddenChildAgentsText(view().agentsHidden, view().agentsHiddenCost); }, children: (line) => (() => { - var _el$101 = createElement("text"); - insert(_el$101, line); - effect((_$p) => setProp(_el$101, "fg", muted(), _$p)); - return _el$101; + var _el$106 = createElement("text"); + insert(_el$106, line); + effect((_$p) => setProp(_el$106, "fg", muted(), _$p)); + return _el$106; })() }), null); - return _el$93; + return _el$98; })() }), null); return _el$36; } }), null); + insert(_el$16, createComponent(Show, { + get when() { + return artifacts().length > 0; + }, + get children() { + var _el$38 = createElement("box"), _el$39 = createElement("box"), _el$40 = createElement("text"); + insertNode(_el$38, _el$39); + setProp(_el$38, "flexDirection", "column"); + setProp(_el$38, "marginTop", 1); + insert(_el$38, createComponent(Show, { + get when() { + return activePlan(); + }, + children: (plan) => (() => { + var _el$107 = createElement("box"), _el$108 = createElement("text"); + insertNode(_el$107, _el$108); + setProp(_el$107, "onMouseDown", () => { + openArtifactsDialog(context, resolveSidebarCwd(context), { initialArtifactId: plan().id }); + }); + setProp(_el$107, "flexShrink", 0); + insert(_el$108, () => `▸ Plan: ${truncateLabel(plan().title, 22)}`); + effect((_$p) => setProp(_el$108, "fg", accent(), _$p)); + return _el$107; + })() + }), _el$39); + insertNode(_el$39, _el$40); + setProp(_el$39, "onMouseDown", () => { + openArtifactsDialog(context, resolveSidebarCwd(context)); + }); + setProp(_el$39, "flexShrink", 0); + insert(_el$40, (() => { + var _c$ = memo(() => !!isPt()); + return () => _c$() ? `◈ Artefatos (${artifacts().length})` : `◈ Artifacts (${artifacts().length})`; + })()); + effect((_$p) => setProp(_el$40, "fg", muted(), _$p)); + return _el$38; + } + }), null); effect((_p$) => { var _v$5 = tuiPrefs().layout.preset === "compact" ? 0 : 1, _v$6 = tuiPrefs().layout.preset === "compact" ? 0 : 1; _v$5 !== _p$.e && (_p$.e = setProp(_el$16, "paddingTop", _v$5, _p$.e)); @@ -9530,25 +11988,25 @@ function DispatchPanel(props) { return model.visible().rows; }, children: (row) => (() => { - var _el$102 = createElement("box"), _el$103 = createElement("text"), _el$104 = createElement("text"); - insertNode(_el$102, _el$103); - insertNode(_el$102, _el$104); - setProp(_el$102, "flexDirection", "row"); - setProp(_el$102, "flexShrink", 0); - insert(_el$103, () => selected(row.id) ? `▸ ` : " "); - insert(_el$104, () => row.text); + var _el$109 = createElement("box"), _el$110 = createElement("text"), _el$111 = createElement("text"); + insertNode(_el$109, _el$110); + insertNode(_el$109, _el$111); + setProp(_el$109, "flexDirection", "row"); + setProp(_el$109, "flexShrink", 0); + insert(_el$110, () => selected(row.id) ? `▸ ` : " "); + insert(_el$111, () => row.text); effect((_p$) => { var _v$11 = selected(row.id) ? text() : muted(), _v$12 = rowFg(row.state), _v$13 = selected(row.id) ? 1 : 0; - _v$11 !== _p$.e && (_p$.e = setProp(_el$103, "fg", _v$11, _p$.e)); - _v$12 !== _p$.t && (_p$.t = setProp(_el$104, "fg", _v$12, _p$.t)); - _v$13 !== _p$.a && (_p$.a = setProp(_el$104, "attributes", _v$13, _p$.a)); + _v$11 !== _p$.e && (_p$.e = setProp(_el$110, "fg", _v$11, _p$.e)); + _v$12 !== _p$.t && (_p$.t = setProp(_el$111, "fg", _v$12, _p$.t)); + _v$13 !== _p$.a && (_p$.a = setProp(_el$111, "attributes", _v$13, _p$.a)); return _p$; }, { e: void 0, t: void 0, a: void 0 }); - return _el$102; + return _el$109; })() }); const detail = () => createComponent(For, { @@ -9556,28 +12014,28 @@ function DispatchPanel(props) { return model.detail(); }, children: (line, index) => (() => { - var _el$105 = createElement("text"); - insert(_el$105, line); - effect((_$p) => setProp(_el$105, "fg", index() === 0 ? text() : muted(), _$p)); - return _el$105; + var _el$112 = createElement("text"); + insert(_el$112, line); + effect((_$p) => setProp(_el$112, "fg", index() === 0 ? text() : muted(), _$p)); + return _el$112; })() }); const empty = () => (() => { - var _el$106 = createElement("text"); - insertNode(_el$106, createTextNode(`No delegated sessions`)); - effect((_$p) => setProp(_el$106, "fg", muted(), _$p)); - return _el$106; + var _el$113 = createElement("text"); + insertNode(_el$113, createTextNode(`No delegated sessions`)); + effect((_$p) => setProp(_el$113, "fg", muted(), _$p)); + return _el$113; })(); return (() => { - var _el$108 = createElement("box"), _el$109 = createElement("text"), _el$110 = createElement("text"), _el$114 = createElement("box"), _el$115 = createElement("text"); - insertNode(_el$108, _el$109); - insertNode(_el$108, _el$110); - insertNode(_el$108, _el$114); - insertNode(_el$108, _el$115); - setProp(_el$108, "flexDirection", "column"); - setProp(_el$108, "width", "100%"); - setProp(_el$108, "padding", 1); - insert(_el$108, createComponent(DispatchPanelKeymap, { + var _el$115 = createElement("box"), _el$116 = createElement("text"), _el$117 = createElement("text"), _el$121 = createElement("box"), _el$122 = createElement("text"); + insertNode(_el$115, _el$116); + insertNode(_el$115, _el$117); + insertNode(_el$115, _el$121); + insertNode(_el$115, _el$122); + setProp(_el$115, "flexDirection", "column"); + setProp(_el$115, "width", "100%"); + setProp(_el$115, "padding", 1); + insert(_el$115, createComponent(DispatchPanelKeymap, { get context() { return props.context; }, @@ -9585,30 +12043,30 @@ function DispatchPanel(props) { return props.panel; }, model - }), _el$109); - setProp(_el$109, "attributes", 1); - insert(_el$109, () => model.title()); - insert(_el$108, createComponent(Show, { + }), _el$116); + setProp(_el$116, "attributes", 1); + insert(_el$116, () => model.title()); + insert(_el$115, createComponent(Show, { get when() { return model.header(); }, children: (line) => (() => { - var _el$116 = createElement("text"); - insert(_el$116, line); - effect((_$p) => setProp(_el$116, "fg", muted(), _$p)); - return _el$116; + var _el$123 = createElement("text"); + insert(_el$123, line); + effect((_$p) => setProp(_el$123, "fg", muted(), _$p)); + return _el$123; })() - }), _el$110); - insert(_el$110, () => dispatchPanelRule(props.panel.width - 2)); - insert(_el$108, createComponent(Show, { + }), _el$117); + insert(_el$117, () => dispatchPanelRule(props.panel.width - 2)); + insert(_el$115, createComponent(Show, { get when() { return model.layout().mode === "wide"; }, get fallback() { return (() => { - var _el$117 = createElement("box"); - setProp(_el$117, "flexDirection", "column"); - insert(_el$117, createComponent(Show, { + var _el$124 = createElement("box"); + setProp(_el$124, "flexDirection", "column"); + insert(_el$124, createComponent(Show, { get when() { return model.rows().length > 0; }, @@ -9616,34 +12074,34 @@ function DispatchPanel(props) { return empty(); }, get children() { - var _el$118 = createElement("box"); - setProp(_el$118, "flexDirection", "column"); - insert(_el$118, rows); - return _el$118; + var _el$125 = createElement("box"); + setProp(_el$125, "flexDirection", "column"); + insert(_el$125, rows); + return _el$125; } }), null); - insert(_el$117, createComponent(Show, { + insert(_el$124, createComponent(Show, { get when() { return model.selectedID(); }, get children() { - var _el$119 = createElement("box"), _el$120 = createElement("box"); - insertNode(_el$119, _el$120); - setProp(_el$119, "flexDirection", "column"); - setProp(_el$120, "height", 1); - insert(_el$119, detail, null); - return _el$119; + var _el$126 = createElement("box"), _el$127 = createElement("box"); + insertNode(_el$126, _el$127); + setProp(_el$126, "flexDirection", "column"); + setProp(_el$127, "height", 1); + insert(_el$126, detail, null); + return _el$126; } }), null); - return _el$117; + return _el$124; })(); }, get children() { - var _el$111 = createElement("box"), _el$112 = createElement("box"); - insertNode(_el$111, _el$112); - setProp(_el$111, "flexDirection", "row"); - setProp(_el$112, "flexDirection", "column"); - insert(_el$112, createComponent(Show, { + var _el$118 = createElement("box"), _el$119 = createElement("box"); + insertNode(_el$118, _el$119); + setProp(_el$118, "flexDirection", "row"); + setProp(_el$119, "flexDirection", "column"); + insert(_el$119, createComponent(Show, { get when() { return model.rows().length > 0; }, @@ -9654,36 +12112,36 @@ function DispatchPanel(props) { return rows(); } })); - insert(_el$111, createComponent(Show, { + insert(_el$118, createComponent(Show, { get when() { return model.selectedID(); }, get children() { - var _el$113 = createElement("box"); - setProp(_el$113, "flexDirection", "column"); - insert(_el$113, detail); - effect((_$p) => setProp(_el$113, "width", model.layout().detailWidth, _$p)); - return _el$113; + var _el$120 = createElement("box"); + setProp(_el$120, "flexDirection", "column"); + insert(_el$120, detail); + effect((_$p) => setProp(_el$120, "width", model.layout().detailWidth, _$p)); + return _el$120; } }), null); - effect((_$p) => setProp(_el$112, "width", model.layout().listWidth, _$p)); - return _el$111; + effect((_$p) => setProp(_el$119, "width", model.layout().listWidth, _$p)); + return _el$118; } - }), _el$114); - setProp(_el$114, "height", 1); - insert(_el$115, () => model.footer()); + }), _el$121); + setProp(_el$121, "height", 1); + insert(_el$122, () => model.footer()); effect((_p$) => { var _v$14 = text(), _v$15 = muted(), _v$16 = muted(); - _v$14 !== _p$.e && (_p$.e = setProp(_el$109, "fg", _v$14, _p$.e)); - _v$15 !== _p$.t && (_p$.t = setProp(_el$110, "fg", _v$15, _p$.t)); - _v$16 !== _p$.a && (_p$.a = setProp(_el$115, "fg", _v$16, _p$.a)); + _v$14 !== _p$.e && (_p$.e = setProp(_el$116, "fg", _v$14, _p$.e)); + _v$15 !== _p$.t && (_p$.t = setProp(_el$117, "fg", _v$15, _p$.t)); + _v$16 !== _p$.a && (_p$.a = setProp(_el$122, "fg", _v$16, _p$.a)); return _p$; }, { e: void 0, t: void 0, a: void 0 }); - return _el$108; + return _el$115; })(); } /** App-level command claim: the only way into the panel. It registers the @@ -9716,29 +12174,99 @@ function DispatchCommandLayer(props) { function PantheonSettingsCommandLayer(props) { props.context.keymap.layer(() => ({ mode: "global", - commands: [{ - id: "pantheon.settings.open", - title: "Pantheon: Settings", - group: "Pantheon", - palette: true, - slash: { name: "pantheon-settings" }, - run: () => { - openPantheonSettings(props.context); + commands: [ + { + id: "pantheon.settings.open", + title: "Pantheon: Settings", + group: "Pantheon", + palette: true, + slash: { name: "pantheon-settings" }, + run: () => { + openPantheonSettings(props.context); + } + }, + { + id: "pantheon.updates.open", + title: "Pantheon: Updates & Cleanup", + group: "Pantheon", + palette: true, + slash: { name: "pantheon-updates" }, + run: () => { + openPantheonSettings(props.context, { initialTab: "updates" }); + } + }, + { + id: "pantheon.whats-new.open", + title: "Pantheon: What's New", + group: "Pantheon", + palette: true, + slash: { + name: "pantheon-whats-new", + aliases: ["whats-new"] + }, + run: () => { + maybeShowWhatsNew(props.context, { force: true }); + } + }, + { + id: "pantheon.artifacts.open", + title: "Pantheon: Artifacts", + group: "Pantheon", + palette: true, + slash: { + name: "pantheon-artifacts", + aliases: ["artifacts"] + }, + run: () => { + openArtifactsDialog(props.context, resolveSidebarCwd(props.context)); + } + }, + { + id: "pantheon.cockpit.open", + title: "Pantheon: Mission Control Cockpit", + group: "Pantheon", + palette: true, + slash: { + name: "pantheon-cockpit", + aliases: ["cockpit"] + }, + run: () => { + openPantheonCockpit(props.context, resolveSidebarCwd(props.context)); + } } - }] + ] })); return null; } +function useWorkspaceArtifacts(context) { + const [entries, setEntries] = createSignal(scanPantheonArtifacts(resolveSidebarCwd(context))); + let lastScan = Date.now(); + const refresh = () => { + const now = Date.now(); + if (now - lastScan < 1500) return; + lastScan = now; + setEntries(scanPantheonArtifacts(resolveSidebarCwd(context))); + }; + onMount(() => { + setEntries(scanPantheonArtifacts(resolveSidebarCwd(context))); + const stop = subscribeSidebarRefresh(context, refresh); + onCleanup(stop); + }); + return entries; +} /** Home-screen status contribution. The sidebar slot is session-scoped, so * before the first prompt the sidebar may not mount at all (Known Issue) — * this keeps a compact Pantheon line visible on the home footer meanwhile. */ function HomeStatus(props) { const preset = useActivePreset(props.context).preset; - const availableUpdate = useAvailableUpdate("2.2.0-beta.11"); + const availableUpdate = useAvailableUpdate("2.2.0"); + const artifacts = useWorkspaceArtifacts(props.context); + const activePlan = () => artifacts().find((entry) => entry.kind === "plan"); + const isPt = () => resolveLanguage(tuiPrefs().layout?.language) === "pt-BR"; const accent = () => resolveAccentColor(tuiDraftPreview()?.theme?.accent ?? tuiPrefs().theme?.accent, props.context.theme); const muted = () => props.context.theme?.text?.muted ?? props.context.theme?.text?.base; - const updateBadge = () => formatUpdateBadge("2.2.0-beta.11", availableUpdate(), { - isPt: resolveLanguage(tuiPrefs().layout?.language) === "pt-BR", + const updateBadge = () => formatUpdateBadge("2.2.0", availableUpdate(), { + isPt: isPt(), compact: true }); return createComponent(Show, { @@ -9746,23 +12274,74 @@ function HomeStatus(props) { return tuiPrefs().footer.home; }, get children() { - var _el$121 = createElement("box"), _el$122 = createElement("text"); - insertNode(_el$121, _el$122); - setProp(_el$121, "flexDirection", "row"); - insert(_el$122, () => `Pantheon v2.2.0-beta.11${preset().name ? ` ▸ ${preset().name}` : ""}`); - insert(_el$121, createComponent(Show, { + var _el$128 = createElement("box"), _el$129 = createElement("text"), _el$132 = createElement("box"), _el$133 = createElement("text"); + insertNode(_el$128, _el$129); + insertNode(_el$128, _el$132); + setProp(_el$128, "flexDirection", "row"); + insert(_el$129, () => `Pantheon v2.2.0${preset().name ? ` ▸ ${preset().name}` : ""}`); + insert(_el$128, createComponent(Show, { get when() { return updateBadge(); }, children: (badge) => (() => { - var _el$123 = createElement("text"); - insert(_el$123, () => ` · ${badge()}`); - effect((_$p) => setProp(_el$123, "fg", accent(), _$p)); - return _el$123; + var _el$135 = createElement("box"), _el$136 = createElement("text"); + insertNode(_el$135, _el$136); + setProp(_el$135, "onMouseDown", () => { + openPantheonSettings(props.context, { initialTab: "updates" }); + }); + insert(_el$136, () => ` · ${badge()}`); + effect((_$p) => setProp(_el$136, "fg", accent(), _$p)); + return _el$135; + })() + }), _el$132); + insert(_el$128, createComponent(Show, { + get when() { + return activePlan(); + }, + children: (plan) => (() => { + var _el$137 = createElement("box"), _el$138 = createElement("text"); + insertNode(_el$137, _el$138); + setProp(_el$137, "onMouseDown", () => { + openArtifactsDialog(props.context, resolveSidebarCwd(props.context), { initialArtifactId: plan().id }); + }); + insert(_el$138, () => ` · ▸ Plan: ${truncateLabel(plan().title, 20)}`); + effect((_$p) => setProp(_el$138, "fg", accent(), _$p)); + return _el$137; })() - }), null); - effect((_$p) => setProp(_el$122, "fg", muted(), _$p)); - return _el$121; + }), _el$132); + insert(_el$128, createComponent(Show, { + get when() { + return artifacts().length > 0; + }, + get children() { + var _el$130 = createElement("box"), _el$131 = createElement("text"); + insertNode(_el$130, _el$131); + setProp(_el$130, "onMouseDown", () => { + openArtifactsDialog(props.context, resolveSidebarCwd(props.context)); + }); + insert(_el$131, (() => { + var _c$2 = memo(() => !!isPt()); + return () => _c$2() ? ` · Artefatos (${artifacts().length})` : ` · Artifacts (${artifacts().length})`; + })()); + effect((_$p) => setProp(_el$131, "fg", muted(), _$p)); + return _el$130; + } + }), _el$132); + insertNode(_el$132, _el$133); + setProp(_el$132, "onMouseDown", () => { + openPantheonCockpit(props.context, resolveSidebarCwd(props.context)); + }); + insertNode(_el$133, createTextNode(` · ◈ Cockpit`)); + effect((_p$) => { + var _v$17 = muted(), _v$18 = muted(); + _v$17 !== _p$.e && (_p$.e = setProp(_el$129, "fg", _v$17, _p$.e)); + _v$18 !== _p$.t && (_p$.t = setProp(_el$133, "fg", _v$18, _p$.t)); + return _p$; + }, { + e: void 0, + t: void 0 + }); + return _el$128; } }); } @@ -9818,10 +12397,10 @@ function PromptFooter(props) { return memo(() => !!tuiPrefs().footer.prompt)() && model.running() > 0; }, get children() { - var _el$124 = createElement("text"); - insert(_el$124, () => `▸${model.preset().name ?? "default"} · ✦${model.running()} ativos`); - effect((_$p) => setProp(_el$124, "fg", muted(), _$p)); - return _el$124; + var _el$139 = createElement("text"); + insert(_el$139, () => `▸${model.preset().name ?? "default"} · ✦${model.running()} ativos`); + effect((_$p) => setProp(_el$139, "fg", muted(), _$p)); + return _el$139; } }); } @@ -9846,7 +12425,7 @@ const plugin = Plugin.define({ append: "home.footer.status", render: () => createComponent(HomeStatus, { context }) }); - setAvailableUpdateVersion(resolveCachedAvailableUpdate("2.2.0-beta.11", updateCheckStateFile().readState())); + setAvailableUpdateVersion(resolveCachedAvailableUpdate("2.2.0", updateCheckStateFile().readState())); const updateNoticeTimer = setTimeout(() => { checkForPantheonUpdate(context).catch(() => {}); }, 3e3); @@ -9887,6 +12466,9 @@ const plugin = Plugin.define({ try { setupPantheonSettings(context, { renderSidebar: (ctx) => createComponent(Sidebar, { context: ctx }) }); } catch {} + try { + setupPantheonCockpit(context, () => resolveSidebarCwd(context)); + } catch {} const unregisterSettingsSlot = context.ui.slot({ append: "session.composer.top", render: (slotProps) => createComponent(PantheonSettingsSlot, { @@ -9912,6 +12494,6 @@ const plugin = Plugin.define({ } }); //#endregion -export { BLOCK_ICONS, CONTEXT_BAR_CELLS, CONTEXT_BAR_EMPTY_CELL, CONTEXT_BAR_FILLED_CELL, DELEGATION_CHILD_STATUS_GRACE_MS, DISPATCH_AGENT_CEILING, DISPATCH_AGENT_WIDTH, DISPATCH_COST_WIDTH, DISPATCH_COUNT_WIDTH, DISPATCH_DONE_MARKER, DISPATCH_DURATION_WIDTH, DISPATCH_GROUP_COST_WIDTH, DISPATCH_KIND_ORIGIN_LABELS, DISPATCH_MAX_LINES, DISPATCH_MAX_WIDTH, DISPATCH_MIN_AGENT_WIDTH, DISPATCH_MODEL_WIDTH, DISPATCH_PANEL_AGENT_WIDTH, DISPATCH_PANEL_COMMANDS, DISPATCH_PANEL_COST_WIDTH, DISPATCH_PANEL_DASH, DISPATCH_PANEL_DURATION_WIDTH, DISPATCH_PANEL_EMPTY_TEXT, DISPATCH_PANEL_FULLSCREEN_BADGE, DISPATCH_PANEL_HEADER_MARKER, DISPATCH_PANEL_KIND_WIDTH, DISPATCH_PANEL_MIN_AGENT_WIDTH, DISPATCH_PANEL_NAME, DISPATCH_PANEL_PAGE_SIZE, DISPATCH_PANEL_RULE_CHAR, DISPATCH_PANEL_SELECTION_GUTTER, DISPATCH_PANEL_SELECTION_MARKER, DISPATCH_PANEL_TITLE_WIDTH, DISPATCH_PANEL_TOAST, DISPATCH_PANEL_WIDE_MIN_WIDTH, DISPATCH_RUNNING_CEILING, GIT_ARROW_DOWN, GIT_ARROW_UP, GIT_CHANGES_DEBOUNCE_MS, GIT_CLI_DEBOUNCE_MS, GIT_CLI_MAX_BUFFER, GIT_CLI_MIN_INTERVAL_MS, GIT_CLI_TIMEOUT_MS, HEADER_MAX_WIDTH, MODEL_USAGE_COST_WIDTH, MODEL_USAGE_DEBOUNCE_MS, MODEL_USAGE_MESSAGE_LIMIT, MODEL_USAGE_MODEL_WIDTH, MODEL_USAGE_SESSION_LIMIT, MODEL_USAGE_TOKEN_WIDTH, MODEL_USAGE_VISIBLE_CEILING, PRESET_MARKER, SIDEBAR_REFRESH_EVENTS, SIDEBAR_WAITING_LABEL, SPEND_30D_LABEL, SPEND_30D_MS, SPEND_LINE_SEPARATOR, SPEND_PROBE_TOLERANCE_MS, SPEND_PROBE_WINDOW_MS, SPEND_REFRESH_DEBOUNCE_MS, SPEND_TODAY_LABEL, TODO_TEXT_WIDTH, TODO_VISIBLE_CEILING, UNKNOWN_AGENT, agentKey, buildDispatchBlock, cacheHitPercent, ceilingModelUsage, ceilingTodoItems, cellWidth, childAgentRowText, classifyDispatchKind, collectChildAgentUsage, collectDispatch, collectModelUsage, collectSubagentCalls, collectWarmupTargets, completedSummaryText, computeContextUsage, contextBar, contextBarFilled, contextBlockRows, contextPerformanceLine, contextProgressColor, contextSpendLine, contextSpendLines, contextUsageTone, countGitChanges, countSessionCompactions, countToolCalls, countUserTurns, createDispatchPanelModel, createFooterModel, createSidebarModel, plugin as default, defaultGitExec, delegationStateFromOutcome, delegationStateFromStatus, detectDelegationCompletions, dispatchAgentText, dispatchElapsed, dispatchHeaderSummary, dispatchKindFromAgent, dispatchKindFromPrefix, dispatchKindSuffix, dispatchModelText, dispatchPanelCell, dispatchPanelDetail, dispatchPanelFooter, dispatchPanelHeader, dispatchPanelKeymapLayer, dispatchPanelLayout, dispatchPanelMarker, dispatchPanelRangeText, dispatchPanelRowText, dispatchPanelRows, dispatchPanelRule, dispatchPanelTitle, dispatchPanelWindow, dispatchTokenLine, dispatchTokens, dispatchTotalCost, extractCompactionInfo, extractTokenAnatomy, failedSuffixText, formatCompactionBadge, formatContextWindow, formatDispatchCost, formatDispatchDuration, formatGitChanges, formatGitSnapshot, formatSpendUSD, formatSpent, formatTokenAnatomyLine, formatTokenAnatomySplit, formatTokenCount, formatToolCallLine, formatTurnCostLine, formatTurnCostUSD, formatTurnsBadge, formatUsageCost, formatUsageTokens, gitProbeAllowed, hiddenChildAgentsText, hiddenModelUsageText, hiddenTodoText, isTodoStatus, isValidSessionID, lastAssistantWithTokens, latestTodoItems, latestTurnCost, messageTokensTotal, modelRefID, modelUsageRowLines, modelUsageRowText, modelUsageRows, navigateToSession, openDispatchPanel, orderDispatchEntries, orderTodoItems, padCell, parseGitAheadBehind, parseGitStatusPorcelain, parsePresetOverrides, parseTodoItems, performDispatchPanelAction, presetFromEnv, presetHeaderLine, providerIDFromModels, providerIDFromRef, readGitSnapshot, resetSpendUnit, resolveActiveModelRef, resolveActivePresetForTui, resolveContextLimit, resolveGateStatus, resolveModelContextSnapshot, resolvedSpendUnit, runDispatchPanelCommand, runningChildRowText, shortModelID, shortSessionID, sidebarMoneyLines, sidebarPlaceholder, sidebarTextLines, spendWindows, spinnerFrame, startOfLocalDay, statsCost, statsRangeMatches, toDelegationView, toDispatchEntry, todoRowText, todoTone, transcriptWindow, truncateLabel, turnTokensPerSecond, withBlockSpacers }; +export { BLOCK_ICONS, CONTEXT_BAR_CELLS, CONTEXT_BAR_EMPTY_CELL, CONTEXT_BAR_FILLED_CELL, DELEGATION_CHILD_STATUS_GRACE_MS, DISPATCH_AGENT_CEILING, DISPATCH_AGENT_WIDTH, DISPATCH_COST_WIDTH, DISPATCH_COUNT_WIDTH, DISPATCH_DONE_MARKER, DISPATCH_DURATION_WIDTH, DISPATCH_GROUP_COST_WIDTH, DISPATCH_KIND_ORIGIN_LABELS, DISPATCH_MAX_LINES, DISPATCH_MAX_WIDTH, DISPATCH_MIN_AGENT_WIDTH, DISPATCH_MODEL_WIDTH, DISPATCH_PANEL_AGENT_WIDTH, DISPATCH_PANEL_COMMANDS, DISPATCH_PANEL_COST_WIDTH, DISPATCH_PANEL_DASH, DISPATCH_PANEL_DURATION_WIDTH, DISPATCH_PANEL_EMPTY_TEXT, DISPATCH_PANEL_FULLSCREEN_BADGE, DISPATCH_PANEL_HEADER_MARKER, DISPATCH_PANEL_KIND_WIDTH, DISPATCH_PANEL_MIN_AGENT_WIDTH, DISPATCH_PANEL_NAME, DISPATCH_PANEL_PAGE_SIZE, DISPATCH_PANEL_RULE_CHAR, DISPATCH_PANEL_SELECTION_GUTTER, DISPATCH_PANEL_SELECTION_MARKER, DISPATCH_PANEL_TITLE_WIDTH, DISPATCH_PANEL_TOAST, DISPATCH_PANEL_WIDE_MIN_WIDTH, DISPATCH_RUNNING_CEILING, GIT_ARROW_DOWN, GIT_ARROW_UP, GIT_CHANGES_DEBOUNCE_MS, GIT_CLI_DEBOUNCE_MS, GIT_CLI_MAX_BUFFER, GIT_CLI_MIN_INTERVAL_MS, GIT_CLI_TIMEOUT_MS, HEADER_MAX_WIDTH, MODEL_USAGE_COST_WIDTH, MODEL_USAGE_DEBOUNCE_MS, MODEL_USAGE_MESSAGE_LIMIT, MODEL_USAGE_MODEL_WIDTH, MODEL_USAGE_SESSION_LIMIT, MODEL_USAGE_TOKEN_WIDTH, MODEL_USAGE_VISIBLE_CEILING, PRESET_MARKER, SIDEBAR_REFRESH_EVENTS, SIDEBAR_WAITING_LABEL, SPEND_30D_LABEL, SPEND_30D_MS, SPEND_LINE_SEPARATOR, SPEND_PROBE_TOLERANCE_MS, SPEND_PROBE_WINDOW_MS, SPEND_REFRESH_DEBOUNCE_MS, SPEND_TODAY_LABEL, TODO_TEXT_WIDTH, TODO_VISIBLE_CEILING, UNKNOWN_AGENT, agentKey, buildDispatchBlock, cacheHitPercent, ceilingModelUsage, ceilingTodoItems, cellWidth, childAgentRowText, classifyDispatchKind, classifyToolPart, collectChildAgentUsage, collectDispatch, collectModelUsage, collectSubagentCalls, collectWarmupTargets, completedSummaryText, computeContextUsage, contextBar, contextBarFilled, contextBlockRows, contextPerformanceLine, contextProgressColor, contextSpendLine, contextSpendLines, contextUsageTone, countGitChanges, countSessionCompactions, countToolCalls, countUserTurns, createDispatchPanelModel, createFooterModel, createSidebarModel, plugin as default, defaultGitExec, delegationStateFromOutcome, delegationStateFromStatus, detectDelegationCompletions, dispatchAgentText, dispatchElapsed, dispatchHeaderSummary, dispatchKindFromAgent, dispatchKindFromPrefix, dispatchKindSuffix, dispatchModelText, dispatchPanelCell, dispatchPanelDetail, dispatchPanelFooter, dispatchPanelHeader, dispatchPanelKeymapLayer, dispatchPanelLayout, dispatchPanelMarker, dispatchPanelRangeText, dispatchPanelRowText, dispatchPanelRows, dispatchPanelRule, dispatchPanelTitle, dispatchPanelWindow, dispatchTokenLine, dispatchTokens, dispatchTotalCost, enrichDispatchEntries, extractChildActivity, extractCompactionInfo, extractTokenAnatomy, failedSuffixText, formatCompactionBadge, formatContextWindow, formatDispatchCost, formatDispatchDuration, formatGitChanges, formatGitSnapshot, formatSpendUSD, formatSpent, formatTokenAnatomyLine, formatTokenAnatomySplit, formatTokenCount, formatToolCallLine, formatToolDomainLine, formatTurnCostLine, formatTurnCostUSD, formatTurnsBadge, formatUsageCost, formatUsageTokens, gitProbeAllowed, hiddenChildAgentsText, hiddenModelUsageText, hiddenTodoText, isTodoStatus, isValidSessionID, lastAssistantWithTokens, latestTodoItems, latestTurnCost, messageTokensTotal, modelRefID, modelUsageRowLines, modelUsageRowText, modelUsageRows, navigateToSession, openDispatchPanel, orderDispatchEntries, orderTodoItems, padCell, parseGitAheadBehind, parseGitStatusPorcelain, parsePresetOverrides, parseTodoItems, performDispatchPanelAction, presetFromEnv, presetHeaderLine, providerIDFromModels, providerIDFromRef, readGitSnapshot, resetSpendUnit, resolveActiveModelRef, resolveActivePresetForTui, resolveContextLimit, resolveGateStatus, resolveModelContextSnapshot, resolvedSpendUnit, runDispatchPanelCommand, runningChildRowText, shortModelID, shortSessionID, sidebarMoneyLines, sidebarPlaceholder, sidebarTextLines, spendWindows, spinnerFrame, startOfLocalDay, statsCost, statsRangeMatches, summarizeToolDomains, toDelegationView, toDispatchEntry, todoRowText, todoTone, transcriptWindow, truncateLabel, turnTokensPerSecond, withBlockSpacers }; //# sourceMappingURL=tui.js.map diff --git a/src/plugins/tui/dist/tui.js.map b/src/plugins/tui/dist/tui.js.map index 25184244..c1b907b1 100644 --- a/src/plugins/tui/dist/tui.js.map +++ b/src/plugins/tui/dist/tui.js.map @@ -1 +1 @@ -{"version":3,"file":"tui.js","names":["numberOrNull","resolveRunningVersion"],"sources":["../src/context-gauge.ts","../src/model-usage-limits.ts","../src/autonomy-state.ts","../src/decision-router-state.ts","../src/pantheon-settings-state.ts","../src/update-notice.ts","../src/doctor-state.ts","../src/settings-i18n.ts","../src/j1-gate-status.ts","../src/legacy-audit.ts","../src/preset-state.ts","../src/quota-state.ts","../src/tui-prefs.ts","../src/update-status.ts","../src/whats-new-highlights.ts","../src/sidebar-width.ts","../src/whats-new-state.ts","../src/whats-new-open.ts"],"sourcesContent":["/** Shared, data-only formatting and visual helpers for compact context gauges. */\n\nexport type ContextProgressTone = 'info' | 'success' | 'warning' | 'error'\n\nexport const CONTEXT_BAR_CELLS = 12\nexport const CONTEXT_BAR_FILLED_CELL = '\\u25B0'\nexport const CONTEXT_BAR_EMPTY_CELL = '\\u25B1'\n\nexport type BarShape = 'block' | 'line' | 'smooth' | 'ascii' | 'dots' | 'braille'\n\nexport interface BarShapeGlyphs {\n filled: string\n empty: string\n mark?: string\n}\n\nexport const BAR_SHAPES: Record = {\n block: { filled: '\\u25B0', empty: '\\u25B1', mark: '│' },\n line: { filled: '━', empty: '─', mark: '┼' },\n smooth: { filled: '█', empty: '░', mark: '┆' },\n ascii: { filled: '=', empty: '-', mark: '|' },\n dots: { filled: '●', empty: '○', mark: '│' },\n braille: { filled: '⣿', empty: '⣀', mark: '⡇' },\n}\n\nexport interface ContextBarOptions {\n cells?: number\n shape?: BarShape\n evenMark?: boolean\n}\n\nfunction numberOrNull(value: unknown): number | null {\n return typeof value === 'number' && Number.isFinite(value) ? value : null\n}\n\nexport function contextUsageTone(percent: number): ContextProgressTone {\n if (percent > 90) return 'error'\n if (percent > 50) return 'warning'\n if (percent > 25) return 'success'\n return 'info'\n}\n\nexport function formatTokenCount(tokens: number | null | undefined): string | null {\n const value = numberOrNull(tokens)\n if (value === null || value < 0) return null\n return Math.round(value).toLocaleString('en-US')\n}\n\nexport function formatContextWindow(limit: number | null | undefined): string | null {\n const value = numberOrNull(limit)\n if (value === null || value <= 0) return null\n if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}M`\n if (value >= 1_000) return `${Math.floor(value / 1_000)}K`\n return `${Math.floor(value)}`\n}\n\nexport function contextBarFilled(percent: number, cells = CONTEXT_BAR_CELLS): number {\n const total = Math.max(1, Math.floor(cells))\n const filled = Math.round((percent / 100) * total)\n if (!Number.isFinite(filled)) return 0\n return Math.min(total, Math.max(0, filled))\n}\n\nexport function contextBar(\n percent: number | null | undefined,\n options: number | ContextBarOptions = CONTEXT_BAR_CELLS,\n): { filled: string; empty: string } | null {\n const value = numberOrNull(percent)\n if (value === null) return null\n const total = Math.max(\n 1,\n Math.floor(typeof options === 'number' ? options : (options?.cells ?? CONTEXT_BAR_CELLS)),\n )\n const shapeKey =\n typeof options === 'object' && options?.shape && options.shape in BAR_SHAPES\n ? options.shape\n : 'block'\n const glyphs = BAR_SHAPES[shapeKey] ?? BAR_SHAPES.block\n const evenMark = typeof options === 'object' ? Boolean(options?.evenMark) : false\n\n const filledCount = contextBarFilled(value, total)\n const emptyCount = total - filledCount\n\n if (!evenMark || total < 4) {\n return {\n filled: glyphs.filled.repeat(filledCount),\n empty: glyphs.empty.repeat(emptyCount),\n }\n }\n\n // Insert even-use mark at the midpoint (50%)\n const mid = Math.floor(total / 2)\n const mark = glyphs.mark ?? '|'\n\n if (filledCount <= mid) {\n // Mark is in the empty portion\n const emptyBefore = mid - filledCount\n const emptyAfter = Math.max(0, emptyCount - emptyBefore - 1)\n return {\n filled: glyphs.filled.repeat(filledCount),\n empty: `${glyphs.empty.repeat(emptyBefore)}${mark}${glyphs.empty.repeat(emptyAfter)}`,\n }\n }\n\n // Mark is in the filled portion\n const filledBefore = mid\n const filledAfter = Math.max(0, filledCount - filledBefore - 1)\n return {\n filled: `${glyphs.filled.repeat(filledBefore)}${mark}${glyphs.filled.repeat(filledAfter)}`,\n empty: glyphs.empty.repeat(emptyCount),\n }\n}\n\nexport function formatSpent(cost: number | null | undefined): string | null {\n const value = numberOrNull(cost)\n if (value === null || value < 0) return null\n return `$${value.toFixed(2)}`\n}\n","/** Shared bounds for cached recent model-usage aggregation. */\nexport const MODEL_USAGE_VISIBLE_CEILING = 3\nexport const MODEL_USAGE_MESSAGE_LIMIT = 400\nexport const MODEL_USAGE_SESSION_LIMIT = 8\n","/**\n * autonomy-state.ts — the Autonomy tab of the settings window.\n *\n * TUI-local copy doctrine. Two surfaces live here:\n *\n * 1. GOAL LOOP — the persisted-mission loop (Wave 3 mechanics) read/written\n * to `options.goal_loop` in the user's opencode.json (the same V2 config\n * copy the context pruner uses). Startup-applied: the runtime resolves it\n * once at plugin setup, so saving requires an OpenCode restart — the tab\n * says so.\n *\n * 2. DECISION BUDGETS — monthly/per-decision USD caps stored in\n * decision-router.json's companion `decision-budget` semantics. The caps\n * the CLI writes via setup-model flags; here they are read from the\n * decision-router.json envelope extension `budget` (v2 superset — the\n * exact-key validator tolerates it via the documented envelope) and\n * applied live per gated call.\n *\n * The decision-gradiente (decide-solo → Jev → human) is DOCUMENTED here, not\n * enforced: J1 owns the risk axis, budgets own the money axis — this tab\n * shows where the thresholds sit today.\n */\nimport type { SettingsTab } from './pantheon-settings-state.ts'\n\nexport interface GoalLoopPrefs {\n enabled: boolean\n cooldownMs: number\n maxContinuations: number\n}\n\nexport const DEFAULT_GOAL_LOOP_PREFS: GoalLoopPrefs = {\n enabled: false,\n cooldownMs: 5000,\n maxContinuations: 25,\n}\n\nexport const GOAL_LOOP_ENABLED_CYCLE: readonly string[] = Object.freeze(['enabled', 'disabled'])\n\nexport const MAX_CONTINUATIONS_CYCLE: readonly string[] = Object.freeze([\n '10',\n '25',\n '50',\n '100',\n '200',\n])\n\nexport const COOLDOWN_MS_CYCLE: readonly string[] = Object.freeze(['1000', '2000', '5000', '10000'])\n\nexport interface DecisionBudgets {\n monthlyUsd: number\n perDecisionUsd: number\n}\n\nexport const DEFAULT_DECISION_BUDGETS: DecisionBudgets = {\n monthlyUsd: 5,\n perDecisionUsd: 0.1,\n}\n\n/** Format USD compactly for a cycler cell (\"$5\", \"$0.10\"). */\nexport function formatUsd(value: number): string {\n return `$${value < 1 ? value.toFixed(2) : String(Math.round(value))}`\n}\n\n/** Build the USD step ladder used by the budget cyclers. */\nexport const MONTHLY_USD_CYCLE: readonly string[] = Object.freeze(\n [1, 2, 5, 10, 20, 50, 100].map((value) => formatUsd(value)),\n)\nexport const PER_DECISION_USD_CYCLE: readonly string[] = Object.freeze(\n [0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1].map((value) => formatUsd(value)),\n)\n\n/** Parse a staged USD cell back to a number; junk keeps the input. */\nexport function parseUsd(cell: string): number | null {\n const value = Number(cell.replace('$', ''))\n return Number.isFinite(value) && value > 0 ? value : null\n}\n\nexport function buildAutonomyTab(input: {\n goalLoop: GoalLoopPrefs\n budgets: DecisionBudgets\n goalLoopRestartPending?: boolean | undefined\n languagePref?: string | undefined\n}): SettingsTab {\n const isPt = input.languagePref === 'pt-BR'\n\n return {\n id: 'autonomy',\n title: isPt ? 'Autonomia' : 'Autonomy',\n groups: [\n {\n title: isPt\n ? 'Loop Contínuo (auto-continuação de sessões multi-turn)'\n : 'Auto-Continue Loop (multi-turn session auto-continuation)',\n rows: [\n {\n id: 'autonomy.goal_loop.enabled',\n name: isPt ? 'Loop Contínuo' : 'Auto-Continue Loop',\n value: input.goalLoop.enabled ? 'enabled' : 'disabled',\n cycle: GOAL_LOOP_ENABLED_CYCLE,\n note: isPt\n ? 'continua tarefas multi-turn quando a sessão fica ociosa' +\n (input.goalLoopRestartPending\n ? ' · [!] reinício necessário para aplicar (restart)'\n : ' · aplicado após reiniciar o OpenCode')\n : 'auto-continues multi-turn tasks when session goes idle' +\n (input.goalLoopRestartPending\n ? ' · [!] restart required to apply'\n : ' · applies after OpenCode restart'),\n },\n {\n id: 'autonomy.goal_loop.maxContinuations',\n name: isPt ? 'Limite continuações' : 'Max continuations',\n value: String(input.goalLoop.maxContinuations),\n cycle: MAX_CONTINUATIONS_CYCLE,\n note: isPt\n ? '1..200 — teto de segurança contra loops infinitos'\n : '1..200 — safety ceiling to prevent runaway tasks',\n },\n {\n id: 'autonomy.goal_loop.cooldownMs',\n name: isPt ? 'Pausa entre turnos (ms)' : 'Cooldown (ms)',\n value: String(input.goalLoop.cooldownMs),\n cycle: COOLDOWN_MS_CYCLE,\n note: isPt\n ? 'intervalo entre turnos autônomos (mín 1000ms)'\n : 'delay between autonomous turns (min 1000ms)',\n },\n ],\n },\n {\n title: isPt ? 'Orçamentos de Decisão (Jev)' : 'Decision Budgets (Jev)',\n rows: [\n {\n id: 'autonomy.budget.monthly',\n name: isPt ? 'Teto Mensal (USD)' : 'Monthly Budget Cap',\n value: formatUsd(input.budgets.monthlyUsd),\n cycle: MONTHLY_USD_CYCLE,\n note: isPt\n ? 'teto mensal em USD para arbitragem do Jev'\n : 'monthly USD ceiling for gated arbitrator decisions',\n },\n {\n id: 'autonomy.budget.perDecision',\n name: isPt ? 'Teto por Consulta' : 'Per-Decision Cap',\n value: formatUsd(input.budgets.perDecisionUsd),\n cycle: PER_DECISION_USD_CYCLE,\n note: isPt\n ? 'teto de custo por decisão — acima disso é recusada'\n : 'price cap — gated decisions above this are refused',\n },\n ],\n },\n {\n title: isPt\n ? 'Gradiente de Decisão (política de referência · governado por J1 e Orçamentos)'\n : 'Decision Gradient (reference policy · governed by J1 & Budgets)',\n rows: [\n {\n id: 'autonomy.gradient.solo',\n name: isPt ? 'Decisão solo' : 'Decide solo',\n value: isPt ? 'autônomo' : 'autonomous',\n note: isPt\n ? 'ações rotineiras de baixo risco · reversível sem travas (sem portão)'\n : 'reversible & low-risk edits, routine fixes (no gate)',\n },\n {\n id: 'autonomy.gradient.jev',\n name: isPt ? 'Decisão Jev' : 'Jev decides',\n value: isPt ? 'arbitrado' : 'arbitrated',\n note: isPt\n ? 'ambiguidade de tipos e rotas · configurado nos Tetos de Orçamento acima'\n : 'typed ambiguity & candidate ranking · configured via Budgets above',\n },\n {\n id: 'autonomy.gradient.human',\n name: isPt ? 'Aprovação humana' : 'Human decides',\n value: isPt ? 'revisão humana' : 'human review',\n note: isPt\n ? 'ações destrutivas e de alto risco · configurado no limiar do Portão J1'\n : 'high-risk & destructive operations · configured via J1 Gate',\n },\n ],\n },\n ],\n }\n}\n","/**\n * decision-router-state.ts — the Decision Model section of the settings window.\n *\n * TUI-local replica of the user-level decision-router config\n * (scripts/install/decision-router-config.mjs — the bundle must stay\n * self-contained); tests/tui-decision-router-state.test.mjs pins the schema\n * version, the exact key set and the provider matrix against that source.\n *\n * The runtime re-reads this file on EVERY gated call (jev-decision-tool.ts),\n * so a write here applies live — no restart. The strict exact-key schema is\n * load-bearing: any unknown key fail-closes the runtime to disabled/local,\n * so the writer validates before persisting.\n *\n * Egress consent is CLI-owned: the window never writes `egress_consent`, and\n * refuses to enable the router while remote candidates exist without it.\n */\nimport { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport type { SettingsRow, SettingsTab } from './pantheon-settings-state.ts'\n\nexport const DECISION_ENABLED_CYCLE: readonly string[] = Object.freeze(['enabled', 'disabled'])\n\nexport const DECISION_CONFIG_SCHEMA_VERSION = 2\n\n/** Exact top-level key set — anything else fail-closes the runtime. */\nexport const DECISION_CONFIG_KEYS: readonly string[] = Object.freeze([\n 'egress_consent',\n 'enabled',\n 'enabled_candidates',\n 'schema_version',\n 'selection',\n])\n\nexport type DecisionSelectionMode = 'local' | 'auto' | 'explicit'\n\nexport interface DecisionSelection {\n mode: DecisionSelectionMode\n provider?: string\n model?: string\n}\n\nexport interface DecisionCandidate {\n provider: string\n model: string\n}\n\nexport interface DecisionRouterConfig {\n schema_version: number\n enabled: boolean\n selection: DecisionSelection\n egress_consent: boolean\n enabled_candidates: readonly DecisionCandidate[]\n}\n\nexport const DEFAULT_DECISION_CONFIG: DecisionRouterConfig = Object.freeze({\n schema_version: DECISION_CONFIG_SCHEMA_VERSION,\n enabled: false,\n selection: Object.freeze({ mode: 'local' as const }),\n egress_consent: false,\n enabled_candidates: Object.freeze([]),\n})\n\n/** The runtime's provider→model matrix (drift-pinned against the installer source). */\nexport const DECISION_KNOWN_PROVIDERS: readonly string[] = Object.freeze([\n 'openai-decisions',\n 'typesafe-jev',\n 'opencode-console-jev',\n 'openrouter-jev',\n 'vercel-gateway-jev',\n 'cloudflare-workers-jev',\n])\n\nexport const DECISION_CONSENT_CYCLE: readonly string[] = Object.freeze(['not granted', 'granted'])\n/** provider → model, straight from the runtime matrix (drift-pinned in tests). */\nexport const DECISION_KNOWN_MODELS: Readonly> = Object.freeze({\n 'openai-decisions': 'gpt-6-luna',\n 'typesafe-jev': 'jev-1.14.0',\n 'opencode-console-jev': 'jev-1.13',\n 'openrouter-jev': 'typesafe/jev-1.13',\n 'vercel-gateway-jev': 'typesafe-ai/jev',\n 'cloudflare-workers-jev': 'clef',\n})\n\n/**\n * Credential surface per provider: the ENV VAR the host provider entry reads\n * (`{env:VAR}` indirection — the window NEVER holds key values) plus the setup\n * note. Drift-pinned against the installer/runtime sources in tests.\n */\nexport const DECISION_PROVIDER_CREDENTIALS: Readonly<\n Record\n> = Object.freeze({\n 'openai-decisions': {\n note: 'host-configured model — provision via `decision-router setup-model openai-decisions`',\n notePt: 'modelo do host — configure via `decision-router setup-model openai-decisions`',\n },\n 'typesafe-jev': {\n env: 'TYPESAFE_API_KEY',\n note: 'export TYPESAFE_API_KEY=… then restart',\n notePt: 'export TYPESAFE_API_KEY=… e depois reinicie',\n },\n 'opencode-console-jev': {\n note: 'rides your OpenCode login — no separate key',\n notePt: 'utiliza login do OpenCode — sem chave separada',\n },\n 'openrouter-jev': {\n env: 'OPENROUTER_API_KEY',\n note: 'export OPENROUTER_API_KEY=… then restart',\n notePt: 'export OPENROUTER_API_KEY=… e depois reinicie',\n },\n 'vercel-gateway-jev': {\n env: 'AI_GATEWAY_API_KEY',\n note: 'export AI_GATEWAY_API_KEY=… then restart',\n notePt: 'export AI_GATEWAY_API_KEY=… e depois reinicie',\n },\n 'cloudflare-workers-jev': {\n env: 'CLOUDFLARE_API_TOKEN',\n note: 'needs accountId (setup-model --account-id=…) + CLOUDFLARE_API_TOKEN',\n notePt: 'requer accountId (setup-model --account-id=…) + CLOUDFLARE_API_TOKEN',\n },\n})\n\nexport const DECISION_TARGET_CYCLE: readonly string[] = Object.freeze(\n DECISION_KNOWN_PROVIDERS.map((provider) => `${provider}/${DECISION_KNOWN_MODELS[provider]}`),\n)\n\nexport function decisionRouterConfigPath(env: Record = process.env) {\n const xdg = env.XDG_CONFIG_HOME\n const home = env.HOME ?? ''\n const root = xdg ?? join(home, '.config')\n return join(root, 'pantheon', 'decision-router.json')\n}\n\nexport interface DecisionConfigRead {\n config: DecisionRouterConfig\n /** The file exists but is not a valid v2 config — the runtime fail-closes. */\n corrupt: boolean\n}\n\n/** Fail-open read: a missing file is the default; an invalid one is reported, not guessed. */\nexport function readDecisionRouterConfig(\n env: Record = process.env,\n): DecisionConfigRead {\n let raw: unknown\n try {\n raw = JSON.parse(readFileSync(decisionRouterConfigPath(env), 'utf8'))\n } catch (error) {\n if ((error as NodeJS.ErrnoException)?.code === 'ENOENT') {\n return { config: cloneDefault(), corrupt: false }\n }\n return { config: cloneDefault(), corrupt: true }\n }\n if (isValidDecisionConfig(raw)) return { config: raw, corrupt: false }\n return { config: cloneDefault(), corrupt: true }\n}\n\nfunction cloneDefault(): DecisionRouterConfig {\n return {\n schema_version: DEFAULT_DECISION_CONFIG.schema_version,\n enabled: DEFAULT_DECISION_CONFIG.enabled,\n selection: { ...DEFAULT_DECISION_CONFIG.selection },\n egress_consent: DEFAULT_DECISION_CONFIG.egress_consent,\n enabled_candidates: [...DEFAULT_DECISION_CONFIG.enabled_candidates],\n }\n}\n\n/** The exact-key, exact-shape validation the runtime applies (fail-closed otherwise). */\nexport function isValidDecisionConfig(value: unknown): value is DecisionRouterConfig {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false\n const record = value as Record\n const keys = Object.keys(record).sort()\n if (keys.length !== DECISION_CONFIG_KEYS.length) return false\n for (const key of DECISION_CONFIG_KEYS) {\n if (!keys.includes(key)) return false\n }\n if (record.schema_version !== DECISION_CONFIG_SCHEMA_VERSION) return false\n if (typeof record.enabled !== 'boolean') return false\n if (typeof record.egress_consent !== 'boolean') return false\n if (!isValidSelection(record.selection)) return false\n if (!Array.isArray(record.enabled_candidates)) return false\n for (const candidate of record.enabled_candidates) {\n if (typeof candidate !== 'object' || candidate === null) return false\n const entry = candidate as Record\n if (typeof entry.provider !== 'string' || typeof entry.model !== 'string') return false\n if (Object.keys(entry).length !== 2) return false\n }\n return true\n}\n\nfunction isValidSelection(value: unknown): value is DecisionSelection {\n if (typeof value !== 'object' || value === null) return false\n const selection = value as Record\n if (selection.mode !== 'local' && selection.mode !== 'auto' && selection.mode !== 'explicit') {\n return false\n }\n const keys = Object.keys(selection).sort()\n for (const key of keys) {\n if (key !== 'mode' && key !== 'provider' && key !== 'model') return false\n }\n if (selection.provider !== undefined && typeof selection.provider !== 'string') return false\n if (selection.model !== undefined && typeof selection.model !== 'string') return false\n return true\n}\n\n/** Stable serializer: exact keys in sorted order, 2-space, trailing newline. */\nexport function serializeDecisionConfig(config: DecisionRouterConfig): string {\n const ordered = {\n egress_consent: config.egress_consent,\n enabled: config.enabled,\n enabled_candidates: config.enabled_candidates.map((candidate) => ({\n model: candidate.model,\n provider: candidate.provider,\n })),\n schema_version: config.schema_version,\n selection: {\n mode: config.selection.mode,\n ...(config.selection.model !== undefined ? { model: config.selection.model } : {}),\n ...(config.selection.provider !== undefined ? { provider: config.selection.provider } : {}),\n },\n }\n return `${JSON.stringify(ordered, null, 2)}\\n`\n}\n\n/**\n * Enable/disable the router in a config copy. The guard mirrors the runtime's\n * fail-close: with remote candidates and no egress consent, an enabled flag\n * would be a lie — enabling requires consent, or a local-only selection.\n * Never touches `egress_consent` (CLI-owned).\n */\nexport function setDecisionEnabled(\n config: DecisionRouterConfig,\n enabled: boolean,\n): { ok: true; config: DecisionRouterConfig } | { ok: false; reason: string } {\n if (enabled) {\n const localOnly = config.selection.mode === 'local' || config.enabled_candidates.length === 0\n if (!localOnly && !config.egress_consent) {\n return {\n ok: false,\n reason:\n 'remote candidates need egress consent — toggle Egress consent in this tab, then enable',\n }\n }\n }\n return { ok: true, config: { ...config, enabled } }\n}\n\n/** Atomic-ish write mirroring the canonical writer's privacy posture (0600). */\nexport function writeDecisionRouterConfig(\n config: DecisionRouterConfig,\n env: Record = process.env,\n): void {\n if (!isValidDecisionConfig(config)) {\n throw new TypeError('Refusing to persist an invalid decision-router configuration')\n }\n const path = decisionRouterConfigPath(env)\n mkdirSync(dirname(path), { recursive: true, mode: 0o700 })\n const temp = `${path}.tui.tmp`\n writeFileSync(temp, serializeDecisionConfig(config), { mode: 0o600 })\n renameSync(temp, path)\n chmodSync(path, 0o600)\n}\n\nexport const DECISION_SELECTION_CYCLE: readonly string[] = Object.freeze([\n 'local',\n 'auto',\n 'explicit',\n])\n\n/** Stage a selection/consent row into a config copy; unknown rows are no-ops. */\nexport function applyDecisionRow(\n config: DecisionRouterConfig,\n id: string,\n value: string,\n): DecisionRouterConfig {\n const next: DecisionRouterConfig = {\n ...config,\n selection: { ...config.selection },\n enabled_candidates: [...config.enabled_candidates],\n }\n switch (id) {\n case 'decision.selection.mode': {\n const mode = value as DecisionSelectionMode\n if (mode !== 'local' && mode !== 'auto' && mode !== 'explicit') return config\n next.selection.mode = mode\n if (mode === 'local') next.enabled_candidates = []\n return next\n }\n case 'decision.selection.target': {\n const separator = value.indexOf('/')\n if (separator <= 0) return config\n const provider = value.slice(0, separator)\n const model = value.slice(separator + 1)\n if (!DECISION_KNOWN_PROVIDERS.includes(provider)) return config\n if (DECISION_KNOWN_MODELS[provider] !== model) return config\n next.selection = { mode: 'explicit', provider, model }\n next.enabled_candidates = [{ provider, model }]\n return next\n }\n case 'decision.consent': {\n next.egress_consent = value === 'granted'\n return next\n }\n default:\n return config\n }\n}\n\n/** The host's provider auth store (`opencode auth login` writes here). */\nexport function decisionAuthStorePath(env: Record = process.env) {\n const xdgData = env.XDG_DATA_HOME\n const home = env.HOME ?? ''\n const root = xdgData ?? join(home, '.local', 'share')\n return join(root, 'opencode', 'auth.json')\n}\n\n/** Provider ids as they appear in the host auth store / config providers. */\nconst PROVIDER_AUTH_NAMES: Readonly> = Object.freeze({\n 'openai-decisions': Object.freeze(['openai']),\n 'typesafe-jev': Object.freeze(['typesafe-ai']),\n 'opencode-console-jev': Object.freeze([]),\n 'openrouter-jev': Object.freeze(['openrouter']),\n 'vercel-gateway-jev': Object.freeze(['vercel-ai-gateway', 'vercel']),\n 'cloudflare-workers-jev': Object.freeze(['cloudflare-workers-ai']),\n})\n\nexport type CredentialForm = 'env' | 'auth store' | 'config' | 'missing'\n\n/**\n * TWO recognition forms (field feedback beta.6: keys registered via\n * `opencode auth login` showed MISSING because only env vars were checked):\n * env var set → 'env'; provider present in the host auth store → 'auth\n * store'; provider entry in opencode.json providers → 'config'. Values are\n * NEVER read — existence only.\n */\nexport function credentialStatus(\n provider: string,\n env: Record,\n authProviders: ReadonlySet,\n configProviders: ReadonlySet,\n): CredentialForm {\n const credential = DECISION_PROVIDER_CREDENTIALS[provider]\n if (credential?.env !== undefined && env[credential.env]) return 'env'\n for (const name of PROVIDER_AUTH_NAMES[provider] ?? []) {\n if (authProviders.has(name)) return 'auth store'\n }\n for (const name of PROVIDER_AUTH_NAMES[provider] ?? []) {\n if (configProviders.has(name)) return 'config'\n }\n if (provider === 'opencode-console-jev') return 'auth store'\n return 'missing'\n}\n\nexport function buildDecisionTab(\n read: DecisionConfigRead,\n env: Record = process.env,\n authProviders: ReadonlySet = new Set(),\n configProviders: ReadonlySet = new Set(),\n languagePref?: string | undefined,\n): SettingsTab {\n const isPt = languagePref === 'pt-BR'\n const { config, corrupt } = read\n const rows: SettingsRow[] = [\n {\n id: 'decision.enabled',\n name: isPt ? 'Assistente Jev' : 'Jev Assistant',\n value: config.enabled ? 'enabled' : 'disabled',\n // Corrupt config → read-only; the notice (glue) carries the remedy.\n ...(corrupt ? {} : { cycle: DECISION_ENABLED_CYCLE }),\n note: corrupt\n ? isPt\n ? 'config inválida — runtime fail-closes; repare via `decision-router setup-model`'\n : 'config unreadable/invalid — runtime fail-closes; repair via `decision-router setup-model`'\n : isPt\n ? 'aplica em tempo real — arbitragem de decisões relida a cada chamada'\n : 'applies live — the runtime re-reads this on every gated call',\n },\n {\n id: 'decision.selection.mode',\n name: isPt ? 'Modo de Operação' : 'Operation Mode',\n value: config.selection.mode,\n ...(corrupt ? {} : { cycle: DECISION_SELECTION_CYCLE }),\n note: isPt\n ? 'local = no seu PC (grátis); auto/explícito = modelo nuvem (OpenRouter)'\n : 'local routes on-device; auto/explicit pick a remote decision model',\n },\n ]\n\n // Model selection row: always visible so the user can choose the decision model\n const explicitTarget = config.selection.provider\n ? `${config.selection.provider}/${config.selection.model ?? ''}`\n : (DECISION_TARGET_CYCLE[0] ?? 'openrouter-jev/typesafe/jev-1.13')\n rows.push({\n id: 'decision.selection.target',\n name: isPt ? 'Modelo de Decisão' : 'Decision Model',\n value:\n config.selection.mode === 'local'\n ? config.selection.provider\n ? `${config.selection.provider}/${config.selection.model ?? ''}`\n : 'local (on-device)'\n : explicitTarget,\n ...(corrupt ? {} : { cycle: DECISION_TARGET_CYCLE }),\n note: isPt\n ? config.selection.mode === 'local'\n ? 'ciclar seleciona modelo remoto e ativa modo explícito'\n : 'provedor/modelo ativo — define candidato para arbitragem'\n : config.selection.mode === 'local'\n ? 'cycle to select a remote model and activate explicit mode'\n : 'provider/model — sets the candidate list',\n })\n\n if ((config.enabled_candidates?.length ?? 0) > 0) {\n rows.push({\n id: 'decision.candidates',\n name: isPt ? 'Candidatos ativos' : 'Candidates',\n value: String(config.enabled_candidates.length),\n note: config.egress_consent\n ? config.enabled_candidates\n .map((candidate) => `${candidate.provider}/${candidate.model}`)\n .join(', ')\n : isPt\n ? 'egress consent NÃO concedido — rotas remotas bloqueadas'\n : 'egress consent NOT granted — remote routes fail closed',\n })\n }\n\n rows.push({\n id: 'decision.consent',\n name: isPt ? 'Acesso à Nuvem' : 'Cloud API Access',\n value: config.egress_consent ? 'granted' : 'not granted',\n ...(corrupt ? {} : { cycle: DECISION_CONSENT_CYCLE }),\n note: isPt\n ? config.egress_consent\n ? 'granted = rotas remotas podem consultar gateway de API (com teto de custo)'\n : 'not granted = chamadas remotas bloqueadas; requer granted para nuvem'\n : config.egress_consent\n ? 'granted = remote decision routes may call their gateway (budget-capped)'\n : 'not granted = remote routes fail closed; grant to allow cloud calls',\n })\n\n return {\n id: 'decision',\n title: isPt ? 'Decisão' : 'Decision',\n groups: [\n { title: isPt ? 'Assistente de Decisão (Jev)' : 'Decision Assistant (Jev)', rows },\n {\n title: isPt\n ? 'Credenciais (status apenas — valores nunca gravados na janela)'\n : 'Credentials (status only — values never enter the window)',\n rows: DECISION_KNOWN_PROVIDERS.map((provider) => {\n const status = credentialStatus(provider, env, authProviders, configProviders)\n const credential = DECISION_PROVIDER_CREDENTIALS[provider] ?? { note: '' }\n return {\n id: `decision.key.${provider}`,\n name: provider,\n value: status === 'missing' ? 'MISSING' : status,\n note: isPt ? (credential.notePt ?? credential.note) : credential.note,\n }\n }),\n },\n ],\n }\n}\n","/**\n * pantheon-settings-state.ts — the pure state core of the settings window.\n *\n * TUI-local copy doctrine (same as cost-data.ts): the bundle must stay\n * self-contained. The behaviors registry mirrors routing.yml's `behaviors:`\n * (drift-pinned by tests/pantheon-settings-state.test.mjs).\n *\n * Model (2.0.0-beta.4, the quota-style full window): the window is a set of\n * TABS; each tab holds GROUPS of setting ROWS; a row carries a display VALUE\n * and — when the setting is editable — the CYCLE of allowed values that\n * ←/→ steps through. Edits stage into a DRAFT (id → pending value); `save`\n * applies the draft through injected writers, `reset` drops it. The disk\n * never changes before save.\n */\n\nexport interface SettingsBehavior {\n id: string\n kind: 'install' | 'runtime'\n title: string\n description: string\n}\n\n/** Mirrors routing.yml `behaviors:` — drift-pinned by the registry test. */\nexport const SETTINGS_BEHAVIORS: readonly SettingsBehavior[] = Object.freeze([\n {\n id: 'skill-auto-continue',\n kind: 'install',\n title: 'Auto-continue skill',\n description: 'Continue multi-step todos while keeping safety gates.',\n },\n {\n id: 'skill-tdd-with-agents',\n kind: 'install',\n title: 'TDD with agents skill',\n description: 'RED, GREEN, REFACTOR test-driven implementation.',\n },\n {\n id: 'skill-code-review-checklist',\n kind: 'install',\n title: 'Code review checklist skill',\n description: 'Systematic code review and quality gates.',\n },\n {\n id: 'skill-prompt-refinery',\n kind: 'install',\n title: 'Prompt refinery skill',\n description: 'Vague requests refined — silent adjust, >> full contract.',\n },\n {\n id: 'gate-idle-todo-enforcer',\n kind: 'runtime',\n title: 'Idle todo enforcer',\n description: 'Continues pending todos when a session goes idle.',\n },\n {\n id: 'gate-context-pruner',\n kind: 'runtime',\n title: 'Context pruner',\n description: 'Prunes repeated tool output before summarization.',\n },\n {\n id: 'gate-j1-risk-gate',\n kind: 'runtime',\n title: 'J1 risk gate',\n description: 'High-risk tool calls demand explicit human approval.',\n },\n])\n\nexport interface OverrideEntry {\n action: 'disable' | 'replace'\n content?: string\n reason?: string\n}\n\nexport type EffectiveOverrides = Record\n\n/** Which behaviors the settings window can write (runtime + install skills). */\nexport const SETTINGS_TOGGLABLE_IDS = new Set(SETTINGS_BEHAVIORS.map((b) => b.id))\n\nexport function isBehaviorDisabled(effective: EffectiveOverrides, id: string): boolean {\n return effective[id]?.action === 'disable'\n}\n\nexport const TOGGLE_REASON = 'toggled in /pantheon-settings'\n\n/**\n * Toggle (a targeted write keeps the toggle semantics: a `replace` entry is\n * never destroyed — disabling keeps its `content`, re-enabling restores the\n * replace; a settings-written disable is removed outright, no toggle noise).\n */\nexport function toggledOverrides(\n effective: EffectiveOverrides,\n id: string,\n reason: string = TOGGLE_REASON,\n): EffectiveOverrides {\n const next: EffectiveOverrides = { ...effective }\n const entry = next[id]\n if (entry?.action === 'disable') {\n if (entry.content !== undefined) {\n next[id] =\n entry.reason === reason\n ? { action: 'replace', content: entry.content }\n : {\n action: 'replace',\n content: entry.content,\n ...(entry.reason !== undefined ? { reason: entry.reason } : {}),\n }\n } else {\n delete next[id]\n }\n } else {\n next[id] =\n entry?.content !== undefined\n ? { action: 'disable', reason, content: entry.content }\n : { action: 'disable', reason }\n }\n return next\n}\n\n/** Set an explicit on/off target (the cycler's save path) via the toggle semantics. */\nexport function setOverrideState(\n effective: EffectiveOverrides,\n id: string,\n target: 'enabled' | 'disabled',\n reason: string = TOGGLE_REASON,\n): EffectiveOverrides {\n const disabled = isBehaviorDisabled(effective, id)\n if ((target === 'disabled') === disabled) return effective\n return toggledOverrides(effective, id, reason)\n}\n\nexport function serializeOverrides(effective: EffectiveOverrides): string {\n const ordered: Record = {}\n for (const id of Object.keys(effective).sort()) ordered[id] = effective[id]\n return `${JSON.stringify(ordered, null, 2)}\\n`\n}\n\n// ── Overrides load (global + project files) ────────────────────────────\n\nexport interface OverridesLoad {\n global: EffectiveOverrides\n project: EffectiveOverrides\n /** The GLOBAL file exists but does not parse — writes are refused. */\n corruptGlobal: boolean\n}\n\n/** Merge for DISPLAY only, mirroring the runtime precedence: project wins per id. */\nexport function mergedOverrides(load: OverridesLoad): EffectiveOverrides {\n return { ...load.global, ...load.project }\n}\n\nexport function canWriteOverrides(load: OverridesLoad): boolean {\n return !load.corruptGlobal\n}\n\n// ── Tab / group / row model (the cycler window) ────────────────────────\n\nexport interface SettingsRow {\n id: string\n name: string\n /** Current effective value (display); the staged draft may differ. */\n value: string\n /** Allowed values for ←/→; presence marks the row as editable. */\n cycle?: readonly string[]\n /** The row's DEFAULT value — what the Defaults action stages. */\n def?: string\n /** Right-column note (writes-where, applies-live, from-where). */\n note?: string\n /** Enter triggers this action instead of cycling (e.g. `update-check`). */\n action?: string\n}\n\nexport interface SettingsGroup {\n /** Bold group header; undefined renders rows without a header. */\n title?: string\n rows: SettingsRow[]\n}\n\nexport interface SettingsTab {\n id: string\n title: string\n groups: SettingsGroup[]\n}\n\n/** Neutral tab for out-of-range indexes (noUncheckedIndexedAccess guard). */\nexport const EMPTY_TAB: SettingsTab = { id: 'empty', title: '', groups: [] }\n\n/** Flat, in-order rows of a tab (the up/down navigation space). */\nexport function tabRows(tab: SettingsTab): SettingsRow[] {\n return tab.groups.flatMap((group) => group.rows)\n}\n\nexport function findRow(tab: SettingsTab, id: string): SettingsRow | undefined {\n return tabRows(tab).find((row) => row.id === id)\n}\n\n// ── The cycler ─────────────────────────────────────────────────────────\n\n/** Step through the cycle with wrap-around; non-cyclable rows return the input. */\nexport function cycleValue(value: string, cycle: readonly string[], direction: 1 | -1): string {\n if (cycle.length === 0) return value\n const index = cycle.indexOf(value)\n if (index === -1) return cycle[0] ?? value\n const next = (index + direction + cycle.length) % cycle.length\n return cycle[next] ?? value\n}\n\n// ── The draft (staged edits; the disk never changes before save) ───────\n\nexport type SettingsDraft = Record\n\nexport function stageValue(\n draft: SettingsDraft,\n row: SettingsRow,\n direction: 1 | -1,\n): SettingsDraft {\n if (row.cycle === undefined) return draft\n const current = draft[row.id] ?? row.value\n const staged = cycleValue(current, row.cycle, direction)\n if (staged === row.value) {\n // staged back onto the disk value — drop the entry (no toggle noise)\n if (draft[row.id] === undefined) return draft\n const next = { ...draft }\n delete next[row.id]\n return next\n }\n return { ...draft, [row.id]: staged }\n}\n\n/** Stage an explicit target value for one row (the Defaults action path). */\nexport function stageRowToValue(\n draft: SettingsDraft,\n row: SettingsRow,\n target: string,\n): SettingsDraft {\n if (!row.cycle?.includes(target)) return draft\n if (target === row.value) {\n if (draft[row.id] === undefined) return draft\n const next = { ...draft }\n delete next[row.id]\n return next\n }\n return { ...draft, [row.id]: target }\n}\n\n/**\n * Stage every cyclable row's DEFAULT value of a tab. Rows already at their\n * default have their staged entry dropped; rows staged elsewhere keep it\n * until the Defaults action targets them.\n */\nexport function stageDefaults(draft: SettingsDraft, tab: SettingsTab): SettingsDraft {\n let next = draft\n for (const row of tabRows(tab)) {\n if (row.cycle === undefined || row.def === undefined) continue\n const candidate = next[row.id] ?? row.value\n if (candidate === row.def) {\n if (next[row.id] !== undefined) {\n const copy = { ...next }\n delete copy[row.id]\n next = copy\n }\n continue\n }\n next = stageRowToValue(next, { ...row, value: candidate }, row.def)\n }\n return next\n}\n\n/** Drop every staged entry of one tab (ctrl+r). */\nexport function resetTab(draft: SettingsDraft, tab: SettingsTab): SettingsDraft {\n const ids = new Set(tabRows(tab).map((row) => row.id))\n const next: SettingsDraft = {}\n for (const [id, value] of Object.entries(draft)) {\n if (!ids.has(id)) next[id] = value\n }\n return next\n}\n\nexport function draftCount(draft: SettingsDraft): number {\n return Object.keys(draft).length\n}\n\nexport function draftDirty(draft: SettingsDraft): boolean {\n return draftCount(draft) > 0\n}\n\nexport function tabDirty(draft: SettingsDraft, tab: SettingsTab): boolean {\n return tabRows(tab).some((row) => draft[row.id] !== undefined)\n}\n\n// ── Applying the draft ─────────────────────────────────────────────────\n\nexport interface DraftWriterResult {\n ok: boolean\n reason?: string\n}\n\n/**\n * One callback that dispatches a staged row to its real writer (gates →\n * overrides file, decision → decision-router.json, preset → active-preset).\n *Injected by the glue so the disk never runs in tests.\n */\nexport type DraftWriter = (id: string, value: string) => DraftWriterResult\n\nexport interface AppliedDraft {\n applied: string[]\n failed: { id: string; reason: string }[]\n}\n\n/** Apply every staged entry; failures are collected, never thrown. */\nexport function applyDraft(draft: SettingsDraft, writer: DraftWriter): AppliedDraft {\n const applied: string[] = []\n const failed: AppliedDraft['failed'] = []\n for (const [id, value] of Object.entries(draft)) {\n const result = writer(id, value)\n if (result.ok) applied.push(id)\n else failed.push({ id, reason: result.reason ?? 'write failed' })\n }\n return { applied, failed }\n}\n\n/** The rows that succeeded and are still in the draft (failed ones stay staged). */\nexport function settledDraft(draft: SettingsDraft, applied: readonly string[]): SettingsDraft {\n const next: SettingsDraft = {}\n for (const [id, value] of Object.entries(draft)) {\n if (!applied.includes(id)) next[id] = value\n }\n return next\n}\n\n// ── Gates / About tabs (behavior-native; the other tabs live in their modules) ──\n\nexport const GATES_ENABLED_CYCLE: readonly string[] = Object.freeze(['enabled', 'disabled'])\nexport type OverridesScope = 'global' | 'project'\nexport const OVERRIDES_SCOPE_CYCLE: readonly OverridesScope[] = Object.freeze(['global', 'project'])\n\nexport function buildGatesTab(\n load: OverridesLoad,\n languagePref?: string,\n overridesScope?: OverridesScope,\n): SettingsTab {\n const isPt = languagePref === 'pt-BR'\n const merged = mergedOverrides(load)\n const editingProject = overridesScope === 'project'\n const rowFor = (behavior: SettingsBehavior): SettingsRow => {\n const fromProject = load.project[behavior.id] !== undefined\n const effective = editingProject\n ? isBehaviorDisabled({ ...load.global, ...load.project }, behavior.id)\n : isBehaviorDisabled(load.global, behavior.id)\n const writable = editingProject ? true : !fromProject && canWriteOverrides(load)\n return {\n id: `gate.${behavior.id}`,\n name: fromProject ? `${behavior.title} (${isPt ? 'projeto' : 'project'})` : behavior.title,\n value: (editingProject ? effective : isBehaviorDisabled(merged, behavior.id))\n ? 'disabled'\n : 'enabled',\n ...(writable ? { cycle: GATES_ENABLED_CYCLE } : {}),\n note:\n !editingProject && fromProject\n ? isPt\n ? 'arquivo do projeto tem precedência · edite .pantheon/overrides.json'\n : 'project file wins at runtime — edit .pantheon/overrides.json'\n : editingProject\n ? isPt\n ? 'salva em .pantheon/overrides.json (escopo do projeto)'\n : 'saves to .pantheon/overrides.json (project scope)'\n : behavior.description,\n }\n }\n const install = SETTINGS_BEHAVIORS.filter((behavior) => behavior.kind === 'install')\n const runtime = SETTINGS_BEHAVIORS.filter((behavior) => behavior.kind === 'runtime')\n const groups: SettingsGroup[] = []\n if (overridesScope !== undefined) {\n groups.push({\n title: isPt ? 'Escopo das regras' : 'Rules Scope',\n rows: [\n {\n id: 'gates.scope',\n name: isPt ? 'Escopo de edição' : 'Edit scope',\n value: overridesScope,\n cycle: OVERRIDES_SCOPE_CYCLE,\n note: isPt\n ? 'alterne entre global (~/.config/opencode) e projeto (.pantheon)'\n : 'switch between global (~/.config/opencode) and project (.pantheon)',\n },\n ],\n })\n }\n groups.push(\n { title: isPt ? 'Skills instaladas' : 'Install skills', rows: install.map(rowFor) },\n { title: isPt ? 'Portões de execução' : 'Runtime gates', rows: runtime.map(rowFor) },\n )\n return {\n id: 'gates',\n title: 'Gates',\n groups,\n }\n}\n\nexport interface AboutTabExtra {\n nodeVersion?: string\n platform?: string\n preset?: string | null\n decisionEnabled?: boolean\n j1Mode?: string\n languagePref?: string\n}\n\nexport function buildAboutTab(version: string, extra?: AboutTabExtra): SettingsTab {\n const isPt = extra?.languagePref === 'pt-BR'\n\n const sysRows: SettingsRow[] = [\n {\n id: 'about.version',\n name: isPt ? 'Versão' : 'Version',\n value: `v${version}`,\n note: isPt\n ? 'OpenCode 2.x nativo — contrato V1 descontinuado'\n : 'OpenCode 2.x only — the V1 contract is removed',\n },\n {\n id: 'about.behaviors',\n name: isPt ? 'Comportamentos' : 'Behaviors',\n value: String(SETTINGS_BEHAVIORS.length),\n note: isPt\n ? 'portões e skills de governança registradas'\n : 'registered governance gates and skills',\n },\n ]\n\n if (extra?.nodeVersion) {\n sysRows.push({\n id: 'about.runtime',\n name: 'Runtime Node.js',\n value: `v${extra.nodeVersion}`,\n note: extra.platform ? `${isPt ? 'plataforma' : 'platform'}: ${extra.platform}` : '',\n })\n }\n\n const govRows: SettingsRow[] = [\n {\n id: 'about.preset',\n name: isPt ? 'Predefinição' : 'Active Preset',\n value: extra?.preset ?? 'none',\n note: isPt ? 'modelo global ativo do Pantheon' : 'global model preset active in Pantheon',\n },\n {\n id: 'about.decision',\n name: isPt ? 'Assistente Jev' : 'Decision Router',\n value: extra?.decisionEnabled\n ? isPt\n ? 'ativado'\n : 'enabled'\n : isPt\n ? 'desativado'\n : 'disabled',\n note: isPt ? 'arbitragem de modelos e candidatos' : 'model and candidate arbitration',\n },\n {\n id: 'about.j1',\n name: isPt ? 'Portão J1' : 'J1 Risk Gate',\n value: extra?.j1Mode ?? 'shadow',\n note: isPt\n ? 'portão de risco de segurança operacional'\n : 'operational safety risk score gate',\n },\n ]\n\n const refRows: SettingsRow[] = [\n {\n id: 'about.license',\n name: isPt ? 'Licença' : 'License',\n value: 'MIT',\n note: 'Open source · Pantheon Project',\n },\n {\n id: 'about.repo',\n name: isPt ? 'Repositório' : 'Repository',\n value: 'ils15/pantheon-opencode',\n note: 'github.com/ils15/pantheon-opencode',\n },\n ]\n\n const groups = [{ title: isPt ? 'Sistema & Plataforma' : 'System & Platform', rows: sysRows }]\n if (extra?.preset !== undefined || extra?.decisionEnabled !== undefined) {\n groups.push({ title: isPt ? 'Governança & Roteamento' : 'Governance & Routing', rows: govRows })\n }\n groups.push({ title: isPt ? 'Projeto & Referências' : 'Project & References', rows: refRows })\n\n return {\n id: 'about',\n title: isPt ? 'Sobre' : 'About',\n groups,\n }\n}\n\nexport interface ChangelogHighlightItem {\n title: string\n detail: string\n group?: string | undefined\n}\n\nexport function buildChangelogTab(\n version: string,\n items: ChangelogHighlightItem[] = [],\n languagePref?: string | undefined,\n): SettingsTab {\n const isPt = languagePref === 'pt-BR'\n\n const rows: SettingsRow[] = []\n if (items.length > 0) {\n items.forEach((item, index) => {\n rows.push({\n id: `changelog.item.${index + 1}`,\n name: item.title.slice(0, 26),\n value: '',\n note: item.detail,\n })\n })\n } else {\n rows.push({\n id: 'changelog.info',\n name: isPt ? 'Versão' : 'Release',\n value: `v${version}`,\n note: isPt\n ? 'veja o histórico completo no CHANGELOG.md ou no GitHub'\n : 'view full history in CHANGELOG.md or GitHub releases',\n })\n }\n\n return {\n id: 'changelog',\n title: isPt ? 'Changelog' : 'Changelog',\n groups: [\n {\n title: isPt ? `Novidades na versão v${version}` : `What's New in v${version}`,\n rows,\n },\n {\n title: isPt ? 'Referências de Versão' : 'Release References',\n rows: [\n {\n id: 'changelog.docs',\n name: isPt ? 'Documentação' : 'Documentation',\n value: 'CHANGELOG.md',\n note: isPt\n ? 'incluído na raiz do plugin e do repositório'\n : 'shipped at plugin root and repository root',\n },\n {\n id: 'changelog.repo',\n name: isPt ? 'Repositório GitHub' : 'GitHub Repository',\n value: 'ils15/pantheon-opencode',\n note: isPt\n ? 'versões, pull requests e discussões'\n : 'releases, pull requests and discussion',\n },\n ],\n },\n ],\n }\n}\n","/**\n * Update notifier core (TUI-local copy — the bundle must stay self-contained,\n * same precedent as cost-data.ts/model-pricing.ts).\n *\n * Pin + notify, never silent auto-update: one notice per newer version,\n * TTL-cached, offline-safe, and a stable install is never advertised a beta\n * (the update guard owns that crossing). docs/design/2.0-settings-and-install.md\n */\n\nexport const UPDATE_CHECK_TTL_MS = 6 * 60 * 60 * 1000\n\nexport interface UpdateCheckState {\n /** Last version a notice was surfaced for (no repeats per version). */\n lastNotifiedVersion?: string\n /** Last version seen on the registry (persisted across TTL restarts). */\n lastKnownLatestVersion?: string\n /** Last time the registry was queried, for the TTL. */\n lastCheckMs?: number\n}\n\nexport interface UpdateNoticeInput {\n currentVersion: string\n latestVersion: string\n state?: UpdateCheckState\n nowMs?: number\n ttlMs?: number\n isPt?: boolean\n}\n\nexport interface UpdateNotice {\n version: string\n message: string\n}\n\nconst isBetaOrRc = (version: string) => /-(?:beta|rc)\\.\\d+$/.test(String(version).trim())\n\n/** True when `latestVersion` is strictly newer and compatible with `currentVersion` channel. */\nexport function isNewerUpdateAvailable(currentVersion: string, latestVersion: string): boolean {\n const current = String(currentVersion).trim()\n const latest = String(latestVersion).trim()\n if (!current || !latest) return false\n // A stable install is never advertised a prerelease: explicit opt-in owns that crossing.\n if (!isBetaOrRc(current) && isBetaOrRc(latest)) return false\n return comparePantheonVersions(latest, current) > 0\n}\n\n/** Package specifier matching the running release line (`@beta` on prereleases). */\nexport function packageSpecForVersion(version: string): string {\n return isBetaOrRc(version) ? 'pantheon-opencode@beta' : 'pantheon-opencode'\n}\n\n/** Format a bilingual toast title + message for a newly discovered update. */\nexport function formatUpdateToast(\n currentVersion: string,\n latestVersion: string,\n isPt = false,\n): { title: string; message: string } {\n const spec = packageSpecForVersion(currentVersion)\n if (isPt) {\n return {\n title: `Pantheon v${latestVersion} disponível`,\n message: `Atualize em /pantheon-settings (Atualizações) ou \\`opencode plugin update ${spec}\\``,\n }\n }\n return {\n title: `Pantheon v${latestVersion} available`,\n message: `Update in /pantheon-settings (Updates) or \\`opencode plugin update ${spec}\\``,\n }\n}\n\n/** Compact persistent badge rendered in Home footer and Sidebar header when an update exists. */\nexport function formatUpdateBadge(\n currentVersion: string,\n latestVersion: string | null | undefined,\n options: { isPt?: boolean; compact?: boolean } = {},\n): string | null {\n if (!latestVersion || !isNewerUpdateAvailable(currentVersion, latestVersion)) return null\n const version = latestVersion.trim().replace(/^v/i, '')\n if (options.compact) return `↑ v${version} (/pantheon-settings)`\n return options.isPt\n ? `↑ v${version} disponível · /pantheon-settings`\n : `↑ v${version} available · /pantheon-settings`\n}\n\n/** Resolve cached newer version from persisted check state (no network call needed). */\nexport function resolveCachedAvailableUpdate(\n currentVersion: string,\n state: UpdateCheckState | undefined,\n): string | null {\n if (!state) return null\n const candidate = state.lastKnownLatestVersion ?? state.lastNotifiedVersion\n if (!candidate) return null\n return isNewerUpdateAvailable(currentVersion, candidate) ? candidate : null\n}\n\n/** Stamp `lastKnownLatestVersion` onto an `UpdateCheckState` without altering TTL/notice fields. */\nexport function withKnownLatest(\n state: UpdateCheckState,\n latestVersion: string | null,\n): UpdateCheckState {\n if (!latestVersion) return state\n return { ...state, lastKnownLatestVersion: latestVersion }\n}\n\nlet availableUpdateState: string | null = null\nconst availableUpdateListeners = new Set<(version: string | null) => void>()\n\nexport function getAvailableUpdateVersion(): string | null {\n return availableUpdateState\n}\n\nexport function setAvailableUpdateVersion(version: string | null): void {\n const normalized = version && version.trim() !== '' ? version.trim() : null\n if (normalized === availableUpdateState) return\n availableUpdateState = normalized\n for (const listener of availableUpdateListeners) {\n try {\n listener(availableUpdateState)\n } catch {}\n }\n}\n\nexport function subscribeAvailableUpdate(listener: (version: string | null) => void): () => void {\n availableUpdateListeners.add(listener)\n return () => {\n availableUpdateListeners.delete(listener)\n }\n}\n\n/** Semver-ish compare for X.Y.Z[-(beta|rc).N]; prereleases sort before their release. */\nexport function comparePantheonVersions(left: string, right: string): number {\n const parse = (version: string) => {\n const match = String(version)\n .trim()\n .match(/^(\\d+)\\.(\\d+)\\.(\\d+)(?:-(beta|rc)\\.(\\d+))?$/)\n if (!match) return null\n const [, major = '', minor = '', patch = '', stage = '', stageNum = ''] = match\n const stageRank = stage === 'beta' ? 1 : stage === 'rc' ? 2 : 3\n return {\n core: [+major, +minor, +patch] as [number, number, number],\n stageRank,\n stageNum: stage !== '' ? +stageNum : Number.POSITIVE_INFINITY,\n }\n }\n const a = parse(left)\n const b = parse(right)\n if (!a || !b) return 0\n const [aMajor, aMinor, aPatch] = a.core\n const [bMajor, bMinor, bPatch] = b.core\n if (aMajor !== bMajor) return aMajor - bMajor\n if (aMinor !== bMinor) return aMinor - bMinor\n if (aPatch !== bPatch) return aPatch - bPatch\n if (a.stageRank !== b.stageRank) return a.stageRank - b.stageRank\n return a.stageNum - b.stageNum\n}\n\nexport function pickUpdateNotice(input: UpdateNoticeInput): UpdateNotice | null {\n const { currentVersion, latestVersion, state = {}, nowMs = Date.now(), isPt = false } = input\n const ttlMs = input.ttlMs ?? UPDATE_CHECK_TTL_MS\n\n const lastCheck = state.lastCheckMs ?? 0\n if (nowMs - lastCheck < ttlMs) return null\n if (state.lastNotifiedVersion === latestVersion) return null\n if (!isNewerUpdateAvailable(currentVersion, latestVersion)) return null\n\n return {\n version: latestVersion,\n message: formatUpdateToast(currentVersion, latestVersion, isPt).message,\n }\n}\n\n/** The state to persist after a check (notified or not) for the TTL. */\nexport function nextCheckState(\n previous: UpdateCheckState,\n notice: UpdateNotice | null,\n nowMs: number,\n): UpdateCheckState {\n const lastNotifiedVersion = notice?.version ?? previous.lastNotifiedVersion\n return {\n lastCheckMs: nowMs,\n ...(lastNotifiedVersion !== undefined ? { lastNotifiedVersion } : {}),\n }\n}\n","/**\n * doctor-state.ts — the Doctor section of the settings window (read-only).\n *\n * TUI-local replica (the bundle must stay self-contained — the installed copy\n * physically lacks the repo tree, so doctor.mjs itself is unreachable). Only\n * the FILE-DERIVABLE checks are mirrored here; everything that spawns\n * processes, reads the network, or writes (MCP smoke, python validators, git,\n * venv pins, --fix quarantines) stays in the CLI and the section says so.\n *\n * The install-state path mirrors doctor's checkInstallVersionDrift\n * (`/opencode/.pantheon/install-state.json`); the Node floor is\n * drift-pinned against scripts/node-engine-policy.mjs by\n * tests/tui-doctor-state.test.mjs.\n */\nimport { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { readDecisionRouterConfig } from './decision-router-state.ts'\nimport type { OverridesLoad } from './pantheon-settings-state.ts'\nimport {\n SETTINGS_BEHAVIORS,\n type SettingsRow,\n type SettingsTab,\n} from './pantheon-settings-state.ts'\nimport { comparePantheonVersions } from './update-notice.ts'\n\n/** Drift-pinned against scripts/node-engine-policy.mjs MIN_SUPPORTED_NODE_VERSION. */\nexport const MIN_SUPPORTED_NODE_VERSION = '26.4.0'\n\nexport function opencodePantheonDir(env: Record = process.env) {\n const xdg = env.XDG_CONFIG_HOME\n const home = env.HOME ?? ''\n const root = xdg ?? join(home, '.config')\n return join(root, 'opencode', '.pantheon')\n}\n\nexport interface InstallVersionHealth {\n status: 'ok' | 'older' | 'newer' | 'unknown'\n installed: string | null\n}\n\n/**\n * H2: the installed package version (install-state) vs the running one.\n * Fail-open: a missing/unreadable state file means \"unknown\", not a failure —\n * pre-2.0 installs may not have one.\n */\nexport function classifyInstallVersion(\n runningVersion: string,\n env: Record = process.env,\n): InstallVersionHealth {\n let installed: string | null = null\n try {\n const path = join(opencodePantheonDir(env), 'install-state.json')\n const raw = JSON.parse(readFileSync(path, 'utf8')) as { pantheon_version?: unknown }\n if (typeof raw?.pantheon_version === 'string' && raw.pantheon_version !== '') {\n installed = raw.pantheon_version\n }\n } catch {\n installed = null\n }\n if (installed === null) return { status: 'unknown', installed: null }\n const compared = comparePantheonVersions(installed, runningVersion)\n if (compared === 0) return { status: 'ok', installed }\n return { status: compared < 0 ? 'older' : 'newer', installed }\n}\n\nexport function isSupportedNodeFloor(version: string): boolean {\n // Same shape as the canonical parser: a prerelease is outside the floor.\n const match = /^v?(\\d+)\\.(\\d+)\\.(\\d+)(?:-([^+]+))?(?:\\+([\\w.-]+))?$/.exec(String(version))\n const minimum = /^v?(\\d+)\\.(\\d+)\\.(\\d+)/.exec(MIN_SUPPORTED_NODE_VERSION)\n if (!match || !minimum) return false\n const [, major = '', minor = '', patch = '', prerelease = ''] = match\n if (prerelease !== '') return false\n const [, minMajor = '0', minMinor = '0', minPatch = '0'] = minimum\n const currentParts = [+major, +minor, +patch]\n const minimumParts = [+minMajor, +minMinor, +minPatch]\n for (let index = 0; index < 3; index += 1) {\n const currentPart = currentParts[index] ?? 0\n const minimumPart = minimumParts[index] ?? 0\n if (currentPart !== minimumPart) return currentPart > minimumPart\n }\n return true\n}\n\nexport interface OverridesHealth {\n status: 'clean' | 'unknown-ids' | 'corrupt'\n unknownIds: string[]\n}\n\n/** K: validate both overrides files against the window's registry. */\nexport function classifyOverridesHealth(load: OverridesLoad): OverridesHealth {\n if (load.corruptGlobal) return { status: 'corrupt', unknownIds: [] }\n const known = new Set(SETTINGS_BEHAVIORS.map((behavior) => behavior.id))\n const unknownIds = Object.keys({ ...load.global, ...load.project }).filter((id) => !known.has(id))\n return { status: unknownIds.length > 0 ? 'unknown-ids' : 'clean', unknownIds }\n}\n\nexport interface DecisionConfigHealth {\n status: 'ok' | 'corrupt' | 'absent'\n}\n\nexport function classifyDecisionConfigHealth(\n env: Record = process.env,\n): DecisionConfigHealth {\n if (\n !existsSync(\n join(\n env.XDG_CONFIG_HOME ?? join(env.HOME ?? '', '.config'),\n 'pantheon',\n 'decision-router.json',\n ),\n )\n ) {\n return { status: 'absent' }\n }\n return readDecisionRouterConfig(env).corrupt ? { status: 'corrupt' } : { status: 'ok' }\n}\n\nexport interface DoctorSectionInput {\n runningVersion: string\n nodeVersion: string\n load: OverridesLoad\n env?: Record\n}\n\nexport function buildDoctorTab(input: DoctorSectionInput): SettingsTab {\n const env = input.env ?? process.env\n const rows: SettingsRow[] = []\n\n const version = classifyInstallVersion(input.runningVersion, env)\n rows.push({\n id: 'doctor.version',\n name: 'Install version',\n value:\n version.status === 'ok'\n ? `v${version.installed} — matches`\n : version.status === 'older'\n ? `v${version.installed} older`\n : version.status === 'newer'\n ? `v${version.installed} newer`\n : 'unknown',\n note:\n version.status === 'older'\n ? 'refresh with `pantheon-opencode update`'\n : 'read from /opencode/.pantheon/install-state.json',\n })\n\n const nodeOk = isSupportedNodeFloor(input.nodeVersion)\n rows.push({\n id: 'doctor.node',\n name: 'Node runtime',\n value: input.nodeVersion.replace(/^v/, ''),\n note: nodeOk\n ? `meets the >= ${MIN_SUPPORTED_NODE_VERSION} floor`\n : `below the >= ${MIN_SUPPORTED_NODE_VERSION} floor — tooling may refuse`,\n })\n\n const overrides = classifyOverridesHealth(input.load)\n rows.push({\n id: 'doctor.overrides',\n name: 'Overrides',\n value:\n overrides.status === 'clean'\n ? 'valid'\n : overrides.status === 'corrupt'\n ? 'unreadable'\n : `${overrides.unknownIds.length} unknown id(s)`,\n note:\n overrides.status === 'unknown-ids'\n ? `${overrides.unknownIds.join(', ')} — harmless; repair with doctor --fix`\n : overrides.status === 'corrupt'\n ? 'writes are refused until repaired (doctor --fix)'\n : 'both files parse against the behavior registry',\n })\n\n const decision = classifyDecisionConfigHealth(env)\n rows.push({\n id: 'doctor.decision',\n name: 'Decision config',\n value:\n decision.status === 'ok' ? 'valid' : decision.status === 'corrupt' ? 'corrupt' : 'absent',\n note:\n decision.status === 'corrupt'\n ? 'runtime fail-closes to disabled · read from /pantheon/decision-router.json'\n : 'read from /pantheon/decision-router.json',\n })\n\n return {\n id: 'doctor',\n title: 'Doctor',\n groups: [\n {\n title: 'Health (file-derived)',\n rows,\n },\n {\n rows: [\n {\n id: 'doctor.cli',\n name: 'Full check',\n value: '`pantheon-opencode doctor`',\n note: 'MCP smoke, venv pins, git stay in the CLI',\n },\n ],\n },\n ],\n }\n}\n","/**\n * settings-i18n.ts — Bilingual (PT-BR / EN) internationalization for TUI settings.\n *\n * Provides localized titles, labels, and explanations for:\n * - Decision Router & Jev model selection\n * - Autonomy & Budgets\n * - Safety & J1 Risk Gate\n *\n * Automatically detects environment locale (LANG / LC_ALL) while allowing\n * manual override in TUI preferences.\n */\n\nexport type SettingsLanguage = 'auto' | 'pt-BR' | 'en'\n\nexport const SETTINGS_LANGUAGES_CYCLE: readonly string[] = Object.freeze(['auto', 'pt-BR', 'en'])\nexport const SUPPORTED_LANGUAGES = SETTINGS_LANGUAGES_CYCLE\n\n/**\n * Resolve effective language: 'pt-BR' or 'en'.\n * Defaults to 'pt-BR' if system locale contains 'pt', if Intl locale is pt,\n * or if system timezone is Brazilian/Portuguese; otherwise 'en'.\n */\nexport function resolveLanguage(\n preference: string = 'auto',\n env: Record = process.env,\n): 'pt-BR' | 'en' {\n if (preference === 'pt-BR') return 'pt-BR'\n if (preference === 'en') return 'en'\n\n // 1. Auto-detection based on environment locale variables\n const lang = (env.LC_ALL ?? env.LC_MESSAGES ?? env.LANG ?? env.LANGUAGE ?? '').toLowerCase()\n if (lang.startsWith('pt')) return 'pt-BR'\n\n // 2. Auto-detection based on Intl locale\n try {\n const intlLocale = Intl.DateTimeFormat().resolvedOptions().locale.toLowerCase()\n if (intlLocale.startsWith('pt')) return 'pt-BR'\n } catch {}\n\n // 3. Auto-detection based on timezone (Brazil & Portugal)\n try {\n const tz = (env.TZ ?? Intl.DateTimeFormat().resolvedOptions().timeZone ?? '').toLowerCase()\n if (\n tz.includes('sao_paulo') ||\n tz.includes('brazil') ||\n tz.includes('fortaleza') ||\n tz.includes('recife') ||\n tz.includes('manaus') ||\n tz.includes('belem') ||\n tz.includes('cuiaba') ||\n tz.includes('campo_grande') ||\n tz.includes('porto_velho') ||\n tz.includes('rio_branco') ||\n tz.includes('boa_vista') ||\n tz.includes('maceio') ||\n tz.includes('bahia') ||\n tz.includes('noronha') ||\n tz.includes('araguaina') ||\n tz.includes('santarem') ||\n tz.includes('lisbon') ||\n tz.includes('madeira') ||\n tz.includes('azores')\n ) {\n return 'pt-BR'\n }\n } catch {}\n\n return 'en'\n}\n\nexport interface I18nStringPair {\n en: string\n pt: string\n}\n\nexport const I18N = {\n tabs: {\n decision: { en: 'Decision (Jev)', pt: 'Decisão (Jev)' },\n autonomy: { en: 'Autonomy', pt: 'Autonomia' },\n safety: { en: 'Safety (J1)', pt: 'Segurança (J1)' },\n tui: { en: 'TUI', pt: 'TUI' },\n },\n decision: {\n groupRouter: {\n en: 'Decision Router (Jev Assistant)',\n pt: 'Assistente de Decisão (Jev)',\n },\n groupCredentials: {\n en: 'Credentials (status only — values never enter the window)',\n pt: 'Credenciais (apenas status — valores protegidos)',\n },\n routerName: {\n en: 'Router (Decision Assistant)',\n pt: 'Assistente Jev',\n },\n routerNote: {\n en: 'applies live — enables intelligent route arbitration and candidate ranking',\n pt: 'aplica em tempo real — motor de arbitragem inteligente e ranking de rotas',\n },\n modelName: {\n en: 'Decision model',\n pt: 'Modelo de Decisão',\n },\n modelNote: {\n en: 'local routes on-device (free); auto/explicit pick a remote decision model',\n pt: 'local decide no seu PC (grátis); auto/explícito usa modelo nuvem (OpenRouter)',\n },\n selectionModeName: {\n en: 'Selection mode',\n pt: 'Modo de operação',\n },\n selectionModeNote: {\n en: 'local routes on-device; auto/explicit pick a remote decision model',\n pt: 'local decide no dispositivo; auto/explícito usa modelo remoto',\n },\n egressName: {\n en: 'Cloud API access (Egress)',\n pt: 'Acesso à Nuvem (Egress)',\n },\n egressNoteGranted: {\n en: 'granted = remote decision routes may call their gateway (budget-capped)',\n pt: 'permitido = rotas remotas podem consultar a API (com limite de orçamento)',\n },\n egressNoteNotGranted: {\n en: 'not granted = remote routes blocked; local heuristic decisions only',\n pt: 'não permitido = chamadas remotas bloqueadas; apenas heurística local',\n },\n candidatesName: {\n en: 'Active candidates',\n pt: 'Candidatos ativos',\n },\n },\n autonomy: {\n groupGoalLoop: {\n en: 'Goal loop (multi-turn session auto-continuation)',\n pt: 'Execução Contínua (Goal Loop)',\n },\n goalLoopName: {\n en: 'Goal loop',\n pt: 'Loop contínuo',\n },\n goalLoopNote: {\n en: 'auto-continues multi-turn tasks when session goes idle · applies after OpenCode restart',\n pt: 'continua tarefas de múltiplos passos automaticamente · requer reinício',\n },\n maxContinuationsName: {\n en: 'Max continuations',\n pt: 'Limite de turnos',\n },\n maxContinuationsNote: {\n en: '1..200 — safety ceiling to prevent runaway tasks',\n pt: '1..200 — teto de segurança contra tarefas infinitas',\n },\n cooldownName: {\n en: 'Cooldown (ms)',\n pt: 'Intervalo (ms)',\n },\n cooldownNote: {\n en: 'delay between autonomous turns (min 1000ms)',\n pt: 'tempo de espera entre turnos autônomos (mín 1000ms)',\n },\n groupBudgets: {\n en: 'Decision budgets (applies live per gated call)',\n pt: 'Orçamento Jev (teto financeiro de proteção)',\n },\n monthlyCapName: {\n en: 'Monthly cap',\n pt: 'Teto mensal (USD)',\n },\n monthlyCapNote: {\n en: 'monthly USD ceiling for gated arbitrator decisions',\n pt: 'teto mensal em dólares para decisões do assistente Jev',\n },\n perDecisionCapName: {\n en: 'Per-decision cap',\n pt: 'Teto por consulta (USD)',\n },\n perDecisionCapNote: {\n en: 'price cap — gated decisions above this are refused',\n pt: 'teto por decisão — consultas remotas que excederem são recusadas',\n },\n groupGradient: {\n en: 'Decision gradient (reference policy · J1 owns the risk axis)',\n pt: 'Níveis de Decisão & Segurança (Referência)',\n },\n soloName: {\n en: 'Decide solo',\n pt: 'Decisão direta',\n },\n soloNote: {\n en: 'reversible & low-risk edits, routine fixes (no gate)',\n pt: 'edições reversíveis e baixo risco, sem portão de bloqueio',\n },\n jevName: {\n en: 'Jev decides',\n pt: 'Decisão Jev',\n },\n jevNote: {\n en: 'typed ambiguity & candidate ranking (budget-capped)',\n pt: 'ambiguidade e ranking de skills com teto de orçamento',\n },\n humanName: {\n en: 'Human decides',\n pt: 'Aprovação humana',\n },\n humanNote: {\n en: 'high-risk & destructive operations (J1 gate)',\n pt: 'ações de alto risco e destrutivas (portão de segurança J1)',\n },\n },\n safety: {\n groupSafety: {\n en: 'Safety & Risk Level (J1 Gate)',\n pt: 'Nível de Proteção & Portão de Risco (J1)',\n },\n modeName: {\n en: 'Protection mode',\n pt: 'Modo de proteção',\n },\n thresholdName: {\n en: 'Enforce threshold',\n pt: 'Teto para bloqueio',\n },\n thresholdNote: {\n en: 'deny at or above · 0..1 · default 0.8',\n pt: 'bloqueia em ou acima de · 0..1 · padrão 0.8',\n },\n gateName: {\n en: 'Safety gate',\n pt: 'Portão de segurança',\n },\n },\n} as const\n\n/** Helper to get localized text */\nexport function t(entry: I18nStringPair, lang: 'pt-BR' | 'en'): string {\n return lang === 'pt-BR' ? entry.pt : entry.en\n}\n","/**\n * j1-gate-status.ts — the J1 Risk Gate section of the settings window.\n *\n * TUI-local replica of the ladder in src/pantheon/jev-risk-gate.ts (the\n * bundle must stay self-contained); tests/tui-settings-j1.test.mjs pins the\n * env names, the ladder values and the default threshold against that source.\n *\n * STATUS ONLY by design: the ladder has no file surface yet — mode and\n * threshold are env-only and read once at plugin setup — so nothing here\n * writes, and the section says so. A file surface is a runtime-plugin change\n * (beta.3 candidate), not a window change.\n */\nimport type { SettingsTab } from './pantheon-settings-state.ts'\nimport { resolveLanguage } from './settings-i18n.ts'\n\nexport const J1_FLAG_ENV = 'PANTHEON_J1_RISK_SCORE'\nexport const J1_THRESHOLD_ENV = 'PANTHEON_J1_ENFORCE_THRESHOLD'\nexport const J1_THRESHOLD_DEFAULT = 0.8\n\nexport type J1Mode = 'off' | 'shadow' | 'warn' | 'enforce'\n\n/** `1`/`on`/`true` map to `shadow` for back-compatibility with the shipped setup. */\nconst FLAG_ON = new Set(['1', 'on', 'true', 'shadow'])\n\nexport function j1ModeFromEnv(env: Record = process.env): J1Mode {\n const raw = (env[J1_FLAG_ENV] ?? '').trim().toLowerCase()\n if (raw === 'enforce') return 'enforce'\n if (raw === 'warn') return 'warn'\n return FLAG_ON.has(raw) ? 'shadow' : 'off'\n}\n\n/** Invalid or out-of-range values fall back to the default — a typo must not disable the gate. */\nexport function j1ThresholdFromEnv(env: Record = process.env): number {\n const text = (env[J1_THRESHOLD_ENV] ?? '').trim()\n if (text === '') return J1_THRESHOLD_DEFAULT\n const raw = Number(text)\n if (!Number.isFinite(raw) || raw < 0 || raw > 1) return J1_THRESHOLD_DEFAULT\n return raw\n}\n\nconst MODE_DESCRIPTION_EN: Record = {\n off: 'nothing fires (hard zero)',\n shadow: 'observe + record; invisible in the session',\n warn: 'RESERVED — behaves as shadow in this release',\n enforce: 'high-risk scores DENY the tool call (fail-open on gate unavailability)',\n}\n\nconst MODE_DESCRIPTION_PT: Record = {\n off: 'desativado (hard zero)',\n shadow: 'observa + registra telemetria (modo silencioso)',\n warn: 'RESERVADO (RESERVED) — comporta-se como shadow nesta versão',\n enforce: 'alto risco bloqueia a ferramenta (fail-open se indisponível)',\n}\n\nexport function buildJ1Tab(\n env: Record,\n disabledByOverride: boolean,\n languagePref?: string | undefined,\n): SettingsTab {\n const lang = resolveLanguage(languagePref)\n const isPt = lang === 'pt-BR'\n const mode = j1ModeFromEnv(env)\n const threshold = j1ThresholdFromEnv(env)\n const gateState = disabledByOverride\n ? 'disabled via overrides'\n : mode === 'off'\n ? 'off (env unset)'\n : 'active'\n const desc = isPt ? MODE_DESCRIPTION_PT[mode] : MODE_DESCRIPTION_EN[mode]\n\n return {\n id: 'j1',\n title: isPt ? 'Segurança J1' : 'J1 Safety',\n groups: [\n {\n title: isPt ? 'Portão de Segurança (J1)' : 'Safety Risk Gate (J1)',\n rows: [\n {\n id: 'j1.mode',\n name: isPt ? 'Modo de Operação' : 'Operation Mode',\n value: mode,\n note: `${desc} · ${isPt ? 'reinício necessário (restart applies)' : 'restart applies'}`,\n },\n {\n id: 'j1.threshold',\n name: isPt ? 'Limiar de bloqueio' : 'Enforce threshold',\n value: String(threshold),\n note: isPt\n ? 'bloqueia em ou acima · 0..1 · padrão 0.8'\n : 'deny at or above · 0..1 · default 0.8',\n },\n {\n id: 'j1.gate',\n name: isPt ? 'Portão de Segurança' : 'Safety Risk Gate',\n value: gateState,\n note: `${J1_FLAG_ENV} / ${J1_THRESHOLD_ENV} · ${isPt ? 'lido na inicialização' : 'read once at startup'}`,\n },\n ],\n },\n ],\n }\n}\n","/**\n * legacy-audit.ts — Self-contained Legacy & Drift Auditor for the TUI Settings panel.\n *\n * Scans global (~/.config/opencode) and workspace () scopes for:\n * - Dead V1 hooks/files (pantheon-hooks.*, tiers.json, fastembed_cache, .migration-checkpoint)\n * - Unmigrated legacy stores (memory.db, persistence/{global,project}.db, goals.json)\n * - Redundant copied canonical Pantheon assets shadowed by native plugin transforms\n * - Drifted copied TUI plugins (plugins/pantheon-tui version != running plugin version)\n * - Old configuration backup sidecars (opencode.json.bak*, active-preset.json.bak*)\n *\n * Always migrates unmigrated legacy context/memory/goals BEFORE deleting obsolete stores,\n * and NEVER touches user-created custom agents or custom user skills.\n */\n\nimport {\n existsSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n realpathSync,\n rmSync,\n statSync,\n writeFileSync,\n} from 'node:fs'\nimport { dirname, join, resolve } from 'node:path'\nimport { DatabaseSync } from 'node:sqlite'\n\nexport type LegacyScope = 'global' | 'project'\nexport type LegacyCategory =\n | 'legacyStore'\n | 'hooks'\n | 'v1Obsolete'\n | 'backup'\n | 'redundantAsset'\n | 'drift'\n\nexport interface LegacyAuditItem {\n readonly path: string\n readonly scope: LegacyScope\n readonly category: LegacyCategory\n readonly reason: string\n readonly bytes: number\n}\n\nexport interface LegacyAuditSummary {\n readonly total: number\n readonly totalBytes: number\n readonly unmigratedStores: number\n readonly byScope: Record\n readonly byCategory: Record\n}\n\nexport interface LegacyAuditScan {\n readonly items: LegacyAuditItem[]\n readonly summary: LegacyAuditSummary\n}\n\nexport interface LegacyCleanResult {\n readonly removed: string[]\n readonly reclaimedBytes: number\n readonly migratedRecords: number\n readonly errors: Array<{ readonly path: string; readonly reason: string }>\n}\n\nexport interface LegacyAuditOptions {\n readonly workspaceDir?: string\n readonly globalConfigDir?: string\n readonly runningVersion?: string\n readonly includeRedundantCopiedAssets?: boolean\n readonly env?: Record\n}\n\nconst SAFE_SEGMENT_RE = /^[a-zA-Z0-9._:-]{1,128}$/\n\nconst CANONICAL_AGENT_MD_FILES: readonly string[] = Object.freeze([\n 'aphrodite.md',\n 'apollo.md',\n 'artemis.md',\n 'athena.md',\n 'demeter.md',\n 'gaia.md',\n 'hephaestus.md',\n 'hermes.md',\n 'iris.md',\n 'mnemosyne.md',\n 'nyx.md',\n 'prometheus.md',\n 'talos.md',\n 'themis.md',\n 'zeus.md',\n])\n\nconst CANONICAL_COMMAND_MD_FILES: readonly string[] = Object.freeze([\n 'pantheon.md',\n 'pantheon-audit.md',\n 'pantheon-deepwork.md',\n 'pantheon-focus.md',\n 'pantheon-model.md',\n 'pantheon-optimize.md',\n 'pantheon-settings.md',\n 'pantheon-vision.md',\n])\n\nconst CANONICAL_SKILL_IDS: readonly string[] = Object.freeze([\n 'agent-coordination',\n 'agent-forge',\n 'artifact-management',\n 'auto-continue',\n 'clonedeps',\n 'code-review-checklist',\n 'codemap',\n 'context-compression',\n 'fast-path-execution',\n 'git-workflow-and-versioning',\n 'incremental-implementation',\n 'instruction-forge',\n 'loop-engineering',\n 'memory-bank',\n 'prompt-refinery',\n 'reflect',\n 'security-hardening',\n 'session-goal',\n 'simplify',\n 'spec-driven-development',\n 'tdd-with-agents',\n 'test-slicing',\n 'verification-planning',\n 'visual-review-pipeline',\n 'worktrees',\n])\n\nconst LEGACY_INSTRUCTION_FILES: readonly string[] = Object.freeze([\n 'zeus-execution-rules.instructions.md',\n 'zeus-orchestration.instructions.md',\n 'zeus-workflow.instructions.md',\n])\n\nexport function resolveAuditGlobalDir(\n env: Record = process.env,\n): string | undefined {\n if (env.PANTHEON_HOME?.trim()) return resolve(env.PANTHEON_HOME.trim())\n if (env.XDG_CONFIG_HOME?.trim()) return join(resolve(env.XDG_CONFIG_HOME.trim()), 'opencode')\n if (env.NODE_TEST_CONTEXT) return undefined\n const home = env.HOME?.trim()\n return home ? join(resolve(home), '.config', 'opencode') : undefined\n}\n\nexport function formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`\n return `${(bytes / (1024 * 1024)).toFixed(2)} MB`\n}\n\nfunction toSafeSegment(raw: unknown, fallback = 'default'): string {\n const str = String(raw ?? '')\n .trim()\n .replace(/[^a-zA-Z0-9._:-]/g, '_')\n .slice(0, 128)\n if (!str || str === '.' || str === '..' || !SAFE_SEGMENT_RE.test(str)) return fallback\n return str\n}\n\nfunction measurePathBytes(targetPath: string, depth = 0): number {\n if (depth > 8) return 0\n try {\n const st = statSync(targetPath)\n if (st.isFile()) return st.size\n if (!st.isDirectory()) return 0\n let total = 0\n for (const entry of readdirSync(targetPath, { withFileTypes: true })) {\n total += measurePathBytes(join(targetPath, entry.name), depth + 1)\n }\n return total\n } catch {\n return 0\n }\n}\n\nfunction samePath(a: string, b: string): boolean {\n if (resolve(a) === resolve(b)) return true\n if (!existsSync(a) || !existsSync(b)) return false\n try {\n return realpathSync(a) === realpathSync(b)\n } catch {\n return false\n }\n}\n\nfunction isConfinedWithin(rootDir: string, targetPath: string): boolean {\n try {\n const realRoot = realpathSync(rootDir)\n const parentReal = realpathSync(dirname(targetPath))\n return parentReal === realRoot || parentReal.startsWith(`${realRoot}/`)\n } catch {\n return false\n }\n}\n\nfunction countTableRows(db: DatabaseSync, tableName: string): number {\n try {\n const row = db\n .prepare(`SELECT count(*) AS cnt FROM \"${tableName.replace(/\"/g, '\"\"')}\"`)\n .get() as { cnt?: number } | undefined\n return Number(row?.cnt ?? 0)\n } catch {\n return 0\n }\n}\n\nfunction tableExists(db: DatabaseSync, name: string): boolean {\n try {\n const row = db\n .prepare(\"SELECT name FROM sqlite_master WHERE type IN ('table','view') AND name = ?\")\n .get(name) as { name?: string } | undefined\n return Boolean(row?.name)\n } catch {\n return false\n }\n}\n\nfunction collectScopeAudit(\n scope: LegacyScope,\n baseRoot: string,\n configRoot: string,\n options: LegacyAuditOptions,\n): { items: LegacyAuditItem[]; unmigratedStores: number } {\n const items: LegacyAuditItem[] = []\n const seen = new Set()\n let unmigratedStores = 0\n\n const addItem = (filePath: string, category: LegacyCategory, reason: string) => {\n const resolved = resolve(filePath)\n if (seen.has(resolved) || !existsSync(resolved)) return\n seen.add(resolved)\n items.push({\n path: resolved,\n scope,\n category,\n reason,\n bytes: measurePathBytes(resolved),\n })\n }\n\n // 1. Dead V1 hooks & obsolete config files\n for (const hookName of ['pantheon-hooks.ts', 'pantheon-hooks.js', 'pantheon-hooks.mjs']) {\n addItem(join(configRoot, 'plugins', hookName), 'hooks', 'Obsolete OpenCode V1 hook plugin')\n }\n addItem(join(configRoot, 'tiers.json'), 'v1Obsolete', 'Obsolete V1 model tiers registry')\n addItem(join(baseRoot, 'tiers.json'), 'v1Obsolete', 'Obsolete V1 model tiers registry')\n\n const pantheonDir = join(baseRoot, '.pantheon')\n addItem(join(pantheonDir, 'fastembed_cache'), 'v1Obsolete', 'Unused legacy fastembed cache')\n addItem(join(pantheonDir, '.fastembed'), 'v1Obsolete', 'Unused legacy fastembed cache')\n addItem(join(baseRoot, 'fastembed_cache'), 'v1Obsolete', 'Unused legacy fastembed cache')\n addItem(\n join(pantheonDir, '.migration-checkpoint'),\n 'v1Obsolete',\n 'Stale migration checkpoint file',\n )\n\n for (const bakDir of [configRoot, pantheonDir]) {\n if (!existsSync(bakDir)) continue\n try {\n for (const name of readdirSync(bakDir)) {\n if (name.startsWith('opencode.json.bak') || name.startsWith('active-preset.json.bak')) {\n addItem(join(bakDir, name), 'backup', 'Old configuration backup sidecar')\n }\n }\n } catch {\n /* ignore */\n }\n }\n\n // 2. Unmigrated legacy stores\n const legacyFlatMemDb = join(pantheonDir, 'memory.db')\n if (existsSync(legacyFlatMemDb)) {\n unmigratedStores += 1\n addItem(legacyFlatMemDb, 'legacyStore', 'Unmigrated flat .pantheon/memory.db')\n }\n\n const canonicalMemDb = join(pantheonDir, 'memory', 'memory.db')\n if (existsSync(canonicalMemDb)) {\n try {\n const db = new DatabaseSync(canonicalMemDb, { readOnly: true })\n const legacyVecTables = [\n 'memories_vec',\n 'vec_memories',\n 'memory_embeddings',\n 'memory_vectors',\n ]\n const hasLegacyVec = legacyVecTables.some((t) => tableExists(db, t))\n db.close()\n if (hasLegacyVec) {\n unmigratedStores += 1\n items.push({\n path: `${canonicalMemDb}#legacy-vec`,\n scope,\n category: 'legacyStore',\n reason: 'Legacy vector tables pending cleanup in memory.db',\n bytes: 0,\n })\n }\n } catch {\n /* ignore */\n }\n }\n\n for (const dbName of ['global.db', 'project.db']) {\n const persDbPath = join(pantheonDir, 'persistence', dbName)\n if (existsSync(persDbPath)) {\n unmigratedStores += 1\n addItem(persDbPath, 'legacyStore', `Unmigrated persistence/${dbName}`)\n }\n }\n\n const legacyGoalsJson = join(pantheonDir, 'goals.json')\n if (existsSync(legacyGoalsJson)) {\n unmigratedStores += 1\n addItem(legacyGoalsJson, 'legacyStore', 'Unmigrated legacy goals.json')\n }\n\n // 3. Redundant copied Pantheon assets shadowed by native plugin transforms\n if (options.includeRedundantCopiedAssets !== false) {\n for (const agentFile of CANONICAL_AGENT_MD_FILES) {\n addItem(\n join(configRoot, 'agents', agentFile),\n 'redundantAsset',\n 'Canonical Pantheon agent copy shadowed by native plugin transform',\n )\n addItem(\n join(configRoot, 'agent', agentFile),\n 'redundantAsset',\n 'Legacy singular agent copy shadowed by native plugin transform',\n )\n addItem(\n join(configRoot, 'prompts', agentFile),\n 'redundantAsset',\n 'Legacy prompt template copy provided in package',\n )\n }\n\n for (const cmdFile of CANONICAL_COMMAND_MD_FILES) {\n addItem(\n join(configRoot, 'commands', cmdFile),\n 'redundantAsset',\n 'Canonical Pantheon command copy shadowed by native plugin transform',\n )\n addItem(\n join(configRoot, 'command', cmdFile),\n 'redundantAsset',\n 'Legacy singular command directory copy',\n )\n }\n\n for (const instr of LEGACY_INSTRUCTION_FILES) {\n addItem(\n join(configRoot, 'instructions', instr),\n 'redundantAsset',\n 'Legacy instruction file superseded by AGENTS.global.md',\n )\n }\n\n for (const skillId of CANONICAL_SKILL_IDS) {\n addItem(\n join(configRoot, 'skills', skillId),\n 'redundantAsset',\n 'Bundled Pantheon skill directory provided natively by plugin',\n )\n }\n\n const tuiCopyDir = join(configRoot, 'plugins', 'pantheon-tui')\n if (existsSync(tuiCopyDir)) {\n let copiedVersion = ''\n try {\n copiedVersion = String(\n JSON.parse(readFileSync(join(tuiCopyDir, 'package.json'), 'utf8')).version ?? '',\n )\n } catch {\n copiedVersion = ''\n }\n const runningVersion = options.runningVersion ? String(options.runningVersion) : ''\n const drifted = Boolean(runningVersion && copiedVersion && copiedVersion !== runningVersion)\n addItem(\n tuiCopyDir,\n drifted ? 'drift' : 'redundantAsset',\n drifted\n ? `Copied TUI plugin v${copiedVersion} drifts from v${runningVersion}`\n : 'Copied TUI directory superseded by npm package export',\n )\n }\n }\n\n return { items, unmigratedStores }\n}\n\nfunction ensureCanonicalMemoryDb(dbPath: string): DatabaseSync {\n mkdirSync(dirname(dbPath), { recursive: true })\n const db = new DatabaseSync(dbPath)\n db.exec(`\n PRAGMA busy_timeout = 3000;\n PRAGMA journal_mode = WAL;\n CREATE TABLE IF NOT EXISTS memories (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n namespace TEXT NOT NULL DEFAULT 'default',\n key TEXT NOT NULL,\n value TEXT NOT NULL,\n importance REAL NOT NULL DEFAULT 0.5,\n created_at TEXT NOT NULL,\n expires_at TEXT,\n UNIQUE(namespace, key)\n );\n CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(\n key, value, namespace,\n content='memories',\n content_rowid='id'\n );\n CREATE TRIGGER IF NOT EXISTS memories_ai AFTER INSERT ON memories BEGIN\n INSERT INTO memories_fts(rowid, key, value, namespace) VALUES (new.id, new.key, new.value, new.namespace);\n END;\n CREATE TRIGGER IF NOT EXISTS memories_ad AFTER DELETE ON memories BEGIN\n INSERT INTO memories_fts(memories_fts, rowid, key, value, namespace) VALUES('delete', old.id, old.key, old.value, old.namespace);\n END;\n CREATE TRIGGER IF NOT EXISTS memories_au AFTER UPDATE ON memories BEGIN\n INSERT INTO memories_fts(memories_fts, rowid, key, value, namespace) VALUES('delete', old.id, old.key, old.value, old.namespace);\n INSERT INTO memories_fts(rowid, key, value, namespace) VALUES (new.id, new.key, new.value, new.namespace);\n END;\n `)\n return db\n}\n\nfunction migrateScopeBeforeDelete(baseRoot: string): number {\n const pantheonDir = join(baseRoot, '.pantheon')\n if (!existsSync(pantheonDir)) return 0\n let migrated = 0\n const nowIso = new Date().toISOString()\n\n // 1. Migrate flat .pantheon/memory.db -> .pantheon/memory/memory.db + drop legacy vector tables\n const flatMemDbPath = join(pantheonDir, 'memory.db')\n const canonicalMemPath = join(pantheonDir, 'memory', 'memory.db')\n if (existsSync(flatMemDbPath)) {\n try {\n const src = new DatabaseSync(flatMemDbPath, { readOnly: true })\n const dst = ensureCanonicalMemoryDb(canonicalMemPath)\n if (tableExists(src, 'memories')) {\n const rows = src\n .prepare('SELECT namespace, key, value, created_at FROM memories')\n .all() as Array<{\n namespace?: string\n key?: string\n value?: string\n created_at?: string\n }>\n const insert = dst.prepare(\n 'INSERT OR IGNORE INTO memories (namespace, key, value, importance, created_at) VALUES (?, ?, ?, ?, ?)',\n )\n dst.exec('BEGIN IMMEDIATE')\n try {\n for (const r of rows) {\n insert.run(\n String(r.namespace ?? 'default'),\n String(r.key ?? ''),\n String(r.value ?? ''),\n 0.5,\n String(r.created_at ?? nowIso),\n )\n migrated += 1\n }\n dst.exec('COMMIT')\n } catch (txErr) {\n try {\n dst.exec('ROLLBACK')\n } catch {\n /* ignore */\n }\n throw txErr\n }\n }\n src.close()\n dst.close()\n } catch {\n /* fail-open */\n }\n }\n\n if (existsSync(canonicalMemPath)) {\n try {\n const db = ensureCanonicalMemoryDb(canonicalMemPath)\n for (const trig of ['memories_vec_ai', 'memories_vec_ad', 'memories_vec_au']) {\n db.exec(`DROP TRIGGER IF EXISTS ${trig}`)\n }\n for (const tbl of ['memories_vec', 'vec_memories', 'memory_embeddings', 'memory_vectors']) {\n if (tableExists(db, tbl)) {\n db.exec(`DROP TABLE IF EXISTS ${tbl}`)\n migrated += 1\n }\n }\n db.close()\n } catch {\n /* fail-open */\n }\n }\n\n // 2. Migrate persistence/{global,project}.db -> persistence//.json\n const persDir = join(pantheonDir, 'persistence')\n for (const dbName of ['global.db', 'project.db']) {\n const dbPath = join(persDir, dbName)\n if (!existsSync(dbPath)) continue\n try {\n const db = new DatabaseSync(dbPath, { readOnly: true })\n for (const tbl of ['kv', 'kv_store', 'context', 'checkpoints', 'sessions']) {\n if (!tableExists(db, tbl) || countTableRows(db, tbl) === 0) continue\n const cols = db.prepare(`PRAGMA table_info(${tbl})`).all() as Array<{ name: string }>\n const colNames = new Set(cols.map((c) => c.name))\n const keyCol = colNames.has('key')\n ? 'key'\n : colNames.has('id')\n ? 'id'\n : colNames.has('session_id')\n ? 'session_id'\n : null\n const valCol = colNames.has('value')\n ? 'value'\n : colNames.has('data')\n ? 'data'\n : colNames.has('content')\n ? 'content'\n : null\n if (!keyCol || !valCol) continue\n const nsSelect = colNames.has('namespace')\n ? 'namespace'\n : `'${tbl === 'checkpoints' || tbl === 'sessions' ? 'checkpoints' : 'default'}' AS namespace`\n const rows = db\n .prepare(`SELECT ${nsSelect}, ${keyCol} AS k, ${valCol} AS v FROM ${tbl}`)\n .all() as Array<{\n namespace?: string\n k?: string\n v?: unknown\n }>\n for (const r of rows) {\n const ns = toSafeSegment(r.namespace, 'default')\n const key = toSafeSegment(r.k, '')\n if (!key) continue\n const targetDir = join(persDir, ns)\n const targetFile = join(targetDir, `${key}.json`)\n if (!existsSync(targetFile)) {\n mkdirSync(targetDir, { recursive: true })\n writeFileSync(\n targetFile,\n JSON.stringify(\n { key, namespace: ns, value: String(r.v ?? ''), updated_at: nowIso },\n null,\n 2,\n ),\n 'utf8',\n )\n migrated += 1\n }\n }\n }\n db.close()\n } catch {\n /* fail-open */\n }\n }\n\n // 3. Migrate legacy goals.json -> .pantheon/goals/.json\n const legacyGoalsPath = join(pantheonDir, 'goals.json')\n if (existsSync(legacyGoalsPath)) {\n try {\n const parsed = JSON.parse(readFileSync(legacyGoalsPath, 'utf8')) as unknown\n const list = Array.isArray(parsed)\n ? parsed\n : parsed &&\n typeof parsed === 'object' &&\n Array.isArray((parsed as { goals?: unknown }).goals)\n ? ((parsed as { goals: unknown[] }).goals ?? [])\n : []\n const goalsDir = join(pantheonDir, 'goals')\n for (const item of list) {\n if (!item || typeof item !== 'object') continue\n const rec = item as Record\n const safeId = toSafeSegment(rec.id ?? rec.goal_id, '')\n if (!safeId) continue\n const target = join(goalsDir, `${safeId}.json`)\n if (!existsSync(target)) {\n mkdirSync(goalsDir, { recursive: true })\n writeFileSync(\n target,\n JSON.stringify(\n {\n id: safeId,\n title: String(rec.title ?? rec.description ?? ''),\n criteria: Array.isArray(rec.criteria) ? rec.criteria.map(String) : [],\n status: String(rec.status ?? 'active'),\n created_at: typeof rec.created_at === 'string' ? rec.created_at : nowIso,\n updated_at: typeof rec.updated_at === 'string' ? rec.updated_at : nowIso,\n },\n null,\n 2,\n ),\n 'utf8',\n )\n migrated += 1\n }\n }\n } catch {\n /* fail-open */\n }\n }\n\n return migrated\n}\n\nexport function scanLegacyArtifacts(options: LegacyAuditOptions = {}): LegacyAuditScan {\n const workspaceDir = options.workspaceDir ? resolve(options.workspaceDir) : undefined\n const globalConfigDir = options.globalConfigDir\n ? resolve(options.globalConfigDir)\n : resolveAuditGlobalDir(options.env)\n\n const items: LegacyAuditItem[] = []\n let unmigratedStores = 0\n\n if (globalConfigDir && existsSync(globalConfigDir) && globalConfigDir !== '/') {\n const res = collectScopeAudit('global', globalConfigDir, globalConfigDir, options)\n items.push(...res.items)\n unmigratedStores += res.unmigratedStores\n }\n\n if (\n workspaceDir &&\n existsSync(workspaceDir) &&\n workspaceDir !== '/' &&\n (!globalConfigDir || !samePath(workspaceDir, globalConfigDir))\n ) {\n const res = collectScopeAudit('project', workspaceDir, join(workspaceDir, '.opencode'), options)\n items.push(...res.items)\n unmigratedStores += res.unmigratedStores\n }\n\n const byScope: Record = { global: 0, project: 0 }\n const byCategory: Record = {}\n let totalBytes = 0\n for (const item of items) {\n byScope[item.scope] = (byScope[item.scope] ?? 0) + 1\n byCategory[item.category] = (byCategory[item.category] ?? 0) + 1\n totalBytes += item.bytes\n }\n\n return {\n items,\n summary: {\n total: items.length,\n totalBytes,\n unmigratedStores,\n byScope,\n byCategory,\n },\n }\n}\n\nexport function cleanLegacyArtifacts(\n options: LegacyAuditOptions & { readonly scope?: 'all' | LegacyScope } = {},\n): LegacyCleanResult {\n const workspaceDir = options.workspaceDir ? resolve(options.workspaceDir) : undefined\n const globalConfigDir = options.globalConfigDir\n ? resolve(options.globalConfigDir)\n : resolveAuditGlobalDir(options.env)\n const scopeFilter = options.scope && options.scope !== 'all' ? options.scope : null\n\n const scan = scanLegacyArtifacts(options)\n let migratedRecords = 0\n\n if (\n scopeFilter !== 'project' &&\n globalConfigDir &&\n existsSync(globalConfigDir) &&\n globalConfigDir !== '/'\n ) {\n migratedRecords += migrateScopeBeforeDelete(globalConfigDir)\n }\n if (\n scopeFilter !== 'global' &&\n workspaceDir &&\n existsSync(workspaceDir) &&\n workspaceDir !== '/' &&\n (!globalConfigDir || !samePath(workspaceDir, globalConfigDir))\n ) {\n migratedRecords += migrateScopeBeforeDelete(workspaceDir)\n }\n\n const removed: string[] = []\n const errors: Array<{ readonly path: string; readonly reason: string }> = []\n let reclaimedBytes = 0\n\n for (const item of scan.items) {\n if (scopeFilter && item.scope !== scopeFilter) continue\n if (item.path.endsWith('#legacy-vec')) {\n removed.push(item.path)\n continue\n }\n const scopeRoot = item.scope === 'global' ? globalConfigDir : workspaceDir\n if (!scopeRoot || !isConfinedWithin(scopeRoot, item.path)) {\n errors.push({ path: item.path, reason: 'Path escapes target scope root' })\n continue\n }\n try {\n if (existsSync(item.path)) {\n rmSync(item.path, { recursive: true, force: true })\n removed.push(item.path)\n reclaimedBytes += item.bytes\n }\n if (item.path.endsWith('.db')) {\n for (const suffix of ['-wal', '-shm', '-journal']) {\n const sidecar = `${item.path}${suffix}`\n if (existsSync(sidecar) && isConfinedWithin(scopeRoot, sidecar)) {\n const sidecarBytes = measurePathBytes(sidecar)\n rmSync(sidecar, { force: true })\n removed.push(sidecar)\n reclaimedBytes += sidecarBytes\n }\n }\n }\n } catch (err) {\n errors.push({\n path: item.path,\n reason: err instanceof Error ? err.message : String(err),\n })\n }\n }\n\n return {\n removed,\n reclaimedBytes,\n migratedRecords,\n errors,\n }\n}\n","/**\n * preset-state.ts — the Model Preset section of the settings window.\n *\n * TUI-local replica (the bundle must stay self-contained). The preset NAMES\n * mirror routing.yml's `presets:` and are drift-pinned by\n * tests/tui-preset-state.test.mjs against `loadPresetDefs()`. The marker file\n * shape mirrors scripts/install/model-picker.mjs's `buildActivePresetFile`\n * (version 1), and the readers (`resolveActivePreset`, vision.ts candidates)\n * only consult `.preset`, so the window writes `source: 'tui-settings'`.\n *\n * Scope note: the window writes the GLOBAL marker only\n * (`/opencode/.pantheon/active-preset.json`). A project marker\n * wins (it precedes the global path in every runtime candidate list), so it\n * is displayed read-only. `none` DELETES the marker with a .bak backup — the\n * same contract as the CLI's `set-tier none`.\n */\nimport {\n copyFileSync,\n existsSync,\n mkdirSync,\n readFileSync,\n renameSync,\n rmSync,\n writeFileSync,\n} from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport type { SettingsRow, SettingsTab } from './pantheon-settings-state.ts'\n\n/** Mirrors routing.yml `presets:` — drift-pinned against loadPresetDefs(). */\nexport const PRESET_NAMES: readonly string[] = Object.freeze([\n 'go-free',\n 'go-fast',\n 'go-premium',\n 'go-hybrid',\n 'anthropic',\n 'openai',\n])\n\nexport interface ActivePresetMarker {\n version: number\n preset: string\n source: string\n updated_at: string\n}\n\nexport function globalActivePresetPath(env: Record = process.env) {\n const xdg = env.XDG_CONFIG_HOME\n const home = env.HOME ?? ''\n const root = xdg ?? join(home, '.config')\n return join(root, 'opencode', '.pantheon', 'active-preset.json')\n}\n\nexport function projectActivePresetPath() {\n return join(process.cwd(), '.pantheon', 'active-preset.json')\n}\n\n/** Fail-open read: missing/corrupt marker = no active preset. */\nexport function readActivePresetMarker(path: string): { name: string; updatedAt: string } | null {\n try {\n const raw = JSON.parse(readFileSync(path, 'utf8')) as { preset?: unknown; updated_at?: unknown }\n if (typeof raw?.preset !== 'string' || raw.preset === '' || raw.preset === 'none') return null\n return {\n name: raw.preset,\n updatedAt: typeof raw.updated_at === 'string' ? raw.updated_at : '',\n }\n } catch {\n return null\n }\n}\n\nfunction writeMarkerAtomically(path: string, content: string): void {\n mkdirSync(dirname(path), { recursive: true })\n const temp = `${path}.tui.tmp`\n writeFileSync(temp, content)\n renameSync(temp, path)\n}\n\n/** Select a preset globally: .bak backup, atomic write, version-1 marker. */\nexport function writeActivePreset(\n path: string,\n name: string,\n nowIso = new Date().toISOString(),\n): void {\n if (!PRESET_NAMES.includes(name)) {\n throw new TypeError(`Refusing to persist unknown preset \"${name}\"`)\n }\n backupMarker(path)\n const marker: ActivePresetMarker = {\n version: 1,\n preset: name,\n source: 'tui-settings',\n updated_at: nowIso,\n }\n writeMarkerAtomically(path, `${JSON.stringify(marker, null, 2)}\\n`)\n}\n\n/** Clear the global marker (the `none` contract): .bak backup, then remove. */\nexport function clearActivePreset(path: string): void {\n backupMarker(path)\n rmSync(path, { force: true })\n}\n\nfunction backupMarker(path: string): void {\n if (!existsSync(path)) return\n mkdirSync(dirname(path), { recursive: true })\n copyFileSync(path, `${path}.bak`)\n}\n\nexport const VISION_MODEL_OPTIONS: readonly string[] = Object.freeze([\n 'auto',\n 'opencode-go/mimo-v2.6-flash',\n 'google/gemini-2.5-flash',\n 'openai/gpt-5-mini',\n 'anthropic/claude-3-5-haiku',\n 'opencode-go/mimo-v2.5',\n])\n\nexport function visionConfigPaths(\n cwd = process.cwd(),\n env: Record = process.env,\n): string[] {\n const home = env.HOME ?? ''\n const xdg = env.XDG_CONFIG_HOME ?? join(home, '.config')\n return [\n join(cwd, '.opencode', 'opencode-vision.json'),\n join(xdg, 'opencode', 'opencode-vision.json'),\n ]\n}\n\nexport function readConfiguredVisionModel(\n cwd = process.cwd(),\n env: Record = process.env,\n): string {\n for (const path of visionConfigPaths(cwd, env)) {\n try {\n if (existsSync(path)) {\n const parsed = JSON.parse(readFileSync(path, 'utf8')) as { visionModel?: unknown }\n if (typeof parsed?.visionModel === 'string' && parsed.visionModel.trim()) {\n return parsed.visionModel.trim()\n }\n }\n } catch {\n // ignore corrupt/missing\n }\n }\n return 'auto'\n}\n\nexport function writeConfiguredVisionModel(\n model: string,\n cwd = process.cwd(),\n env: Record = process.env,\n): void {\n const home = env.HOME ?? ''\n const xdg = env.XDG_CONFIG_HOME ?? join(home, '.config')\n const projectDir = join(cwd, '.opencode')\n const targetPath = existsSync(projectDir)\n ? join(projectDir, 'opencode-vision.json')\n : join(xdg, 'opencode', 'opencode-vision.json')\n\n let current: Record = {}\n try {\n if (existsSync(targetPath)) {\n current = JSON.parse(readFileSync(targetPath, 'utf8')) as Record\n }\n } catch {\n current = {}\n }\n\n if (model === 'auto' || !model.trim()) {\n delete current.visionModel\n } else {\n current.visionModel = model.trim()\n }\n\n mkdirSync(dirname(targetPath), { recursive: true })\n const temp = `${targetPath}.tui.tmp`\n writeFileSync(temp, `${JSON.stringify(current, null, 2)}\\n`, 'utf8')\n renameSync(temp, targetPath)\n}\n\nexport interface PresetSectionInput {\n globalName: string | null\n projectName: string | null\n visionModel?: string\n}\n\n/** The staged value 'none' means: delete the global marker (the CLI contract). */\nexport const PRESET_NONE = 'none'\n\nexport const PRESET_CYCLE: readonly string[] = Object.freeze([PRESET_NONE, ...PRESET_NAMES])\n\nexport function buildPresetTab(input: PresetSectionInput, languagePref?: string): SettingsTab {\n const isPt = languagePref === 'pt-BR'\n const rows: SettingsRow[] = [\n {\n id: 'preset',\n name: isPt ? 'Predefinição' : 'Preset',\n value: input.globalName ?? PRESET_NONE,\n cycle: PRESET_CYCLE,\n note: isPt\n ? 'marcador global · gravação atômica, backup .bak · none = padrão OpenCode'\n : 'global marker · atomic write, .bak backup · none = opencode defaults',\n },\n ]\n if (input.projectName !== null) {\n rows.push({\n id: 'preset.project',\n name: isPt ? 'Projeto' : 'Project',\n value: input.projectName,\n note: isPt\n ? `${projectActivePresetPath()} tem precedência sobre o global — somente leitura aqui`\n : `${projectActivePresetPath()} wins over the global marker — read-only here`,\n })\n }\n if (input.visionModel !== undefined) {\n rows.push({\n id: 'preset.vision_model',\n name: isPt ? 'Modelo de Visão' : 'Vision Model',\n value: input.visionModel || 'auto',\n cycle: VISION_MODEL_OPTIONS,\n note: isPt\n ? 'modelo para inspeção de imagens (vision_describe) · salvo em opencode-vision.json'\n : 'model for image inspection (vision_describe) · saved in opencode-vision.json',\n })\n }\n return {\n id: 'preset',\n title: 'Preset',\n groups: [{ title: isPt ? 'Predefinição de modelo' : 'Model preset', rows }],\n }\n}\n","/**\n * quota-state.ts — the Quotas & Spend tab (inspired by opencode-quota).\n *\n * Exposes live model token spending, daily budgets, rate-limits per provider,\n * and context token telemetry in a dedicated tab in the Pantheon Settings window.\n */\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { dirname, join } from 'node:path'\nimport type { SettingsTab } from './pantheon-settings-state.ts'\nimport { resolveLanguage } from './settings-i18n.ts'\n\nexport interface QuotaSnapshot {\n todaySpend?: string\n monthSpend?: string\n sessionSpend?: string\n sessionTokens?: string\n cacheHit?: string\n speed?: string\n}\n\nexport interface QuotaPrefs {\n sessionCap: string\n alertThreshold: 'enabled' | 'disabled'\n autoCompact: 'enabled' | 'disabled'\n}\n\nexport const DEFAULT_QUOTA_PREFS: QuotaPrefs = {\n sessionCap: '$5.00',\n alertThreshold: 'enabled',\n autoCompact: 'enabled',\n}\n\nexport function resolveQuotaPrefsPath(): string {\n const xdg = process.env.XDG_CONFIG_HOME\n const base = xdg?.startsWith('/') ? xdg : join(homedir(), '.config')\n return join(base, 'opencode', 'pantheon-quota.json')\n}\n\nexport function readQuotaPrefs(filePath = resolveQuotaPrefsPath()): QuotaPrefs {\n try {\n if (!existsSync(filePath)) return { ...DEFAULT_QUOTA_PREFS }\n const raw = JSON.parse(readFileSync(filePath, 'utf8')) as Partial\n return {\n sessionCap:\n typeof raw.sessionCap === 'string' &&\n ['$1.00', '$2.00', '$5.00', '$10.00', 'unlimited'].includes(raw.sessionCap)\n ? raw.sessionCap\n : DEFAULT_QUOTA_PREFS.sessionCap,\n alertThreshold: raw.alertThreshold === 'disabled' ? 'disabled' : 'enabled',\n autoCompact: raw.autoCompact === 'disabled' ? 'disabled' : 'enabled',\n }\n } catch {\n return { ...DEFAULT_QUOTA_PREFS }\n }\n}\n\nexport function writeQuotaPrefs(prefs: QuotaPrefs, filePath = resolveQuotaPrefsPath()): void {\n mkdirSync(dirname(filePath), { recursive: true })\n writeFileSync(filePath, `${JSON.stringify(prefs, null, 2)}\\n`, 'utf8')\n}\n\nexport function applyQuotaRow(prefs: QuotaPrefs, id: string, value: string): QuotaPrefs {\n const next = { ...prefs }\n if (id === 'quota.budget.sessionCap') {\n if (['$1.00', '$2.00', '$5.00', '$10.00', 'unlimited'].includes(value)) {\n next.sessionCap = value\n }\n } else if (id === 'quota.budget.alertThreshold') {\n next.alertThreshold = value === 'disabled' ? 'disabled' : 'enabled'\n } else if (id === 'quota.compaction.auto') {\n next.autoCompact = value === 'disabled' ? 'disabled' : 'enabled'\n }\n return next\n}\n\nexport function buildQuotaTab(\n snapshot?: QuotaSnapshot,\n languagePref?: string,\n prefs: QuotaPrefs = readQuotaPrefs(),\n): SettingsTab {\n const isPt = resolveLanguage(languagePref) === 'pt-BR'\n\n return {\n id: 'quota',\n title: isPt ? 'Cotas & Gastos' : 'Quotas & Spend',\n groups: [\n {\n title: isPt ? 'Consumo & Gastos de Sessão' : 'Session Spend & Tokens',\n rows: [\n {\n id: 'quota.spend.today',\n name: isPt ? 'Gasto hoje (00h-agora)' : 'Spend today (00h-now)',\n value: snapshot?.todaySpend ?? '—',\n note: isPt ? 'Calculado a partir de opencode.db' : 'Derived from opencode.db ledger',\n },\n {\n id: 'quota.spend.month',\n name: isPt ? 'Gasto acumulado (30d)' : 'Spend last 30 days',\n value: snapshot?.monthSpend ?? '—',\n note: isPt ? 'Janela móvel de 30 dias' : 'Rolling 30-day window',\n },\n {\n id: 'quota.spend.session',\n name: isPt ? 'Gasto na sessão ativa' : 'Active session spend',\n value: snapshot?.sessionSpend ?? '—',\n note: isPt ? 'Custo de todas as mensagens do turno' : 'Sum of turn assistant messages',\n },\n {\n id: 'quota.tokens.context',\n name: isPt ? 'Tokens de contexto' : 'Context tokens',\n value: snapshot?.sessionTokens ?? '—',\n note: isPt\n ? 'Tokens consumidos vs janela do modelo'\n : 'Tokens used vs model context limit',\n },\n {\n id: 'quota.tokens.cache',\n name: isPt ? 'Eficiência de cache' : 'Prompt cache hit',\n value: snapshot?.cacheHit ?? '—',\n note: isPt ? 'Desconto de leitura em cache aplicado' : 'Cache read discount applied',\n },\n ],\n },\n {\n title: isPt ? 'Limites & Teto de Orçamento' : 'Rate Limits & Budget Caps',\n rows: [\n {\n id: 'quota.budget.sessionCap',\n name: isPt ? 'Teto por sessão' : 'Session budget cap',\n value: prefs.sessionCap,\n cycle: ['$1.00', '$2.00', '$5.00', '$10.00', 'unlimited'],\n note: isPt\n ? 'Avisa ou pausa ao atingir o teto'\n : 'Warns or pauses when session spend reaches cap',\n },\n {\n id: 'quota.budget.alertThreshold',\n name: isPt ? 'Alerta em 80% do teto' : 'Alert at 80% of cap',\n value: prefs.alertThreshold,\n cycle: ['enabled', 'disabled'],\n note: isPt\n ? 'Emite aviso visual no footer da TUI'\n : 'Shows visual notice in TUI footer',\n },\n {\n id: 'quota.compaction.auto',\n name: isPt ? 'Auto-compactar em 80% do contexto' : 'Auto-compact at 80% context',\n value: prefs.autoCompact,\n cycle: ['enabled', 'disabled'],\n note: isPt\n ? 'Aciona compressão automática de histórico'\n : 'Triggers automatic context compaction',\n },\n ],\n },\n {\n title: isPt\n ? 'Provedores & Janelas de Cota (Referência)'\n : 'Providers & Quota Windows (Reference)',\n rows: [\n {\n id: 'quota.ref.anthropic',\n name: 'Anthropic (Claude 3.7)',\n value: 'Tier 4',\n note: isPt\n ? '400k TPM · Reset diário às 00:00 UTC'\n : '400k TPM · Daily reset at 00:00 UTC',\n },\n {\n id: 'quota.ref.openai',\n name: 'OpenAI (GPT-4o)',\n value: 'Tier 4',\n note: isPt\n ? '800k TPM · Reset por janela móvel de 1 min'\n : '800k TPM · 1-minute rolling window',\n },\n {\n id: 'quota.ref.google',\n name: 'Google (Gemini 2.5)',\n value: 'Pay-as-you-go',\n note: isPt\n ? '4M TPM · Alta capacidade com cota flexível'\n : '4M TPM · High capacity with flexible quota',\n },\n ],\n },\n ],\n }\n}\n","// biome-ignore-all lint/suspicious/noExplicitAny: stored prefs are host JSON of a known shape.\n/**\n * tui-prefs.ts — the TUI personalization core (the settings window's TUI tab).\n *\n * TUI-local copy doctrine (same as cost-data.ts): the bundle must stay\n * self-contained. Persistence is the HOST's durable plugin storage\n * (`context.storage.store('tui-prefs', { initial })` — reactive solid store,\n * live-synced across TUI instances); this module owns the SHAPE and the pure\n * operations, never the store handle.\n *\n * v1 surfaces: sidebar fixed headers, sidebar blocks, the Context block's\n * sub-lines and gauge style, and the two Pantheon footer lines. Everything\n * defaults to on — the window exists to turn things OFF.\n */\n\nimport type { Context } from '@opencode/plugin/tui/context'\nimport type { Accessor, Setter } from 'solid-js'\nimport { createSignal } from 'solid-js'\nimport type { SettingsDraft, SettingsRow, SettingsTab } from './pantheon-settings-state.ts'\nimport { resolveLanguage } from './settings-i18n.ts'\n\n// ── The durable store handle (host storage, one per plugin) ────────────\n// Created once at setup and stashed under a globalThis symbol so\n// hot-reload generations keep sharing the same live store (the same\n// singleton doctrine as the plugin's SINGLETON guard).\n\nconst PREFS_SYMBOL = Symbol.for('pantheon.tui.prefs.v1')\nconst DRAFT_PREVIEW_SYMBOL = Symbol.for('pantheon.tui.draft_preview.v1')\ntype PrefsStore = readonly [TuiPrefs, (mutation: (draft: TuiPrefs) => void) => Promise]\ntype DraftSignal = [Accessor, Setter]\n\nfunction stash(): PrefsStore | undefined {\n return (globalThis as Record)[PREFS_SYMBOL] as PrefsStore | undefined\n}\n\nfunction getDraftPreviewSignal(): DraftSignal {\n const g = globalThis as Record\n if (!g[DRAFT_PREVIEW_SYMBOL]) {\n g[DRAFT_PREVIEW_SYMBOL] = createSignal(undefined)\n }\n return g[DRAFT_PREVIEW_SYMBOL] as DraftSignal\n}\n\n/** Set the active draft preview overlay (used by settings window to provide live preview). */\nexport function setTuiDraftPreview(draft: SettingsDraft | undefined): void {\n const [, setDraft] = getDraftPreviewSignal()\n setDraft(draft && Object.keys(draft).length > 0 ? { ...draft } : undefined)\n}\n\n/** Clear the active draft preview overlay. */\nexport function clearTuiDraftPreview(): void {\n const [, setDraft] = getDraftPreviewSignal()\n setDraft(undefined)\n}\n\n/** The active draft preview accessor. */\nexport function tuiDraftPreview(): SettingsDraft | undefined {\n const [draft] = getDraftPreviewSignal()\n return draft()\n}\n\n/** Create (or reuse) the durable prefs store. Fail-open: without host\n * storage the consumers fall back to DEFAULT_TUI_PREFS (read-only). */\nexport function initTuiPrefs(context: Context): void {\n if (stash() !== undefined) return\n try {\n const handle = context.storage?.store?.('tui-prefs', { initial: DEFAULT_TUI_PREFS }) as\n | PrefsStore\n | undefined\n if (handle !== undefined) {\n ;(globalThis as unknown as Record)[PREFS_SYMBOL] = handle\n // Self-heal: if store was persisted before layout existed or lacks new fields, backfill defaults\n if (\n !handle[0]?.layout ||\n typeof handle[0]?.sidebar?.context?.turnCost !== 'boolean' ||\n typeof handle[0]?.sidebar?.context?.tokenAnatomy !== 'boolean'\n ) {\n handle[1]((draft: any) => {\n if (!draft.layout) {\n draft.layout = { ...DEFAULT_TUI_PREFS.layout }\n }\n if (draft.sidebar?.context) {\n if (typeof draft.sidebar.context.turnCost !== 'boolean') {\n draft.sidebar.context.turnCost = true\n }\n if (typeof draft.sidebar.context.tokenAnatomy !== 'boolean') {\n draft.sidebar.context.tokenAnatomy = true\n }\n }\n }).catch(() => {})\n }\n }\n } catch {\n /* no host storage — defaults stay read-only */\n }\n}\n\n/** Deep clone and overlay staged settings draft onto base TuiPrefs. */\nexport function previewTuiPrefs(base: TuiPrefs, draft?: SettingsDraft): TuiPrefs {\n if (!draft || Object.keys(draft).length === 0) return base\n let hasTui = false\n for (const k of Object.keys(draft)) {\n if (k.startsWith('tui.')) {\n hasTui = true\n break\n }\n }\n if (!hasTui) return base\n\n const normalized = normalizeTuiPrefs(base)\n const effective: TuiPrefs = {\n version: 1,\n layout: { ...normalized.layout },\n ...(normalized.theme ? { theme: { ...normalized.theme } } : {}),\n sidebar: {\n header: { ...normalized.sidebar.header },\n ...(normalized.sidebar.pinnedSessions\n ? { pinnedSessions: [...normalized.sidebar.pinnedSessions] }\n : {}),\n blocks: { ...normalized.sidebar.blocks },\n context: { ...normalized.sidebar.context },\n },\n footer: { ...normalized.footer },\n }\n\n for (const [id, value] of Object.entries(draft)) {\n if (id.startsWith('tui.')) {\n applyTuiRow(effective, id, value)\n }\n }\n return effective\n}\n\n/** The raw persisted prefs from host storage (no draft overlay). */\nexport function savedTuiPrefs(): TuiPrefs {\n const s = stash()?.[0]\n if (!s) return DEFAULT_TUI_PREFS\n return normalizeTuiPrefs(s)\n}\n\n/** The live reactive prefs (read properties inside memos/JSX — tracked).\n * When a settings window has an active draft, preview overlays on top\n * of durable storage in real time. */\nexport function tuiPrefs(): TuiPrefs {\n const base = savedTuiPrefs()\n const preview = tuiDraftPreview()\n if (!preview) return base\n return previewTuiPrefs(base, preview)\n}\n\n/** Stage a mutation against the durable store; resolves when persisted. */\nexport function mutateTuiPrefs(mutation: (draft: TuiPrefs) => void): Promise {\n const handle = stash()\n if (handle === undefined) return Promise.resolve()\n return handle[1](mutation)\n}\n\nexport const GAUGE_STYLES: readonly string[] = Object.freeze(['both', 'bar', 'percent', 'off'])\nexport const ENABLED_CYCLE: readonly string[] = Object.freeze(['enabled', 'disabled'])\n\nexport const BAR_SHAPES_CYCLE: readonly string[] = Object.freeze([\n 'smooth',\n 'line',\n 'block',\n 'ascii',\n 'dots',\n 'braille',\n])\nexport const BAR_WIDTHS_CYCLE: readonly string[] = Object.freeze([\n 'standard',\n 'compact',\n 'wide',\n 'full',\n])\nexport const LAYOUT_PRESETS_CYCLE: readonly string[] = Object.freeze(['comfortable', 'compact'])\nexport const SEPARATOR_STYLES_CYCLE: readonly string[] = Object.freeze([\n 'spaces',\n 'pipes',\n 'dots',\n 'slashes',\n])\nexport const SETTINGS_VIEW_MODES: readonly string[] = Object.freeze([\n 'docked',\n 'fullscreen',\n 'dialog',\n])\n\nexport type GaugeStyle = 'both' | 'bar' | 'percent' | 'off'\nexport type BarShapePref = 'line' | 'block' | 'smooth' | 'ascii' | 'dots' | 'braille'\nexport type BarWidthPref = 'standard' | 'compact' | 'wide' | 'full'\nexport type LayoutPresetPref = 'comfortable' | 'compact'\nexport type SeparatorStylePref = 'spaces' | 'pipes' | 'dots' | 'slashes'\nexport type SettingsViewModePref = 'docked' | 'fullscreen' | 'dialog'\nexport type LanguagePref = 'auto' | 'pt-BR' | 'en'\n\nexport const LANGUAGE_CYCLE: readonly string[] = Object.freeze(['auto', 'pt-BR', 'en'])\n\nexport type ThemeModePref = 'auto' | 'dark' | 'light'\nexport const THEME_MODES_CYCLE: readonly string[] = Object.freeze(['auto', 'dark', 'light'])\n\nexport type AccentColorPref = 'host' | 'pantheon' | 'emerald' | 'cyan' | 'amber' | 'purple' | 'rose'\nexport const ACCENT_COLORS_CYCLE: readonly string[] = Object.freeze([\n 'host',\n 'pantheon',\n 'emerald',\n 'cyan',\n 'amber',\n 'purple',\n 'rose',\n])\n\nexport const ACCENT_PALETTE: Record<\n AccentColorPref,\n { primary: string; hover: string; muted: string }\n> = {\n host: { primary: '#fba970', hover: '#fdba74', muted: '#a1a1aa' },\n pantheon: { primary: '#fba970', hover: '#fdba74', muted: '#a1a1aa' },\n emerald: { primary: '#10b981', hover: '#34d399', muted: '#059669' },\n cyan: { primary: '#06b6d4', hover: '#22d3ee', muted: '#0891b2' },\n amber: { primary: '#f59e0b', hover: '#fbbf24', muted: '#d97706' },\n purple: { primary: '#a855f7', hover: '#c084fc', muted: '#9333ea' },\n rose: { primary: '#f43f5e', hover: '#fb7185', muted: '#e11d48' },\n}\n\nexport function resolveAccentColor(accent: AccentColorPref | undefined, contextTheme: any): string {\n if (!accent || accent === 'host') {\n return contextTheme?.text?.feedback?.warning?.base ?? contextTheme?.text?.base ?? '#fba970'\n }\n return ACCENT_PALETTE[accent]?.primary ?? '#fba970'\n}\n\nexport interface TuiPrefs {\n version: 1\n layout: {\n preset: LayoutPresetPref\n separator: SeparatorStylePref\n settingsView?: SettingsViewModePref\n language?: LanguagePref\n }\n theme?: {\n mode?: ThemeModePref\n accent?: AccentColorPref\n }\n sidebar: {\n header: { version: boolean; preset: boolean; session: boolean }\n pinnedSessions?: string[]\n blocks: { context: boolean; git: boolean; todo?: boolean; dispatch: boolean }\n context: {\n gauge: GaugeStyle\n barShape: BarShapePref\n barWidth: BarWidthPref\n evenMark: boolean\n tokens: boolean\n spent: boolean\n modelUsage: boolean\n performance: boolean\n localSpend: boolean\n turnCost: boolean\n tokenAnatomy: boolean\n }\n }\n footer: { prompt: boolean; home: boolean }\n}\n\nexport const DEFAULT_TUI_PREFS: TuiPrefs = {\n version: 1,\n layout: {\n preset: 'comfortable',\n separator: 'spaces',\n settingsView: 'docked',\n language: 'auto',\n },\n theme: {\n mode: 'auto',\n accent: 'host',\n },\n sidebar: {\n header: { version: true, preset: true, session: true },\n pinnedSessions: [],\n blocks: { context: true, git: true, todo: false, dispatch: true },\n context: {\n gauge: 'both',\n barShape: 'smooth',\n barWidth: 'standard',\n evenMark: false,\n tokens: true,\n spent: true,\n modelUsage: true,\n performance: true,\n localSpend: true,\n turnCost: true,\n tokenAnatomy: true,\n },\n },\n footer: { prompt: true, home: true },\n}\n\nfunction asBool(value: unknown, fallback: boolean): boolean {\n return typeof value === 'boolean' ? value : fallback\n}\n\n/** Deep-merge stored JSON over the defaults; unknown keys and junk are ignored. */\nexport function normalizeTuiPrefs(raw: unknown): TuiPrefs {\n const stored = (typeof raw === 'object' && raw !== null ? raw : {}) as Record\n const layout = (\n typeof stored.layout === 'object' && stored.layout !== null ? stored.layout : {}\n ) as Record\n const sidebar = (\n typeof stored.sidebar === 'object' && stored.sidebar !== null ? stored.sidebar : {}\n ) as Record\n const header = (\n typeof sidebar.header === 'object' && sidebar.header !== null ? sidebar.header : {}\n ) as Record\n const blocks = (\n typeof sidebar.blocks === 'object' && sidebar.blocks !== null ? sidebar.blocks : {}\n ) as Record\n const context = (\n typeof sidebar.context === 'object' && sidebar.context !== null ? sidebar.context : {}\n ) as Record\n const footer = (\n typeof stored.footer === 'object' && stored.footer !== null ? stored.footer : {}\n ) as Record\n const rawTheme = (\n typeof stored.theme === 'object' && stored.theme !== null ? stored.theme : {}\n ) as Record\n const themeMode = THEME_MODES_CYCLE.includes(rawTheme.mode as string)\n ? (rawTheme.mode as ThemeModePref)\n : (DEFAULT_TUI_PREFS.theme?.mode ?? 'auto')\n const themeAccent = ACCENT_COLORS_CYCLE.includes(rawTheme.accent as string)\n ? (rawTheme.accent as AccentColorPref)\n : (DEFAULT_TUI_PREFS.theme?.accent ?? 'host')\n const preset = LAYOUT_PRESETS_CYCLE.includes(layout.preset as string)\n ? (layout.preset as LayoutPresetPref)\n : DEFAULT_TUI_PREFS.layout.preset\n const separator = SEPARATOR_STYLES_CYCLE.includes(layout.separator as string)\n ? (layout.separator as SeparatorStylePref)\n : DEFAULT_TUI_PREFS.layout.separator\n const settingsView = (\n SETTINGS_VIEW_MODES.includes(layout.settingsView as string)\n ? layout.settingsView\n : DEFAULT_TUI_PREFS.layout.settingsView\n ) as SettingsViewModePref\n const language = (\n LANGUAGE_CYCLE.includes(layout.language as string)\n ? layout.language\n : DEFAULT_TUI_PREFS.layout.language\n ) as LanguagePref\n const gauge = GAUGE_STYLES.includes(context.gauge as string)\n ? (context.gauge as GaugeStyle)\n : DEFAULT_TUI_PREFS.sidebar.context.gauge\n const barShape = BAR_SHAPES_CYCLE.includes(context.barShape as string)\n ? (context.barShape as BarShapePref)\n : DEFAULT_TUI_PREFS.sidebar.context.barShape\n const barWidth = BAR_WIDTHS_CYCLE.includes(context.barWidth as string)\n ? (context.barWidth as BarWidthPref)\n : DEFAULT_TUI_PREFS.sidebar.context.barWidth\n const evenMark = asBool(context.evenMark, DEFAULT_TUI_PREFS.sidebar.context.evenMark)\n\n return {\n version: 1,\n layout: {\n preset,\n separator,\n settingsView,\n language,\n },\n theme: {\n mode: themeMode,\n accent: themeAccent,\n },\n sidebar: {\n header: {\n version: asBool(header.version, true),\n preset: asBool(header.preset, true),\n session: asBool(header.session, true),\n },\n pinnedSessions: Array.isArray(sidebar.pinnedSessions)\n ? sidebar.pinnedSessions.filter((s: unknown) => typeof s === 'string')\n : [],\n blocks: {\n context: asBool(blocks.context, true),\n git: asBool(blocks.git, true),\n todo: asBool(blocks.todo, false),\n dispatch: asBool(blocks.dispatch, true),\n },\n context: {\n gauge,\n barShape,\n barWidth,\n evenMark,\n tokens: asBool(context.tokens, true),\n spent: asBool(context.spent, true),\n modelUsage: asBool(context.modelUsage, true),\n performance: asBool(context.performance, true),\n localSpend: asBool(context.localSpend, true),\n turnCost: asBool(context.turnCost, true),\n tokenAnatomy: asBool(context.tokenAnatomy, true),\n },\n },\n footer: {\n prompt: asBool(footer.prompt, true),\n home: asBool(footer.home, true),\n },\n }\n}\n\n// ── The TUI tab (cycler rows over the dotted pref paths) ───────────────\n\nconst onOff = ENABLED_CYCLE\nconst row = (id: string, name: string, value: boolean, note: string): SettingsRow => ({\n id,\n name,\n value: value ? 'enabled' : 'disabled',\n cycle: onOff,\n note,\n})\n\nexport function buildTuiTab(prefs: TuiPrefs, languagePref?: string): SettingsTab {\n const isPt = resolveLanguage(languagePref ?? prefs.layout?.language) === 'pt-BR'\n return {\n id: 'tui',\n title: 'TUI',\n groups: [\n {\n title: isPt ? 'Predefinição & Layout' : 'Preset & Layout',\n rows: [\n {\n id: 'tui.layout.preset',\n name: isPt ? 'Predefinição de layout' : 'Layout preset',\n value: prefs.layout?.preset ?? DEFAULT_TUI_PREFS.layout.preset,\n cycle: LAYOUT_PRESETS_CYCLE,\n note: isPt\n ? 'comfortable | compact — define espaçamento e bordas'\n : 'comfortable | compact — sets spacing & borders',\n },\n {\n id: 'tui.layout.separator',\n name: isPt ? 'Separador' : 'Separator',\n value: prefs.layout?.separator ?? DEFAULT_TUI_PREFS.layout.separator,\n cycle: SEPARATOR_STYLES_CYCLE,\n note: isPt\n ? 'spaces | pipes | dots | slashes — glifos na linha de status'\n : 'spaces | pipes | dots | slashes — status line glyphs',\n },\n {\n id: 'tui.layout.settingsView',\n name: isPt ? 'Superfície de configurações' : 'Settings surface',\n value: tuiRowValue(prefs, 'tui.layout.settingsView') ?? 'docked',\n cycle: SETTINGS_VIEW_MODES,\n note: isPt\n ? 'docked (acima do prompt) | fullscreen | dialog'\n : 'docked (above prompt) | fullscreen router page | dialog overlay',\n },\n {\n id: 'tui.layout.language',\n name: isPt ? 'Idioma / Language' : 'Language / Idioma',\n value: tuiRowValue(prefs, 'tui.layout.language') ?? 'auto',\n cycle: LANGUAGE_CYCLE,\n note: isPt\n ? 'auto (detecta via fuso/locale) | pt-BR (Português) | en (English)'\n : 'auto (detect via timezone/locale) | pt-BR (Português) | en (English)',\n },\n ],\n },\n {\n title: isPt ? 'Cores & Tema' : 'Colors & Theme',\n rows: [\n {\n id: 'tui.theme.mode',\n name: isPt ? 'Modo do tema' : 'Theme mode',\n value: tuiRowValue(prefs, 'tui.theme.mode') ?? 'auto',\n cycle: THEME_MODES_CYCLE,\n note: isPt\n ? 'auto (segue o OpenCode) | dark | light'\n : 'auto (follow OpenCode theme) | dark | light',\n },\n {\n id: 'tui.theme.accent',\n name: isPt ? 'Cor de destaque' : 'Accent color',\n value: tuiRowValue(prefs, 'tui.theme.accent') ?? 'host',\n cycle: ACCENT_COLORS_CYCLE,\n note: isPt\n ? 'host (segue tema) | pantheon | emerald | cyan | amber | purple | rose'\n : 'host (follow theme) | pantheon | emerald | cyan | amber | purple | rose',\n },\n ],\n },\n {\n title: isPt ? 'Barras & Medidores' : 'Bars & Gauges',\n rows: [\n {\n id: 'tui.sidebar.context.barShape',\n name: isPt ? 'Formato da barra' : 'Bar shape',\n value: prefs.sidebar.context.barShape,\n cycle: BAR_SHAPES_CYCLE,\n note: 'line (━─) | block (▰▱) | smooth (█░) | ascii (=) | dots (●○) | braille',\n },\n {\n id: 'tui.sidebar.context.barWidth',\n name: isPt ? 'Largura da barra' : 'Bar width',\n value: prefs.sidebar.context.barWidth,\n cycle: BAR_WIDTHS_CYCLE,\n note: isPt\n ? 'standard (12) | compact (8) | wide (16) | full (20 células)'\n : 'standard (12) | compact (8) | wide (16) | full (20 cells)',\n },\n row(\n 'tui.sidebar.context.evenMark',\n isPt ? 'Marca central (50%)' : 'Even-use mark',\n prefs.sidebar.context.evenMark,\n isPt\n ? '| indicador aos 50% nas barras de medição'\n : '| indicator at 50% midpoint in gauge bars',\n ),\n {\n id: 'tui.sidebar.context.gauge',\n name: isPt ? 'Estilo do medidor' : 'Gauge style',\n value: prefs.sidebar.context.gauge,\n cycle: GAUGE_STYLES,\n note: 'both | bar | percent | off — `▰▱ 42% of 200k`',\n },\n ],\n },\n {\n title: isPt ? 'Cabeçalho da barra lateral' : 'Sidebar header',\n rows: [\n row(\n 'tui.sidebar.header.version',\n isPt ? 'Linha de versão' : 'Version line',\n prefs.sidebar.header.version,\n isPt ? 'linha `Pantheon v…`' : 'the `Pantheon v…` line',\n ),\n row(\n 'tui.sidebar.header.preset',\n isPt ? 'Linha de preset' : 'Preset line',\n prefs.sidebar.header.preset,\n isPt ? 'linha `▸ preset · provider`' : 'the `▸ preset · provider` line',\n ),\n row(\n 'tui.sidebar.header.session',\n isPt ? 'Linha de sessão' : 'Session line',\n prefs.sidebar.header.session,\n isPt ? 'título da sessão ativa' : 'the active session title',\n ),\n ],\n },\n {\n title: isPt ? 'Blocos da barra lateral' : 'Sidebar blocks',\n rows: [\n row(\n 'tui.sidebar.block.context',\n isPt ? 'Bloco de contexto' : 'Context block',\n prefs.sidebar.blocks.context,\n isPt ? 'tokens, medidor, custo, uso de modelos' : 'tokens, gauge, spend, model usage',\n ),\n row(\n 'tui.sidebar.block.git',\n isPt ? 'Bloco do Git' : 'Git block',\n prefs.sidebar.blocks.git,\n isPt ? 'branch + contagem de alterações' : 'branch + working-tree counts',\n ),\n row(\n 'tui.sidebar.block.dispatch',\n isPt ? 'Bloco Dispatch' : 'Dispatch block',\n prefs.sidebar.blocks.dispatch,\n isPt ? 'delegações em tempo real' : 'live delegations + rollup',\n ),\n ],\n },\n {\n title: isPt ? 'Detalhe do bloco de contexto' : 'Context block detail',\n rows: [\n row(\n 'tui.sidebar.context.tokens',\n isPt ? 'Linha de tokens' : 'Tokens row',\n prefs.sidebar.context.tokens,\n isPt ? 'contagem bruta de tokens' : 'the raw token count line',\n ),\n row(\n 'tui.sidebar.context.spent',\n isPt ? 'Linha de custo' : 'Spent row',\n prefs.sidebar.context.spent,\n isPt ? 'linha `$… gastos na sessão`' : 'the `$… spent in session` line',\n ),\n row(\n 'tui.sidebar.context.modelUsage',\n isPt ? 'Tabela de uso de modelos' : 'Model usage table',\n prefs.sidebar.context.modelUsage,\n isPt ? 'resumo de chamadas por modelo' : 'per-model tokens/USD',\n ),\n row(\n 'tui.sidebar.context.performance',\n isPt ? 'Linha de desempenho' : 'Performance row',\n prefs.sidebar.context.performance,\n isPt ? 'tokens/segundo e latência' : 'cache % + tok/s',\n ),\n row(\n 'tui.sidebar.context.turnCost',\n isPt ? 'Custo do turno' : 'Turn cost',\n prefs.sidebar.context.turnCost,\n isPt ? 'linha `Turn: $… (prev: $…)`' : 'the `Turn: $… (prev: $…)` line',\n ),\n row(\n 'tui.sidebar.context.tokenAnatomy',\n isPt ? 'Anatomia de tokens' : 'Token anatomy',\n prefs.sidebar.context.tokenAnatomy,\n isPt ? 'linha `↑in ↓out ✦think`' : 'the `↑in ↓out ✦think` line',\n ),\n row(\n 'tui.sidebar.context.localSpend',\n isPt ? 'Linha de custo local' : 'Local spend row',\n prefs.sidebar.context.localSpend,\n isPt ? 'totais de hoje / 30 dias' : 'hoje / 30d totals',\n ),\n ],\n },\n {\n title: isPt ? 'Rodapés' : 'Footers',\n rows: [\n row(\n 'tui.footer.prompt',\n isPt ? 'Prompt inferior' : 'Prompt footer',\n prefs.footer.prompt,\n isPt\n ? 'linha `▸preset · ✦n ativos` durante delegações'\n : 'the `▸preset · ✦n ativos` line while delegations run',\n ),\n row(\n 'tui.footer.home',\n isPt ? 'Status inicial' : 'Home status',\n prefs.footer.home,\n isPt\n ? 'linha `Pantheon v…` sob o prompt inicial'\n : 'the `Pantheon v…` line under the home prompt',\n ),\n ],\n },\n ],\n }\n}\n\n/**\n * Apply one staged row INTO a prefs draft (in place — the storage mutate\n * callback hands an immer-style draft). Unknown ids or junk values are no-ops.\n */\nexport function applyTuiRow(draft: TuiPrefs, id: string, value: string): void {\n const enabled = value === 'enabled'\n switch (id) {\n case 'tui.layout.preset':\n if (LAYOUT_PRESETS_CYCLE.includes(value)) {\n if (!draft.layout) draft.layout = { ...DEFAULT_TUI_PREFS.layout }\n draft.layout.preset = value as LayoutPresetPref\n }\n return\n case 'tui.layout.separator':\n if (SEPARATOR_STYLES_CYCLE.includes(value)) {\n if (!draft.layout) draft.layout = { ...DEFAULT_TUI_PREFS.layout }\n draft.layout.separator = value as SeparatorStylePref\n }\n return\n case 'tui.layout.settingsView':\n if (SETTINGS_VIEW_MODES.includes(value)) {\n if (!draft.layout) draft.layout = { ...DEFAULT_TUI_PREFS.layout }\n draft.layout.settingsView = value as SettingsViewModePref\n }\n return\n case 'tui.layout.language':\n if (LANGUAGE_CYCLE.includes(value)) {\n if (!draft.layout) draft.layout = { ...DEFAULT_TUI_PREFS.layout }\n draft.layout.language = value as LanguagePref\n }\n return\n case 'tui.theme.mode':\n if (THEME_MODES_CYCLE.includes(value)) {\n if (!draft.theme) draft.theme = { ...DEFAULT_TUI_PREFS.theme }\n draft.theme.mode = value as ThemeModePref\n }\n return\n case 'tui.theme.accent':\n if (ACCENT_COLORS_CYCLE.includes(value)) {\n if (!draft.theme) draft.theme = { ...DEFAULT_TUI_PREFS.theme }\n draft.theme.accent = value as AccentColorPref\n }\n return\n case 'tui.sidebar.context.barShape':\n if (BAR_SHAPES_CYCLE.includes(value)) draft.sidebar.context.barShape = value as BarShapePref\n return\n case 'tui.sidebar.context.barWidth':\n if (BAR_WIDTHS_CYCLE.includes(value)) draft.sidebar.context.barWidth = value as BarWidthPref\n return\n case 'tui.sidebar.context.evenMark':\n draft.sidebar.context.evenMark = enabled\n return\n case 'tui.sidebar.header.version':\n draft.sidebar.header.version = enabled\n return\n case 'tui.sidebar.header.preset':\n draft.sidebar.header.preset = enabled\n return\n case 'tui.sidebar.header.session':\n draft.sidebar.header.session = enabled\n return\n case 'tui.sidebar.block.context':\n draft.sidebar.blocks.context = enabled\n return\n case 'tui.sidebar.block.git':\n draft.sidebar.blocks.git = enabled\n return\n case 'tui.sidebar.block.todo':\n draft.sidebar.blocks.todo = enabled\n return\n case 'tui.sidebar.block.dispatch':\n draft.sidebar.blocks.dispatch = enabled\n return\n case 'tui.sidebar.context.gauge':\n if (GAUGE_STYLES.includes(value)) draft.sidebar.context.gauge = value as GaugeStyle\n return\n case 'tui.sidebar.context.tokens':\n draft.sidebar.context.tokens = enabled\n return\n case 'tui.sidebar.context.spent':\n draft.sidebar.context.spent = enabled\n return\n case 'tui.sidebar.context.modelUsage':\n draft.sidebar.context.modelUsage = enabled\n return\n case 'tui.sidebar.context.performance':\n draft.sidebar.context.performance = enabled\n return\n case 'tui.sidebar.context.localSpend':\n draft.sidebar.context.localSpend = enabled\n return\n case 'tui.sidebar.context.turnCost':\n draft.sidebar.context.turnCost = enabled\n return\n case 'tui.sidebar.context.tokenAnatomy':\n draft.sidebar.context.tokenAnatomy = enabled\n return\n case 'tui.footer.prompt':\n draft.footer.prompt = enabled\n return\n case 'tui.footer.home':\n draft.footer.home = enabled\n return\n default:\n return\n }\n}\n\n/** Read the current pref value for a row id ('enabled'/'disabled'/gauge/custom). */\nexport function tuiRowValue(prefs: TuiPrefs, id: string): string | undefined {\n if (id === 'tui.layout.preset') return prefs.layout?.preset ?? DEFAULT_TUI_PREFS.layout.preset\n if (id === 'tui.layout.separator')\n return prefs.layout?.separator ?? DEFAULT_TUI_PREFS.layout.separator\n if (id === 'tui.layout.settingsView')\n return prefs.layout?.settingsView ?? DEFAULT_TUI_PREFS.layout.settingsView ?? 'docked'\n if (id === 'tui.layout.language') return prefs.layout?.language ?? 'auto'\n if (id === 'tui.theme.mode') return prefs.theme?.mode ?? DEFAULT_TUI_PREFS.theme?.mode ?? 'auto'\n if (id === 'tui.theme.accent')\n return prefs.theme?.accent ?? DEFAULT_TUI_PREFS.theme?.accent ?? 'host'\n if (id === 'tui.sidebar.context.barShape') return prefs.sidebar.context.barShape\n if (id === 'tui.sidebar.context.barWidth') return prefs.sidebar.context.barWidth\n if (id === 'tui.sidebar.context.gauge') return prefs.sidebar.context.gauge\n if (id === 'tui.sidebar.context.evenMark')\n return prefs.sidebar.context.evenMark ? 'enabled' : 'disabled'\n const enabled = (() => {\n switch (id) {\n case 'tui.sidebar.header.version':\n return prefs.sidebar.header.version\n case 'tui.sidebar.header.preset':\n return prefs.sidebar.header.preset\n case 'tui.sidebar.header.session':\n return prefs.sidebar.header.session\n case 'tui.sidebar.block.context':\n return prefs.sidebar.blocks.context\n case 'tui.sidebar.block.git':\n return prefs.sidebar.blocks.git\n case 'tui.sidebar.block.todo':\n return prefs.sidebar.blocks.todo\n case 'tui.sidebar.block.dispatch':\n return prefs.sidebar.blocks.dispatch\n case 'tui.sidebar.context.tokens':\n return prefs.sidebar.context.tokens\n case 'tui.sidebar.context.spent':\n return prefs.sidebar.context.spent\n case 'tui.sidebar.context.modelUsage':\n return prefs.sidebar.context.modelUsage\n case 'tui.sidebar.context.performance':\n return prefs.sidebar.context.performance\n case 'tui.sidebar.context.localSpend':\n return prefs.sidebar.context.localSpend\n case 'tui.sidebar.context.turnCost':\n return prefs.sidebar.context.turnCost\n case 'tui.sidebar.context.tokenAnatomy':\n return prefs.sidebar.context.tokenAnatomy\n case 'tui.footer.prompt':\n return prefs.footer.prompt\n case 'tui.footer.home':\n return prefs.footer.home\n default:\n return undefined\n }\n })()\n return enabled === undefined ? undefined : enabled ? 'enabled' : 'disabled'\n}\n\nexport function isSessionPinned(sessionID: string | undefined): boolean {\n if (!sessionID) return false\n const list = tuiPrefs().sidebar.pinnedSessions\n return Array.isArray(list) && list.includes(sessionID)\n}\n\nexport function togglePinSession(sessionID: string | undefined): Promise {\n if (!sessionID) return Promise.resolve()\n return mutateTuiPrefs((draft) => {\n if (!Array.isArray(draft.sidebar.pinnedSessions)) {\n draft.sidebar.pinnedSessions = []\n }\n const idx = draft.sidebar.pinnedSessions.indexOf(sessionID)\n if (idx >= 0) {\n draft.sidebar.pinnedSessions.splice(idx, 1)\n } else {\n draft.sidebar.pinnedSessions.push(sessionID)\n }\n })\n}\n","/**\n * update-status.ts — the Updates section of the settings window.\n *\n * TUI-local; derives rows from the update-notice.ts primitives. The registry\n * fetch and state persistence stay in the .tsx glue (host side) — this module\n * only classifies the channel and builds rows from injected state, so the\n * whole thing is testable without network.\n */\n\nimport { formatBytes, type LegacyAuditSummary } from './legacy-audit.ts'\nimport type { SettingsRow, SettingsTab } from './pantheon-settings-state.ts'\nimport { comparePantheonVersions, type UpdateCheckState } from './update-notice.ts'\n\nexport type UpdateChannel = 'stable' | 'beta'\n\n/** The running version's channel: a `-beta.N` suffix rides the beta dist-tag. */\nexport function updateChannelFor(version: string): UpdateChannel {\n return /-beta\\.\\d+$/.test(version) ? 'beta' : 'stable'\n}\n\n/** The npm dist-tag the registry check should query for the channel. */\nexport function registryTagForChannel(channel: UpdateChannel): string {\n return channel === 'beta' ? 'beta' : 'latest'\n}\n\nexport function registryUrlForChannel(channel: UpdateChannel): string {\n return `https://registry.npmjs.org/pantheon-opencode/${registryTagForChannel(channel)}`\n}\n\nfunction formatAgo(ms: number, isPt = false): string {\n if (ms < 60_000) return isPt ? 'agora mesmo' : 'just now'\n if (ms < 3_600_000)\n return isPt ? `há ${Math.floor(ms / 60_000)}m` : `${Math.floor(ms / 60_000)}m ago`\n if (ms < 86_400_000)\n return isPt ? `há ${Math.floor(ms / 3_600_000)}h` : `${Math.floor(ms / 3_600_000)}h ago`\n return isPt ? `há ${Math.floor(ms / 86_400_000)}d` : `${Math.floor(ms / 86_400_000)}d ago`\n}\n\nexport interface UpdatesSectionInput {\n currentVersion: string\n state: UpdateCheckState\n /** Selected channel (defaults to updateChannelFor(currentVersion)). */\n selectedChannel?: UpdateChannel\n /** Latest version seen this session (a check-now inside this window). */\n lastCheckedVersion?: string\n /** A check-now is in flight (this window). */\n checking?: boolean\n /** An update run is in flight (this window). */\n updating?: boolean\n /** Latest scan summary from legacy-audit.ts (global + project). */\n legacyAudit?: LegacyAuditSummary | null\n /** Whether a legacy scan is currently running. */\n legacyScanning?: boolean\n /** Whether a legacy cleanup is currently running. */\n legacyCleaning?: boolean\n /** Outcome notice from the last scan/clean action. */\n legacyNotice?: string\n nowMs?: number\n languagePref?: string\n}\n\nexport function buildUpdatesTab(input: UpdatesSectionInput): SettingsTab {\n const isPt = input.languagePref === 'pt-BR'\n const nowMs = input.nowMs ?? Date.now()\n const channel = input.selectedChannel ?? updateChannelFor(input.currentVersion)\n const lastCheckMs = input.state.lastCheckMs\n const latest = input.lastCheckedVersion ?? input.state.lastNotifiedVersion\n\n const stable = (version: string) => !/-beta\\.\\d+$/.test(version)\n const newer =\n latest !== undefined &&\n comparePantheonVersions(latest, input.currentVersion) > 0 &&\n !(stable(input.currentVersion) && !stable(latest))\n\n const rows: SettingsRow[] = [\n {\n id: 'update.channel',\n name: isPt ? 'Canal' : 'Channel',\n value: channel,\n cycle: ['stable', 'beta'] as const,\n note: isPt\n ? 'stable segue npm `latest`; beta segue npm `beta`'\n : 'stable tracks npm `latest`; beta tracks npm `beta`',\n },\n {\n id: 'update.check',\n name: isPt ? 'Verificar agora' : 'Check now',\n value: input.checking\n ? isPt\n ? 'verificando…'\n : 'checking…'\n : lastCheckMs\n ? isPt\n ? `verificado ${formatAgo(nowMs - lastCheckMs, true)}`\n : `last check ${formatAgo(nowMs - lastCheckMs, false)}`\n : isPt\n ? 'nunca verificado'\n : 'never checked',\n action: 'update-check',\n note: isPt\n ? 'enter consulta o registro npm para o canal ativo'\n : 'enter probes the registry for the running channel',\n },\n ]\n\n const pkgSpec = channel === 'beta' ? 'pantheon-opencode@beta' : 'pantheon-opencode'\n const pluginCommand = `opencode plugin update ${pkgSpec}`\n\n if (latest) {\n rows.push({\n id: 'update.latest',\n name: isPt ? 'Registro (npm)' : 'Registry',\n value: newer\n ? `v${latest} ${isPt ? 'disponível' : 'available'}`\n : isPt\n ? 'atualizado'\n : 'up to date',\n ...(newer ? { action: 'update-run' as const } : {}),\n note: newer\n ? isPt\n ? `enter atualiza agora · ou rode \\`${pluginCommand}\\``\n : `enter updates now · or run \\`${pluginCommand}\\``\n : isPt\n ? 'nenhuma versão mais recente compatível'\n : 'no newer compatible version',\n })\n rows.push({\n id: 'update.run',\n name: isPt ? 'Atualizar plugin' : 'Update plugin',\n value: input.updating\n ? isPt\n ? 'atualizando…'\n : 'updating…'\n : newer\n ? `${isPt ? 'atualizar' : 'update'} v${latest}`\n : isPt\n ? 'reinstalar plugin'\n : 'refresh plugin',\n action: 'update-run',\n note: newer\n ? isPt\n ? `enter executa \\`${pluginCommand}\\` + reload`\n : `enter runs \\`${pluginCommand}\\` + reload`\n : isPt\n ? 'enter força atualização do plugin instalado'\n : 'enter refreshes the installed plugin',\n })\n }\n\n rows.push({\n id: 'update.command',\n name: isPt ? 'Comando no terminal' : 'CLI Command',\n value: 'opencode plugin update',\n note: isPt\n ? `sem npx: \\`${pluginCommand} && opencode reload\\``\n : `native CLI (no npx): \\`${pluginCommand} && opencode reload\\``,\n })\n\n const audit = input.legacyAudit\n const legacyRows: SettingsRow[] = [\n {\n id: 'legacy.status',\n name: isPt ? 'Auditoria legada' : 'Legacy & Drift',\n value: input.legacyScanning\n ? isPt\n ? 'escaneando…'\n : 'scanning…'\n : audit === undefined || audit === null\n ? isPt\n ? 'não escaneado'\n : 'not scanned'\n : audit.total === 0\n ? isPt\n ? 'limpo (0 obsoletos)'\n : 'clean (0 obsolete)'\n : isPt\n ? `${audit.total} arquivo(s) (${formatBytes(audit.totalBytes)})`\n : `${audit.total} file(s) (${formatBytes(audit.totalBytes)})`,\n note: input.legacyNotice\n ? input.legacyNotice\n : audit && audit.total > 0\n ? isPt\n ? `global: ${audit.byScope.global} · projeto: ${audit.byScope.project}${audit.unmigratedStores > 0 ? ` · ${audit.unmigratedStores} store(s) p/ migrar` : ''}`\n : `global: ${audit.byScope.global} · project: ${audit.byScope.project}${audit.unmigratedStores > 0 ? ` · ${audit.unmigratedStores} store(s) to migrate` : ''}`\n : isPt\n ? 'verifica hooks V1, bancos não migrados e cópias redundantes'\n : 'checks V1 hooks, unmigrated stores & redundant plugin copies',\n },\n {\n id: 'legacy.scan',\n name: isPt ? 'Escanear obsoletos' : 'Scan legacy & drift',\n value: input.legacyScanning\n ? isPt\n ? 'escaneando…'\n : 'scanning…'\n : isPt\n ? 'escanear agora'\n : 'scan global + project',\n action: 'legacy-scan',\n note: isPt\n ? 'enter escaneia sem modificar ou apagar nenhum arquivo'\n : 'enter scans read-only without deleting anything',\n },\n {\n id: 'legacy.clean',\n name: isPt ? 'Migrar & limpar' : 'Migrate & clean obsolete',\n value: input.legacyCleaning\n ? isPt\n ? 'limpando…'\n : 'cleaning…'\n : audit && audit.total > 0\n ? isPt\n ? `remover ${audit.total} (${formatBytes(audit.totalBytes)})`\n : `remove ${audit.total} (${formatBytes(audit.totalBytes)})`\n : isPt\n ? 'nada para remover'\n : 'nothing to remove',\n action: 'legacy-clean',\n note: isPt\n ? 'migra memória/contexto/goals antes e preserva agentes/skills custom'\n : 'migrates memory/context/goals first · preserves custom agents/skills',\n },\n ]\n\n return {\n id: 'updates',\n title: isPt ? 'Atualizações' : 'Updates',\n groups: [\n { title: isPt ? 'Atualizações do Plugin' : 'Plugin Updates', rows },\n { title: isPt ? 'Legados, Drift & Limpeza' : 'Legacy, Drift & Cleanup', rows: legacyRows },\n ],\n }\n}\n","/**\n * whats-new-highlights.ts — release highlights for the one-time \"What's new\"\n * window, extracted from the CHANGELOG.md shipped with the plugin copy.\n *\n * The section-finding logic is an inline replica of scripts/changelog-extract.mjs\n * `extractSection` (pinned by a parity test in tests/tui-whats-new.test.mjs):\n * the copied plugin ships only dist/ + package.json (+ CHANGELOG.md, copied by\n * both installers), so it cannot reach scripts/ at runtime — the same reason\n * the preset resolver is mirrored in index.tsx/index-v2.tsx rather than\n * imported. The script's CLI main is NOT replicated; the plugin only needs the\n * pure extraction.\n *\n * Everything is reduced to bounded plain text: no markdown syntax artifacts,\n * at most WHATS_NEW_MAX_ITEMS bullets. Missing CHANGELOG.md, an unknown\n * version or an empty section all resolve to an empty highlight set — the\n * window simply does not show (fail-open, like the rest of the plugin).\n */\nimport { readFile } from 'node:fs/promises'\nimport { dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\n/** Hard cap on bullets shown in the window (the remainder is counted). */\nexport const WHATS_NEW_MAX_ITEMS = 12\n\n/**\n * Cap for the curated `🆕 What's New` summary block — the window shows the\n * summary, never the full Added/Changed/Fixed walls.\n */\nexport const WHATS_NEW_SUMMARY_MAX_ITEMS = 6\n\n/** Bullets longer than this are truncated with an ellipsis (one-line rule). */\nexport const WHATS_NEW_ITEM_MAX_CHARS = 140\n\n/** Prefix of the \"+N more\" line appended when the bullet budget is exceeded. */\nexport const WHATS_NEW_MORE_PREFIX = '… +'\n\n/** H3 subsection headings are kept as plain-text group labels. */\nexport interface WhatsNewGroup {\n heading: string | null\n items: string[]\n}\n\nexport interface WhatsNewHighlights {\n /** Normalized version the highlights belong to (null when not found). */\n version: string | null\n found: boolean\n groups: WhatsNewGroup[]\n /** Total bullets in the section, before the WHATS_NEW_MAX_ITEMS cut. */\n totalItems: number\n /** True when totalItems exceeded WHATS_NEW_MAX_ITEMS. */\n truncated: boolean\n}\n\nexport const EMPTY_HIGHLIGHTS: WhatsNewHighlights = {\n version: null,\n found: false,\n groups: [],\n totalItems: 0,\n truncated: false,\n}\n\n/** Escape regex metacharacters so a version like 1.0.0 matches literally. */\nfunction escapeRegExp(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\n/**\n * Extract the body of a version section from changelog text — inline replica\n * of scripts/changelog-extract.mjs `extractSection` (see that file for the\n * full contract: `## [] - YYYY-MM-DD`, leading `v` and the date\n * optional, `## [Unreleased]` never matched).\n */\nexport function extractSection(\n changelogText: string,\n version: string,\n): { found: boolean; body: string | null } {\n const normalized = String(version).trim().replace(/^v/i, '')\n if (!normalized || /^unreleased$/i.test(normalized)) return { found: false, body: null }\n\n const escaped = escapeRegExp(normalized)\n // Single-line heading: `## [v?1.2.1]` optionally followed by ` - YYYY-MM-DD`.\n // [ \\t] (not \\s) keeps the match from crossing newlines; the lookahead\n // requires end-of-line or whitespace so `[1.0.0-beta]` can never match `1.0.0`.\n const headingRe = new RegExp(\n `^##[ \\\\t]+\\\\[v?${escaped}\\\\](?:[ \\\\t]*-[ \\\\t]*\\\\d{4}-\\\\d{2}-\\\\d{2})?(?=[ \\\\t]|$)`,\n 'm',\n )\n const match = headingRe.exec(changelogText)\n if (!match) return { found: false, body: null }\n\n // Advance past the heading line (match.index may point mid-line).\n const newline = changelogText.indexOf('\\n', match.index)\n const start = newline === -1 ? changelogText.length : newline + 1\n\n // Body ends at the next `## [` heading or end of text.\n const nextHeading = /^##[ \\t]+\\[/m.exec(changelogText.slice(start))\n const end = nextHeading ? start + nextHeading.index : changelogText.length\n\n return { found: true, body: changelogText.slice(start, end).trim() }\n}\n\n/**\n * Reduce one markdown line to plain text: links keep their label, emphasis\n * and inline-code markers are dropped, HTML comment fragments are removed,\n * and whitespace collapses. Deliberately simple — the input is our own\n * CHANGELOG (lint-capped at 200 chars per bullet), not hostile input.\n */\nexport function stripMarkdown(text: string): string {\n return text\n .replace(//g, ' ')\n .replace(/\\[([^\\]]+)\\]\\([^)]*\\)/g, '$1')\n .replace(/(\\*\\*|__)/g, '')\n .replace(/`/g, '')\n .replace(/\\s+/g, ' ')\n .trim()\n}\n\n/** Strip the leading H3 marker (`### Added` → `Added`). */\nfunction stripHeading(text: string): string {\n return text.replace(/^#{1,6}[ \\t]+/, '').trim()\n}\n\n/**\n * Extract the curated summary block (`### 🆕 What's New` or `## 🆕 What's New`)\n * from a section body: its bullets only, each truncated to\n * WHATS_NEW_ITEM_MAX_CHARS, capped to WHATS_NEW_SUMMARY_MAX_ITEMS. Null when\n * the section carries no summary block (the full-section fallback applies).\n */\nexport function extractWhatsNewSummary(body: string): string[] | null {\n const lines = body.split('\\n')\n const start = lines.findIndex((line) => /^#{2,3}[ \\t]+.*What'?s New/i.test(line.trim()))\n if (start === -1) return null\n const items: string[] = []\n for (const rawLine of lines.slice(start + 1)) {\n const line = rawLine.trim()\n if (line === '' || line.startsWith('|-\\.->|==>)\\|([^|]+)\\||--\\s+([^->\\n]+?)\\s+-->|-\\.\\s*([^.]+?)\\s*\\.->|==\\s*([^=]+?)\\s*==>|-->|-\\.->|==>|---)`\nconst EDGE_RE = new RegExp(String.raw`^(.*?)\\s+${ARROW_PATTERN}\\s+(.*)$`)\n\nfunction splitChainOperands(line: string): {\n parts: string[]\n connectors: Array<{ label?: string; dashed: boolean }>\n} {\n // Walk left-to-right extracting arrow connectors between operand groups\n const arrowTokenRe = new RegExp(String.raw`\\s+(${ARROW_PATTERN})\\s+`, 'g')\n const parts: string[] = []\n const connectors: Array<{ label?: string; dashed: boolean }> = []\n let lastIdx = 0\n for (const m of line.matchAll(arrowTokenRe)) {\n const idx = m.index ?? 0\n parts.push(line.slice(lastIdx, idx).trim())\n const arrow = m[1] ?? ''\n const labelRaw = m[2] ?? m[3] ?? m[4] ?? m[5]\n connectors.push({\n label: labelRaw ? cleanLabel(labelRaw) : undefined,\n dashed: arrow.includes('-.'),\n })\n lastIdx = idx + m[0].length\n }\n parts.push(line.slice(lastIdx).trim())\n return { parts, connectors }\n}\n\nfunction parseFlowchart(lines: readonly string[]): {\n direction: 'LR' | 'TD'\n nodes: Map\n edges: FlowEdge[]\n} {\n const nodes = new Map()\n const edges: FlowEdge[] = []\n let direction: 'LR' | 'TD' = 'TD'\n\n const ensureNode = (id: string, label?: string): void => {\n const existing = nodes.get(id)\n if (existing) {\n if (label && existing.label === existing.id) existing.label = label\n return\n }\n nodes.set(id, { id, label: label ?? id })\n }\n\n for (const rawLine of lines) {\n const stripped = rawLine.trim()\n if (!stripped || stripped.startsWith('%%')) continue\n if (/^(flowchart|graph)\\s+/i.test(stripped)) {\n if (/\\bLR\\b|\\bRL\\b/i.test(stripped)) direction = 'LR'\n continue\n }\n if (/^(classDef|style|linkStyle|click|class|direction|subgraph|end)\\b/i.test(stripped)) {\n continue\n }\n\n for (const stmt of stripped.split(';')) {\n const s = stmt.trim()\n if (!s) continue\n if (EDGE_RE.test(` ${s} `) || ['-->', '-.->', '==>', '---'].some((tok) => s.includes(tok))) {\n const { parts, connectors } = splitChainOperands(s)\n if (parts.length >= 2 && connectors.length === parts.length - 1) {\n for (let i = 0; i < connectors.length; i += 1) {\n const leftGroup = splitOperandsOutsideDelimiters(parts[i] ?? '')\n const rightGroup = splitOperandsOutsideDelimiters(parts[i + 1] ?? '')\n const conn = connectors[i]\n for (const lTok of leftGroup) {\n const left = parseNodeToken(lTok)\n ensureNode(left.id, left.label)\n for (const rTok of rightGroup) {\n const right = parseNodeToken(rTok)\n ensureNode(right.id, right.label)\n edges.push({\n from: left.id,\n to: right.id,\n label: conn?.label,\n dashed: Boolean(conn?.dashed),\n })\n }\n }\n }\n continue\n }\n }\n\n const single = parseNodeToken(s)\n if (single.id) ensureNode(single.id, single.label)\n }\n }\n\n return { direction, nodes, edges }\n}\n\nfunction renderHorizontalChain(\n chain: readonly FlowNode[],\n edges: readonly FlowEdge[],\n maxWidth: number,\n): string[] | null {\n if (chain.length < 2 || chain.length > 5) return null\n const boxes = chain.map((n) => drawBox(n.label, 28))\n const edgeWidths = edges.map((e) => (e.label ? Math.max(5, e.label.length + 4) : 4))\n const totalW =\n boxes.reduce((sum, b) => sum + (b[0]?.length ?? 0), 0) +\n edgeWidths.reduce((sum, w) => sum + w, 0)\n if (totalW > maxWidth) return null\n\n const top: string[] = []\n const mid: string[] = []\n const bot: string[] = []\n for (let i = 0; i < boxes.length; i += 1) {\n const box = boxes[i]\n if (!box) continue\n top.push(box[0] ?? '')\n mid.push(box[1] ?? '')\n bot.push(box[2] ?? '')\n if (i < edges.length) {\n const ew = edgeWidths[i] ?? 4\n const lbl = edges[i]?.label\n const stem = edges[i]?.dashed ? '╌' : '─'\n const arrowMid = `${stem.repeat(ew - 1)}►`\n const arrowTop = lbl ? ` ${lbl}`.padEnd(ew, ' ') : ' '.repeat(ew)\n top.push(arrowTop)\n mid.push(arrowMid)\n bot.push(' '.repeat(ew))\n }\n }\n return [top.join(''), mid.join(''), bot.join('')]\n}\n\nfunction renderFlowchart(lines: readonly string[], maxWidth: number): string[] | null {\n const { direction, nodes, edges } = parseFlowchart(lines)\n if (nodes.size === 0) return null\n\n const outEdges = new Map()\n const inDegree = new Map()\n const incomingSources = new Map()\n for (const id of nodes.keys()) {\n outEdges.set(id, [])\n inDegree.set(id, 0)\n incomingSources.set(id, [])\n }\n for (const e of edges) {\n outEdges.get(e.from)?.push(e)\n inDegree.set(e.to, (inDegree.get(e.to) ?? 0) + 1)\n incomingSources.get(e.to)?.push(e.from)\n }\n\n // Try horizontal side-by-side rendering for concise LR chains\n const isSimpleChain =\n edges.length === nodes.size - 1 &&\n [...outEdges.values()].every((list) => list.length <= 1) &&\n [...inDegree.values()].every((deg) => deg <= 1)\n if (direction === 'LR' && isSimpleChain) {\n const startId = [...nodes.keys()].find((id) => (inDegree.get(id) ?? 0) === 0)\n if (startId) {\n const chain: FlowNode[] = []\n const chainEdges: FlowEdge[] = []\n let cur: string | undefined = startId\n const seen = new Set()\n while (cur && !seen.has(cur)) {\n seen.add(cur)\n const node = nodes.get(cur)\n if (!node) break\n chain.push(node)\n const nextEdge = outEdges.get(cur)?.[0]\n if (!nextEdge) break\n chainEdges.push(nextEdge)\n cur = nextEdge.to\n }\n const horiz = renderHorizontalChain(chain, chainEdges, maxWidth)\n if (horiz) return horiz\n }\n }\n\n // General vertical DAG/tree box renderer\n const out: string[] = []\n const visited = new Set()\n const renderedJoin = new Set()\n\n const renderSubtree = (\n nodeId: string,\n prefix: string,\n isRoot: boolean,\n edgeFromParent?: FlowEdge,\n ): void => {\n const node = nodes.get(nodeId)\n if (!node) return\n const deg = inDegree.get(nodeId) ?? 0\n\n if (!isRoot && deg > 1 && !renderedJoin.has(nodeId)) {\n const sources = incomingSources.get(nodeId) ?? []\n const remaining = sources.some((src) => !visited.has(src) && src !== edgeFromParent?.from)\n if (remaining) {\n const lbl = edgeFromParent?.label ? ` (${edgeFromParent.label})` : ''\n out.push(\n `${prefix} ╰─► converges at ${truncateText(node.label, Math.max(12, maxWidth - prefix.length - 20))}${lbl}`,\n )\n return\n }\n renderedJoin.add(nodeId)\n }\n\n if (visited.has(nodeId)) {\n const lbl = edgeFromParent?.label ? ` (${edgeFromParent.label})` : ''\n out.push(\n `${prefix} ╰─► ↺ ${truncateText(node.label, Math.max(12, maxWidth - prefix.length - 10))}${lbl}`,\n )\n return\n }\n visited.add(nodeId)\n\n if (!isRoot && deg > 1) {\n const sources = (incomingSources.get(nodeId) ?? [])\n .map((s) => nodes.get(s)?.id ?? s)\n .filter((v, i, arr) => arr.indexOf(v) === i)\n out.push(`${prefix} (from ${sources.join(', ')})`)\n }\n\n const box = drawBox(node.label, maxWidth, prefix)\n out.push(...box)\n\n const children = outEdges.get(nodeId) ?? []\n if (children.length === 0) return\n\n if (children.length === 1 && children[0]) {\n const child = children[0]\n const stemX = `${prefix} `\n const lineChar = child.dashed ? '┆' : '│'\n const lbl = child.label ? ` ${child.label}` : ''\n out.push(`${stemX}${lineChar}${lbl}`)\n out.push(`${stemX}▼`)\n renderSubtree(child.to, prefix, false, child)\n return\n }\n\n for (let i = 0; i < children.length; i += 1) {\n const child = children[i]\n if (!child) continue\n const isLast = i === children.length - 1\n const branch = isLast ? '└──►' : '├──►'\n const edgeTag = child.label ? `[${child.label}] ` : ''\n const childPrefix = `${prefix} ${isLast ? ' ' : '│ '}`\n out.push(\n `${prefix} ${branch} ${edgeTag}${truncateText(nodes.get(child.to)?.label ?? child.to, Math.max(12, maxWidth - prefix.length - edgeTag.length - 8))}`,\n )\n const grandChildren = outEdges.get(child.to) ?? []\n if (!visited.has(child.to)) {\n visited.add(child.to)\n if (grandChildren.length > 0) {\n for (let j = 0; j < grandChildren.length; j += 1) {\n const gc = grandChildren[j]\n if (!gc) continue\n const gcDeg = inDegree.get(gc.to) ?? 0\n if (gcDeg > 1) {\n const srcs = incomingSources.get(gc.to) ?? []\n const pending = srcs.some((s) => !visited.has(s))\n if (pending) {\n out.push(\n `${childPrefix} ╰─► converges at ${truncateText(nodes.get(gc.to)?.label ?? gc.to, Math.max(12, maxWidth - childPrefix.length - 20))}`,\n )\n continue\n }\n }\n out.push(`${childPrefix} │`)\n out.push(`${childPrefix} ▼`)\n renderSubtree(gc.to, childPrefix, false, gc)\n }\n }\n }\n }\n }\n\n const roots = [...nodes.keys()].filter((id) => (inDegree.get(id) ?? 0) === 0)\n const queue = roots.length > 0 ? roots : [...nodes.keys()].slice(0, 1)\n for (let i = 0; i < queue.length; i += 1) {\n const rootId = queue[i]\n if (!rootId || visited.has(rootId)) continue\n if (out.length > 0) out.push('')\n renderSubtree(rootId, '', true)\n }\n\n for (const id of nodes.keys()) {\n if (!visited.has(id)) {\n if (out.length > 0) out.push('')\n renderSubtree(id, '', true)\n }\n }\n\n return out\n}\n\nfunction renderSequence(lines: readonly string[], maxWidth: number): string[] | null {\n const participants = new Map()\n const messages: Array<{ from: string; to: string; text: string; dashed: boolean }> = []\n\n const addParticipant = (id: string, label?: string): void => {\n if (!participants.has(id)) participants.set(id, cleanLabel(label ?? id))\n else if (label) participants.set(id, cleanLabel(label))\n }\n\n for (const raw of lines) {\n const s = raw.trim()\n if (!s || s.startsWith('%%') || /^sequenceDiagram\\b/i.test(s)) continue\n const partMatch = /^(?:participant|actor)\\s+([A-Za-z0-9_.-]+)(?:\\s+as\\s+(.+))?$/i.exec(s)\n if (partMatch?.[1]) {\n addParticipant(partMatch[1], partMatch[2])\n continue\n }\n const msgMatch = /^([A-Za-z0-9_.-]+)\\s*(-->>|->>|-->|->)\\s*([A-Za-z0-9_.-]+)\\s*:\\s*(.*)$/.exec(\n s,\n )\n if (msgMatch?.[1] && msgMatch[2] && msgMatch[3]) {\n addParticipant(msgMatch[1])\n addParticipant(msgMatch[3])\n messages.push({\n from: msgMatch[1],\n to: msgMatch[3],\n text: cleanLabel(msgMatch[4] ?? ''),\n dashed: msgMatch[2].startsWith('--'),\n })\n }\n }\n\n if (participants.size === 0 || messages.length === 0) return null\n const ids = [...participants.keys()]\n const count = ids.length\n const colStep = Math.floor((maxWidth - 4) / Math.max(1, count - 1))\n\n // Render full aligned lifelines when 2-4 participants fit comfortably\n if (count >= 2 && count <= 4 && colStep >= 18) {\n const centers = ids.map((_, idx) => 5 + idx * Math.min(colStep, 22))\n const totalW = (centers[count - 1] ?? 10) + 8\n const out: string[] = []\n const topLine = Array(totalW).fill(' ')\n const midLine = Array(totalW).fill(' ')\n const botLine = Array(totalW).fill(' ')\n\n for (let i = 0; i < count; i += 1) {\n const id = ids[i]\n if (!id) continue\n const label = truncateText(participants.get(id) ?? id, 12)\n const boxW = label.length + 4\n const start = Math.max(0, (centers[i] ?? 0) - Math.floor(boxW / 2))\n const top = `╭${'─'.repeat(label.length + 2)}╮`\n const mid = `│ ${label} │`\n const bot = `╰${'─'.repeat(label.length + 2)}╯`\n for (let k = 0; k < boxW; k += 1) {\n if (start + k < totalW) {\n topLine[start + k] = top[k]\n midLine[start + k] = mid[k]\n botLine[start + k] = k === (centers[i] ?? 0) - start ? '┬' : bot[k]\n }\n }\n }\n out.push(topLine.join('').trimEnd(), midLine.join('').trimEnd(), botLine.join('').trimEnd())\n\n const emptyLifelines = (): string[] => {\n const arr = Array(totalW).fill(' ')\n for (const c of centers) arr[c] = '│'\n return arr\n }\n\n for (const msg of messages) {\n const iFrom = ids.indexOf(msg.from)\n const iTo = ids.indexOf(msg.to)\n if (iFrom < 0 || iTo < 0) continue\n const cFrom = centers[iFrom] ?? 0\n const cTo = centers[iTo] ?? 0\n const left = Math.min(cFrom, cTo)\n const right = Math.max(cFrom, cTo)\n\n const labelRow = emptyLifelines()\n const msgText = truncateText(msg.text, Math.max(6, right - left - 2))\n for (let k = 0; k < msgText.length; k += 1) {\n if (left + 2 + k < totalW) labelRow[left + 2 + k] = msgText[k]\n }\n out.push(labelRow.join('').trimEnd())\n\n const arrowRow = emptyLifelines()\n const wire = msg.dashed ? '┄' : '─'\n for (let x = left + 1; x < right; x += 1) arrowRow[x] = wire\n if (cFrom < cTo) {\n arrowRow[left] = '├'\n arrowRow[right - 1] = '►'\n } else {\n arrowRow[left + 1] = '◄'\n arrowRow[right] = '┤'\n }\n out.push(arrowRow.join('').trimEnd())\n }\n out.push(emptyLifelines().join('').trimEnd())\n return out\n }\n\n // Fallback compact sequence list\n return messages.map((m, idx) => {\n const arrow = m.dashed ? '╌╌►' : '──►'\n const fromLbl = participants.get(m.from) ?? m.from\n const toLbl = participants.get(m.to) ?? m.to\n return truncateText(`${idx + 1}. [${fromLbl}] ${arrow} [${toLbl}]: ${m.text}`, maxWidth)\n })\n}\n\nfunction renderStateDiagram(lines: readonly string[], maxWidth: number): string[] | null {\n const normalized = lines.map((line) => {\n const trimmed = line.trim()\n if (/^stateDiagram(?:-v2)?$/i.test(trimmed)) return 'flowchart TD'\n // Convert \"A --> B : label\" into \"A -->|label| B\"\n const arrowWithLabel = /^(.+?)\\s*-->\\s*(.+?)\\s*:\\s*(.+)$/.exec(trimmed)\n if (arrowWithLabel?.[1] && arrowWithLabel[2] && arrowWithLabel[3]) {\n return `${arrowWithLabel[1].trim()} -->|${arrowWithLabel[3].trim()}| ${arrowWithLabel[2].trim()}`\n }\n return line\n })\n return renderFlowchart(normalized, maxWidth)\n}\n\nexport function renderMermaidToUnicode(\n rawLines: readonly string[],\n maxWidth = 76,\n): { header: string; lines: string[] } {\n const firstMeaningful = rawLines.map((l) => l.trim()).find((l) => l && !l.startsWith('%%')) ?? ''\n\n if (/^(?:flowchart|graph)\\b/i.test(firstMeaningful)) {\n const rendered = renderFlowchart(rawLines, maxWidth)\n if (rendered && rendered.length > 0) {\n return { header: '[Diagram: Flowchart]', lines: rendered }\n }\n } else if (/^sequenceDiagram\\b/i.test(firstMeaningful)) {\n const rendered = renderSequence(rawLines, maxWidth)\n if (rendered && rendered.length > 0) {\n return { header: '[Diagram: Sequence]', lines: rendered }\n }\n } else if (/^stateDiagram/i.test(firstMeaningful)) {\n const rendered = renderStateDiagram(rawLines, maxWidth)\n if (rendered && rendered.length > 0) {\n return { header: '[Diagram: State]', lines: rendered }\n }\n }\n\n return {\n header: '[Mermaid Diagram]',\n lines: rawLines.map((l) => ` ${l.trim()}`).filter((l) => l.trim().length > 0),\n }\n}\n","/**\n * artifacts-state.ts — Pure scanner, formatter, and paginator for Pantheon\n * Markdown artifacts (`.pantheon/deepwork//*.md`, `.pantheon/reports/*.md`,\n * `docs/adr/*.md`, `.pantheon/memory-bank/adr/*.md`).\n *\n * Zero JSX and zero host dependencies so the full scanning, formatting, and\n * pagination logic is directly unit-testable in Node.\n */\n\nimport { existsSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs'\nimport { basename, dirname, join, relative, resolve } from 'node:path'\nimport { renderMermaidToUnicode } from './mermaid-ascii.ts'\n\nexport type ArtifactKind = 'plan' | 'report' | 'adr'\n\nexport interface PantheonArtifactEntry {\n readonly id: string\n readonly kind: ArtifactKind\n readonly badge: string\n readonly title: string\n readonly path: string\n readonly relPath: string\n readonly modifiedMs: number\n readonly lineCount: number\n readonly bytes: number\n}\n\nexport const ARTIFACT_PAGE_SIZE = 16\nexport const ARTIFACT_LINE_WIDTH = 76\n\nconst GFM_ALERT_RE = /^>\\s*\\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\\]\\s*$/i\n\nfunction resolveArtifactRoots(workspaceDir: string): string[] {\n const roots: string[] = []\n const seen = new Set()\n const pushRoot = (candidate: string) => {\n try {\n if (!existsSync(candidate)) return\n const real = realpathSync(candidate)\n if (!seen.has(real)) {\n seen.add(real)\n roots.push(real)\n }\n } catch {\n /* ignore inaccessible root */\n }\n }\n\n pushRoot(workspaceDir)\n try {\n let cur = resolve(workspaceDir)\n for (let depth = 0; depth < 24; depth += 1) {\n const dotGit = join(cur, '.git')\n if (existsSync(dotGit)) {\n const st = statSync(dotGit)\n if (st.isFile()) {\n const content = readFileSync(dotGit, 'utf8')\n const match = /^gitdir:\\s*(.+)$/m.exec(content)\n if (match?.[1]) {\n const gitDir = resolve(cur, match[1].trim())\n const commonFile = join(gitDir, 'commondir')\n const commonGitDir = existsSync(commonFile)\n ? resolve(gitDir, readFileSync(commonFile, 'utf8').trim())\n : basename(dirname(gitDir)) === 'worktrees'\n ? dirname(dirname(gitDir))\n : null\n if (commonGitDir && basename(commonGitDir) === '.git') {\n pushRoot(dirname(commonGitDir))\n }\n }\n }\n break\n }\n const parent = dirname(cur)\n if (parent === cur) break\n cur = parent\n }\n } catch {\n /* fail-open */\n }\n return roots\n}\n\nfunction extractTitle(content: string, fallbackFile: string): string {\n for (const line of content.split(/\\r?\\n/)) {\n const match = /^#\\s+(.+?)\\s*$/.exec(line.trim())\n if (match?.[1]) return match[1].trim()\n }\n return fallbackFile.replace(/\\.md$/i, '')\n}\n\nfunction addArtifactFile(\n out: PantheonArtifactEntry[],\n seenPaths: Set,\n root: string,\n filePath: string,\n kind: ArtifactKind,\n): void {\n try {\n const real = realpathSync(filePath)\n if (seenPaths.has(real)) return\n const st = statSync(real)\n if (!st.isFile()) return\n const raw = readFileSync(real, 'utf8')\n const lineCount = raw === '' ? 0 : raw.split(/\\r?\\n/).length\n const relPath = relative(root, real).replace(/\\\\/g, '/')\n const badge = kind === 'plan' ? 'PLAN' : kind === 'report' ? 'REPORT' : 'ADR'\n seenPaths.add(real)\n out.push({\n id: real,\n kind,\n badge,\n title: extractTitle(raw, basename(real)),\n path: real,\n relPath,\n modifiedMs: st.mtimeMs,\n lineCount,\n bytes: st.size,\n })\n } catch {\n /* skip unreadable file */\n }\n}\n\nexport function scanPantheonArtifacts(workspaceDir: string): PantheonArtifactEntry[] {\n if (!workspaceDir || !existsSync(workspaceDir)) return []\n const roots = resolveArtifactRoots(workspaceDir)\n const out: PantheonArtifactEntry[] = []\n const seenPaths = new Set()\n\n for (const root of roots) {\n // 1. Deepwork plans & reports under .pantheon/deepwork//*.md\n const deepworkDir = join(root, '.pantheon', 'deepwork')\n if (existsSync(deepworkDir)) {\n try {\n for (const entry of readdirSync(deepworkDir, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue\n const slugDir = join(deepworkDir, entry.name)\n for (const file of readdirSync(slugDir, { withFileTypes: true })) {\n if (!file.isFile() || !file.name.endsWith('.md')) continue\n const kind: ArtifactKind = file.name.startsWith('VERIFICATION') ? 'report' : 'plan'\n addArtifactFile(out, seenPaths, root, join(slugDir, file.name), kind)\n }\n }\n } catch {\n /* ignore */\n }\n }\n\n // 2. Executive & audit reports under .pantheon/reports/*.md\n const reportsDir = join(root, '.pantheon', 'reports')\n if (existsSync(reportsDir)) {\n try {\n for (const file of readdirSync(reportsDir, { withFileTypes: true })) {\n if (!file.isFile() || !file.name.endsWith('.md')) continue\n addArtifactFile(out, seenPaths, root, join(reportsDir, file.name), 'report')\n }\n } catch {\n /* ignore */\n }\n }\n\n // 3. Architecture Decision Records under docs/adr/*.md and .pantheon/memory-bank/adr/*.md\n for (const adrDir of [\n join(root, 'docs', 'adr'),\n join(root, '.pantheon', 'memory-bank', 'adr'),\n ]) {\n if (!existsSync(adrDir)) continue\n try {\n for (const file of readdirSync(adrDir, { withFileTypes: true })) {\n if (!file.isFile() || !file.name.endsWith('.md')) continue\n if (file.name.toLowerCase() === 'readme.md') continue\n addArtifactFile(out, seenPaths, root, join(adrDir, file.name), 'adr')\n }\n } catch {\n /* ignore */\n }\n }\n }\n\n return out.sort((a, b) => b.modifiedMs - a.modifiedMs || a.relPath.localeCompare(b.relPath))\n}\n\nfunction wrapLine(text: string, width: number): string[] {\n const max = Number.isInteger(width) && width >= 20 ? width : ARTIFACT_LINE_WIDTH\n if (text.length <= max) return [text]\n const rows: string[] = []\n let rest = text\n while (rest.length > max) {\n let split = rest.lastIndexOf(' ', max)\n if (split < Math.floor(max * 0.4)) split = max\n rows.push(rest.slice(0, split).trimEnd())\n rest = rest.slice(split).trimStart()\n }\n if (rest.length > 0) rows.push(rest)\n return rows\n}\n\nfunction simplifyLinks(line: string): string {\n return line.replace(/\\[([^\\]]+)\\]\\(([^)]+)\\)/g, (_m, label: string, target: string) => {\n if (target.startsWith('file://')) {\n const clean = target.replace(/^file:\\/\\//, '')\n const hashIdx = clean.indexOf('#')\n const pathPart = hashIdx >= 0 ? clean.slice(0, hashIdx) : clean\n const anchor = hashIdx >= 0 ? clean.slice(hashIdx) : ''\n const base = basename(pathPart)\n return base === label ? `${label}${anchor}` : `${label} (${base}${anchor})`\n }\n return label\n })\n}\n\nexport function formatArtifactLines(\n markdown: string,\n width: number = ARTIFACT_LINE_WIDTH,\n): string[] {\n const max = Number.isInteger(width) && width >= 20 ? width : ARTIFACT_LINE_WIDTH\n const out: string[] = []\n let inMermaid = false\n let mermaidBuffer: string[] = []\n let inCode = false\n let activeAlert: string | null = null\n\n for (const rawLine of markdown.split(/\\r?\\n/)) {\n const trimmed = rawLine.trim()\n\n if (/^```mermaid/i.test(trimmed)) {\n inMermaid = true\n inCode = true\n mermaidBuffer = []\n continue\n }\n if (/^```/.test(trimmed)) {\n if (inCode) {\n if (inMermaid) {\n const rendered = renderMermaidToUnicode(mermaidBuffer, max)\n out.push(rendered.header)\n for (const dLine of rendered.lines) out.push(dLine)\n mermaidBuffer = []\n }\n inCode = false\n inMermaid = false\n out.push('')\n } else {\n inCode = true\n const lang = trimmed.slice(3).trim()\n out.push(lang ? `[Code: ${lang}]` : '[Code]')\n }\n continue\n }\n if (inCode) {\n if (inMermaid) {\n mermaidBuffer.push(rawLine)\n } else {\n out.push(...wrapLine(` ${trimmed}`, max))\n }\n continue\n }\n\n const alertMatch = GFM_ALERT_RE.exec(trimmed)\n if (alertMatch?.[1]) {\n activeAlert = alertMatch[1].toUpperCase()\n out.push(`[${activeAlert}]`)\n continue\n }\n if (trimmed.startsWith('>')) {\n const body = simplifyLinks(trimmed.replace(/^>\\s?/, ''))\n const prefix = activeAlert ? ' ' : '> '\n if (body === '') continue\n out.push(...wrapLine(`${prefix}${body}`, max))\n continue\n }\n activeAlert = null\n\n if (trimmed === '---' || trimmed === '***') {\n out.push('─'.repeat(Math.min(max, 64)))\n continue\n }\n if (trimmed === '') {\n if (out.length > 0 && out[out.length - 1] !== '') out.push('')\n continue\n }\n\n const cleaned = simplifyLinks(rawLine).replace(/\\*\\*/g, '')\n const hMatch = /^(#{1,3})\\s+(.+)$/.exec(cleaned.trim())\n if (hMatch?.[1] && hMatch[2]) {\n const level = hMatch[1].length\n const heading = level === 1 ? hMatch[2].toUpperCase() : hMatch[2]\n if (out.length > 0 && out[out.length - 1] !== '') out.push('')\n out.push(...wrapLine(level === 1 ? heading : `${'· '.repeat(level - 1)}${heading}`, max))\n continue\n }\n\n const bulletMatch = /^[-*]\\s+(.+)$/.exec(cleaned.trim())\n if (bulletMatch?.[1]) {\n out.push(...wrapLine(`• ${bulletMatch[1]}`, max))\n continue\n }\n\n out.push(...wrapLine(cleaned.trimEnd(), max))\n }\n\n while (out.length > 0 && out[out.length - 1] === '') out.pop()\n return out\n}\n\nexport function paginateArtifactLines(\n lines: readonly string[],\n pageSize: number = ARTIFACT_PAGE_SIZE,\n): string[][] {\n const size = Number.isInteger(pageSize) && pageSize > 0 ? pageSize : ARTIFACT_PAGE_SIZE\n if (lines.length === 0) return [[]]\n const pages: string[][] = []\n for (let i = 0; i < lines.length; i += size) {\n pages.push(lines.slice(i, i + size))\n }\n return pages\n}\n\nexport function artifactKindLabel(kind: ArtifactKind, isPt = false): string {\n if (kind === 'plan') return isPt ? 'Plano' : 'Plan'\n if (kind === 'report') return isPt ? 'Relatório' : 'Report'\n return 'ADR'\n}\n","/**\n * settings-i18n.ts — Bilingual (PT-BR / EN) internationalization for TUI settings.\n *\n * Provides localized titles, labels, and explanations for:\n * - Decision Router & Jev model selection\n * - Autonomy & Budgets\n * - Safety & J1 Risk Gate\n *\n * Automatically detects environment locale (LANG / LC_ALL) while allowing\n * manual override in TUI preferences.\n */\n\nexport type SettingsLanguage = 'auto' | 'pt-BR' | 'en'\n\nexport const SETTINGS_LANGUAGES_CYCLE: readonly string[] = Object.freeze(['auto', 'pt-BR', 'en'])\nexport const SUPPORTED_LANGUAGES = SETTINGS_LANGUAGES_CYCLE\n\n/**\n * Resolve effective language: 'pt-BR' or 'en'.\n * Defaults to 'pt-BR' if system locale contains 'pt', if Intl locale is pt,\n * or if system timezone is Brazilian/Portuguese; otherwise 'en'.\n */\nexport function resolveLanguage(\n preference: string = 'auto',\n env: Record = process.env,\n): 'pt-BR' | 'en' {\n if (preference === 'pt-BR') return 'pt-BR'\n if (preference === 'en') return 'en'\n\n // 1. Auto-detection based on environment locale variables\n const lang = (env.LC_ALL ?? env.LC_MESSAGES ?? env.LANG ?? env.LANGUAGE ?? '').toLowerCase()\n if (lang.startsWith('pt')) return 'pt-BR'\n\n // 2. Auto-detection based on Intl locale\n try {\n const intlLocale = Intl.DateTimeFormat().resolvedOptions().locale.toLowerCase()\n if (intlLocale.startsWith('pt')) return 'pt-BR'\n } catch {}\n\n // 3. Auto-detection based on timezone (Brazil & Portugal)\n try {\n const tz = (env.TZ ?? Intl.DateTimeFormat().resolvedOptions().timeZone ?? '').toLowerCase()\n if (\n tz.includes('sao_paulo') ||\n tz.includes('brazil') ||\n tz.includes('fortaleza') ||\n tz.includes('recife') ||\n tz.includes('manaus') ||\n tz.includes('belem') ||\n tz.includes('cuiaba') ||\n tz.includes('campo_grande') ||\n tz.includes('porto_velho') ||\n tz.includes('rio_branco') ||\n tz.includes('boa_vista') ||\n tz.includes('maceio') ||\n tz.includes('bahia') ||\n tz.includes('noronha') ||\n tz.includes('araguaina') ||\n tz.includes('santarem') ||\n tz.includes('lisbon') ||\n tz.includes('madeira') ||\n tz.includes('azores')\n ) {\n return 'pt-BR'\n }\n } catch {}\n\n return 'en'\n}\n\nexport interface I18nStringPair {\n en: string\n pt: string\n}\n\nexport const I18N = {\n tabs: {\n decision: { en: 'Decision (Jev)', pt: 'Decisão (Jev)' },\n autonomy: { en: 'Autonomy', pt: 'Autonomia' },\n safety: { en: 'Safety (J1)', pt: 'Segurança (J1)' },\n tui: { en: 'TUI', pt: 'TUI' },\n },\n decision: {\n groupRouter: {\n en: 'Decision Router (Jev Assistant)',\n pt: 'Assistente de Decisão (Jev)',\n },\n groupCredentials: {\n en: 'Credentials (status only — values never enter the window)',\n pt: 'Credenciais (apenas status — valores protegidos)',\n },\n routerName: {\n en: 'Router (Decision Assistant)',\n pt: 'Assistente Jev',\n },\n routerNote: {\n en: 'applies live — enables intelligent route arbitration and candidate ranking',\n pt: 'aplica em tempo real — motor de arbitragem inteligente e ranking de rotas',\n },\n modelName: {\n en: 'Decision model',\n pt: 'Modelo de Decisão',\n },\n modelNote: {\n en: 'local routes on-device (free); auto/explicit pick a remote decision model',\n pt: 'local decide no seu PC (grátis); auto/explícito usa modelo nuvem (OpenRouter)',\n },\n selectionModeName: {\n en: 'Selection mode',\n pt: 'Modo de operação',\n },\n selectionModeNote: {\n en: 'local routes on-device; auto/explicit pick a remote decision model',\n pt: 'local decide no dispositivo; auto/explícito usa modelo remoto',\n },\n egressName: {\n en: 'Cloud API access (Egress)',\n pt: 'Acesso à Nuvem (Egress)',\n },\n egressNoteGranted: {\n en: 'granted = remote decision routes may call their gateway (budget-capped)',\n pt: 'permitido = rotas remotas podem consultar a API (com limite de orçamento)',\n },\n egressNoteNotGranted: {\n en: 'not granted = remote routes blocked; local heuristic decisions only',\n pt: 'não permitido = chamadas remotas bloqueadas; apenas heurística local',\n },\n candidatesName: {\n en: 'Active candidates',\n pt: 'Candidatos ativos',\n },\n },\n autonomy: {\n groupGoalLoop: {\n en: 'Goal loop (multi-turn session auto-continuation)',\n pt: 'Execução Contínua (Goal Loop)',\n },\n goalLoopName: {\n en: 'Goal loop',\n pt: 'Loop contínuo',\n },\n goalLoopNote: {\n en: 'auto-continues multi-turn tasks when session goes idle · applies after OpenCode restart',\n pt: 'continua tarefas de múltiplos passos automaticamente · requer reinício',\n },\n maxContinuationsName: {\n en: 'Max continuations',\n pt: 'Limite de turnos',\n },\n maxContinuationsNote: {\n en: '1..200 — safety ceiling to prevent runaway tasks',\n pt: '1..200 — teto de segurança contra tarefas infinitas',\n },\n cooldownName: {\n en: 'Cooldown (ms)',\n pt: 'Intervalo (ms)',\n },\n cooldownNote: {\n en: 'delay between autonomous turns (min 1000ms)',\n pt: 'tempo de espera entre turnos autônomos (mín 1000ms)',\n },\n groupBudgets: {\n en: 'Decision budgets (applies live per gated call)',\n pt: 'Orçamento Jev (teto financeiro de proteção)',\n },\n monthlyCapName: {\n en: 'Monthly cap',\n pt: 'Teto mensal (USD)',\n },\n monthlyCapNote: {\n en: 'monthly USD ceiling for gated arbitrator decisions',\n pt: 'teto mensal em dólares para decisões do assistente Jev',\n },\n perDecisionCapName: {\n en: 'Per-decision cap',\n pt: 'Teto por consulta (USD)',\n },\n perDecisionCapNote: {\n en: 'price cap — gated decisions above this are refused',\n pt: 'teto por decisão — consultas remotas que excederem são recusadas',\n },\n groupGradient: {\n en: 'Decision gradient (reference policy · J1 owns the risk axis)',\n pt: 'Níveis de Decisão & Segurança (Referência)',\n },\n soloName: {\n en: 'Decide solo',\n pt: 'Decisão direta',\n },\n soloNote: {\n en: 'reversible & low-risk edits, routine fixes (no gate)',\n pt: 'edições reversíveis e baixo risco, sem portão de bloqueio',\n },\n jevName: {\n en: 'Jev decides',\n pt: 'Decisão Jev',\n },\n jevNote: {\n en: 'typed ambiguity & candidate ranking (budget-capped)',\n pt: 'ambiguidade e ranking de skills com teto de orçamento',\n },\n humanName: {\n en: 'Human decides',\n pt: 'Aprovação humana',\n },\n humanNote: {\n en: 'high-risk & destructive operations (J1 gate)',\n pt: 'ações de alto risco e destrutivas (portão de segurança J1)',\n },\n },\n safety: {\n groupSafety: {\n en: 'Safety & Risk Level (J1 Gate)',\n pt: 'Nível de Proteção & Portão de Risco (J1)',\n },\n modeName: {\n en: 'Protection mode',\n pt: 'Modo de proteção',\n },\n thresholdName: {\n en: 'Enforce threshold',\n pt: 'Teto para bloqueio',\n },\n thresholdNote: {\n en: 'deny at or above · 0..1 · default 0.8',\n pt: 'bloqueia em ou acima de · 0..1 · padrão 0.8',\n },\n gateName: {\n en: 'Safety gate',\n pt: 'Portão de segurança',\n },\n },\n} as const\n\n/** Helper to get localized text */\nexport function t(entry: I18nStringPair, lang: 'pt-BR' | 'en'): string {\n return lang === 'pt-BR' ? entry.pt : entry.en\n}\n","// biome-ignore-all lint/suspicious/noExplicitAny: stored prefs are host JSON of a known shape.\n/**\n * tui-prefs.ts — the TUI personalization core (the settings window's TUI tab).\n *\n * TUI-local copy doctrine (same as cost-data.ts): the bundle must stay\n * self-contained. Persistence is the HOST's durable plugin storage\n * (`context.storage.store('tui-prefs', { initial })` — reactive solid store,\n * live-synced across TUI instances); this module owns the SHAPE and the pure\n * operations, never the store handle.\n *\n * v1 surfaces: sidebar fixed headers, sidebar blocks, the Context block's\n * sub-lines and gauge style, and the two Pantheon footer lines. Everything\n * defaults to on — the window exists to turn things OFF.\n */\n\nimport type { Context } from '@opencode/plugin/tui/context'\nimport type { Accessor, Setter } from 'solid-js'\nimport { createSignal } from 'solid-js'\nimport type { SettingsDraft, SettingsRow, SettingsTab } from './pantheon-settings-state.ts'\nimport { resolveLanguage } from './settings-i18n.ts'\n\n// ── The durable store handle (host storage, one per plugin) ────────────\n// Created once at setup and stashed under a globalThis symbol so\n// hot-reload generations keep sharing the same live store (the same\n// singleton doctrine as the plugin's SINGLETON guard).\n\nconst PREFS_SYMBOL = Symbol.for('pantheon.tui.prefs.v1')\nconst DRAFT_PREVIEW_SYMBOL = Symbol.for('pantheon.tui.draft_preview.v1')\ntype PrefsStore = readonly [TuiPrefs, (mutation: (draft: TuiPrefs) => void) => Promise]\ntype DraftSignal = [Accessor, Setter]\n\nfunction stash(): PrefsStore | undefined {\n return (globalThis as Record)[PREFS_SYMBOL] as PrefsStore | undefined\n}\n\nfunction getDraftPreviewSignal(): DraftSignal {\n const g = globalThis as Record\n if (!g[DRAFT_PREVIEW_SYMBOL]) {\n g[DRAFT_PREVIEW_SYMBOL] = createSignal(undefined)\n }\n return g[DRAFT_PREVIEW_SYMBOL] as DraftSignal\n}\n\n/** Set the active draft preview overlay (used by settings window to provide live preview). */\nexport function setTuiDraftPreview(draft: SettingsDraft | undefined): void {\n const [, setDraft] = getDraftPreviewSignal()\n setDraft(draft && Object.keys(draft).length > 0 ? { ...draft } : undefined)\n}\n\n/** Clear the active draft preview overlay. */\nexport function clearTuiDraftPreview(): void {\n const [, setDraft] = getDraftPreviewSignal()\n setDraft(undefined)\n}\n\n/** The active draft preview accessor. */\nexport function tuiDraftPreview(): SettingsDraft | undefined {\n const [draft] = getDraftPreviewSignal()\n return draft()\n}\n\n/** Create (or reuse) the durable prefs store. Fail-open: without host\n * storage the consumers fall back to DEFAULT_TUI_PREFS (read-only). */\nexport function initTuiPrefs(context: Context): void {\n if (stash() !== undefined) return\n try {\n const handle = context.storage?.store?.('tui-prefs', { initial: DEFAULT_TUI_PREFS }) as\n | PrefsStore\n | undefined\n if (handle !== undefined) {\n ;(globalThis as unknown as Record)[PREFS_SYMBOL] = handle\n // Self-heal: if store was persisted before layout existed or lacks new fields, backfill defaults\n if (\n !handle[0]?.layout ||\n typeof handle[0]?.sidebar?.context?.turnCost !== 'boolean' ||\n typeof handle[0]?.sidebar?.context?.tokenAnatomy !== 'boolean'\n ) {\n handle[1]((draft: any) => {\n if (!draft.layout) {\n draft.layout = { ...DEFAULT_TUI_PREFS.layout }\n }\n if (draft.sidebar?.context) {\n if (typeof draft.sidebar.context.turnCost !== 'boolean') {\n draft.sidebar.context.turnCost = true\n }\n if (typeof draft.sidebar.context.tokenAnatomy !== 'boolean') {\n draft.sidebar.context.tokenAnatomy = true\n }\n }\n }).catch(() => {})\n }\n }\n } catch {\n /* no host storage — defaults stay read-only */\n }\n}\n\n/** Deep clone and overlay staged settings draft onto base TuiPrefs. */\nexport function previewTuiPrefs(base: TuiPrefs, draft?: SettingsDraft): TuiPrefs {\n if (!draft || Object.keys(draft).length === 0) return base\n let hasTui = false\n for (const k of Object.keys(draft)) {\n if (k.startsWith('tui.')) {\n hasTui = true\n break\n }\n }\n if (!hasTui) return base\n\n const normalized = normalizeTuiPrefs(base)\n const effective: TuiPrefs = {\n version: 1,\n layout: { ...normalized.layout },\n ...(normalized.theme ? { theme: { ...normalized.theme } } : {}),\n sidebar: {\n header: { ...normalized.sidebar.header },\n ...(normalized.sidebar.pinnedSessions\n ? { pinnedSessions: [...normalized.sidebar.pinnedSessions] }\n : {}),\n blocks: { ...normalized.sidebar.blocks },\n context: { ...normalized.sidebar.context },\n },\n footer: { ...normalized.footer },\n }\n\n for (const [id, value] of Object.entries(draft)) {\n if (id.startsWith('tui.')) {\n applyTuiRow(effective, id, value)\n }\n }\n return effective\n}\n\n/** The raw persisted prefs from host storage (no draft overlay). */\nexport function savedTuiPrefs(): TuiPrefs {\n const s = stash()?.[0]\n if (!s) return DEFAULT_TUI_PREFS\n return normalizeTuiPrefs(s)\n}\n\n/** The live reactive prefs (read properties inside memos/JSX — tracked).\n * When a settings window has an active draft, preview overlays on top\n * of durable storage in real time. */\nexport function tuiPrefs(): TuiPrefs {\n const base = savedTuiPrefs()\n const preview = tuiDraftPreview()\n if (!preview) return base\n return previewTuiPrefs(base, preview)\n}\n\n/** Stage a mutation against the durable store; resolves when persisted. */\nexport function mutateTuiPrefs(mutation: (draft: TuiPrefs) => void): Promise {\n const handle = stash()\n if (handle === undefined) return Promise.resolve()\n return handle[1](mutation)\n}\n\nexport const GAUGE_STYLES: readonly string[] = Object.freeze(['both', 'bar', 'percent', 'off'])\nexport const ENABLED_CYCLE: readonly string[] = Object.freeze(['enabled', 'disabled'])\n\nexport const BAR_SHAPES_CYCLE: readonly string[] = Object.freeze([\n 'smooth',\n 'line',\n 'block',\n 'ascii',\n 'dots',\n 'braille',\n])\nexport const BAR_WIDTHS_CYCLE: readonly string[] = Object.freeze([\n 'standard',\n 'compact',\n 'wide',\n 'full',\n])\nexport const LAYOUT_PRESETS_CYCLE: readonly string[] = Object.freeze(['comfortable', 'compact'])\nexport const SEPARATOR_STYLES_CYCLE: readonly string[] = Object.freeze([\n 'spaces',\n 'pipes',\n 'dots',\n 'slashes',\n])\nexport const SETTINGS_VIEW_MODES: readonly string[] = Object.freeze([\n 'docked',\n 'fullscreen',\n 'dialog',\n])\n\nexport type GaugeStyle = 'both' | 'bar' | 'percent' | 'off'\nexport type BarShapePref = 'line' | 'block' | 'smooth' | 'ascii' | 'dots' | 'braille'\nexport type BarWidthPref = 'standard' | 'compact' | 'wide' | 'full'\nexport type LayoutPresetPref = 'comfortable' | 'compact'\nexport type SeparatorStylePref = 'spaces' | 'pipes' | 'dots' | 'slashes'\nexport type SettingsViewModePref = 'docked' | 'fullscreen' | 'dialog'\nexport type LanguagePref = 'auto' | 'pt-BR' | 'en'\n\nexport const LANGUAGE_CYCLE: readonly string[] = Object.freeze(['auto', 'pt-BR', 'en'])\n\nexport type ThemeModePref = 'auto' | 'dark' | 'light'\nexport const THEME_MODES_CYCLE: readonly string[] = Object.freeze(['auto', 'dark', 'light'])\n\nexport type AccentColorPref = 'host' | 'pantheon' | 'emerald' | 'cyan' | 'amber' | 'purple' | 'rose'\nexport const ACCENT_COLORS_CYCLE: readonly string[] = Object.freeze([\n 'host',\n 'pantheon',\n 'emerald',\n 'cyan',\n 'amber',\n 'purple',\n 'rose',\n])\n\nexport const ACCENT_PALETTE: Record<\n AccentColorPref,\n { primary: string; hover: string; muted: string }\n> = {\n host: { primary: '#fba970', hover: '#fdba74', muted: '#a1a1aa' },\n pantheon: { primary: '#fba970', hover: '#fdba74', muted: '#a1a1aa' },\n emerald: { primary: '#10b981', hover: '#34d399', muted: '#059669' },\n cyan: { primary: '#06b6d4', hover: '#22d3ee', muted: '#0891b2' },\n amber: { primary: '#f59e0b', hover: '#fbbf24', muted: '#d97706' },\n purple: { primary: '#a855f7', hover: '#c084fc', muted: '#9333ea' },\n rose: { primary: '#f43f5e', hover: '#fb7185', muted: '#e11d48' },\n}\n\nexport function resolveAccentColor(accent: AccentColorPref | undefined, contextTheme: any): string {\n if (!accent || accent === 'host') {\n return contextTheme?.text?.feedback?.warning?.base ?? contextTheme?.text?.base ?? '#fba970'\n }\n return ACCENT_PALETTE[accent]?.primary ?? '#fba970'\n}\n\nexport interface TuiPrefs {\n version: 1\n layout: {\n preset: LayoutPresetPref\n separator: SeparatorStylePref\n settingsView?: SettingsViewModePref\n language?: LanguagePref\n }\n theme?: {\n mode?: ThemeModePref\n accent?: AccentColorPref\n }\n sidebar: {\n header: { version: boolean; preset: boolean; session: boolean }\n pinnedSessions?: string[]\n blocks: { context: boolean; git: boolean; todo?: boolean; dispatch: boolean }\n context: {\n gauge: GaugeStyle\n barShape: BarShapePref\n barWidth: BarWidthPref\n evenMark: boolean\n tokens: boolean\n spent: boolean\n modelUsage: boolean\n performance: boolean\n localSpend: boolean\n turnCost: boolean\n tokenAnatomy: boolean\n }\n }\n footer: { prompt: boolean; home: boolean }\n}\n\nexport const DEFAULT_TUI_PREFS: TuiPrefs = {\n version: 1,\n layout: {\n preset: 'comfortable',\n separator: 'spaces',\n settingsView: 'docked',\n language: 'auto',\n },\n theme: {\n mode: 'auto',\n accent: 'host',\n },\n sidebar: {\n header: { version: true, preset: true, session: true },\n pinnedSessions: [],\n blocks: { context: true, git: true, todo: false, dispatch: true },\n context: {\n gauge: 'both',\n barShape: 'smooth',\n barWidth: 'standard',\n evenMark: false,\n tokens: true,\n spent: true,\n modelUsage: true,\n performance: true,\n localSpend: true,\n turnCost: true,\n tokenAnatomy: true,\n },\n },\n footer: { prompt: true, home: true },\n}\n\nfunction asBool(value: unknown, fallback: boolean): boolean {\n return typeof value === 'boolean' ? value : fallback\n}\n\n/** Deep-merge stored JSON over the defaults; unknown keys and junk are ignored. */\nexport function normalizeTuiPrefs(raw: unknown): TuiPrefs {\n const stored = (typeof raw === 'object' && raw !== null ? raw : {}) as Record\n const layout = (\n typeof stored.layout === 'object' && stored.layout !== null ? stored.layout : {}\n ) as Record\n const sidebar = (\n typeof stored.sidebar === 'object' && stored.sidebar !== null ? stored.sidebar : {}\n ) as Record\n const header = (\n typeof sidebar.header === 'object' && sidebar.header !== null ? sidebar.header : {}\n ) as Record\n const blocks = (\n typeof sidebar.blocks === 'object' && sidebar.blocks !== null ? sidebar.blocks : {}\n ) as Record\n const context = (\n typeof sidebar.context === 'object' && sidebar.context !== null ? sidebar.context : {}\n ) as Record\n const footer = (\n typeof stored.footer === 'object' && stored.footer !== null ? stored.footer : {}\n ) as Record\n const rawTheme = (\n typeof stored.theme === 'object' && stored.theme !== null ? stored.theme : {}\n ) as Record\n const themeMode = THEME_MODES_CYCLE.includes(rawTheme.mode as string)\n ? (rawTheme.mode as ThemeModePref)\n : (DEFAULT_TUI_PREFS.theme?.mode ?? 'auto')\n const themeAccent = ACCENT_COLORS_CYCLE.includes(rawTheme.accent as string)\n ? (rawTheme.accent as AccentColorPref)\n : (DEFAULT_TUI_PREFS.theme?.accent ?? 'host')\n const preset = LAYOUT_PRESETS_CYCLE.includes(layout.preset as string)\n ? (layout.preset as LayoutPresetPref)\n : DEFAULT_TUI_PREFS.layout.preset\n const separator = SEPARATOR_STYLES_CYCLE.includes(layout.separator as string)\n ? (layout.separator as SeparatorStylePref)\n : DEFAULT_TUI_PREFS.layout.separator\n const settingsView = (\n SETTINGS_VIEW_MODES.includes(layout.settingsView as string)\n ? layout.settingsView\n : DEFAULT_TUI_PREFS.layout.settingsView\n ) as SettingsViewModePref\n const language = (\n LANGUAGE_CYCLE.includes(layout.language as string)\n ? layout.language\n : DEFAULT_TUI_PREFS.layout.language\n ) as LanguagePref\n const gauge = GAUGE_STYLES.includes(context.gauge as string)\n ? (context.gauge as GaugeStyle)\n : DEFAULT_TUI_PREFS.sidebar.context.gauge\n const barShape = BAR_SHAPES_CYCLE.includes(context.barShape as string)\n ? (context.barShape as BarShapePref)\n : DEFAULT_TUI_PREFS.sidebar.context.barShape\n const barWidth = BAR_WIDTHS_CYCLE.includes(context.barWidth as string)\n ? (context.barWidth as BarWidthPref)\n : DEFAULT_TUI_PREFS.sidebar.context.barWidth\n const evenMark = asBool(context.evenMark, DEFAULT_TUI_PREFS.sidebar.context.evenMark)\n\n return {\n version: 1,\n layout: {\n preset,\n separator,\n settingsView,\n language,\n },\n theme: {\n mode: themeMode,\n accent: themeAccent,\n },\n sidebar: {\n header: {\n version: asBool(header.version, true),\n preset: asBool(header.preset, true),\n session: asBool(header.session, true),\n },\n pinnedSessions: Array.isArray(sidebar.pinnedSessions)\n ? sidebar.pinnedSessions.filter((s: unknown) => typeof s === 'string')\n : [],\n blocks: {\n context: asBool(blocks.context, true),\n git: asBool(blocks.git, true),\n todo: asBool(blocks.todo, false),\n dispatch: asBool(blocks.dispatch, true),\n },\n context: {\n gauge,\n barShape,\n barWidth,\n evenMark,\n tokens: asBool(context.tokens, true),\n spent: asBool(context.spent, true),\n modelUsage: asBool(context.modelUsage, true),\n performance: asBool(context.performance, true),\n localSpend: asBool(context.localSpend, true),\n turnCost: asBool(context.turnCost, true),\n tokenAnatomy: asBool(context.tokenAnatomy, true),\n },\n },\n footer: {\n prompt: asBool(footer.prompt, true),\n home: asBool(footer.home, true),\n },\n }\n}\n\n// ── The TUI tab (cycler rows over the dotted pref paths) ───────────────\n\nconst onOff = ENABLED_CYCLE\nconst row = (id: string, name: string, value: boolean, note: string): SettingsRow => ({\n id,\n name,\n value: value ? 'enabled' : 'disabled',\n cycle: onOff,\n note,\n})\n\nexport function buildTuiTab(prefs: TuiPrefs, languagePref?: string): SettingsTab {\n const isPt = resolveLanguage(languagePref ?? prefs.layout?.language) === 'pt-BR'\n return {\n id: 'tui',\n title: 'TUI',\n groups: [\n {\n title: isPt ? 'Predefinição & Layout' : 'Preset & Layout',\n rows: [\n {\n id: 'tui.layout.preset',\n name: isPt ? 'Predefinição de layout' : 'Layout preset',\n value: prefs.layout?.preset ?? DEFAULT_TUI_PREFS.layout.preset,\n cycle: LAYOUT_PRESETS_CYCLE,\n note: isPt\n ? 'comfortable | compact — define espaçamento e bordas'\n : 'comfortable | compact — sets spacing & borders',\n },\n {\n id: 'tui.layout.separator',\n name: isPt ? 'Separador' : 'Separator',\n value: prefs.layout?.separator ?? DEFAULT_TUI_PREFS.layout.separator,\n cycle: SEPARATOR_STYLES_CYCLE,\n note: isPt\n ? 'spaces | pipes | dots | slashes — glifos na linha de status'\n : 'spaces | pipes | dots | slashes — status line glyphs',\n },\n {\n id: 'tui.layout.settingsView',\n name: isPt ? 'Superfície de configurações' : 'Settings surface',\n value: tuiRowValue(prefs, 'tui.layout.settingsView') ?? 'docked',\n cycle: SETTINGS_VIEW_MODES,\n note: isPt\n ? 'docked (acima do prompt) | fullscreen | dialog'\n : 'docked (above prompt) | fullscreen router page | dialog overlay',\n },\n {\n id: 'tui.layout.language',\n name: isPt ? 'Idioma / Language' : 'Language / Idioma',\n value: tuiRowValue(prefs, 'tui.layout.language') ?? 'auto',\n cycle: LANGUAGE_CYCLE,\n note: isPt\n ? 'auto (detecta via fuso/locale) | pt-BR (Português) | en (English)'\n : 'auto (detect via timezone/locale) | pt-BR (Português) | en (English)',\n },\n ],\n },\n {\n title: isPt ? 'Cores & Tema' : 'Colors & Theme',\n rows: [\n {\n id: 'tui.theme.mode',\n name: isPt ? 'Modo do tema' : 'Theme mode',\n value: tuiRowValue(prefs, 'tui.theme.mode') ?? 'auto',\n cycle: THEME_MODES_CYCLE,\n note: isPt\n ? 'auto (segue o OpenCode) | dark | light'\n : 'auto (follow OpenCode theme) | dark | light',\n },\n {\n id: 'tui.theme.accent',\n name: isPt ? 'Cor de destaque' : 'Accent color',\n value: tuiRowValue(prefs, 'tui.theme.accent') ?? 'host',\n cycle: ACCENT_COLORS_CYCLE,\n note: isPt\n ? 'host (segue tema) | pantheon | emerald | cyan | amber | purple | rose'\n : 'host (follow theme) | pantheon | emerald | cyan | amber | purple | rose',\n },\n ],\n },\n {\n title: isPt ? 'Barras & Medidores' : 'Bars & Gauges',\n rows: [\n {\n id: 'tui.sidebar.context.barShape',\n name: isPt ? 'Formato da barra' : 'Bar shape',\n value: prefs.sidebar.context.barShape,\n cycle: BAR_SHAPES_CYCLE,\n note: 'line (━─) | block (▰▱) | smooth (█░) | ascii (=) | dots (●○) | braille',\n },\n {\n id: 'tui.sidebar.context.barWidth',\n name: isPt ? 'Largura da barra' : 'Bar width',\n value: prefs.sidebar.context.barWidth,\n cycle: BAR_WIDTHS_CYCLE,\n note: isPt\n ? 'standard (12) | compact (8) | wide (16) | full (20 células)'\n : 'standard (12) | compact (8) | wide (16) | full (20 cells)',\n },\n row(\n 'tui.sidebar.context.evenMark',\n isPt ? 'Marca central (50%)' : 'Even-use mark',\n prefs.sidebar.context.evenMark,\n isPt\n ? '| indicador aos 50% nas barras de medição'\n : '| indicator at 50% midpoint in gauge bars',\n ),\n {\n id: 'tui.sidebar.context.gauge',\n name: isPt ? 'Estilo do medidor' : 'Gauge style',\n value: prefs.sidebar.context.gauge,\n cycle: GAUGE_STYLES,\n note: 'both | bar | percent | off — `▰▱ 42% of 200k`',\n },\n ],\n },\n {\n title: isPt ? 'Cabeçalho da barra lateral' : 'Sidebar header',\n rows: [\n row(\n 'tui.sidebar.header.version',\n isPt ? 'Linha de versão' : 'Version line',\n prefs.sidebar.header.version,\n isPt ? 'linha `Pantheon v…`' : 'the `Pantheon v…` line',\n ),\n row(\n 'tui.sidebar.header.preset',\n isPt ? 'Linha de preset' : 'Preset line',\n prefs.sidebar.header.preset,\n isPt ? 'linha `▸ preset · provider`' : 'the `▸ preset · provider` line',\n ),\n row(\n 'tui.sidebar.header.session',\n isPt ? 'Linha de sessão' : 'Session line',\n prefs.sidebar.header.session,\n isPt ? 'título da sessão ativa' : 'the active session title',\n ),\n ],\n },\n {\n title: isPt ? 'Blocos da barra lateral' : 'Sidebar blocks',\n rows: [\n row(\n 'tui.sidebar.block.context',\n isPt ? 'Bloco de contexto' : 'Context block',\n prefs.sidebar.blocks.context,\n isPt ? 'tokens, medidor, custo, uso de modelos' : 'tokens, gauge, spend, model usage',\n ),\n row(\n 'tui.sidebar.block.git',\n isPt ? 'Bloco do Git' : 'Git block',\n prefs.sidebar.blocks.git,\n isPt ? 'branch + contagem de alterações' : 'branch + working-tree counts',\n ),\n row(\n 'tui.sidebar.block.dispatch',\n isPt ? 'Bloco Dispatch' : 'Dispatch block',\n prefs.sidebar.blocks.dispatch,\n isPt ? 'delegações em tempo real' : 'live delegations + rollup',\n ),\n ],\n },\n {\n title: isPt ? 'Detalhe do bloco de contexto' : 'Context block detail',\n rows: [\n row(\n 'tui.sidebar.context.tokens',\n isPt ? 'Linha de tokens' : 'Tokens row',\n prefs.sidebar.context.tokens,\n isPt ? 'contagem bruta de tokens' : 'the raw token count line',\n ),\n row(\n 'tui.sidebar.context.spent',\n isPt ? 'Linha de custo' : 'Spent row',\n prefs.sidebar.context.spent,\n isPt ? 'linha `$… gastos na sessão`' : 'the `$… spent in session` line',\n ),\n row(\n 'tui.sidebar.context.modelUsage',\n isPt ? 'Tabela de uso de modelos' : 'Model usage table',\n prefs.sidebar.context.modelUsage,\n isPt ? 'resumo de chamadas por modelo' : 'per-model tokens/USD',\n ),\n row(\n 'tui.sidebar.context.performance',\n isPt ? 'Linha de desempenho' : 'Performance row',\n prefs.sidebar.context.performance,\n isPt ? 'tokens/segundo e latência' : 'cache % + tok/s',\n ),\n row(\n 'tui.sidebar.context.turnCost',\n isPt ? 'Custo do turno' : 'Turn cost',\n prefs.sidebar.context.turnCost,\n isPt ? 'linha `Turn: $… (prev: $…)`' : 'the `Turn: $… (prev: $…)` line',\n ),\n row(\n 'tui.sidebar.context.tokenAnatomy',\n isPt ? 'Anatomia de tokens' : 'Token anatomy',\n prefs.sidebar.context.tokenAnatomy,\n isPt ? 'linha `↑in ↓out ✦think`' : 'the `↑in ↓out ✦think` line',\n ),\n row(\n 'tui.sidebar.context.localSpend',\n isPt ? 'Linha de custo local' : 'Local spend row',\n prefs.sidebar.context.localSpend,\n isPt ? 'totais de hoje / 30 dias' : 'hoje / 30d totals',\n ),\n ],\n },\n {\n title: isPt ? 'Rodapés' : 'Footers',\n rows: [\n row(\n 'tui.footer.prompt',\n isPt ? 'Prompt inferior' : 'Prompt footer',\n prefs.footer.prompt,\n isPt\n ? 'linha `▸preset · ✦n ativos` durante delegações'\n : 'the `▸preset · ✦n ativos` line while delegations run',\n ),\n row(\n 'tui.footer.home',\n isPt ? 'Status inicial' : 'Home status',\n prefs.footer.home,\n isPt\n ? 'linha `Pantheon v…` sob o prompt inicial'\n : 'the `Pantheon v…` line under the home prompt',\n ),\n ],\n },\n ],\n }\n}\n\n/**\n * Apply one staged row INTO a prefs draft (in place — the storage mutate\n * callback hands an immer-style draft). Unknown ids or junk values are no-ops.\n */\nexport function applyTuiRow(draft: TuiPrefs, id: string, value: string): void {\n const enabled = value === 'enabled'\n switch (id) {\n case 'tui.layout.preset':\n if (LAYOUT_PRESETS_CYCLE.includes(value)) {\n if (!draft.layout) draft.layout = { ...DEFAULT_TUI_PREFS.layout }\n draft.layout.preset = value as LayoutPresetPref\n }\n return\n case 'tui.layout.separator':\n if (SEPARATOR_STYLES_CYCLE.includes(value)) {\n if (!draft.layout) draft.layout = { ...DEFAULT_TUI_PREFS.layout }\n draft.layout.separator = value as SeparatorStylePref\n }\n return\n case 'tui.layout.settingsView':\n if (SETTINGS_VIEW_MODES.includes(value)) {\n if (!draft.layout) draft.layout = { ...DEFAULT_TUI_PREFS.layout }\n draft.layout.settingsView = value as SettingsViewModePref\n }\n return\n case 'tui.layout.language':\n if (LANGUAGE_CYCLE.includes(value)) {\n if (!draft.layout) draft.layout = { ...DEFAULT_TUI_PREFS.layout }\n draft.layout.language = value as LanguagePref\n }\n return\n case 'tui.theme.mode':\n if (THEME_MODES_CYCLE.includes(value)) {\n if (!draft.theme) draft.theme = { ...DEFAULT_TUI_PREFS.theme }\n draft.theme.mode = value as ThemeModePref\n }\n return\n case 'tui.theme.accent':\n if (ACCENT_COLORS_CYCLE.includes(value)) {\n if (!draft.theme) draft.theme = { ...DEFAULT_TUI_PREFS.theme }\n draft.theme.accent = value as AccentColorPref\n }\n return\n case 'tui.sidebar.context.barShape':\n if (BAR_SHAPES_CYCLE.includes(value)) draft.sidebar.context.barShape = value as BarShapePref\n return\n case 'tui.sidebar.context.barWidth':\n if (BAR_WIDTHS_CYCLE.includes(value)) draft.sidebar.context.barWidth = value as BarWidthPref\n return\n case 'tui.sidebar.context.evenMark':\n draft.sidebar.context.evenMark = enabled\n return\n case 'tui.sidebar.header.version':\n draft.sidebar.header.version = enabled\n return\n case 'tui.sidebar.header.preset':\n draft.sidebar.header.preset = enabled\n return\n case 'tui.sidebar.header.session':\n draft.sidebar.header.session = enabled\n return\n case 'tui.sidebar.block.context':\n draft.sidebar.blocks.context = enabled\n return\n case 'tui.sidebar.block.git':\n draft.sidebar.blocks.git = enabled\n return\n case 'tui.sidebar.block.todo':\n draft.sidebar.blocks.todo = enabled\n return\n case 'tui.sidebar.block.dispatch':\n draft.sidebar.blocks.dispatch = enabled\n return\n case 'tui.sidebar.context.gauge':\n if (GAUGE_STYLES.includes(value)) draft.sidebar.context.gauge = value as GaugeStyle\n return\n case 'tui.sidebar.context.tokens':\n draft.sidebar.context.tokens = enabled\n return\n case 'tui.sidebar.context.spent':\n draft.sidebar.context.spent = enabled\n return\n case 'tui.sidebar.context.modelUsage':\n draft.sidebar.context.modelUsage = enabled\n return\n case 'tui.sidebar.context.performance':\n draft.sidebar.context.performance = enabled\n return\n case 'tui.sidebar.context.localSpend':\n draft.sidebar.context.localSpend = enabled\n return\n case 'tui.sidebar.context.turnCost':\n draft.sidebar.context.turnCost = enabled\n return\n case 'tui.sidebar.context.tokenAnatomy':\n draft.sidebar.context.tokenAnatomy = enabled\n return\n case 'tui.footer.prompt':\n draft.footer.prompt = enabled\n return\n case 'tui.footer.home':\n draft.footer.home = enabled\n return\n default:\n return\n }\n}\n\n/** Read the current pref value for a row id ('enabled'/'disabled'/gauge/custom). */\nexport function tuiRowValue(prefs: TuiPrefs, id: string): string | undefined {\n if (id === 'tui.layout.preset') return prefs.layout?.preset ?? DEFAULT_TUI_PREFS.layout.preset\n if (id === 'tui.layout.separator')\n return prefs.layout?.separator ?? DEFAULT_TUI_PREFS.layout.separator\n if (id === 'tui.layout.settingsView')\n return prefs.layout?.settingsView ?? DEFAULT_TUI_PREFS.layout.settingsView ?? 'docked'\n if (id === 'tui.layout.language') return prefs.layout?.language ?? 'auto'\n if (id === 'tui.theme.mode') return prefs.theme?.mode ?? DEFAULT_TUI_PREFS.theme?.mode ?? 'auto'\n if (id === 'tui.theme.accent')\n return prefs.theme?.accent ?? DEFAULT_TUI_PREFS.theme?.accent ?? 'host'\n if (id === 'tui.sidebar.context.barShape') return prefs.sidebar.context.barShape\n if (id === 'tui.sidebar.context.barWidth') return prefs.sidebar.context.barWidth\n if (id === 'tui.sidebar.context.gauge') return prefs.sidebar.context.gauge\n if (id === 'tui.sidebar.context.evenMark')\n return prefs.sidebar.context.evenMark ? 'enabled' : 'disabled'\n const enabled = (() => {\n switch (id) {\n case 'tui.sidebar.header.version':\n return prefs.sidebar.header.version\n case 'tui.sidebar.header.preset':\n return prefs.sidebar.header.preset\n case 'tui.sidebar.header.session':\n return prefs.sidebar.header.session\n case 'tui.sidebar.block.context':\n return prefs.sidebar.blocks.context\n case 'tui.sidebar.block.git':\n return prefs.sidebar.blocks.git\n case 'tui.sidebar.block.todo':\n return prefs.sidebar.blocks.todo\n case 'tui.sidebar.block.dispatch':\n return prefs.sidebar.blocks.dispatch\n case 'tui.sidebar.context.tokens':\n return prefs.sidebar.context.tokens\n case 'tui.sidebar.context.spent':\n return prefs.sidebar.context.spent\n case 'tui.sidebar.context.modelUsage':\n return prefs.sidebar.context.modelUsage\n case 'tui.sidebar.context.performance':\n return prefs.sidebar.context.performance\n case 'tui.sidebar.context.localSpend':\n return prefs.sidebar.context.localSpend\n case 'tui.sidebar.context.turnCost':\n return prefs.sidebar.context.turnCost\n case 'tui.sidebar.context.tokenAnatomy':\n return prefs.sidebar.context.tokenAnatomy\n case 'tui.footer.prompt':\n return prefs.footer.prompt\n case 'tui.footer.home':\n return prefs.footer.home\n default:\n return undefined\n }\n })()\n return enabled === undefined ? undefined : enabled ? 'enabled' : 'disabled'\n}\n\nexport function isSessionPinned(sessionID: string | undefined): boolean {\n if (!sessionID) return false\n const list = tuiPrefs().sidebar.pinnedSessions\n return Array.isArray(list) && list.includes(sessionID)\n}\n\nexport function togglePinSession(sessionID: string | undefined): Promise {\n if (!sessionID) return Promise.resolve()\n return mutateTuiPrefs((draft) => {\n if (!Array.isArray(draft.sidebar.pinnedSessions)) {\n draft.sidebar.pinnedSessions = []\n }\n const idx = draft.sidebar.pinnedSessions.indexOf(sessionID)\n if (idx >= 0) {\n draft.sidebar.pinnedSessions.splice(idx, 1)\n } else {\n draft.sidebar.pinnedSessions.push(sessionID)\n }\n })\n}\n","/**\n * cockpit-state.ts — Pure selectors, Gantt renderers, Work Map topology, and\n * Gate Matrix aggregation for the TUI Mission Control Cockpit (`Overview`,\n * `Swarm`, `Flightdeck`).\n */\n\nimport { existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs'\nimport { dirname, join, resolve, sep } from 'node:path'\nimport { scanPantheonArtifacts } from './artifacts-state.ts'\n\nexport type CockpitTabId = 'overview' | 'swarm' | 'flightdeck'\n\nexport interface CockpitChildEntry {\n readonly id: string\n readonly agent: string\n readonly kind: string\n readonly status: 'running' | 'completed' | 'failed' | 'interrupted' | 'unknown'\n readonly cost: number\n readonly startedAt: number\n readonly updatedAt: number\n readonly tokens: number\n readonly model?: string\n}\n\nexport interface CockpitLogEntry {\n readonly kind: string\n readonly timestamp: number\n readonly agent: string\n readonly detail: string\n readonly severity: 'ok' | 'warn' | 'error'\n}\n\nexport interface CockpitStepEntry {\n readonly stepKey: string\n readonly objective: string\n readonly agent: string\n readonly state: string\n readonly taskType?: string\n readonly mutatedCount: number\n readonly receiptId?: string\n readonly hasBaselineTree: boolean\n readonly updatedAt: string\n}\n\nexport interface CockpitInput {\n readonly workspaceDir: string\n readonly sessionTitle?: string\n readonly modelName?: string\n readonly contextTokens?: number\n readonly contextWindow?: number\n readonly sessionCost?: number\n readonly cacheRate?: number\n readonly children: readonly CockpitChildEntry[]\n readonly events?: readonly CockpitLogEntry[]\n readonly isPt?: boolean\n}\n\nexport interface CockpitSnapshot {\n readonly sessionTitle: string\n readonly modelName: string\n readonly overview: {\n readonly contextTokens: number\n readonly contextWindow: number\n readonly contextPercent: number\n readonly contextGauge: string\n readonly sessionCost: number\n readonly cacheRate: number\n readonly subagentCount: number\n readonly runningCount: number\n readonly velocityBars: string\n readonly workMap: readonly string[]\n readonly surfaces: ReadonlyArray<{ readonly label: string; readonly status: string }>\n }\n readonly swarm: {\n readonly activeCount: number\n readonly completedCount: number\n readonly failedCount: number\n readonly totalCost: number\n readonly rows: ReadonlyArray<\n CockpitChildEntry & {\n readonly durationSec: number\n readonly ganttBar: string\n }\n >\n }\n readonly flightdeck: {\n readonly allowed: number\n readonly approved: number\n readonly waiting: number\n readonly blocked: number\n readonly gateGlyphs: string\n readonly gateSummary: string\n readonly steps: readonly CockpitStepEntry[]\n readonly logs: readonly CockpitLogEntry[]\n }\n}\n\nexport function formatGanttBar(\n startMs: number,\n endMs: number,\n minMs: number,\n maxMs: number,\n width = 24,\n): string {\n const span = Math.max(1, maxMs - minMs)\n const s = Math.max(0, Math.min(width - 1, Math.floor(((startMs - minMs) / span) * width)))\n const e = Math.max(s + 1, Math.min(width, Math.ceil(((endMs - minMs) / span) * width)))\n const cells: string[] = []\n for (let i = 0; i < width; i += 1) {\n cells.push(i >= s && i < e ? '█' : '░')\n }\n return cells.join('')\n}\n\nexport function formatGateMatrixGlyphs(\n allowed: number,\n approved: number,\n waiting: number,\n blocked: number,\n): string {\n const cap = (n: number, ch: string) => ch.repeat(Math.min(12, Math.max(0, n)))\n const parts = [\n cap(allowed, '■'),\n cap(approved, '▣'),\n cap(waiting, '□'),\n cap(blocked, '✗'),\n ].filter(Boolean)\n return parts.length > 0 ? parts.join(' ') : '■'\n}\n\nexport function renderWorkMapLines(counts: {\n readonly subagents: number\n readonly artifacts: number\n readonly stepsDone: number\n readonly stepsTotal: number\n}): string[] {\n const subs = String(counts.subagents).padStart(2, ' ')\n const arts = String(counts.artifacts).padStart(2, ' ')\n const stps = `${counts.stepsDone}/${counts.stepsTotal}`\n return [\n ` [You] ────── [Zeus] ────── [Swarm (${subs})]`,\n ` │ │`,\n ` [Artifacts ${arts}] ─┼─ [Step Ledger ${stps}] ─ [Review & Gates]`,\n ` │`,\n ` [FTS5 Memory] ─┴─ [AST + LSP Diagnostics]`,\n ]\n}\n\nfunction loadStepEntries(workspaceDir: string): CockpitStepEntry[] {\n const ledgerPath = join(workspaceDir, '.pantheon', 'ledger', 'step-ledger.json')\n if (!existsSync(ledgerPath)) return []\n try {\n const parsed = JSON.parse(readFileSync(ledgerPath, 'utf8')) as {\n steps?: Record>\n }\n const list = Object.values(parsed.steps ?? {})\n return list\n .map((s) => ({\n stepKey: String(s.stepKey ?? ''),\n objective: String(s.objective ?? ''),\n agent: String(s.agent ?? 'specialist'),\n state: String(s.state ?? 'pending'),\n ...(typeof s.taskType === 'string' ? { taskType: s.taskType } : {}),\n mutatedCount: Array.isArray(s.mutatedFiles) ? s.mutatedFiles.length : 0,\n ...(typeof s.receiptId === 'string' ? { receiptId: s.receiptId } : {}),\n hasBaselineTree: typeof s.baselineTree === 'string' && s.baselineTree.length === 40,\n updatedAt: String(s.updatedAt ?? ''),\n }))\n .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))\n } catch {\n return []\n }\n}\n\nfunction resolveSharedTelemetryRoot(workspaceDir: string): string {\n try {\n let cur = resolve(workspaceDir)\n for (let i = 0; i < 10; i += 1) {\n const gitEntry = join(cur, '.git')\n if (existsSync(gitEntry)) {\n const statText = readFileSync(gitEntry, 'utf8')\n const gitDirMatch = /^gitdir:\\s*(.+)$/m.exec(statText)\n if (gitDirMatch?.[1]) {\n const gitDir = resolve(cur, gitDirMatch[1].trim())\n const commonPath = join(gitDir, 'commondir')\n if (existsSync(commonPath)) {\n const commonDir = resolve(gitDir, readFileSync(commonPath, 'utf8').trim())\n if (commonDir.endsWith(`${sep}.git`)) return dirname(commonDir)\n }\n }\n return cur\n }\n const parent = dirname(cur)\n if (parent === cur) break\n cur = parent\n }\n } catch {\n /* ignore */\n }\n return workspaceDir\n}\n\nfunction loadPersistedCockpitEvents(workspaceDir: string): CockpitLogEntry[] {\n try {\n const root = resolveSharedTelemetryRoot(workspaceDir)\n const filePath = join(root, '.pantheon', 'telemetry', 'cockpit-events.ndjson')\n if (!existsSync(filePath)) return []\n const lines = readFileSync(filePath, 'utf8').split(/\\r?\\n/).filter(Boolean)\n const out: CockpitLogEntry[] = []\n for (const line of lines.slice(-60)) {\n try {\n const parsed = JSON.parse(line) as Partial\n if (typeof parsed.kind === 'string' && typeof parsed.detail === 'string') {\n out.push({\n kind: parsed.kind,\n timestamp: typeof parsed.timestamp === 'number' ? parsed.timestamp : Date.now(),\n agent: typeof parsed.agent === 'string' ? parsed.agent : 'pantheon',\n detail: parsed.detail,\n severity:\n parsed.severity === 'ok' || parsed.severity === 'warn' || parsed.severity === 'error'\n ? parsed.severity\n : 'info',\n })\n }\n } catch {\n /* ignore malformed event line */\n }\n }\n return out\n } catch {\n return []\n }\n}\n\nexport function buildCockpitSnapshot(input: CockpitInput): CockpitSnapshot {\n const ctxTokens = Math.max(0, input.contextTokens ?? 0)\n const ctxWindow = Math.max(1, input.contextWindow ?? 200_000)\n const ctxPct = Math.min(100, Math.round((ctxTokens / ctxWindow) * 100))\n const filled = Math.min(20, Math.round((ctxPct / 100) * 20))\n const gauge = `[${'█'.repeat(filled)}${'░'.repeat(20 - filled)}] ${ctxPct}%`\n\n const artifacts = input.workspaceDir ? scanPantheonArtifacts(input.workspaceDir) : []\n const steps = input.workspaceDir ? loadStepEntries(input.workspaceDir) : []\n const stepsDone = steps.filter((s) => s.state === 'done').length\n\n const runningCount = input.children.filter((c) => c.status === 'running').length\n const completedCount = input.children.filter((c) => c.status === 'completed').length\n const failedCount = input.children.filter(\n (c) => c.status === 'failed' || c.status === 'interrupted',\n ).length\n const childCost = input.children.reduce((acc, c) => acc + c.cost, 0)\n\n const minMs = input.children.reduce((m, c) => Math.min(m, c.startedAt), Infinity)\n const maxMs = input.children.reduce((m, c) => Math.max(m, c.updatedAt), 0)\n const safeMin = Number.isFinite(minMs) ? minMs : 0\n const safeMax = maxMs > safeMin ? maxMs : safeMin + 1000\n\n const swarmRows = input.children.map((c) => ({\n ...c,\n durationSec: Math.max(0, Math.round((c.updatedAt - c.startedAt) / 100) / 10),\n ganttBar: formatGanttBar(c.startedAt, Math.max(c.startedAt + 1, c.updatedAt), safeMin, safeMax),\n }))\n\n const persistedEvents = input.workspaceDir ? loadPersistedCockpitEvents(input.workspaceDir) : []\n const mergedEvents = [...(input.events ?? []), ...persistedEvents]\n const dedup = new Map()\n for (const ev of mergedEvents) {\n dedup.set(`${ev.kind}:${ev.timestamp}:${ev.agent}:${ev.detail}`, ev)\n }\n const events = Array.from(dedup.values())\n .sort((a, b) => b.timestamp - a.timestamp)\n .slice(0, 40)\n const allowed = stepsDone + events.filter((e) => e.severity === 'ok').length + completedCount\n const approved = steps.filter((s) => Boolean(s.receiptId)).length\n const waiting =\n steps.filter((s) => s.state === 'in_progress' || s.state === 'pending').length + runningCount\n const blocked =\n steps.filter((s) => s.state === 'blocked' || s.state === 'rolled_back').length +\n events.filter((e) => e.severity === 'error').length +\n failedCount\n\n const velocityBlocks =\n input.children.length > 0\n ? input.children\n .slice(0, 14)\n .map((c) =>\n c.tokens > 20_000 ? '█' : c.tokens > 10_000 ? '▆' : c.tokens > 3_000 ? '▄' : '▂',\n )\n .join('')\n : '▁▃▅▆▄▂'\n\n return {\n sessionTitle: input.sessionTitle?.trim() || (input.isPt ? 'Sessão ativa' : 'Active Session'),\n modelName: input.modelName?.trim() || 'auto',\n overview: {\n contextTokens: ctxTokens,\n contextWindow: ctxWindow,\n contextPercent: ctxPct,\n contextGauge: gauge,\n sessionCost: input.sessionCost ?? childCost,\n cacheRate: input.cacheRate ?? 0,\n subagentCount: input.children.length,\n runningCount,\n velocityBars: velocityBlocks,\n workMap: renderWorkMapLines({\n subagents: input.children.length,\n artifacts: artifacts.length,\n stepsDone,\n stepsTotal: steps.length,\n }),\n surfaces: [\n { label: 'Native Tools (30)', status: 'active' },\n { label: 'FTS5 Memory + Worktree', status: 'ready' },\n { label: 'Step-Ledger & Checkpoints', status: `${stepsDone}/${steps.length} done` },\n { label: 'LSP + Per-Edit Guardrails', status: 'active' },\n { label: 'Artifacts & Mermaid', status: `${artifacts.length} file(s)` },\n ],\n },\n swarm: {\n activeCount: runningCount,\n completedCount,\n failedCount,\n totalCost: childCost,\n rows: swarmRows,\n },\n flightdeck: {\n allowed,\n approved,\n waiting,\n blocked,\n gateGlyphs: formatGateMatrixGlyphs(allowed, approved, waiting, blocked),\n gateSummary: `${allowed} allowed · ${approved} receipts · ${waiting} active · ${blocked} blocked`,\n steps,\n logs: events,\n },\n }\n}\n\nexport interface CockpitReplayExport {\n readonly filename: string\n readonly relPath: string\n readonly markdown: string\n}\n\n/**\n * Render a deterministic Markdown + Mermaid Flightdeck replay trace ready for\n * archival under `.pantheon/reports/` and inspection via `/pantheon-artifacts`.\n */\nexport function formatCockpitReplayArtifact(\n snapshot: CockpitSnapshot,\n now: Date = new Date(),\n): CockpitReplayExport {\n const stamp = now.toISOString().replace(/[:.]/g, '-').slice(0, 19)\n const filename = `cockpit-replay-${stamp}.md`\n const relPath = `.pantheon/reports/${filename}`\n const seqLines: string[] = [\n '```mermaid',\n 'sequenceDiagram',\n ' participant You',\n ' participant Zeus',\n ]\n const seenAgents = new Set()\n for (const row of snapshot.swarm.rows.slice(0, 12)) {\n const cleanAgent = row.agent.replace(/[^A-Za-z0-9_-]/g, '') || 'specialist'\n if (!seenAgents.has(cleanAgent)) {\n seenAgents.add(cleanAgent)\n seqLines.push(` participant ${cleanAgent}`)\n }\n seqLines.push(\n ` Zeus->>${cleanAgent}: ${row.kind} ($${row.cost.toFixed(3)}, ${row.durationSec}s)`,\n )\n seqLines.push(` ${cleanAgent}-->>Zeus: ${row.status}`)\n }\n if (snapshot.swarm.rows.length === 0) {\n seqLines.push(' You->>Zeus: active session telemetry snapshot')\n seqLines.push(' Zeus-->>You: Flightdeck gate check')\n }\n seqLines.push('```')\n\n const ganttRows =\n snapshot.swarm.rows.length > 0\n ? snapshot.swarm.rows\n .map(\n (r) =>\n `| \\`@${r.agent}\\` | ${r.status} | \\`${r.ganttBar}\\` | ${r.durationSec}s | $${r.cost.toFixed(4)} |`,\n )\n .join('\\n')\n : '| _none_ | — | `░░░░░░░░░░░░` | 0s | $0.0000 |'\n\n const stepLines =\n snapshot.flightdeck.steps.length > 0\n ? snapshot.flightdeck.steps\n .map((s) => `- **${s.stepKey}** (\\`${s.state}\\`, \\`@${s.agent}\\`) — ${s.objective}`)\n .join('\\n')\n : '- No step-ledger entries recorded.'\n\n const eventLines =\n snapshot.flightdeck.logs.length > 0\n ? snapshot.flightdeck.logs\n .map((e) => `- \\`[${e.kind}]\\` **@${e.agent}**: ${e.detail}`)\n .join('\\n')\n : '- No semantic bus events recorded.'\n\n const markdown = [\n `# Pantheon Cockpit Flightdeck Replay`,\n '',\n `- **Session:** ${snapshot.sessionTitle}`,\n `- **Model:** ${snapshot.modelName}`,\n `- **Captured At:** ${now.toISOString()}`,\n `- **Spend / Context:** $${snapshot.overview.sessionCost.toFixed(4)} · ${snapshot.overview.contextTokens} tokens (${snapshot.overview.contextPercent}%)`,\n `- **Gate Matrix:** ${snapshot.flightdeck.gateSummary}`,\n '',\n '## Execution Replay Diagram',\n '',\n ...seqLines,\n '',\n '## Swarm Concurrency Timeline',\n '',\n '| Agent | Status | Gantt Window | Duration | Cost |',\n '|---|---|---|---|---|',\n ganttRows,\n '',\n '## Step-Ledger Checkpoints',\n '',\n stepLines,\n '',\n '## Semantic Event Stream',\n '',\n eventLines,\n '',\n ].join('\\n')\n\n return { filename, relPath, markdown }\n}\n\n/** Confined export helper writing a Cockpit replay trace under `/.pantheon/reports/`. */\nexport function writeCockpitReplayArtifact(\n workspaceDir: string,\n snapshot: CockpitSnapshot,\n now: Date = new Date(),\n): string {\n const reportsDir = join(workspaceDir, '.pantheon', 'reports')\n mkdirSync(reportsDir, { recursive: true })\n const canonicalReports = realpathSync(reportsDir)\n const artifact = formatCockpitReplayArtifact(snapshot, now)\n const target = resolve(canonicalReports, artifact.filename)\n const prefix = canonicalReports.endsWith(sep) ? canonicalReports : `${canonicalReports}${sep}`\n if (!target.startsWith(prefix)) {\n throw new Error('Cockpit replay target escaped .pantheon/reports')\n }\n writeFileSync(target, artifact.markdown, 'utf8')\n return artifact.relPath\n}\n","/** Shared, data-only formatting and visual helpers for compact context gauges. */\n\nexport type ContextProgressTone = 'info' | 'success' | 'warning' | 'error'\n\nexport const CONTEXT_BAR_CELLS = 12\nexport const CONTEXT_BAR_FILLED_CELL = '\\u25B0'\nexport const CONTEXT_BAR_EMPTY_CELL = '\\u25B1'\n\nexport type BarShape = 'block' | 'line' | 'smooth' | 'ascii' | 'dots' | 'braille'\n\nexport interface BarShapeGlyphs {\n filled: string\n empty: string\n mark?: string\n}\n\nexport const BAR_SHAPES: Record = {\n block: { filled: '\\u25B0', empty: '\\u25B1', mark: '│' },\n line: { filled: '━', empty: '─', mark: '┼' },\n smooth: { filled: '█', empty: '░', mark: '┆' },\n ascii: { filled: '=', empty: '-', mark: '|' },\n dots: { filled: '●', empty: '○', mark: '│' },\n braille: { filled: '⣿', empty: '⣀', mark: '⡇' },\n}\n\nexport interface ContextBarOptions {\n cells?: number\n shape?: BarShape\n evenMark?: boolean\n}\n\nfunction numberOrNull(value: unknown): number | null {\n return typeof value === 'number' && Number.isFinite(value) ? value : null\n}\n\nexport function contextUsageTone(percent: number): ContextProgressTone {\n if (percent > 90) return 'error'\n if (percent > 50) return 'warning'\n if (percent > 25) return 'success'\n return 'info'\n}\n\nexport function formatTokenCount(tokens: number | null | undefined): string | null {\n const value = numberOrNull(tokens)\n if (value === null || value < 0) return null\n return Math.round(value).toLocaleString('en-US')\n}\n\nexport function formatContextWindow(limit: number | null | undefined): string | null {\n const value = numberOrNull(limit)\n if (value === null || value <= 0) return null\n if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}M`\n if (value >= 1_000) return `${Math.floor(value / 1_000)}K`\n return `${Math.floor(value)}`\n}\n\nexport function contextBarFilled(percent: number, cells = CONTEXT_BAR_CELLS): number {\n const total = Math.max(1, Math.floor(cells))\n const filled = Math.round((percent / 100) * total)\n if (!Number.isFinite(filled)) return 0\n return Math.min(total, Math.max(0, filled))\n}\n\nexport function contextBar(\n percent: number | null | undefined,\n options: number | ContextBarOptions = CONTEXT_BAR_CELLS,\n): { filled: string; empty: string } | null {\n const value = numberOrNull(percent)\n if (value === null) return null\n const total = Math.max(\n 1,\n Math.floor(typeof options === 'number' ? options : (options?.cells ?? CONTEXT_BAR_CELLS)),\n )\n const shapeKey =\n typeof options === 'object' && options?.shape && options.shape in BAR_SHAPES\n ? options.shape\n : 'block'\n const glyphs = BAR_SHAPES[shapeKey] ?? BAR_SHAPES.block\n const evenMark = typeof options === 'object' ? Boolean(options?.evenMark) : false\n\n const filledCount = contextBarFilled(value, total)\n const emptyCount = total - filledCount\n\n if (!evenMark || total < 4) {\n return {\n filled: glyphs.filled.repeat(filledCount),\n empty: glyphs.empty.repeat(emptyCount),\n }\n }\n\n // Insert even-use mark at the midpoint (50%)\n const mid = Math.floor(total / 2)\n const mark = glyphs.mark ?? '|'\n\n if (filledCount <= mid) {\n // Mark is in the empty portion\n const emptyBefore = mid - filledCount\n const emptyAfter = Math.max(0, emptyCount - emptyBefore - 1)\n return {\n filled: glyphs.filled.repeat(filledCount),\n empty: `${glyphs.empty.repeat(emptyBefore)}${mark}${glyphs.empty.repeat(emptyAfter)}`,\n }\n }\n\n // Mark is in the filled portion\n const filledBefore = mid\n const filledAfter = Math.max(0, filledCount - filledBefore - 1)\n return {\n filled: `${glyphs.filled.repeat(filledBefore)}${mark}${glyphs.filled.repeat(filledAfter)}`,\n empty: glyphs.empty.repeat(emptyCount),\n }\n}\n\nexport function formatSpent(cost: number | null | undefined): string | null {\n const value = numberOrNull(cost)\n if (value === null || value < 0) return null\n return `$${value.toFixed(2)}`\n}\n","/** Shared bounds for cached recent model-usage aggregation. */\nexport const MODEL_USAGE_VISIBLE_CEILING = 3\nexport const MODEL_USAGE_MESSAGE_LIMIT = 400\nexport const MODEL_USAGE_SESSION_LIMIT = 8\n","/**\n * autonomy-state.ts — the Autonomy tab of the settings window.\n *\n * TUI-local copy doctrine. Two surfaces live here:\n *\n * 1. GOAL LOOP — the persisted-mission loop (Wave 3 mechanics) read/written\n * to `options.goal_loop` in the user's opencode.json (the same V2 config\n * copy the context pruner uses). Startup-applied: the runtime resolves it\n * once at plugin setup, so saving requires an OpenCode restart — the tab\n * says so.\n *\n * 2. DECISION BUDGETS — monthly/per-decision USD caps stored in\n * decision-router.json's companion `decision-budget` semantics. The caps\n * the CLI writes via setup-model flags; here they are read from the\n * decision-router.json envelope extension `budget` (v2 superset — the\n * exact-key validator tolerates it via the documented envelope) and\n * applied live per gated call.\n *\n * The decision-gradiente (decide-solo → Jev → human) is DOCUMENTED here, not\n * enforced: J1 owns the risk axis, budgets own the money axis — this tab\n * shows where the thresholds sit today.\n */\nimport type { SettingsTab } from './pantheon-settings-state.ts'\n\nexport interface GoalLoopPrefs {\n enabled: boolean\n cooldownMs: number\n maxContinuations: number\n}\n\nexport const DEFAULT_GOAL_LOOP_PREFS: GoalLoopPrefs = {\n enabled: false,\n cooldownMs: 5000,\n maxContinuations: 25,\n}\n\nexport const GOAL_LOOP_ENABLED_CYCLE: readonly string[] = Object.freeze(['enabled', 'disabled'])\n\nexport const MAX_CONTINUATIONS_CYCLE: readonly string[] = Object.freeze([\n '10',\n '25',\n '50',\n '100',\n '200',\n])\n\nexport const COOLDOWN_MS_CYCLE: readonly string[] = Object.freeze(['1000', '2000', '5000', '10000'])\n\nexport interface DecisionBudgets {\n monthlyUsd: number\n perDecisionUsd: number\n}\n\nexport const DEFAULT_DECISION_BUDGETS: DecisionBudgets = {\n monthlyUsd: 5,\n perDecisionUsd: 0.1,\n}\n\n/** Format USD compactly for a cycler cell (\"$5\", \"$0.10\"). */\nexport function formatUsd(value: number): string {\n return `$${value < 1 ? value.toFixed(2) : String(Math.round(value))}`\n}\n\n/** Build the USD step ladder used by the budget cyclers. */\nexport const MONTHLY_USD_CYCLE: readonly string[] = Object.freeze(\n [1, 2, 5, 10, 20, 50, 100].map((value) => formatUsd(value)),\n)\nexport const PER_DECISION_USD_CYCLE: readonly string[] = Object.freeze(\n [0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1].map((value) => formatUsd(value)),\n)\n\n/** Parse a staged USD cell back to a number; junk keeps the input. */\nexport function parseUsd(cell: string): number | null {\n const value = Number(cell.replace('$', ''))\n return Number.isFinite(value) && value > 0 ? value : null\n}\n\nexport function buildAutonomyTab(input: {\n goalLoop: GoalLoopPrefs\n budgets: DecisionBudgets\n goalLoopRestartPending?: boolean | undefined\n languagePref?: string | undefined\n}): SettingsTab {\n const isPt = input.languagePref === 'pt-BR'\n\n return {\n id: 'autonomy',\n title: isPt ? 'Autonomia' : 'Autonomy',\n groups: [\n {\n title: isPt\n ? 'Loop Contínuo (auto-continuação de sessões multi-turn)'\n : 'Auto-Continue Loop (multi-turn session auto-continuation)',\n rows: [\n {\n id: 'autonomy.goal_loop.enabled',\n name: isPt ? 'Loop Contínuo' : 'Auto-Continue Loop',\n value: input.goalLoop.enabled ? 'enabled' : 'disabled',\n cycle: GOAL_LOOP_ENABLED_CYCLE,\n note: isPt\n ? 'continua tarefas multi-turn quando a sessão fica ociosa' +\n (input.goalLoopRestartPending\n ? ' · [!] reinício necessário para aplicar (restart)'\n : ' · aplicado após reiniciar o OpenCode')\n : 'auto-continues multi-turn tasks when session goes idle' +\n (input.goalLoopRestartPending\n ? ' · [!] restart required to apply'\n : ' · applies after OpenCode restart'),\n },\n {\n id: 'autonomy.goal_loop.maxContinuations',\n name: isPt ? 'Limite continuações' : 'Max continuations',\n value: String(input.goalLoop.maxContinuations),\n cycle: MAX_CONTINUATIONS_CYCLE,\n note: isPt\n ? '1..200 — teto de segurança contra loops infinitos'\n : '1..200 — safety ceiling to prevent runaway tasks',\n },\n {\n id: 'autonomy.goal_loop.cooldownMs',\n name: isPt ? 'Pausa entre turnos (ms)' : 'Cooldown (ms)',\n value: String(input.goalLoop.cooldownMs),\n cycle: COOLDOWN_MS_CYCLE,\n note: isPt\n ? 'intervalo entre turnos autônomos (mín 1000ms)'\n : 'delay between autonomous turns (min 1000ms)',\n },\n ],\n },\n {\n title: isPt ? 'Orçamentos de Decisão (Jev)' : 'Decision Budgets (Jev)',\n rows: [\n {\n id: 'autonomy.budget.monthly',\n name: isPt ? 'Teto Mensal (USD)' : 'Monthly Budget Cap',\n value: formatUsd(input.budgets.monthlyUsd),\n cycle: MONTHLY_USD_CYCLE,\n note: isPt\n ? 'teto mensal em USD para arbitragem do Jev'\n : 'monthly USD ceiling for gated arbitrator decisions',\n },\n {\n id: 'autonomy.budget.perDecision',\n name: isPt ? 'Teto por Consulta' : 'Per-Decision Cap',\n value: formatUsd(input.budgets.perDecisionUsd),\n cycle: PER_DECISION_USD_CYCLE,\n note: isPt\n ? 'teto de custo por decisão — acima disso é recusada'\n : 'price cap — gated decisions above this are refused',\n },\n ],\n },\n {\n title: isPt\n ? 'Gradiente de Decisão (política de referência · governado por J1 e Orçamentos)'\n : 'Decision Gradient (reference policy · governed by J1 & Budgets)',\n rows: [\n {\n id: 'autonomy.gradient.solo',\n name: isPt ? 'Decisão solo' : 'Decide solo',\n value: isPt ? 'autônomo' : 'autonomous',\n note: isPt\n ? 'ações rotineiras de baixo risco · reversível sem travas (sem portão)'\n : 'reversible & low-risk edits, routine fixes (no gate)',\n },\n {\n id: 'autonomy.gradient.jev',\n name: isPt ? 'Decisão Jev' : 'Jev decides',\n value: isPt ? 'arbitrado' : 'arbitrated',\n note: isPt\n ? 'ambiguidade de tipos e rotas · configurado nos Tetos de Orçamento acima'\n : 'typed ambiguity & candidate ranking · configured via Budgets above',\n },\n {\n id: 'autonomy.gradient.human',\n name: isPt ? 'Aprovação humana' : 'Human decides',\n value: isPt ? 'revisão humana' : 'human review',\n note: isPt\n ? 'ações destrutivas e de alto risco · configurado no limiar do Portão J1'\n : 'high-risk & destructive operations · configured via J1 Gate',\n },\n ],\n },\n ],\n }\n}\n","/**\n * decision-router-state.ts — the Decision Model section of the settings window.\n *\n * TUI-local replica of the user-level decision-router config\n * (scripts/install/decision-router-config.mjs — the bundle must stay\n * self-contained); tests/tui-decision-router-state.test.mjs pins the schema\n * version, the exact key set and the provider matrix against that source.\n *\n * The runtime re-reads this file on EVERY gated call (jev-decision-tool.ts),\n * so a write here applies live — no restart. The strict exact-key schema is\n * load-bearing: any unknown key fail-closes the runtime to disabled/local,\n * so the writer validates before persisting.\n *\n * Egress consent is CLI-owned: the window never writes `egress_consent`, and\n * refuses to enable the router while remote candidates exist without it.\n */\nimport { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport type { SettingsRow, SettingsTab } from './pantheon-settings-state.ts'\n\nexport const DECISION_ENABLED_CYCLE: readonly string[] = Object.freeze(['enabled', 'disabled'])\n\nexport const DECISION_CONFIG_SCHEMA_VERSION = 2\n\n/** Exact top-level key set — anything else fail-closes the runtime. */\nexport const DECISION_CONFIG_KEYS: readonly string[] = Object.freeze([\n 'egress_consent',\n 'enabled',\n 'enabled_candidates',\n 'schema_version',\n 'selection',\n])\n\nexport type DecisionSelectionMode = 'local' | 'auto' | 'explicit'\n\nexport interface DecisionSelection {\n mode: DecisionSelectionMode\n provider?: string\n model?: string\n}\n\nexport interface DecisionCandidate {\n provider: string\n model: string\n}\n\nexport interface DecisionRouterConfig {\n schema_version: number\n enabled: boolean\n selection: DecisionSelection\n egress_consent: boolean\n enabled_candidates: readonly DecisionCandidate[]\n}\n\nexport const DEFAULT_DECISION_CONFIG: DecisionRouterConfig = Object.freeze({\n schema_version: DECISION_CONFIG_SCHEMA_VERSION,\n enabled: false,\n selection: Object.freeze({ mode: 'local' as const }),\n egress_consent: false,\n enabled_candidates: Object.freeze([]),\n})\n\n/** The runtime's provider→model matrix (drift-pinned against the installer source). */\nexport const DECISION_KNOWN_PROVIDERS: readonly string[] = Object.freeze([\n 'openai-decisions',\n 'typesafe-jev',\n 'opencode-console-jev',\n 'openrouter-jev',\n 'vercel-gateway-jev',\n 'cloudflare-workers-jev',\n])\n\nexport const DECISION_CONSENT_CYCLE: readonly string[] = Object.freeze(['not granted', 'granted'])\n/** provider → model, straight from the runtime matrix (drift-pinned in tests). */\nexport const DECISION_KNOWN_MODELS: Readonly> = Object.freeze({\n 'openai-decisions': 'gpt-6-luna',\n 'typesafe-jev': 'jev-1.14.0',\n 'opencode-console-jev': 'jev-1.13',\n 'openrouter-jev': 'typesafe/jev-1.13',\n 'vercel-gateway-jev': 'typesafe-ai/jev',\n 'cloudflare-workers-jev': 'clef',\n})\n\n/**\n * Credential surface per provider: the ENV VAR the host provider entry reads\n * (`{env:VAR}` indirection — the window NEVER holds key values) plus the setup\n * note. Drift-pinned against the installer/runtime sources in tests.\n */\nexport const DECISION_PROVIDER_CREDENTIALS: Readonly<\n Record\n> = Object.freeze({\n 'openai-decisions': {\n note: 'host-configured model — provision via `decision-router setup-model openai-decisions`',\n notePt: 'modelo do host — configure via `decision-router setup-model openai-decisions`',\n },\n 'typesafe-jev': {\n env: 'TYPESAFE_API_KEY',\n note: 'export TYPESAFE_API_KEY=… then restart',\n notePt: 'export TYPESAFE_API_KEY=… e depois reinicie',\n },\n 'opencode-console-jev': {\n note: 'rides your OpenCode login — no separate key',\n notePt: 'utiliza login do OpenCode — sem chave separada',\n },\n 'openrouter-jev': {\n env: 'OPENROUTER_API_KEY',\n note: 'export OPENROUTER_API_KEY=… then restart',\n notePt: 'export OPENROUTER_API_KEY=… e depois reinicie',\n },\n 'vercel-gateway-jev': {\n env: 'AI_GATEWAY_API_KEY',\n note: 'export AI_GATEWAY_API_KEY=… then restart',\n notePt: 'export AI_GATEWAY_API_KEY=… e depois reinicie',\n },\n 'cloudflare-workers-jev': {\n env: 'CLOUDFLARE_API_TOKEN',\n note: 'needs accountId (setup-model --account-id=…) + CLOUDFLARE_API_TOKEN',\n notePt: 'requer accountId (setup-model --account-id=…) + CLOUDFLARE_API_TOKEN',\n },\n})\n\nexport const DECISION_TARGET_CYCLE: readonly string[] = Object.freeze(\n DECISION_KNOWN_PROVIDERS.map((provider) => `${provider}/${DECISION_KNOWN_MODELS[provider]}`),\n)\n\nexport function decisionRouterConfigPath(env: Record = process.env) {\n const xdg = env.XDG_CONFIG_HOME\n const home = env.HOME ?? ''\n const root = xdg ?? join(home, '.config')\n return join(root, 'pantheon', 'decision-router.json')\n}\n\nexport interface DecisionConfigRead {\n config: DecisionRouterConfig\n /** The file exists but is not a valid v2 config — the runtime fail-closes. */\n corrupt: boolean\n}\n\n/** Fail-open read: a missing file is the default; an invalid one is reported, not guessed. */\nexport function readDecisionRouterConfig(\n env: Record = process.env,\n): DecisionConfigRead {\n let raw: unknown\n try {\n raw = JSON.parse(readFileSync(decisionRouterConfigPath(env), 'utf8'))\n } catch (error) {\n if ((error as NodeJS.ErrnoException)?.code === 'ENOENT') {\n return { config: cloneDefault(), corrupt: false }\n }\n return { config: cloneDefault(), corrupt: true }\n }\n if (isValidDecisionConfig(raw)) return { config: raw, corrupt: false }\n return { config: cloneDefault(), corrupt: true }\n}\n\nfunction cloneDefault(): DecisionRouterConfig {\n return {\n schema_version: DEFAULT_DECISION_CONFIG.schema_version,\n enabled: DEFAULT_DECISION_CONFIG.enabled,\n selection: { ...DEFAULT_DECISION_CONFIG.selection },\n egress_consent: DEFAULT_DECISION_CONFIG.egress_consent,\n enabled_candidates: [...DEFAULT_DECISION_CONFIG.enabled_candidates],\n }\n}\n\n/** The exact-key, exact-shape validation the runtime applies (fail-closed otherwise). */\nexport function isValidDecisionConfig(value: unknown): value is DecisionRouterConfig {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false\n const record = value as Record\n const keys = Object.keys(record).sort()\n if (keys.length !== DECISION_CONFIG_KEYS.length) return false\n for (const key of DECISION_CONFIG_KEYS) {\n if (!keys.includes(key)) return false\n }\n if (record.schema_version !== DECISION_CONFIG_SCHEMA_VERSION) return false\n if (typeof record.enabled !== 'boolean') return false\n if (typeof record.egress_consent !== 'boolean') return false\n if (!isValidSelection(record.selection)) return false\n if (!Array.isArray(record.enabled_candidates)) return false\n for (const candidate of record.enabled_candidates) {\n if (typeof candidate !== 'object' || candidate === null) return false\n const entry = candidate as Record\n if (typeof entry.provider !== 'string' || typeof entry.model !== 'string') return false\n if (Object.keys(entry).length !== 2) return false\n }\n return true\n}\n\nfunction isValidSelection(value: unknown): value is DecisionSelection {\n if (typeof value !== 'object' || value === null) return false\n const selection = value as Record\n if (selection.mode !== 'local' && selection.mode !== 'auto' && selection.mode !== 'explicit') {\n return false\n }\n const keys = Object.keys(selection).sort()\n for (const key of keys) {\n if (key !== 'mode' && key !== 'provider' && key !== 'model') return false\n }\n if (selection.provider !== undefined && typeof selection.provider !== 'string') return false\n if (selection.model !== undefined && typeof selection.model !== 'string') return false\n return true\n}\n\n/** Stable serializer: exact keys in sorted order, 2-space, trailing newline. */\nexport function serializeDecisionConfig(config: DecisionRouterConfig): string {\n const ordered = {\n egress_consent: config.egress_consent,\n enabled: config.enabled,\n enabled_candidates: config.enabled_candidates.map((candidate) => ({\n model: candidate.model,\n provider: candidate.provider,\n })),\n schema_version: config.schema_version,\n selection: {\n mode: config.selection.mode,\n ...(config.selection.model !== undefined ? { model: config.selection.model } : {}),\n ...(config.selection.provider !== undefined ? { provider: config.selection.provider } : {}),\n },\n }\n return `${JSON.stringify(ordered, null, 2)}\\n`\n}\n\n/**\n * Enable/disable the router in a config copy. The guard mirrors the runtime's\n * fail-close: with remote candidates and no egress consent, an enabled flag\n * would be a lie — enabling requires consent, or a local-only selection.\n * Never touches `egress_consent` (CLI-owned).\n */\nexport function setDecisionEnabled(\n config: DecisionRouterConfig,\n enabled: boolean,\n): { ok: true; config: DecisionRouterConfig } | { ok: false; reason: string } {\n if (enabled) {\n const localOnly = config.selection.mode === 'local' || config.enabled_candidates.length === 0\n if (!localOnly && !config.egress_consent) {\n return {\n ok: false,\n reason:\n 'remote candidates need egress consent — toggle Egress consent in this tab, then enable',\n }\n }\n }\n return { ok: true, config: { ...config, enabled } }\n}\n\n/** Atomic-ish write mirroring the canonical writer's privacy posture (0600). */\nexport function writeDecisionRouterConfig(\n config: DecisionRouterConfig,\n env: Record = process.env,\n): void {\n if (!isValidDecisionConfig(config)) {\n throw new TypeError('Refusing to persist an invalid decision-router configuration')\n }\n const path = decisionRouterConfigPath(env)\n mkdirSync(dirname(path), { recursive: true, mode: 0o700 })\n const temp = `${path}.tui.tmp`\n writeFileSync(temp, serializeDecisionConfig(config), { mode: 0o600 })\n renameSync(temp, path)\n chmodSync(path, 0o600)\n}\n\nexport const DECISION_SELECTION_CYCLE: readonly string[] = Object.freeze([\n 'local',\n 'auto',\n 'explicit',\n])\n\n/** Stage a selection/consent row into a config copy; unknown rows are no-ops. */\nexport function applyDecisionRow(\n config: DecisionRouterConfig,\n id: string,\n value: string,\n): DecisionRouterConfig {\n const next: DecisionRouterConfig = {\n ...config,\n selection: { ...config.selection },\n enabled_candidates: [...config.enabled_candidates],\n }\n switch (id) {\n case 'decision.selection.mode': {\n const mode = value as DecisionSelectionMode\n if (mode !== 'local' && mode !== 'auto' && mode !== 'explicit') return config\n next.selection.mode = mode\n if (mode === 'local') next.enabled_candidates = []\n return next\n }\n case 'decision.selection.target': {\n const separator = value.indexOf('/')\n if (separator <= 0) return config\n const provider = value.slice(0, separator)\n const model = value.slice(separator + 1)\n if (!DECISION_KNOWN_PROVIDERS.includes(provider)) return config\n if (DECISION_KNOWN_MODELS[provider] !== model) return config\n next.selection = { mode: 'explicit', provider, model }\n next.enabled_candidates = [{ provider, model }]\n return next\n }\n case 'decision.consent': {\n next.egress_consent = value === 'granted'\n return next\n }\n default:\n return config\n }\n}\n\n/** The host's provider auth store (`opencode auth login` writes here). */\nexport function decisionAuthStorePath(env: Record = process.env) {\n const xdgData = env.XDG_DATA_HOME\n const home = env.HOME ?? ''\n const root = xdgData ?? join(home, '.local', 'share')\n return join(root, 'opencode', 'auth.json')\n}\n\n/** Provider ids as they appear in the host auth store / config providers. */\nconst PROVIDER_AUTH_NAMES: Readonly> = Object.freeze({\n 'openai-decisions': Object.freeze(['openai']),\n 'typesafe-jev': Object.freeze(['typesafe-ai']),\n 'opencode-console-jev': Object.freeze([]),\n 'openrouter-jev': Object.freeze(['openrouter']),\n 'vercel-gateway-jev': Object.freeze(['vercel-ai-gateway', 'vercel']),\n 'cloudflare-workers-jev': Object.freeze(['cloudflare-workers-ai']),\n})\n\nexport type CredentialForm = 'env' | 'auth store' | 'config' | 'missing'\n\n/**\n * TWO recognition forms (field feedback beta.6: keys registered via\n * `opencode auth login` showed MISSING because only env vars were checked):\n * env var set → 'env'; provider present in the host auth store → 'auth\n * store'; provider entry in opencode.json providers → 'config'. Values are\n * NEVER read — existence only.\n */\nexport function credentialStatus(\n provider: string,\n env: Record,\n authProviders: ReadonlySet,\n configProviders: ReadonlySet,\n): CredentialForm {\n const credential = DECISION_PROVIDER_CREDENTIALS[provider]\n if (credential?.env !== undefined && env[credential.env]) return 'env'\n for (const name of PROVIDER_AUTH_NAMES[provider] ?? []) {\n if (authProviders.has(name)) return 'auth store'\n }\n for (const name of PROVIDER_AUTH_NAMES[provider] ?? []) {\n if (configProviders.has(name)) return 'config'\n }\n if (provider === 'opencode-console-jev') return 'auth store'\n return 'missing'\n}\n\nexport function buildDecisionTab(\n read: DecisionConfigRead,\n env: Record = process.env,\n authProviders: ReadonlySet = new Set(),\n configProviders: ReadonlySet = new Set(),\n languagePref?: string | undefined,\n): SettingsTab {\n const isPt = languagePref === 'pt-BR'\n const { config, corrupt } = read\n const rows: SettingsRow[] = [\n {\n id: 'decision.enabled',\n name: isPt ? 'Assistente Jev' : 'Jev Assistant',\n value: config.enabled ? 'enabled' : 'disabled',\n // Corrupt config → read-only; the notice (glue) carries the remedy.\n ...(corrupt ? {} : { cycle: DECISION_ENABLED_CYCLE }),\n note: corrupt\n ? isPt\n ? 'config inválida — runtime fail-closes; repare via `decision-router setup-model`'\n : 'config unreadable/invalid — runtime fail-closes; repair via `decision-router setup-model`'\n : isPt\n ? 'aplica em tempo real — arbitragem de decisões relida a cada chamada'\n : 'applies live — the runtime re-reads this on every gated call',\n },\n {\n id: 'decision.selection.mode',\n name: isPt ? 'Modo de Operação' : 'Operation Mode',\n value: config.selection.mode,\n ...(corrupt ? {} : { cycle: DECISION_SELECTION_CYCLE }),\n note: isPt\n ? 'local = no seu PC (grátis); auto/explícito = modelo nuvem (OpenRouter)'\n : 'local routes on-device; auto/explicit pick a remote decision model',\n },\n ]\n\n // Model selection row: always visible so the user can choose the decision model\n const explicitTarget = config.selection.provider\n ? `${config.selection.provider}/${config.selection.model ?? ''}`\n : (DECISION_TARGET_CYCLE[0] ?? 'openrouter-jev/typesafe/jev-1.13')\n rows.push({\n id: 'decision.selection.target',\n name: isPt ? 'Modelo de Decisão' : 'Decision Model',\n value:\n config.selection.mode === 'local'\n ? config.selection.provider\n ? `${config.selection.provider}/${config.selection.model ?? ''}`\n : 'local (on-device)'\n : explicitTarget,\n ...(corrupt ? {} : { cycle: DECISION_TARGET_CYCLE }),\n note: isPt\n ? config.selection.mode === 'local'\n ? 'ciclar seleciona modelo remoto e ativa modo explícito'\n : 'provedor/modelo ativo — define candidato para arbitragem'\n : config.selection.mode === 'local'\n ? 'cycle to select a remote model and activate explicit mode'\n : 'provider/model — sets the candidate list',\n })\n\n if ((config.enabled_candidates?.length ?? 0) > 0) {\n rows.push({\n id: 'decision.candidates',\n name: isPt ? 'Candidatos ativos' : 'Candidates',\n value: String(config.enabled_candidates.length),\n note: config.egress_consent\n ? config.enabled_candidates\n .map((candidate) => `${candidate.provider}/${candidate.model}`)\n .join(', ')\n : isPt\n ? 'egress consent NÃO concedido — rotas remotas bloqueadas'\n : 'egress consent NOT granted — remote routes fail closed',\n })\n }\n\n rows.push({\n id: 'decision.consent',\n name: isPt ? 'Acesso à Nuvem' : 'Cloud API Access',\n value: config.egress_consent ? 'granted' : 'not granted',\n ...(corrupt ? {} : { cycle: DECISION_CONSENT_CYCLE }),\n note: isPt\n ? config.egress_consent\n ? 'granted = rotas remotas podem consultar gateway de API (com teto de custo)'\n : 'not granted = chamadas remotas bloqueadas; requer granted para nuvem'\n : config.egress_consent\n ? 'granted = remote decision routes may call their gateway (budget-capped)'\n : 'not granted = remote routes fail closed; grant to allow cloud calls',\n })\n\n return {\n id: 'decision',\n title: isPt ? 'Decisão' : 'Decision',\n groups: [\n { title: isPt ? 'Assistente de Decisão (Jev)' : 'Decision Assistant (Jev)', rows },\n {\n title: isPt\n ? 'Credenciais (status apenas — valores nunca gravados na janela)'\n : 'Credentials (status only — values never enter the window)',\n rows: DECISION_KNOWN_PROVIDERS.map((provider) => {\n const status = credentialStatus(provider, env, authProviders, configProviders)\n const credential = DECISION_PROVIDER_CREDENTIALS[provider] ?? { note: '' }\n return {\n id: `decision.key.${provider}`,\n name: provider,\n value: status === 'missing' ? 'MISSING' : status,\n note: isPt ? (credential.notePt ?? credential.note) : credential.note,\n }\n }),\n },\n ],\n }\n}\n","/**\n * pantheon-settings-state.ts — the pure state core of the settings window.\n *\n * TUI-local copy doctrine (same as cost-data.ts): the bundle must stay\n * self-contained. The behaviors registry mirrors routing.yml's `behaviors:`\n * (drift-pinned by tests/pantheon-settings-state.test.mjs).\n *\n * Model (2.0.0-beta.4, the quota-style full window): the window is a set of\n * TABS; each tab holds GROUPS of setting ROWS; a row carries a display VALUE\n * and — when the setting is editable — the CYCLE of allowed values that\n * ←/→ steps through. Edits stage into a DRAFT (id → pending value); `save`\n * applies the draft through injected writers, `reset` drops it. The disk\n * never changes before save.\n */\n\nexport interface SettingsBehavior {\n id: string\n kind: 'install' | 'runtime'\n title: string\n description: string\n}\n\n/** Mirrors routing.yml `behaviors:` — drift-pinned by the registry test. */\nexport const SETTINGS_BEHAVIORS: readonly SettingsBehavior[] = Object.freeze([\n {\n id: 'skill-auto-continue',\n kind: 'install',\n title: 'Auto-continue skill',\n description: 'Continue multi-step todos while keeping safety gates.',\n },\n {\n id: 'skill-tdd-with-agents',\n kind: 'install',\n title: 'TDD with agents skill',\n description: 'RED, GREEN, REFACTOR test-driven implementation.',\n },\n {\n id: 'skill-code-review-checklist',\n kind: 'install',\n title: 'Code review checklist skill',\n description: 'Systematic code review and quality gates.',\n },\n {\n id: 'skill-prompt-refinery',\n kind: 'install',\n title: 'Prompt refinery skill',\n description: 'Vague requests refined — silent adjust, >> full contract.',\n },\n {\n id: 'gate-idle-todo-enforcer',\n kind: 'runtime',\n title: 'Idle todo enforcer',\n description: 'Continues pending todos when a session goes idle.',\n },\n {\n id: 'gate-context-pruner',\n kind: 'runtime',\n title: 'Context pruner',\n description: 'Prunes repeated tool output before summarization.',\n },\n {\n id: 'gate-j1-risk-gate',\n kind: 'runtime',\n title: 'J1 risk gate',\n description: 'High-risk tool calls demand explicit human approval.',\n },\n])\n\nexport interface OverrideEntry {\n action: 'disable' | 'replace'\n content?: string\n reason?: string\n}\n\nexport type EffectiveOverrides = Record\n\n/** Which behaviors the settings window can write (runtime + install skills). */\nexport const SETTINGS_TOGGLABLE_IDS = new Set(SETTINGS_BEHAVIORS.map((b) => b.id))\n\nexport function isBehaviorDisabled(effective: EffectiveOverrides, id: string): boolean {\n return effective[id]?.action === 'disable'\n}\n\nexport const TOGGLE_REASON = 'toggled in /pantheon-settings'\n\n/**\n * Toggle (a targeted write keeps the toggle semantics: a `replace` entry is\n * never destroyed — disabling keeps its `content`, re-enabling restores the\n * replace; a settings-written disable is removed outright, no toggle noise).\n */\nexport function toggledOverrides(\n effective: EffectiveOverrides,\n id: string,\n reason: string = TOGGLE_REASON,\n): EffectiveOverrides {\n const next: EffectiveOverrides = { ...effective }\n const entry = next[id]\n if (entry?.action === 'disable') {\n if (entry.content !== undefined) {\n next[id] =\n entry.reason === reason\n ? { action: 'replace', content: entry.content }\n : {\n action: 'replace',\n content: entry.content,\n ...(entry.reason !== undefined ? { reason: entry.reason } : {}),\n }\n } else {\n delete next[id]\n }\n } else {\n next[id] =\n entry?.content !== undefined\n ? { action: 'disable', reason, content: entry.content }\n : { action: 'disable', reason }\n }\n return next\n}\n\n/** Set an explicit on/off target (the cycler's save path) via the toggle semantics. */\nexport function setOverrideState(\n effective: EffectiveOverrides,\n id: string,\n target: 'enabled' | 'disabled',\n reason: string = TOGGLE_REASON,\n): EffectiveOverrides {\n const disabled = isBehaviorDisabled(effective, id)\n if ((target === 'disabled') === disabled) return effective\n return toggledOverrides(effective, id, reason)\n}\n\nexport function serializeOverrides(effective: EffectiveOverrides): string {\n const ordered: Record = {}\n for (const id of Object.keys(effective).sort()) ordered[id] = effective[id]\n return `${JSON.stringify(ordered, null, 2)}\\n`\n}\n\n// ── Overrides load (global + project files) ────────────────────────────\n\nexport interface OverridesLoad {\n global: EffectiveOverrides\n project: EffectiveOverrides\n /** The GLOBAL file exists but does not parse — writes are refused. */\n corruptGlobal: boolean\n}\n\n/** Merge for DISPLAY only, mirroring the runtime precedence: project wins per id. */\nexport function mergedOverrides(load: OverridesLoad): EffectiveOverrides {\n return { ...load.global, ...load.project }\n}\n\nexport function canWriteOverrides(load: OverridesLoad): boolean {\n return !load.corruptGlobal\n}\n\n// ── Tab / group / row model (the cycler window) ────────────────────────\n\nexport interface SettingsRow {\n id: string\n name: string\n /** Current effective value (display); the staged draft may differ. */\n value: string\n /** Allowed values for ←/→; presence marks the row as editable. */\n cycle?: readonly string[]\n /** The row's DEFAULT value — what the Defaults action stages. */\n def?: string\n /** Right-column note (writes-where, applies-live, from-where). */\n note?: string\n /** Enter triggers this action instead of cycling (e.g. `update-check`). */\n action?: string\n}\n\nexport interface SettingsGroup {\n /** Bold group header; undefined renders rows without a header. */\n title?: string\n rows: SettingsRow[]\n}\n\nexport interface SettingsTab {\n id: string\n title: string\n groups: SettingsGroup[]\n}\n\n/** Neutral tab for out-of-range indexes (noUncheckedIndexedAccess guard). */\nexport const EMPTY_TAB: SettingsTab = { id: 'empty', title: '', groups: [] }\n\n/** Flat, in-order rows of a tab (the up/down navigation space). */\nexport function tabRows(tab: SettingsTab): SettingsRow[] {\n return tab.groups.flatMap((group) => group.rows)\n}\n\nexport function findRow(tab: SettingsTab, id: string): SettingsRow | undefined {\n return tabRows(tab).find((row) => row.id === id)\n}\n\n// ── The cycler ─────────────────────────────────────────────────────────\n\n/** Step through the cycle with wrap-around; non-cyclable rows return the input. */\nexport function cycleValue(value: string, cycle: readonly string[], direction: 1 | -1): string {\n if (cycle.length === 0) return value\n const index = cycle.indexOf(value)\n if (index === -1) return cycle[0] ?? value\n const next = (index + direction + cycle.length) % cycle.length\n return cycle[next] ?? value\n}\n\n// ── The draft (staged edits; the disk never changes before save) ───────\n\nexport type SettingsDraft = Record\n\nexport function stageValue(\n draft: SettingsDraft,\n row: SettingsRow,\n direction: 1 | -1,\n): SettingsDraft {\n if (row.cycle === undefined) return draft\n const current = draft[row.id] ?? row.value\n const staged = cycleValue(current, row.cycle, direction)\n if (staged === row.value) {\n // staged back onto the disk value — drop the entry (no toggle noise)\n if (draft[row.id] === undefined) return draft\n const next = { ...draft }\n delete next[row.id]\n return next\n }\n return { ...draft, [row.id]: staged }\n}\n\n/** Stage an explicit target value for one row (the Defaults action path). */\nexport function stageRowToValue(\n draft: SettingsDraft,\n row: SettingsRow,\n target: string,\n): SettingsDraft {\n if (!row.cycle?.includes(target)) return draft\n if (target === row.value) {\n if (draft[row.id] === undefined) return draft\n const next = { ...draft }\n delete next[row.id]\n return next\n }\n return { ...draft, [row.id]: target }\n}\n\n/**\n * Stage every cyclable row's DEFAULT value of a tab. Rows already at their\n * default have their staged entry dropped; rows staged elsewhere keep it\n * until the Defaults action targets them.\n */\nexport function stageDefaults(draft: SettingsDraft, tab: SettingsTab): SettingsDraft {\n let next = draft\n for (const row of tabRows(tab)) {\n if (row.cycle === undefined || row.def === undefined) continue\n const candidate = next[row.id] ?? row.value\n if (candidate === row.def) {\n if (next[row.id] !== undefined) {\n const copy = { ...next }\n delete copy[row.id]\n next = copy\n }\n continue\n }\n next = stageRowToValue(next, { ...row, value: candidate }, row.def)\n }\n return next\n}\n\n/** Drop every staged entry of one tab (ctrl+r). */\nexport function resetTab(draft: SettingsDraft, tab: SettingsTab): SettingsDraft {\n const ids = new Set(tabRows(tab).map((row) => row.id))\n const next: SettingsDraft = {}\n for (const [id, value] of Object.entries(draft)) {\n if (!ids.has(id)) next[id] = value\n }\n return next\n}\n\nexport function draftCount(draft: SettingsDraft): number {\n return Object.keys(draft).length\n}\n\nexport function draftDirty(draft: SettingsDraft): boolean {\n return draftCount(draft) > 0\n}\n\nexport function tabDirty(draft: SettingsDraft, tab: SettingsTab): boolean {\n return tabRows(tab).some((row) => draft[row.id] !== undefined)\n}\n\n// ── Applying the draft ─────────────────────────────────────────────────\n\nexport interface DraftWriterResult {\n ok: boolean\n reason?: string\n}\n\n/**\n * One callback that dispatches a staged row to its real writer (gates →\n * overrides file, decision → decision-router.json, preset → active-preset).\n *Injected by the glue so the disk never runs in tests.\n */\nexport type DraftWriter = (id: string, value: string) => DraftWriterResult\n\nexport interface AppliedDraft {\n applied: string[]\n failed: { id: string; reason: string }[]\n}\n\n/** Apply every staged entry; failures are collected, never thrown. */\nexport function applyDraft(draft: SettingsDraft, writer: DraftWriter): AppliedDraft {\n const applied: string[] = []\n const failed: AppliedDraft['failed'] = []\n for (const [id, value] of Object.entries(draft)) {\n const result = writer(id, value)\n if (result.ok) applied.push(id)\n else failed.push({ id, reason: result.reason ?? 'write failed' })\n }\n return { applied, failed }\n}\n\n/** The rows that succeeded and are still in the draft (failed ones stay staged). */\nexport function settledDraft(draft: SettingsDraft, applied: readonly string[]): SettingsDraft {\n const next: SettingsDraft = {}\n for (const [id, value] of Object.entries(draft)) {\n if (!applied.includes(id)) next[id] = value\n }\n return next\n}\n\n// ── Gates / About tabs (behavior-native; the other tabs live in their modules) ──\n\nexport const GATES_ENABLED_CYCLE: readonly string[] = Object.freeze(['enabled', 'disabled'])\nexport type OverridesScope = 'global' | 'project'\nexport const OVERRIDES_SCOPE_CYCLE: readonly OverridesScope[] = Object.freeze(['global', 'project'])\n\nexport function buildGatesTab(\n load: OverridesLoad,\n languagePref?: string,\n overridesScope?: OverridesScope,\n): SettingsTab {\n const isPt = languagePref === 'pt-BR'\n const merged = mergedOverrides(load)\n const editingProject = overridesScope === 'project'\n const rowFor = (behavior: SettingsBehavior): SettingsRow => {\n const fromProject = load.project[behavior.id] !== undefined\n const effective = editingProject\n ? isBehaviorDisabled({ ...load.global, ...load.project }, behavior.id)\n : isBehaviorDisabled(load.global, behavior.id)\n const writable = editingProject ? true : !fromProject && canWriteOverrides(load)\n return {\n id: `gate.${behavior.id}`,\n name: fromProject ? `${behavior.title} (${isPt ? 'projeto' : 'project'})` : behavior.title,\n value: (editingProject ? effective : isBehaviorDisabled(merged, behavior.id))\n ? 'disabled'\n : 'enabled',\n ...(writable ? { cycle: GATES_ENABLED_CYCLE } : {}),\n note:\n !editingProject && fromProject\n ? isPt\n ? 'arquivo do projeto tem precedência · edite .pantheon/overrides.json'\n : 'project file wins at runtime — edit .pantheon/overrides.json'\n : editingProject\n ? isPt\n ? 'salva em .pantheon/overrides.json (escopo do projeto)'\n : 'saves to .pantheon/overrides.json (project scope)'\n : behavior.description,\n }\n }\n const install = SETTINGS_BEHAVIORS.filter((behavior) => behavior.kind === 'install')\n const runtime = SETTINGS_BEHAVIORS.filter((behavior) => behavior.kind === 'runtime')\n const groups: SettingsGroup[] = []\n if (overridesScope !== undefined) {\n groups.push({\n title: isPt ? 'Escopo das regras' : 'Rules Scope',\n rows: [\n {\n id: 'gates.scope',\n name: isPt ? 'Escopo de edição' : 'Edit scope',\n value: overridesScope,\n cycle: OVERRIDES_SCOPE_CYCLE,\n note: isPt\n ? 'alterne entre global (~/.config/opencode) e projeto (.pantheon)'\n : 'switch between global (~/.config/opencode) and project (.pantheon)',\n },\n ],\n })\n }\n groups.push(\n { title: isPt ? 'Skills instaladas' : 'Install skills', rows: install.map(rowFor) },\n { title: isPt ? 'Portões de execução' : 'Runtime gates', rows: runtime.map(rowFor) },\n )\n return {\n id: 'gates',\n title: 'Gates',\n groups,\n }\n}\n\nexport interface AboutTabExtra {\n nodeVersion?: string\n platform?: string\n preset?: string | null\n decisionEnabled?: boolean\n j1Mode?: string\n languagePref?: string\n}\n\nexport function buildAboutTab(version: string, extra?: AboutTabExtra): SettingsTab {\n const isPt = extra?.languagePref === 'pt-BR'\n\n const sysRows: SettingsRow[] = [\n {\n id: 'about.version',\n name: isPt ? 'Versão' : 'Version',\n value: `v${version}`,\n note: isPt\n ? 'OpenCode 2.x nativo — contrato V1 descontinuado'\n : 'OpenCode 2.x only — the V1 contract is removed',\n },\n {\n id: 'about.behaviors',\n name: isPt ? 'Comportamentos' : 'Behaviors',\n value: String(SETTINGS_BEHAVIORS.length),\n note: isPt\n ? 'portões e skills de governança registradas'\n : 'registered governance gates and skills',\n },\n ]\n\n if (extra?.nodeVersion) {\n sysRows.push({\n id: 'about.runtime',\n name: 'Runtime Node.js',\n value: `v${extra.nodeVersion}`,\n note: extra.platform ? `${isPt ? 'plataforma' : 'platform'}: ${extra.platform}` : '',\n })\n }\n\n const govRows: SettingsRow[] = [\n {\n id: 'about.preset',\n name: isPt ? 'Predefinição' : 'Active Preset',\n value: extra?.preset ?? 'none',\n note: isPt ? 'modelo global ativo do Pantheon' : 'global model preset active in Pantheon',\n },\n {\n id: 'about.decision',\n name: isPt ? 'Assistente Jev' : 'Decision Router',\n value: extra?.decisionEnabled\n ? isPt\n ? 'ativado'\n : 'enabled'\n : isPt\n ? 'desativado'\n : 'disabled',\n note: isPt ? 'arbitragem de modelos e candidatos' : 'model and candidate arbitration',\n },\n {\n id: 'about.j1',\n name: isPt ? 'Portão J1' : 'J1 Risk Gate',\n value: extra?.j1Mode ?? 'shadow',\n note: isPt\n ? 'portão de risco de segurança operacional'\n : 'operational safety risk score gate',\n },\n ]\n\n const refRows: SettingsRow[] = [\n {\n id: 'about.license',\n name: isPt ? 'Licença' : 'License',\n value: 'MIT',\n note: 'Open source · Pantheon Project',\n },\n {\n id: 'about.repo',\n name: isPt ? 'Repositório' : 'Repository',\n value: 'ils15/pantheon-opencode',\n note: 'github.com/ils15/pantheon-opencode',\n },\n ]\n\n const toolRows: SettingsRow[] = [\n {\n id: 'about.tools.memory',\n name: isPt ? 'Memória FTS5' : 'FTS5 Memory',\n value: isPt ? 'ativo · 6 tools' : 'active · 6 tools',\n note: 'memory_store, memory_recall, memory_search, memory_forget, memory_list, memory_stats',\n },\n {\n id: 'about.tools.persistence',\n name: isPt ? 'Checkpoints & Metas' : 'Checkpoints & Goals',\n value: isPt ? 'ativo · 6 tools' : 'active · 6 tools',\n note: 'context_save, context_get, goal_create, goal_get, goal_update, goal_done',\n },\n {\n id: 'about.tools.codemap',\n name: isPt ? 'Codemap & AST' : 'Codemap & AST',\n value: isPt ? 'ativo · 5 tools' : 'active · 5 tools',\n note: 'code_index, code_query, code_neighbors, ast_search, ast_rewrite',\n },\n {\n id: 'about.tools.edit',\n name: isPt ? 'Edição & Execução' : 'Edit & Execution',\n value: isPt ? 'ativo · 4 tools' : 'active · 4 tools',\n note: 'hashline_edit, shell, todowrite, todoread',\n },\n {\n id: 'about.tools.governance',\n name: isPt ? 'Orquestração & Custos' : 'Orchestration & Cost',\n value: isPt ? 'ativo · 9 tools' : 'active · 9 tools',\n note: 'pantheon_cost, pantheon_model, pantheon_skill_search, pantheon_deepwork, pantheon_step_ledger, pantheon_agent_forge, pantheon_local_decision, pantheon_review_verdict, pantheon_worktree',\n },\n ]\n\n const groups = [{ title: isPt ? 'Sistema & Plataforma' : 'System & Platform', rows: sysRows }]\n if (extra?.preset !== undefined || extra?.decisionEnabled !== undefined) {\n groups.push({ title: isPt ? 'Governança & Roteamento' : 'Governance & Routing', rows: govRows })\n }\n groups.push({ title: isPt ? 'Projeto & Referências' : 'Project & References', rows: refRows })\n groups.push({\n title: isPt ? 'Ferramentas Nativas (30)' : 'Native Tools (30)',\n rows: toolRows,\n })\n\n return {\n id: 'about',\n title: isPt ? 'Sobre' : 'About',\n groups,\n }\n}\n\nexport interface ChangelogHighlightItem {\n title: string\n detail: string\n group?: string | undefined\n}\n\nexport function buildChangelogTab(\n version: string,\n items: ChangelogHighlightItem[] = [],\n languagePref?: string | undefined,\n): SettingsTab {\n const isPt = languagePref === 'pt-BR'\n\n const rows: SettingsRow[] = []\n if (items.length > 0) {\n items.forEach((item, index) => {\n rows.push({\n id: `changelog.item.${index + 1}`,\n name: item.title.slice(0, 26),\n value: '',\n note: item.detail,\n })\n })\n } else {\n rows.push({\n id: 'changelog.info',\n name: isPt ? 'Versão' : 'Release',\n value: `v${version}`,\n note: isPt\n ? 'veja o histórico completo no CHANGELOG.md ou no GitHub'\n : 'view full history in CHANGELOG.md or GitHub releases',\n })\n }\n\n return {\n id: 'changelog',\n title: isPt ? 'Changelog' : 'Changelog',\n groups: [\n {\n title: isPt ? `Novidades na versão v${version}` : `What's New in v${version}`,\n rows,\n },\n {\n title: isPt ? 'Referências de Versão' : 'Release References',\n rows: [\n {\n id: 'changelog.docs',\n name: isPt ? 'Documentação' : 'Documentation',\n value: 'CHANGELOG.md',\n note: isPt\n ? 'incluído na raiz do plugin e do repositório'\n : 'shipped at plugin root and repository root',\n },\n {\n id: 'changelog.repo',\n name: isPt ? 'Repositório GitHub' : 'GitHub Repository',\n value: 'ils15/pantheon-opencode',\n note: isPt\n ? 'versões, pull requests e discussões'\n : 'releases, pull requests and discussion',\n },\n ],\n },\n ],\n }\n}\n","/**\n * Update notifier core (TUI-local copy — the bundle must stay self-contained,\n * same precedent as cost-data.ts/model-pricing.ts).\n *\n * Pin + notify, never silent auto-update: one notice per newer version,\n * TTL-cached, offline-safe, and a stable install is never advertised a beta\n * (the update guard owns that crossing). docs/design/2.0-settings-and-install.md\n */\n\nexport const UPDATE_CHECK_TTL_MS = 6 * 60 * 60 * 1000\n\nexport interface UpdateCheckState {\n /** Last version a notice was surfaced for (no repeats per version). */\n lastNotifiedVersion?: string\n /** Last version seen on the registry (persisted across TTL restarts). */\n lastKnownLatestVersion?: string\n /** Last time the registry was queried, for the TTL. */\n lastCheckMs?: number\n}\n\nexport interface UpdateNoticeInput {\n currentVersion: string\n latestVersion: string\n state?: UpdateCheckState\n nowMs?: number\n ttlMs?: number\n isPt?: boolean\n}\n\nexport interface UpdateNotice {\n version: string\n message: string\n}\n\nconst isBetaOrRc = (version: string) => /-(?:beta|rc)\\.\\d+$/.test(String(version).trim())\n\n/** True when `latestVersion` is strictly newer and compatible with `currentVersion` channel. */\nexport function isNewerUpdateAvailable(currentVersion: string, latestVersion: string): boolean {\n const current = String(currentVersion).trim()\n const latest = String(latestVersion).trim()\n if (!current || !latest) return false\n // A stable install is never advertised a prerelease: explicit opt-in owns that crossing.\n if (!isBetaOrRc(current) && isBetaOrRc(latest)) return false\n return comparePantheonVersions(latest, current) > 0\n}\n\n/** Package specifier matching the running release line (`@beta` on prereleases). */\nexport function packageSpecForVersion(version: string): string {\n return isBetaOrRc(version) ? 'pantheon-opencode@beta' : 'pantheon-opencode'\n}\n\n/** Format a bilingual toast title + message for a newly discovered update. */\nexport function formatUpdateToast(\n currentVersion: string,\n latestVersion: string,\n isPt = false,\n): { title: string; message: string } {\n const spec = packageSpecForVersion(currentVersion)\n if (isPt) {\n return {\n title: `Pantheon v${latestVersion} disponível`,\n message: `Atualize em /pantheon-settings (Atualizações) ou \\`opencode plugin update ${spec}\\``,\n }\n }\n return {\n title: `Pantheon v${latestVersion} available`,\n message: `Update in /pantheon-settings (Updates) or \\`opencode plugin update ${spec}\\``,\n }\n}\n\n/** Compact persistent badge rendered in Home footer and Sidebar header when an update exists. */\nexport function formatUpdateBadge(\n currentVersion: string,\n latestVersion: string | null | undefined,\n options: { isPt?: boolean; compact?: boolean } = {},\n): string | null {\n if (!latestVersion || !isNewerUpdateAvailable(currentVersion, latestVersion)) return null\n const version = latestVersion.trim().replace(/^v/i, '')\n if (options.compact) return `↑ v${version} (/pantheon-settings)`\n return options.isPt\n ? `↑ v${version} disponível · /pantheon-settings`\n : `↑ v${version} available · /pantheon-settings`\n}\n\n/** Resolve cached newer version from persisted check state (no network call needed). */\nexport function resolveCachedAvailableUpdate(\n currentVersion: string,\n state: UpdateCheckState | undefined,\n): string | null {\n if (!state) return null\n const candidate = state.lastKnownLatestVersion ?? state.lastNotifiedVersion\n if (!candidate) return null\n return isNewerUpdateAvailable(currentVersion, candidate) ? candidate : null\n}\n\n/** Stamp `lastKnownLatestVersion` onto an `UpdateCheckState` without altering TTL/notice fields. */\nexport function withKnownLatest(\n state: UpdateCheckState,\n latestVersion: string | null,\n): UpdateCheckState {\n if (!latestVersion) return state\n return { ...state, lastKnownLatestVersion: latestVersion }\n}\n\nlet availableUpdateState: string | null = null\nconst availableUpdateListeners = new Set<(version: string | null) => void>()\n\nexport function getAvailableUpdateVersion(): string | null {\n return availableUpdateState\n}\n\nexport function setAvailableUpdateVersion(version: string | null): void {\n const normalized = version && version.trim() !== '' ? version.trim() : null\n if (normalized === availableUpdateState) return\n availableUpdateState = normalized\n for (const listener of availableUpdateListeners) {\n try {\n listener(availableUpdateState)\n } catch {}\n }\n}\n\nexport function subscribeAvailableUpdate(listener: (version: string | null) => void): () => void {\n availableUpdateListeners.add(listener)\n return () => {\n availableUpdateListeners.delete(listener)\n }\n}\n\n/** Semver-ish compare for X.Y.Z[-(beta|rc).N]; prereleases sort before their release. */\nexport function comparePantheonVersions(left: string, right: string): number {\n const parse = (version: string) => {\n const match = String(version)\n .trim()\n .match(/^(\\d+)\\.(\\d+)\\.(\\d+)(?:-(beta|rc)\\.(\\d+))?$/)\n if (!match) return null\n const [, major = '', minor = '', patch = '', stage = '', stageNum = ''] = match\n const stageRank = stage === 'beta' ? 1 : stage === 'rc' ? 2 : 3\n return {\n core: [+major, +minor, +patch] as [number, number, number],\n stageRank,\n stageNum: stage !== '' ? +stageNum : Number.POSITIVE_INFINITY,\n }\n }\n const a = parse(left)\n const b = parse(right)\n if (!a || !b) return 0\n const [aMajor, aMinor, aPatch] = a.core\n const [bMajor, bMinor, bPatch] = b.core\n if (aMajor !== bMajor) return aMajor - bMajor\n if (aMinor !== bMinor) return aMinor - bMinor\n if (aPatch !== bPatch) return aPatch - bPatch\n if (a.stageRank !== b.stageRank) return a.stageRank - b.stageRank\n return a.stageNum - b.stageNum\n}\n\nexport function pickUpdateNotice(input: UpdateNoticeInput): UpdateNotice | null {\n const { currentVersion, latestVersion, state = {}, nowMs = Date.now(), isPt = false } = input\n const ttlMs = input.ttlMs ?? UPDATE_CHECK_TTL_MS\n\n const lastCheck = state.lastCheckMs ?? 0\n if (nowMs - lastCheck < ttlMs) return null\n if (state.lastNotifiedVersion === latestVersion) return null\n if (!isNewerUpdateAvailable(currentVersion, latestVersion)) return null\n\n return {\n version: latestVersion,\n message: formatUpdateToast(currentVersion, latestVersion, isPt).message,\n }\n}\n\n/** The state to persist after a check (notified or not) for the TTL. */\nexport function nextCheckState(\n previous: UpdateCheckState,\n notice: UpdateNotice | null,\n nowMs: number,\n): UpdateCheckState {\n const lastNotifiedVersion = notice?.version ?? previous.lastNotifiedVersion\n return {\n lastCheckMs: nowMs,\n ...(lastNotifiedVersion !== undefined ? { lastNotifiedVersion } : {}),\n }\n}\n","/**\n * doctor-state.ts — the Doctor section of the settings window (read-only).\n *\n * TUI-local replica (the bundle must stay self-contained — the installed copy\n * physically lacks the repo tree, so doctor.mjs itself is unreachable). Only\n * the FILE-DERIVABLE checks are mirrored here; everything that spawns\n * processes, reads the network, or writes (MCP smoke, python validators, git,\n * venv pins, --fix quarantines) stays in the CLI and the section says so.\n *\n * The install-state path mirrors doctor's checkInstallVersionDrift\n * (`/opencode/.pantheon/install-state.json`); the Node floor is\n * drift-pinned against scripts/node-engine-policy.mjs by\n * tests/tui-doctor-state.test.mjs.\n */\nimport { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { readDecisionRouterConfig } from './decision-router-state.ts'\nimport type { OverridesLoad } from './pantheon-settings-state.ts'\nimport {\n SETTINGS_BEHAVIORS,\n type SettingsRow,\n type SettingsTab,\n} from './pantheon-settings-state.ts'\nimport { comparePantheonVersions } from './update-notice.ts'\n\n/** Drift-pinned against scripts/node-engine-policy.mjs MIN_SUPPORTED_NODE_VERSION. */\nexport const MIN_SUPPORTED_NODE_VERSION = '26.4.0'\n\nexport function opencodePantheonDir(env: Record = process.env) {\n const xdg = env.XDG_CONFIG_HOME\n const home = env.HOME ?? ''\n const root = xdg ?? join(home, '.config')\n return join(root, 'opencode', '.pantheon')\n}\n\nexport interface InstallVersionHealth {\n status: 'ok' | 'older' | 'newer' | 'unknown'\n installed: string | null\n}\n\n/**\n * H2: the installed package version (install-state) vs the running one.\n * Fail-open: a missing/unreadable state file means \"unknown\", not a failure —\n * pre-2.0 installs may not have one.\n */\nexport function classifyInstallVersion(\n runningVersion: string,\n env: Record = process.env,\n): InstallVersionHealth {\n let installed: string | null = null\n try {\n const path = join(opencodePantheonDir(env), 'install-state.json')\n const raw = JSON.parse(readFileSync(path, 'utf8')) as { pantheon_version?: unknown }\n if (typeof raw?.pantheon_version === 'string' && raw.pantheon_version !== '') {\n installed = raw.pantheon_version\n }\n } catch {\n installed = null\n }\n if (installed === null) return { status: 'unknown', installed: null }\n const compared = comparePantheonVersions(installed, runningVersion)\n if (compared === 0) return { status: 'ok', installed }\n return { status: compared < 0 ? 'older' : 'newer', installed }\n}\n\nexport function isSupportedNodeFloor(version: string): boolean {\n // Same shape as the canonical parser: a prerelease is outside the floor.\n const match = /^v?(\\d+)\\.(\\d+)\\.(\\d+)(?:-([^+]+))?(?:\\+([\\w.-]+))?$/.exec(String(version))\n const minimum = /^v?(\\d+)\\.(\\d+)\\.(\\d+)/.exec(MIN_SUPPORTED_NODE_VERSION)\n if (!match || !minimum) return false\n const [, major = '', minor = '', patch = '', prerelease = ''] = match\n if (prerelease !== '') return false\n const [, minMajor = '0', minMinor = '0', minPatch = '0'] = minimum\n const currentParts = [+major, +minor, +patch]\n const minimumParts = [+minMajor, +minMinor, +minPatch]\n for (let index = 0; index < 3; index += 1) {\n const currentPart = currentParts[index] ?? 0\n const minimumPart = minimumParts[index] ?? 0\n if (currentPart !== minimumPart) return currentPart > minimumPart\n }\n return true\n}\n\nexport interface OverridesHealth {\n status: 'clean' | 'unknown-ids' | 'corrupt'\n unknownIds: string[]\n}\n\n/** K: validate both overrides files against the window's registry. */\nexport function classifyOverridesHealth(load: OverridesLoad): OverridesHealth {\n if (load.corruptGlobal) return { status: 'corrupt', unknownIds: [] }\n const known = new Set(SETTINGS_BEHAVIORS.map((behavior) => behavior.id))\n const unknownIds = Object.keys({ ...load.global, ...load.project }).filter((id) => !known.has(id))\n return { status: unknownIds.length > 0 ? 'unknown-ids' : 'clean', unknownIds }\n}\n\nexport interface DecisionConfigHealth {\n status: 'ok' | 'corrupt' | 'absent'\n}\n\nexport function classifyDecisionConfigHealth(\n env: Record = process.env,\n): DecisionConfigHealth {\n if (\n !existsSync(\n join(\n env.XDG_CONFIG_HOME ?? join(env.HOME ?? '', '.config'),\n 'pantheon',\n 'decision-router.json',\n ),\n )\n ) {\n return { status: 'absent' }\n }\n return readDecisionRouterConfig(env).corrupt ? { status: 'corrupt' } : { status: 'ok' }\n}\n\nexport interface DoctorSectionInput {\n runningVersion: string\n nodeVersion: string\n load: OverridesLoad\n env?: Record\n}\n\nexport function buildDoctorTab(input: DoctorSectionInput): SettingsTab {\n const env = input.env ?? process.env\n const rows: SettingsRow[] = []\n\n const version = classifyInstallVersion(input.runningVersion, env)\n rows.push({\n id: 'doctor.version',\n name: 'Install version',\n value:\n version.status === 'ok'\n ? `v${version.installed} — matches`\n : version.status === 'older'\n ? `v${version.installed} older`\n : version.status === 'newer'\n ? `v${version.installed} newer`\n : 'unknown',\n note:\n version.status === 'older'\n ? 'refresh with `pantheon-opencode update`'\n : 'read from /opencode/.pantheon/install-state.json',\n })\n\n const nodeOk = isSupportedNodeFloor(input.nodeVersion)\n rows.push({\n id: 'doctor.node',\n name: 'Node runtime',\n value: input.nodeVersion.replace(/^v/, ''),\n note: nodeOk\n ? `meets the >= ${MIN_SUPPORTED_NODE_VERSION} floor`\n : `below the >= ${MIN_SUPPORTED_NODE_VERSION} floor — tooling may refuse`,\n })\n\n const overrides = classifyOverridesHealth(input.load)\n rows.push({\n id: 'doctor.overrides',\n name: 'Overrides',\n value:\n overrides.status === 'clean'\n ? 'valid'\n : overrides.status === 'corrupt'\n ? 'unreadable'\n : `${overrides.unknownIds.length} unknown id(s)`,\n note:\n overrides.status === 'unknown-ids'\n ? `${overrides.unknownIds.join(', ')} — harmless; repair with doctor --fix`\n : overrides.status === 'corrupt'\n ? 'writes are refused until repaired (doctor --fix)'\n : 'both files parse against the behavior registry',\n })\n\n const decision = classifyDecisionConfigHealth(env)\n rows.push({\n id: 'doctor.decision',\n name: 'Decision config',\n value:\n decision.status === 'ok' ? 'valid' : decision.status === 'corrupt' ? 'corrupt' : 'absent',\n note:\n decision.status === 'corrupt'\n ? 'runtime fail-closes to disabled · read from /pantheon/decision-router.json'\n : 'read from /pantheon/decision-router.json',\n })\n\n return {\n id: 'doctor',\n title: 'Doctor',\n groups: [\n {\n title: 'Health (file-derived)',\n rows,\n },\n {\n rows: [\n {\n id: 'doctor.cli',\n name: 'Full check',\n value: '`pantheon-opencode doctor`',\n note: 'MCP smoke, venv pins, git stay in the CLI',\n },\n ],\n },\n ],\n }\n}\n","/**\n * j1-gate-status.ts — the J1 Risk Gate section of the settings window.\n *\n * TUI-local replica of the ladder in src/pantheon/jev-risk-gate.ts (the\n * bundle must stay self-contained); tests/tui-settings-j1.test.mjs pins the\n * env names, the ladder values and the default threshold against that source.\n *\n * STATUS ONLY by design: the ladder has no file surface yet — mode and\n * threshold are env-only and read once at plugin setup — so nothing here\n * writes, and the section says so. A file surface is a runtime-plugin change\n * (beta.3 candidate), not a window change.\n */\nimport type { SettingsTab } from './pantheon-settings-state.ts'\nimport { resolveLanguage } from './settings-i18n.ts'\n\nexport const J1_FLAG_ENV = 'PANTHEON_J1_RISK_SCORE'\nexport const J1_THRESHOLD_ENV = 'PANTHEON_J1_ENFORCE_THRESHOLD'\nexport const J1_THRESHOLD_DEFAULT = 0.8\n\nexport type J1Mode = 'off' | 'shadow' | 'warn' | 'enforce'\n\n/** `1`/`on`/`true` map to `shadow` for back-compatibility with the shipped setup. */\nconst FLAG_ON = new Set(['1', 'on', 'true', 'shadow'])\n\nexport function j1ModeFromEnv(env: Record = process.env): J1Mode {\n const raw = (env[J1_FLAG_ENV] ?? '').trim().toLowerCase()\n if (raw === 'enforce') return 'enforce'\n if (raw === 'warn') return 'warn'\n return FLAG_ON.has(raw) ? 'shadow' : 'off'\n}\n\n/** Invalid or out-of-range values fall back to the default — a typo must not disable the gate. */\nexport function j1ThresholdFromEnv(env: Record = process.env): number {\n const text = (env[J1_THRESHOLD_ENV] ?? '').trim()\n if (text === '') return J1_THRESHOLD_DEFAULT\n const raw = Number(text)\n if (!Number.isFinite(raw) || raw < 0 || raw > 1) return J1_THRESHOLD_DEFAULT\n return raw\n}\n\nconst MODE_DESCRIPTION_EN: Record = {\n off: 'nothing fires (hard zero)',\n shadow: 'observe + record; invisible in the session',\n warn: 'RESERVED — behaves as shadow in this release',\n enforce: 'high-risk scores DENY the tool call (fail-open on gate unavailability)',\n}\n\nconst MODE_DESCRIPTION_PT: Record = {\n off: 'desativado (hard zero)',\n shadow: 'observa + registra telemetria (modo silencioso)',\n warn: 'RESERVADO (RESERVED) — comporta-se como shadow nesta versão',\n enforce: 'alto risco bloqueia a ferramenta (fail-open se indisponível)',\n}\n\nexport function buildJ1Tab(\n env: Record,\n disabledByOverride: boolean,\n languagePref?: string | undefined,\n): SettingsTab {\n const lang = resolveLanguage(languagePref)\n const isPt = lang === 'pt-BR'\n const mode = j1ModeFromEnv(env)\n const threshold = j1ThresholdFromEnv(env)\n const gateState = disabledByOverride\n ? 'disabled via overrides'\n : mode === 'off'\n ? 'off (env unset)'\n : 'active'\n const desc = isPt ? MODE_DESCRIPTION_PT[mode] : MODE_DESCRIPTION_EN[mode]\n\n return {\n id: 'j1',\n title: isPt ? 'Segurança J1' : 'J1 Safety',\n groups: [\n {\n title: isPt ? 'Portão de Segurança (J1)' : 'Safety Risk Gate (J1)',\n rows: [\n {\n id: 'j1.mode',\n name: isPt ? 'Modo de Operação' : 'Operation Mode',\n value: mode,\n note: `${desc} · ${isPt ? 'reinício necessário (restart applies)' : 'restart applies'}`,\n },\n {\n id: 'j1.threshold',\n name: isPt ? 'Limiar de bloqueio' : 'Enforce threshold',\n value: String(threshold),\n note: isPt\n ? 'bloqueia em ou acima · 0..1 · padrão 0.8'\n : 'deny at or above · 0..1 · default 0.8',\n },\n {\n id: 'j1.gate',\n name: isPt ? 'Portão de Segurança' : 'Safety Risk Gate',\n value: gateState,\n note: `${J1_FLAG_ENV} / ${J1_THRESHOLD_ENV} · ${isPt ? 'lido na inicialização' : 'read once at startup'}`,\n },\n ],\n },\n ],\n }\n}\n","/**\n * legacy-audit.ts — Self-contained Legacy & Drift Auditor for the TUI Settings panel.\n *\n * Scans global (~/.config/opencode) and workspace () scopes for:\n * - Dead V1 hooks/files (pantheon-hooks.*, tiers.json, fastembed_cache, .migration-checkpoint)\n * - Unmigrated legacy stores (memory.db, persistence/{global,project}.db, goals.json)\n * - Redundant copied canonical Pantheon assets shadowed by native plugin transforms\n * - Drifted copied TUI plugins (plugins/pantheon-tui version != running plugin version)\n * - Old configuration backup sidecars (opencode.json.bak*, active-preset.json.bak*)\n *\n * Always migrates unmigrated legacy context/memory/goals BEFORE deleting obsolete stores,\n * and NEVER touches user-created custom agents or custom user skills.\n */\n\nimport {\n existsSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n realpathSync,\n rmSync,\n statSync,\n writeFileSync,\n} from 'node:fs'\nimport { dirname, join, resolve } from 'node:path'\nimport { DatabaseSync } from 'node:sqlite'\n\nexport type LegacyScope = 'global' | 'project'\nexport type LegacyCategory =\n | 'legacyStore'\n | 'hooks'\n | 'v1Obsolete'\n | 'backup'\n | 'redundantAsset'\n | 'drift'\n\nexport interface LegacyAuditItem {\n readonly path: string\n readonly scope: LegacyScope\n readonly category: LegacyCategory\n readonly reason: string\n readonly bytes: number\n}\n\nexport interface LegacyAuditSummary {\n readonly total: number\n readonly totalBytes: number\n readonly unmigratedStores: number\n readonly byScope: Record\n readonly byCategory: Record\n}\n\nexport interface LegacyAuditScan {\n readonly items: LegacyAuditItem[]\n readonly summary: LegacyAuditSummary\n}\n\nexport interface LegacyCleanResult {\n readonly removed: string[]\n readonly reclaimedBytes: number\n readonly migratedRecords: number\n readonly errors: Array<{ readonly path: string; readonly reason: string }>\n}\n\nexport interface LegacyAuditOptions {\n readonly workspaceDir?: string\n readonly globalConfigDir?: string\n readonly cacheDir?: string\n readonly runningVersion?: string\n readonly activeBundlePath?: string\n readonly includeRedundantCopiedAssets?: boolean\n readonly env?: Record\n}\n\nconst SAFE_SEGMENT_RE = /^[a-zA-Z0-9._:-]{1,128}$/\n\nconst CANONICAL_AGENT_MD_FILES: readonly string[] = Object.freeze([\n 'aphrodite.md',\n 'apollo.md',\n 'artemis.md',\n 'athena.md',\n 'demeter.md',\n 'gaia.md',\n 'hephaestus.md',\n 'hermes.md',\n 'iris.md',\n 'mnemosyne.md',\n 'nyx.md',\n 'prometheus.md',\n 'talos.md',\n 'themis.md',\n 'zeus.md',\n])\n\nconst CANONICAL_COMMAND_MD_FILES: readonly string[] = Object.freeze([\n 'pantheon.md',\n 'pantheon-audit.md',\n 'pantheon-deepwork.md',\n 'pantheon-focus.md',\n 'pantheon-model.md',\n 'pantheon-optimize.md',\n 'pantheon-settings.md',\n 'pantheon-vision.md',\n])\n\nconst CANONICAL_SKILL_IDS: readonly string[] = Object.freeze([\n 'agent-coordination',\n 'agent-forge',\n 'artifact-management',\n 'auto-continue',\n 'clonedeps',\n 'code-review-checklist',\n 'codemap',\n 'context-compression',\n 'fast-path-execution',\n 'git-workflow-and-versioning',\n 'incremental-implementation',\n 'instruction-forge',\n 'loop-engineering',\n 'memory-bank',\n 'prompt-refinery',\n 'reflect',\n 'security-hardening',\n 'session-goal',\n 'simplify',\n 'spec-driven-development',\n 'tdd-with-agents',\n 'test-slicing',\n 'verification-planning',\n 'visual-review-pipeline',\n 'worktrees',\n])\n\nconst LEGACY_INSTRUCTION_FILES: readonly string[] = Object.freeze([\n 'zeus-execution-rules.instructions.md',\n 'zeus-orchestration.instructions.md',\n 'zeus-workflow.instructions.md',\n])\n\nexport function resolveAuditCacheDir(\n env: Record = process.env,\n): string | undefined {\n if (env.NODE_TEST_CONTEXT) return undefined\n if (env.XDG_CACHE_HOME?.trim()) return join(resolve(env.XDG_CACHE_HOME.trim()), 'opencode', 'npm')\n const home = env.HOME?.trim()\n return home ? join(resolve(home), '.cache', 'opencode', 'npm') : undefined\n}\n\nfunction readCachedPackageVersion(candidateDir: string): string | null {\n for (const manifest of [\n join(candidateDir, 'node_modules', 'pantheon-opencode', 'package.json'),\n join(candidateDir, 'package.json'),\n ]) {\n try {\n if (!existsSync(manifest)) continue\n const parsed = JSON.parse(readFileSync(manifest, 'utf8')) as { version?: unknown }\n if (typeof parsed.version === 'string' && parsed.version.trim() !== '') {\n return parsed.version.trim()\n }\n } catch {\n /* ignore */\n }\n }\n return null\n}\n\nfunction isUnderPath(parentDir: string, targetPath: string): boolean {\n try {\n const parentReal = realpathSync(parentDir)\n const targetReal = realpathSync(targetPath)\n return targetReal === parentReal || targetReal.startsWith(`${parentReal}/`)\n } catch {\n return false\n }\n}\n\nfunction collectCacheAudit(cacheNpmDir: string, options: LegacyAuditOptions): LegacyAuditItem[] {\n const items: LegacyAuditItem[] = []\n if (!existsSync(cacheNpmDir) || cacheNpmDir === '/') return items\n\n const activeBundlePath = options.activeBundlePath ?? ''\n const runningVersion = options.runningVersion ? String(options.runningVersion).trim() : ''\n const runningIsStable = runningVersion !== '' && !/-(?:beta|rc)\\./i.test(runningVersion)\n const seen = new Set()\n\n const pushCacheItem = (targetPath: string, reason: string) => {\n const resolved = resolve(targetPath)\n if (seen.has(resolved) || !existsSync(resolved)) return\n if (activeBundlePath && isUnderPath(resolved, activeBundlePath)) return\n seen.add(resolved)\n items.push({\n path: resolved,\n scope: 'global',\n category: 'drift',\n reason,\n bytes: measurePathBytes(resolved),\n })\n }\n\n let channelEntries: Array<{ name: string; isDirectory: () => boolean }> = []\n try {\n channelEntries = readdirSync(cacheNpmDir, { withFileTypes: true })\n } catch {\n return items\n }\n\n for (const entry of channelEntries) {\n if (!entry.isDirectory()) continue\n if (entry.name !== 'pantheon-opencode' && !entry.name.startsWith('pantheon-opencode@')) {\n continue\n }\n const channelDir = join(cacheNpmDir, entry.name)\n\n // Flag coexisting @beta channel cache once user runs a stable install.\n if (runningIsStable && entry.name === 'pantheon-opencode@beta') {\n pushCacheItem(channelDir, 'Stale @beta plugin cache coexisting with stable install')\n continue\n }\n\n // Keep only the active (or newest) timestamp/version revision inside a channel directory.\n try {\n const revisions = readdirSync(channelDir, { withFileTypes: true })\n .filter(\n (sub) => sub.isDirectory() && sub.name !== 'node_modules' && !sub.name.startsWith('.'),\n )\n .map((sub) => {\n const full = join(channelDir, sub.name)\n let mtime = 0\n try {\n mtime = statSync(full).mtimeMs\n } catch {}\n return {\n path: full,\n mtime,\n active: Boolean(activeBundlePath && isUnderPath(full, activeBundlePath)),\n }\n })\n if (revisions.length > 1) {\n revisions.sort((a, b) => Number(b.active) - Number(a.active) || b.mtime - a.mtime)\n for (const stale of revisions.slice(1)) {\n const ver = readCachedPackageVersion(stale.path)\n pushCacheItem(\n stale.path,\n ver\n ? `Stale cached Pantheon plugin revision (v${ver})`\n : 'Stale cached Pantheon plugin revision',\n )\n }\n }\n } catch {\n /* ignore unreadable cache dir */\n }\n }\n\n return items\n}\n\nexport function resolveAuditGlobalDir(\n env: Record = process.env,\n): string | undefined {\n if (env.PANTHEON_HOME?.trim()) return resolve(env.PANTHEON_HOME.trim())\n if (env.XDG_CONFIG_HOME?.trim()) return join(resolve(env.XDG_CONFIG_HOME.trim()), 'opencode')\n if (env.NODE_TEST_CONTEXT) return undefined\n const home = env.HOME?.trim()\n return home ? join(resolve(home), '.config', 'opencode') : undefined\n}\n\nexport function formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`\n return `${(bytes / (1024 * 1024)).toFixed(2)} MB`\n}\n\nfunction toSafeSegment(raw: unknown, fallback = 'default'): string {\n const str = String(raw ?? '')\n .trim()\n .replace(/[^a-zA-Z0-9._:-]/g, '_')\n .slice(0, 128)\n if (!str || str === '.' || str === '..' || !SAFE_SEGMENT_RE.test(str)) return fallback\n return str\n}\n\nfunction measurePathBytes(targetPath: string, depth = 0): number {\n if (depth > 8) return 0\n try {\n const st = statSync(targetPath)\n if (st.isFile()) return st.size\n if (!st.isDirectory()) return 0\n let total = 0\n for (const entry of readdirSync(targetPath, { withFileTypes: true })) {\n total += measurePathBytes(join(targetPath, entry.name), depth + 1)\n }\n return total\n } catch {\n return 0\n }\n}\n\nfunction samePath(a: string, b: string): boolean {\n if (resolve(a) === resolve(b)) return true\n if (!existsSync(a) || !existsSync(b)) return false\n try {\n return realpathSync(a) === realpathSync(b)\n } catch {\n return false\n }\n}\n\nfunction isConfinedWithin(rootDir: string, targetPath: string): boolean {\n try {\n const realRoot = realpathSync(rootDir)\n const parentReal = realpathSync(dirname(targetPath))\n return parentReal === realRoot || parentReal.startsWith(`${realRoot}/`)\n } catch {\n return false\n }\n}\n\nfunction countTableRows(db: DatabaseSync, tableName: string): number {\n try {\n const row = db\n .prepare(`SELECT count(*) AS cnt FROM \"${tableName.replace(/\"/g, '\"\"')}\"`)\n .get() as { cnt?: number } | undefined\n return Number(row?.cnt ?? 0)\n } catch {\n return 0\n }\n}\n\nfunction tableExists(db: DatabaseSync, name: string): boolean {\n try {\n const row = db\n .prepare(\"SELECT name FROM sqlite_master WHERE type IN ('table','view') AND name = ?\")\n .get(name) as { name?: string } | undefined\n return Boolean(row?.name)\n } catch {\n return false\n }\n}\n\nfunction collectScopeAudit(\n scope: LegacyScope,\n baseRoot: string,\n configRoot: string,\n options: LegacyAuditOptions,\n): { items: LegacyAuditItem[]; unmigratedStores: number } {\n const items: LegacyAuditItem[] = []\n const seen = new Set()\n let unmigratedStores = 0\n\n const addItem = (filePath: string, category: LegacyCategory, reason: string) => {\n const resolved = resolve(filePath)\n if (seen.has(resolved) || !existsSync(resolved)) return\n seen.add(resolved)\n items.push({\n path: resolved,\n scope,\n category,\n reason,\n bytes: measurePathBytes(resolved),\n })\n }\n\n // 1. Dead V1 hooks & obsolete config files\n for (const hookName of ['pantheon-hooks.ts', 'pantheon-hooks.js', 'pantheon-hooks.mjs']) {\n addItem(join(configRoot, 'plugins', hookName), 'hooks', 'Obsolete OpenCode V1 hook plugin')\n }\n addItem(join(configRoot, 'tiers.json'), 'v1Obsolete', 'Obsolete V1 model tiers registry')\n addItem(join(baseRoot, 'tiers.json'), 'v1Obsolete', 'Obsolete V1 model tiers registry')\n\n const pantheonDir = join(baseRoot, '.pantheon')\n addItem(join(pantheonDir, 'fastembed_cache'), 'v1Obsolete', 'Unused legacy fastembed cache')\n addItem(join(pantheonDir, '.fastembed'), 'v1Obsolete', 'Unused legacy fastembed cache')\n addItem(join(baseRoot, 'fastembed_cache'), 'v1Obsolete', 'Unused legacy fastembed cache')\n addItem(\n join(pantheonDir, '.migration-checkpoint'),\n 'v1Obsolete',\n 'Stale migration checkpoint file',\n )\n\n for (const bakDir of [configRoot, pantheonDir]) {\n if (!existsSync(bakDir)) continue\n try {\n for (const name of readdirSync(bakDir)) {\n if (name.startsWith('opencode.json.bak') || name.startsWith('active-preset.json.bak')) {\n addItem(join(bakDir, name), 'backup', 'Old configuration backup sidecar')\n }\n }\n } catch {\n /* ignore */\n }\n }\n\n // 2. Unmigrated legacy stores\n const legacyFlatMemDb = join(pantheonDir, 'memory.db')\n if (existsSync(legacyFlatMemDb)) {\n unmigratedStores += 1\n addItem(legacyFlatMemDb, 'legacyStore', 'Unmigrated flat .pantheon/memory.db')\n }\n\n const canonicalMemDb = join(pantheonDir, 'memory', 'memory.db')\n if (existsSync(canonicalMemDb)) {\n try {\n const db = new DatabaseSync(canonicalMemDb, { readOnly: true })\n const legacyVecTables = [\n 'memories_vec',\n 'vec_memories',\n 'memory_embeddings',\n 'memory_vectors',\n ]\n const hasLegacyVec = legacyVecTables.some((t) => tableExists(db, t))\n db.close()\n if (hasLegacyVec) {\n unmigratedStores += 1\n items.push({\n path: `${canonicalMemDb}#legacy-vec`,\n scope,\n category: 'legacyStore',\n reason: 'Legacy vector tables pending cleanup in memory.db',\n bytes: 0,\n })\n }\n } catch {\n /* ignore */\n }\n }\n\n for (const dbName of ['global.db', 'project.db']) {\n const persDbPath = join(pantheonDir, 'persistence', dbName)\n if (existsSync(persDbPath)) {\n unmigratedStores += 1\n addItem(persDbPath, 'legacyStore', `Unmigrated persistence/${dbName}`)\n }\n }\n\n const legacyGoalsJson = join(pantheonDir, 'goals.json')\n if (existsSync(legacyGoalsJson)) {\n unmigratedStores += 1\n addItem(legacyGoalsJson, 'legacyStore', 'Unmigrated legacy goals.json')\n }\n\n // 3. Redundant copied Pantheon assets shadowed by native plugin transforms\n if (options.includeRedundantCopiedAssets !== false) {\n for (const agentFile of CANONICAL_AGENT_MD_FILES) {\n addItem(\n join(configRoot, 'agents', agentFile),\n 'redundantAsset',\n 'Canonical Pantheon agent copy shadowed by native plugin transform',\n )\n addItem(\n join(configRoot, 'agent', agentFile),\n 'redundantAsset',\n 'Legacy singular agent copy shadowed by native plugin transform',\n )\n addItem(\n join(configRoot, 'prompts', agentFile),\n 'redundantAsset',\n 'Legacy prompt template copy provided in package',\n )\n }\n\n for (const cmdFile of CANONICAL_COMMAND_MD_FILES) {\n addItem(\n join(configRoot, 'commands', cmdFile),\n 'redundantAsset',\n 'Canonical Pantheon command copy shadowed by native plugin transform',\n )\n addItem(\n join(configRoot, 'command', cmdFile),\n 'redundantAsset',\n 'Legacy singular command directory copy',\n )\n }\n\n for (const instr of LEGACY_INSTRUCTION_FILES) {\n addItem(\n join(configRoot, 'instructions', instr),\n 'redundantAsset',\n 'Legacy instruction file superseded by AGENTS.global.md',\n )\n }\n\n for (const skillId of CANONICAL_SKILL_IDS) {\n addItem(\n join(configRoot, 'skills', skillId),\n 'redundantAsset',\n 'Bundled Pantheon skill directory provided natively by plugin',\n )\n }\n\n const tuiCopyDir = join(configRoot, 'plugins', 'pantheon-tui')\n if (existsSync(tuiCopyDir)) {\n let copiedVersion = ''\n try {\n copiedVersion = String(\n JSON.parse(readFileSync(join(tuiCopyDir, 'package.json'), 'utf8')).version ?? '',\n )\n } catch {\n copiedVersion = ''\n }\n const runningVersion = options.runningVersion ? String(options.runningVersion) : ''\n const drifted = Boolean(runningVersion && copiedVersion && copiedVersion !== runningVersion)\n addItem(\n tuiCopyDir,\n drifted ? 'drift' : 'redundantAsset',\n drifted\n ? `Copied TUI plugin v${copiedVersion} drifts from v${runningVersion}`\n : 'Copied TUI directory superseded by npm package export',\n )\n }\n }\n\n return { items, unmigratedStores }\n}\n\nfunction ensureCanonicalMemoryDb(dbPath: string): DatabaseSync {\n mkdirSync(dirname(dbPath), { recursive: true })\n const db = new DatabaseSync(dbPath)\n db.exec(`\n PRAGMA busy_timeout = 3000;\n PRAGMA journal_mode = WAL;\n CREATE TABLE IF NOT EXISTS memories (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n namespace TEXT NOT NULL DEFAULT 'default',\n key TEXT NOT NULL,\n value TEXT NOT NULL,\n importance REAL NOT NULL DEFAULT 0.5,\n created_at TEXT NOT NULL,\n expires_at TEXT,\n UNIQUE(namespace, key)\n );\n CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(\n key, value, namespace,\n content='memories',\n content_rowid='id'\n );\n CREATE TRIGGER IF NOT EXISTS memories_ai AFTER INSERT ON memories BEGIN\n INSERT INTO memories_fts(rowid, key, value, namespace) VALUES (new.id, new.key, new.value, new.namespace);\n END;\n CREATE TRIGGER IF NOT EXISTS memories_ad AFTER DELETE ON memories BEGIN\n INSERT INTO memories_fts(memories_fts, rowid, key, value, namespace) VALUES('delete', old.id, old.key, old.value, old.namespace);\n END;\n CREATE TRIGGER IF NOT EXISTS memories_au AFTER UPDATE ON memories BEGIN\n INSERT INTO memories_fts(memories_fts, rowid, key, value, namespace) VALUES('delete', old.id, old.key, old.value, old.namespace);\n INSERT INTO memories_fts(rowid, key, value, namespace) VALUES (new.id, new.key, new.value, new.namespace);\n END;\n `)\n return db\n}\n\nfunction migrateScopeBeforeDelete(baseRoot: string): number {\n const pantheonDir = join(baseRoot, '.pantheon')\n if (!existsSync(pantheonDir)) return 0\n let migrated = 0\n const nowIso = new Date().toISOString()\n\n // 1. Migrate flat .pantheon/memory.db -> .pantheon/memory/memory.db + drop legacy vector tables\n const flatMemDbPath = join(pantheonDir, 'memory.db')\n const canonicalMemPath = join(pantheonDir, 'memory', 'memory.db')\n if (existsSync(flatMemDbPath)) {\n try {\n const src = new DatabaseSync(flatMemDbPath, { readOnly: true })\n const dst = ensureCanonicalMemoryDb(canonicalMemPath)\n if (tableExists(src, 'memories')) {\n const rows = src\n .prepare('SELECT namespace, key, value, created_at FROM memories')\n .all() as Array<{\n namespace?: string\n key?: string\n value?: string\n created_at?: string\n }>\n const insert = dst.prepare(\n 'INSERT OR IGNORE INTO memories (namespace, key, value, importance, created_at) VALUES (?, ?, ?, ?, ?)',\n )\n dst.exec('BEGIN IMMEDIATE')\n try {\n for (const r of rows) {\n insert.run(\n String(r.namespace ?? 'default'),\n String(r.key ?? ''),\n String(r.value ?? ''),\n 0.5,\n String(r.created_at ?? nowIso),\n )\n migrated += 1\n }\n dst.exec('COMMIT')\n } catch (txErr) {\n try {\n dst.exec('ROLLBACK')\n } catch {\n /* ignore */\n }\n throw txErr\n }\n }\n src.close()\n dst.close()\n } catch {\n /* fail-open */\n }\n }\n\n if (existsSync(canonicalMemPath)) {\n try {\n const db = ensureCanonicalMemoryDb(canonicalMemPath)\n for (const trig of ['memories_vec_ai', 'memories_vec_ad', 'memories_vec_au']) {\n db.exec(`DROP TRIGGER IF EXISTS ${trig}`)\n }\n for (const tbl of ['memories_vec', 'vec_memories', 'memory_embeddings', 'memory_vectors']) {\n if (tableExists(db, tbl)) {\n db.exec(`DROP TABLE IF EXISTS ${tbl}`)\n migrated += 1\n }\n }\n db.close()\n } catch {\n /* fail-open */\n }\n }\n\n // 2. Migrate persistence/{global,project}.db -> persistence//.json\n const persDir = join(pantheonDir, 'persistence')\n for (const dbName of ['global.db', 'project.db']) {\n const dbPath = join(persDir, dbName)\n if (!existsSync(dbPath)) continue\n try {\n const db = new DatabaseSync(dbPath, { readOnly: true })\n for (const tbl of ['kv', 'kv_store', 'context', 'checkpoints', 'sessions']) {\n if (!tableExists(db, tbl) || countTableRows(db, tbl) === 0) continue\n const cols = db.prepare(`PRAGMA table_info(${tbl})`).all() as Array<{ name: string }>\n const colNames = new Set(cols.map((c) => c.name))\n const keyCol = colNames.has('key')\n ? 'key'\n : colNames.has('id')\n ? 'id'\n : colNames.has('session_id')\n ? 'session_id'\n : null\n const valCol = colNames.has('value')\n ? 'value'\n : colNames.has('data')\n ? 'data'\n : colNames.has('content')\n ? 'content'\n : null\n if (!keyCol || !valCol) continue\n const nsSelect = colNames.has('namespace')\n ? 'namespace'\n : `'${tbl === 'checkpoints' || tbl === 'sessions' ? 'checkpoints' : 'default'}' AS namespace`\n const rows = db\n .prepare(`SELECT ${nsSelect}, ${keyCol} AS k, ${valCol} AS v FROM ${tbl}`)\n .all() as Array<{\n namespace?: string\n k?: string\n v?: unknown\n }>\n for (const r of rows) {\n const ns = toSafeSegment(r.namespace, 'default')\n const key = toSafeSegment(r.k, '')\n if (!key) continue\n const targetDir = join(persDir, ns)\n const targetFile = join(targetDir, `${key}.json`)\n if (!existsSync(targetFile)) {\n mkdirSync(targetDir, { recursive: true })\n writeFileSync(\n targetFile,\n JSON.stringify(\n { key, namespace: ns, value: String(r.v ?? ''), updated_at: nowIso },\n null,\n 2,\n ),\n 'utf8',\n )\n migrated += 1\n }\n }\n }\n db.close()\n } catch {\n /* fail-open */\n }\n }\n\n // 3. Migrate legacy goals.json -> .pantheon/goals/.json\n const legacyGoalsPath = join(pantheonDir, 'goals.json')\n if (existsSync(legacyGoalsPath)) {\n try {\n const parsed = JSON.parse(readFileSync(legacyGoalsPath, 'utf8')) as unknown\n const list = Array.isArray(parsed)\n ? parsed\n : parsed &&\n typeof parsed === 'object' &&\n Array.isArray((parsed as { goals?: unknown }).goals)\n ? ((parsed as { goals: unknown[] }).goals ?? [])\n : []\n const goalsDir = join(pantheonDir, 'goals')\n for (const item of list) {\n if (!item || typeof item !== 'object') continue\n const rec = item as Record\n const safeId = toSafeSegment(rec.id ?? rec.goal_id, '')\n if (!safeId) continue\n const target = join(goalsDir, `${safeId}.json`)\n if (!existsSync(target)) {\n mkdirSync(goalsDir, { recursive: true })\n writeFileSync(\n target,\n JSON.stringify(\n {\n id: safeId,\n title: String(rec.title ?? rec.description ?? ''),\n criteria: Array.isArray(rec.criteria) ? rec.criteria.map(String) : [],\n status: String(rec.status ?? 'active'),\n created_at: typeof rec.created_at === 'string' ? rec.created_at : nowIso,\n updated_at: typeof rec.updated_at === 'string' ? rec.updated_at : nowIso,\n },\n null,\n 2,\n ),\n 'utf8',\n )\n migrated += 1\n }\n }\n } catch {\n /* fail-open */\n }\n }\n\n return migrated\n}\n\nexport function scanLegacyArtifacts(options: LegacyAuditOptions = {}): LegacyAuditScan {\n const workspaceDir = options.workspaceDir ? resolve(options.workspaceDir) : undefined\n const globalConfigDir = options.globalConfigDir\n ? resolve(options.globalConfigDir)\n : resolveAuditGlobalDir(options.env)\n const cacheNpmDir = options.cacheDir\n ? resolve(options.cacheDir)\n : resolveAuditCacheDir(options.env)\n\n const items: LegacyAuditItem[] = []\n let unmigratedStores = 0\n\n if (globalConfigDir && existsSync(globalConfigDir) && globalConfigDir !== '/') {\n const res = collectScopeAudit('global', globalConfigDir, globalConfigDir, options)\n items.push(...res.items)\n unmigratedStores += res.unmigratedStores\n }\n\n if (cacheNpmDir && existsSync(cacheNpmDir) && cacheNpmDir !== '/') {\n items.push(...collectCacheAudit(cacheNpmDir, options))\n }\n\n if (\n workspaceDir &&\n existsSync(workspaceDir) &&\n workspaceDir !== '/' &&\n (!globalConfigDir || !samePath(workspaceDir, globalConfigDir))\n ) {\n const res = collectScopeAudit('project', workspaceDir, join(workspaceDir, '.opencode'), options)\n items.push(...res.items)\n unmigratedStores += res.unmigratedStores\n }\n\n const byScope: Record = { global: 0, project: 0 }\n const byCategory: Record = {}\n let totalBytes = 0\n for (const item of items) {\n byScope[item.scope] = (byScope[item.scope] ?? 0) + 1\n byCategory[item.category] = (byCategory[item.category] ?? 0) + 1\n totalBytes += item.bytes\n }\n\n return {\n items,\n summary: {\n total: items.length,\n totalBytes,\n unmigratedStores,\n byScope,\n byCategory,\n },\n }\n}\n\nexport function cleanLegacyArtifacts(\n options: LegacyAuditOptions & { readonly scope?: 'all' | LegacyScope } = {},\n): LegacyCleanResult {\n const workspaceDir = options.workspaceDir ? resolve(options.workspaceDir) : undefined\n const globalConfigDir = options.globalConfigDir\n ? resolve(options.globalConfigDir)\n : resolveAuditGlobalDir(options.env)\n const cacheNpmDir = options.cacheDir\n ? resolve(options.cacheDir)\n : resolveAuditCacheDir(options.env)\n const scopeFilter = options.scope && options.scope !== 'all' ? options.scope : null\n\n const scan = scanLegacyArtifacts(options)\n let migratedRecords = 0\n\n if (\n scopeFilter !== 'project' &&\n globalConfigDir &&\n existsSync(globalConfigDir) &&\n globalConfigDir !== '/'\n ) {\n migratedRecords += migrateScopeBeforeDelete(globalConfigDir)\n }\n if (\n scopeFilter !== 'global' &&\n workspaceDir &&\n existsSync(workspaceDir) &&\n workspaceDir !== '/' &&\n (!globalConfigDir || !samePath(workspaceDir, globalConfigDir))\n ) {\n migratedRecords += migrateScopeBeforeDelete(workspaceDir)\n }\n\n const removed: string[] = []\n const errors: Array<{ readonly path: string; readonly reason: string }> = []\n let reclaimedBytes = 0\n\n for (const item of scan.items) {\n if (scopeFilter && item.scope !== scopeFilter) continue\n if (item.path.endsWith('#legacy-vec')) {\n removed.push(item.path)\n continue\n }\n const scopeRoot = item.scope === 'global' ? globalConfigDir : workspaceDir\n const confineRoot =\n item.scope === 'global' && cacheNpmDir && isConfinedWithin(cacheNpmDir, item.path)\n ? cacheNpmDir\n : scopeRoot\n if (!confineRoot || !isConfinedWithin(confineRoot, item.path)) {\n errors.push({ path: item.path, reason: 'Path escapes target scope root' })\n continue\n }\n try {\n if (existsSync(item.path)) {\n rmSync(item.path, { recursive: true, force: true })\n removed.push(item.path)\n reclaimedBytes += item.bytes\n }\n if (item.path.endsWith('.db')) {\n for (const suffix of ['-wal', '-shm', '-journal']) {\n const sidecar = `${item.path}${suffix}`\n if (existsSync(sidecar) && isConfinedWithin(confineRoot, sidecar)) {\n const sidecarBytes = measurePathBytes(sidecar)\n rmSync(sidecar, { force: true })\n removed.push(sidecar)\n reclaimedBytes += sidecarBytes\n }\n }\n }\n } catch (err) {\n errors.push({\n path: item.path,\n reason: err instanceof Error ? err.message : String(err),\n })\n }\n }\n\n return {\n removed,\n reclaimedBytes,\n migratedRecords,\n errors,\n }\n}\n","/**\n * preset-state.ts — the Model Preset section of the settings window.\n *\n * TUI-local replica (the bundle must stay self-contained). The preset NAMES\n * mirror routing.yml's `presets:` and are drift-pinned by\n * tests/tui-preset-state.test.mjs against `loadPresetDefs()`. The marker file\n * shape mirrors scripts/install/model-picker.mjs's `buildActivePresetFile`\n * (version 1), and the readers (`resolveActivePreset`, vision.ts candidates)\n * only consult `.preset`, so the window writes `source: 'tui-settings'`.\n *\n * Scope note: the window writes the GLOBAL marker only\n * (`/opencode/.pantheon/active-preset.json`). A project marker\n * wins (it precedes the global path in every runtime candidate list), so it\n * is displayed read-only. `none` DELETES the marker with a .bak backup — the\n * same contract as the CLI's `set-tier none`.\n */\nimport {\n copyFileSync,\n existsSync,\n mkdirSync,\n readFileSync,\n renameSync,\n rmSync,\n writeFileSync,\n} from 'node:fs'\nimport { dirname, join } from 'node:path'\nimport type { SettingsRow, SettingsTab } from './pantheon-settings-state.ts'\n\n/** Mirrors routing.yml `presets:` — drift-pinned against loadPresetDefs(). */\nexport const PRESET_NAMES: readonly string[] = Object.freeze([\n 'go-free',\n 'go-fast',\n 'go-premium',\n 'go-hybrid',\n 'anthropic',\n 'openai',\n])\n\nexport interface ActivePresetMarker {\n version: number\n preset: string\n source: string\n updated_at: string\n}\n\nexport function globalActivePresetPath(env: Record = process.env) {\n const xdg = env.XDG_CONFIG_HOME\n const home = env.HOME ?? ''\n const root = xdg ?? join(home, '.config')\n return join(root, 'opencode', '.pantheon', 'active-preset.json')\n}\n\nexport function projectActivePresetPath() {\n return join(process.cwd(), '.pantheon', 'active-preset.json')\n}\n\n/** Fail-open read: missing/corrupt marker = no active preset. */\nexport function readActivePresetMarker(path: string): { name: string; updatedAt: string } | null {\n try {\n const raw = JSON.parse(readFileSync(path, 'utf8')) as { preset?: unknown; updated_at?: unknown }\n if (typeof raw?.preset !== 'string' || raw.preset === '' || raw.preset === 'none') return null\n return {\n name: raw.preset,\n updatedAt: typeof raw.updated_at === 'string' ? raw.updated_at : '',\n }\n } catch {\n return null\n }\n}\n\nfunction writeMarkerAtomically(path: string, content: string): void {\n mkdirSync(dirname(path), { recursive: true })\n const temp = `${path}.tui.tmp`\n writeFileSync(temp, content)\n renameSync(temp, path)\n}\n\n/** Select a preset globally: .bak backup, atomic write, version-1 marker. */\nexport function writeActivePreset(\n path: string,\n name: string,\n nowIso = new Date().toISOString(),\n): void {\n if (!PRESET_NAMES.includes(name)) {\n throw new TypeError(`Refusing to persist unknown preset \"${name}\"`)\n }\n backupMarker(path)\n const marker: ActivePresetMarker = {\n version: 1,\n preset: name,\n source: 'tui-settings',\n updated_at: nowIso,\n }\n writeMarkerAtomically(path, `${JSON.stringify(marker, null, 2)}\\n`)\n}\n\n/** Clear the global marker (the `none` contract): .bak backup, then remove. */\nexport function clearActivePreset(path: string): void {\n backupMarker(path)\n rmSync(path, { force: true })\n}\n\nfunction backupMarker(path: string): void {\n if (!existsSync(path)) return\n mkdirSync(dirname(path), { recursive: true })\n copyFileSync(path, `${path}.bak`)\n}\n\nexport const VISION_MODEL_OPTIONS: readonly string[] = Object.freeze([\n 'auto',\n 'opencode-go/mimo-v2.6-flash',\n 'google/gemini-2.5-flash',\n 'openai/gpt-5-mini',\n 'anthropic/claude-3-5-haiku',\n 'opencode-go/mimo-v2.5',\n])\n\nexport function visionConfigPaths(\n cwd = process.cwd(),\n env: Record = process.env,\n): string[] {\n const home = env.HOME ?? ''\n const xdg = env.XDG_CONFIG_HOME ?? join(home, '.config')\n return [\n join(cwd, '.opencode', 'opencode-vision.json'),\n join(xdg, 'opencode', 'opencode-vision.json'),\n ]\n}\n\nexport function readConfiguredVisionModel(\n cwd = process.cwd(),\n env: Record = process.env,\n): string {\n for (const path of visionConfigPaths(cwd, env)) {\n try {\n if (existsSync(path)) {\n const parsed = JSON.parse(readFileSync(path, 'utf8')) as { visionModel?: unknown }\n if (typeof parsed?.visionModel === 'string' && parsed.visionModel.trim()) {\n return parsed.visionModel.trim()\n }\n }\n } catch {\n // ignore corrupt/missing\n }\n }\n return 'auto'\n}\n\nexport function writeConfiguredVisionModel(\n model: string,\n cwd = process.cwd(),\n env: Record = process.env,\n): void {\n const home = env.HOME ?? ''\n const xdg = env.XDG_CONFIG_HOME ?? join(home, '.config')\n const projectDir = join(cwd, '.opencode')\n const targetPath = existsSync(projectDir)\n ? join(projectDir, 'opencode-vision.json')\n : join(xdg, 'opencode', 'opencode-vision.json')\n\n let current: Record = {}\n try {\n if (existsSync(targetPath)) {\n current = JSON.parse(readFileSync(targetPath, 'utf8')) as Record\n }\n } catch {\n current = {}\n }\n\n if (model === 'auto' || !model.trim()) {\n delete current.visionModel\n } else {\n current.visionModel = model.trim()\n }\n\n mkdirSync(dirname(targetPath), { recursive: true })\n const temp = `${targetPath}.tui.tmp`\n writeFileSync(temp, `${JSON.stringify(current, null, 2)}\\n`, 'utf8')\n renameSync(temp, targetPath)\n}\n\nexport interface PresetSectionInput {\n globalName: string | null\n projectName: string | null\n visionModel?: string\n}\n\n/** The staged value 'none' means: delete the global marker (the CLI contract). */\nexport const PRESET_NONE = 'none'\n\nexport const PRESET_CYCLE: readonly string[] = Object.freeze([PRESET_NONE, ...PRESET_NAMES])\n\nexport function buildPresetTab(input: PresetSectionInput, languagePref?: string): SettingsTab {\n const isPt = languagePref === 'pt-BR'\n const rows: SettingsRow[] = [\n {\n id: 'preset',\n name: isPt ? 'Predefinição' : 'Preset',\n value: input.globalName ?? PRESET_NONE,\n cycle: PRESET_CYCLE,\n note: isPt\n ? 'marcador global · gravação atômica, backup .bak · none = padrão OpenCode'\n : 'global marker · atomic write, .bak backup · none = opencode defaults',\n },\n ]\n if (input.projectName !== null) {\n rows.push({\n id: 'preset.project',\n name: isPt ? 'Projeto' : 'Project',\n value: input.projectName,\n note: isPt\n ? `${projectActivePresetPath()} tem precedência sobre o global — somente leitura aqui`\n : `${projectActivePresetPath()} wins over the global marker — read-only here`,\n })\n }\n if (input.visionModel !== undefined) {\n rows.push({\n id: 'preset.vision_model',\n name: isPt ? 'Modelo de Visão' : 'Vision Model',\n value: input.visionModel || 'auto',\n cycle: VISION_MODEL_OPTIONS,\n note: isPt\n ? 'modelo para inspeção de imagens (vision_describe) · salvo em opencode-vision.json'\n : 'model for image inspection (vision_describe) · saved in opencode-vision.json',\n })\n }\n return {\n id: 'preset',\n title: 'Preset',\n groups: [{ title: isPt ? 'Predefinição de modelo' : 'Model preset', rows }],\n }\n}\n","/**\n * update-status.ts — the Updates section of the settings window.\n *\n * TUI-local; derives rows from the update-notice.ts primitives. The registry\n * fetch and state persistence stay in the .tsx glue (host side) — this module\n * only classifies the channel and builds rows from injected state, so the\n * whole thing is testable without network.\n */\n\nimport { formatBytes, type LegacyAuditSummary } from './legacy-audit.ts'\nimport type { SettingsRow, SettingsTab } from './pantheon-settings-state.ts'\nimport { comparePantheonVersions, type UpdateCheckState } from './update-notice.ts'\n\nexport type UpdateChannel = 'stable' | 'beta'\n\n/** The running version's channel: a `-beta.N` suffix rides the beta dist-tag. */\nexport function updateChannelFor(version: string): UpdateChannel {\n return /-beta\\.\\d+$/.test(version) ? 'beta' : 'stable'\n}\n\n/** The npm dist-tag the registry check should query for the channel. */\nexport function registryTagForChannel(channel: UpdateChannel): string {\n return channel === 'beta' ? 'beta' : 'latest'\n}\n\nexport function registryUrlForChannel(channel: UpdateChannel): string {\n return `https://registry.npmjs.org/pantheon-opencode/${registryTagForChannel(channel)}`\n}\n\nfunction formatAgo(ms: number, isPt = false): string {\n if (ms < 60_000) return isPt ? 'agora mesmo' : 'just now'\n if (ms < 3_600_000)\n return isPt ? `há ${Math.floor(ms / 60_000)}m` : `${Math.floor(ms / 60_000)}m ago`\n if (ms < 86_400_000)\n return isPt ? `há ${Math.floor(ms / 3_600_000)}h` : `${Math.floor(ms / 3_600_000)}h ago`\n return isPt ? `há ${Math.floor(ms / 86_400_000)}d` : `${Math.floor(ms / 86_400_000)}d ago`\n}\n\nexport interface UpdatesSectionInput {\n currentVersion: string\n state: UpdateCheckState\n /** Selected channel (defaults to updateChannelFor(currentVersion)). */\n selectedChannel?: UpdateChannel\n /** Latest version seen this session (a check-now inside this window). */\n lastCheckedVersion?: string\n /** A check-now is in flight (this window). */\n checking?: boolean\n /** An update run is in flight (this window). */\n updating?: boolean\n /** Latest scan summary from legacy-audit.ts (global + project). */\n legacyAudit?: LegacyAuditSummary | null\n /** Whether a legacy scan is currently running. */\n legacyScanning?: boolean\n /** Whether a legacy cleanup is currently running. */\n legacyCleaning?: boolean\n /** Outcome notice from the last scan/clean action. */\n legacyNotice?: string\n nowMs?: number\n languagePref?: string\n}\n\nexport function buildUpdatesTab(input: UpdatesSectionInput): SettingsTab {\n const isPt = input.languagePref === 'pt-BR'\n const nowMs = input.nowMs ?? Date.now()\n const channel = input.selectedChannel ?? updateChannelFor(input.currentVersion)\n const lastCheckMs = input.state.lastCheckMs\n const latest = input.lastCheckedVersion ?? input.state.lastNotifiedVersion\n\n const stable = (version: string) => !/-beta\\.\\d+$/.test(version)\n const newer =\n latest !== undefined &&\n comparePantheonVersions(latest, input.currentVersion) > 0 &&\n !(stable(input.currentVersion) && !stable(latest))\n\n const rows: SettingsRow[] = [\n {\n id: 'update.channel',\n name: isPt ? 'Canal' : 'Channel',\n value: channel,\n cycle: ['stable', 'beta'] as const,\n note: isPt\n ? 'stable segue npm `latest`; beta segue npm `beta`'\n : 'stable tracks npm `latest`; beta tracks npm `beta`',\n },\n {\n id: 'update.check',\n name: isPt ? 'Verificar agora' : 'Check now',\n value: input.checking\n ? isPt\n ? 'verificando…'\n : 'checking…'\n : lastCheckMs\n ? isPt\n ? `verificado ${formatAgo(nowMs - lastCheckMs, true)}`\n : `last check ${formatAgo(nowMs - lastCheckMs, false)}`\n : isPt\n ? 'nunca verificado'\n : 'never checked',\n action: 'update-check',\n note: isPt\n ? 'enter consulta o registro npm para o canal ativo'\n : 'enter probes the registry for the running channel',\n },\n ]\n\n const pkgSpec = channel === 'beta' ? 'pantheon-opencode@beta' : 'pantheon-opencode'\n const pluginCommand = `opencode plugin update ${pkgSpec}`\n\n if (latest) {\n rows.push({\n id: 'update.latest',\n name: isPt ? 'Registro (npm)' : 'Registry',\n value: newer\n ? `v${latest} ${isPt ? 'disponível' : 'available'}`\n : isPt\n ? 'atualizado'\n : 'up to date',\n ...(newer ? { action: 'update-run' as const } : {}),\n note: newer\n ? isPt\n ? `enter atualiza agora · ou rode \\`${pluginCommand}\\``\n : `enter updates now · or run \\`${pluginCommand}\\``\n : isPt\n ? 'nenhuma versão mais recente compatível'\n : 'no newer compatible version',\n })\n rows.push({\n id: 'update.run',\n name: isPt ? 'Atualizar plugin' : 'Update plugin',\n value: input.updating\n ? isPt\n ? 'atualizando…'\n : 'updating…'\n : newer\n ? `${isPt ? 'atualizar' : 'update'} v${latest}`\n : isPt\n ? 'reinstalar plugin'\n : 'refresh plugin',\n action: 'update-run',\n note: newer\n ? isPt\n ? `enter executa \\`${pluginCommand}\\` + reload`\n : `enter runs \\`${pluginCommand}\\` + reload`\n : isPt\n ? 'enter força atualização do plugin instalado'\n : 'enter refreshes the installed plugin',\n })\n }\n\n rows.push({\n id: 'update.command',\n name: isPt ? 'Comando no terminal' : 'CLI Command',\n value: 'opencode plugin update',\n note: isPt\n ? `rode \\`${pluginCommand} && opencode reload\\` (sem npx)`\n : `run \\`${pluginCommand} && opencode reload\\` (no npx)`,\n })\n\n const audit = input.legacyAudit\n const legacyRows: SettingsRow[] = [\n {\n id: 'legacy.status',\n name: isPt ? 'Auditoria legada' : 'Legacy & Drift',\n value: input.legacyScanning\n ? isPt\n ? 'escaneando…'\n : 'scanning…'\n : audit === undefined || audit === null\n ? isPt\n ? 'não escaneado'\n : 'not scanned'\n : audit.total === 0\n ? isPt\n ? 'limpo (0 obsoletos)'\n : 'clean (0 obsolete)'\n : isPt\n ? `${audit.total} item(ns) (${formatBytes(audit.totalBytes)})`\n : `${audit.total} item(s) (${formatBytes(audit.totalBytes)})`,\n note: input.legacyNotice\n ? input.legacyNotice\n : audit && audit.total > 0\n ? isPt\n ? `global: ${audit.byScope.global} · projeto: ${audit.byScope.project}${audit.unmigratedStores > 0 ? ` · ${audit.unmigratedStores} store(s) p/ migrar` : ''}`\n : `global: ${audit.byScope.global} · project: ${audit.byScope.project}${audit.unmigratedStores > 0 ? ` · ${audit.unmigratedStores} store(s) to migrate` : ''}`\n : isPt\n ? 'verifica caches npm antigos, hooks V1, bancos e cópias redundantes'\n : 'checks stale npm caches, V1 hooks, unmigrated stores & copied files',\n },\n {\n id: 'legacy.scan',\n name: isPt ? 'Escanear obsoletos' : 'Scan legacy & drift',\n value: input.legacyScanning\n ? isPt\n ? 'escaneando…'\n : 'scanning…'\n : isPt\n ? 'escanear agora'\n : 'scan global + project',\n action: 'legacy-scan',\n note: isPt\n ? 'enter verifica global, projeto e cache npm sem apagar nada'\n : 'enter scans global, project & npm cache read-only',\n },\n {\n id: 'legacy.clean',\n name: isPt ? 'Migrar & limpar' : 'Migrate & clean obsolete',\n value: input.legacyCleaning\n ? isPt\n ? 'limpando…'\n : 'cleaning…'\n : audit && audit.total > 0\n ? isPt\n ? `limpar ${audit.total} (${formatBytes(audit.totalBytes)})`\n : `remove ${audit.total} (${formatBytes(audit.totalBytes)})`\n : isPt\n ? 'nada a remover'\n : 'nothing to remove',\n action: 'legacy-clean',\n note: isPt\n ? 'migra memória/contexto/goals antes; preserva agentes/skills custom'\n : 'migrates memory/context/goals first · preserves custom agents/skills',\n },\n ]\n\n return {\n id: 'updates',\n title: isPt ? 'Atualizações' : 'Updates',\n groups: [\n { title: isPt ? 'Atualizações do Plugin' : 'Plugin Updates', rows },\n { title: isPt ? 'Legados, Drift & Limpeza' : 'Legacy, Drift & Cleanup', rows: legacyRows },\n ],\n }\n}\n","/**\n * whats-new-highlights.ts — release highlights for the one-time \"What's new\"\n * window, extracted from the CHANGELOG.md shipped with the plugin copy.\n *\n * The section-finding logic is an inline replica of scripts/changelog-extract.mjs\n * `extractSection` (pinned by a parity test in tests/tui-whats-new.test.mjs):\n * the copied plugin ships only dist/ + package.json (+ CHANGELOG.md, copied by\n * both installers), so it cannot reach scripts/ at runtime — the same reason\n * the preset resolver is mirrored in index.tsx/index-v2.tsx rather than\n * imported. The script's CLI main is NOT replicated; the plugin only needs the\n * pure extraction.\n *\n * Everything is reduced to bounded plain text: no markdown syntax artifacts,\n * at most WHATS_NEW_MAX_ITEMS bullets. Missing CHANGELOG.md, an unknown\n * version or an empty section all resolve to an empty highlight set — the\n * window simply does not show (fail-open, like the rest of the plugin).\n */\nimport { readFile } from 'node:fs/promises'\nimport { dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\n/** Hard cap on bullets shown in the window (the remainder is counted). */\nexport const WHATS_NEW_MAX_ITEMS = 12\n\n/**\n * Cap for the curated `🆕 What's New` summary block — the window shows the\n * summary, never the full Added/Changed/Fixed walls.\n */\nexport const WHATS_NEW_SUMMARY_MAX_ITEMS = 6\n\n/** Bullets longer than this are truncated with an ellipsis (one-line rule). */\nexport const WHATS_NEW_ITEM_MAX_CHARS = 140\n\n/** Prefix of the \"+N more\" line appended when the bullet budget is exceeded. */\nexport const WHATS_NEW_MORE_PREFIX = '… +'\n\n/** H3 subsection headings are kept as plain-text group labels. */\nexport interface WhatsNewGroup {\n heading: string | null\n items: string[]\n}\n\nexport interface WhatsNewHighlights {\n /** Normalized version the highlights belong to (null when not found). */\n version: string | null\n found: boolean\n groups: WhatsNewGroup[]\n /** Total bullets in the section, before the WHATS_NEW_MAX_ITEMS cut. */\n totalItems: number\n /** True when totalItems exceeded WHATS_NEW_MAX_ITEMS. */\n truncated: boolean\n}\n\nexport const EMPTY_HIGHLIGHTS: WhatsNewHighlights = {\n version: null,\n found: false,\n groups: [],\n totalItems: 0,\n truncated: false,\n}\n\n/** Escape regex metacharacters so a version like 1.0.0 matches literally. */\nfunction escapeRegExp(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\n/**\n * Extract the body of a version section from changelog text — inline replica\n * of scripts/changelog-extract.mjs `extractSection` (see that file for the\n * full contract: `## [] - YYYY-MM-DD`, leading `v` and the date\n * optional, `## [Unreleased]` never matched).\n */\nexport function extractSection(\n changelogText: string,\n version: string,\n): { found: boolean; body: string | null } {\n const normalized = String(version).trim().replace(/^v/i, '')\n if (!normalized || /^unreleased$/i.test(normalized)) return { found: false, body: null }\n\n const escaped = escapeRegExp(normalized)\n // Single-line heading: `## [v?1.2.1]` optionally followed by ` - YYYY-MM-DD`.\n // [ \\t] (not \\s) keeps the match from crossing newlines; the lookahead\n // requires end-of-line or whitespace so `[1.0.0-beta]` can never match `1.0.0`.\n const headingRe = new RegExp(\n `^##[ \\\\t]+\\\\[v?${escaped}\\\\](?:[ \\\\t]*-[ \\\\t]*\\\\d{4}-\\\\d{2}-\\\\d{2})?(?=[ \\\\t]|$)`,\n 'm',\n )\n const match = headingRe.exec(changelogText)\n if (!match) return { found: false, body: null }\n\n // Advance past the heading line (match.index may point mid-line).\n const newline = changelogText.indexOf('\\n', match.index)\n const start = newline === -1 ? changelogText.length : newline + 1\n\n // Body ends at the next `## [` heading or end of text.\n const nextHeading = /^##[ \\t]+\\[/m.exec(changelogText.slice(start))\n const end = nextHeading ? start + nextHeading.index : changelogText.length\n\n return { found: true, body: changelogText.slice(start, end).trim() }\n}\n\n/**\n * Reduce one markdown line to plain text: links keep their label, emphasis\n * and inline-code markers are dropped, HTML comment fragments are removed,\n * and whitespace collapses. Deliberately simple — the input is our own\n * CHANGELOG (lint-capped at 200 chars per bullet), not hostile input.\n */\nexport function stripMarkdown(text: string): string {\n return text\n .replace(//g, ' ')\n .replace(/\\[([^\\]]+)\\]\\([^)]*\\)/g, '$1')\n .replace(/(\\*\\*|__)/g, '')\n .replace(/`/g, '')\n .replace(/\\s+/g, ' ')\n .trim()\n}\n\n/** Strip the leading H3 marker (`### Added` → `Added`). */\nfunction stripHeading(text: string): string {\n return text.replace(/^#{1,6}[ \\t]+/, '').trim()\n}\n\n/**\n * Extract the curated summary block (`### 🆕 What's New` or `## 🆕 What's New`)\n * from a section body: its bullets only, each truncated to\n * WHATS_NEW_ITEM_MAX_CHARS, capped to WHATS_NEW_SUMMARY_MAX_ITEMS. Null when\n * the section carries no summary block (the full-section fallback applies).\n */\nexport function extractWhatsNewSummary(body: string): string[] | null {\n const lines = body.split('\\n')\n const start = lines.findIndex((line) => /^#{2,3}[ \\t]+.*What'?s New/i.test(line.trim()))\n if (start === -1) return null\n const items: string[] = []\n for (const rawLine of lines.slice(start + 1)) {\n const line = rawLine.trim()\n if (line === '' || line.startsWith('>Zeus: ${row.status}`) + } + if (snapshot.swarm.rows.length === 0) { + seqLines.push(' You->>Zeus: active session telemetry snapshot') + seqLines.push(' Zeus-->>You: Flightdeck gate check') + } + seqLines.push('```') + + const ganttRows = + snapshot.swarm.rows.length > 0 + ? snapshot.swarm.rows + .map( + (r) => + `| \`@${r.agent}\` | ${r.status} | \`${r.ganttBar}\` | ${r.durationSec}s | $${r.cost.toFixed(4)} |`, + ) + .join('\n') + : '| _none_ | — | `░░░░░░░░░░░░` | 0s | $0.0000 |' + + const stepLines = + snapshot.flightdeck.steps.length > 0 + ? snapshot.flightdeck.steps + .map((s) => `- **${s.stepKey}** (\`${s.state}\`, \`@${s.agent}\`) — ${s.objective}`) + .join('\n') + : '- No step-ledger entries recorded.' + + const eventLines = + snapshot.flightdeck.logs.length > 0 + ? snapshot.flightdeck.logs + .map((e) => `- \`[${e.kind}]\` **@${e.agent}**: ${e.detail}`) + .join('\n') + : '- No semantic bus events recorded.' + + const markdown = [ + `# Pantheon Cockpit Flightdeck Replay`, + '', + `- **Session:** ${snapshot.sessionTitle}`, + `- **Model:** ${snapshot.modelName}`, + `- **Captured At:** ${now.toISOString()}`, + `- **Spend / Context:** $${snapshot.overview.sessionCost.toFixed(4)} · ${snapshot.overview.contextTokens} tokens (${snapshot.overview.contextPercent}%)`, + `- **Gate Matrix:** ${snapshot.flightdeck.gateSummary}`, + '', + '## Execution Replay Diagram', + '', + ...seqLines, + '', + '## Swarm Concurrency Timeline', + '', + '| Agent | Status | Gantt Window | Duration | Cost |', + '|---|---|---|---|---|', + ganttRows, + '', + '## Step-Ledger Checkpoints', + '', + stepLines, + '', + '## Semantic Event Stream', + '', + eventLines, + '', + ].join('\n') + + return { filename, relPath, markdown } +} + +/** Confined export helper writing a Cockpit replay trace under `/.pantheon/reports/`. */ +export function writeCockpitReplayArtifact( + workspaceDir: string, + snapshot: CockpitSnapshot, + now: Date = new Date(), +): string { + const reportsDir = join(workspaceDir, '.pantheon', 'reports') + mkdirSync(reportsDir, { recursive: true }) + const canonicalReports = realpathSync(reportsDir) + const artifact = formatCockpitReplayArtifact(snapshot, now) + const target = resolve(canonicalReports, artifact.filename) + const prefix = canonicalReports.endsWith(sep) ? canonicalReports : `${canonicalReports}${sep}` + if (!target.startsWith(prefix)) { + throw new Error('Cockpit replay target escaped .pantheon/reports') + } + writeFileSync(target, artifact.markdown, 'utf8') + return artifact.relPath +} diff --git a/src/plugins/tui/src/cockpit.tsx b/src/plugins/tui/src/cockpit.tsx new file mode 100644 index 00000000..25da790a --- /dev/null +++ b/src/plugins/tui/src/cockpit.tsx @@ -0,0 +1,643 @@ +// biome-ignore-all lint/suspicious/noExplicitAny: OpenCode exposes its TUI API at runtime. +// biome-ignore-all lint/a11y/noStaticElementInteractions: TUI elements, not DOM +/** @jsxImportSource @opentui/solid */ + +/** + * cockpit.tsx — High-Density TUI Mission Control Cockpit (Overview, Swarm, + * Flightdeck) rendered natively on `@opentui/solid` via `ui.router.register`. + */ + +import type { Context, WindowRoute } from '@opencode/plugin/tui/context' +import { createSignal, For, onCleanup, onMount, Show } from 'solid-js' +import { + buildCockpitSnapshot, + type CockpitChildEntry, + type CockpitLogEntry, + type CockpitTabId, + writeCockpitReplayArtifact, +} from './cockpit-state.ts' +import { resolveLanguage } from './settings-i18n' +import { resolveAccentColor, tuiPrefs } from './tui-prefs' + +const ROUTE_NAME = 'pantheon.cockpit' +const ROUTE_MODE = 'pantheon-cockpit' +const TABS: ReadonlyArray<{ + readonly id: CockpitTabId + readonly label: string + readonly key: string +}> = [ + { id: 'overview', label: '1 Overview', key: '1' }, + { id: 'swarm', label: '2 Swarm', key: '2' }, + { id: 'flightdeck', label: '3 Flightdeck', key: '3' }, +] + +let routerReady = false +let cockpitController: + | { + setTab: (id: CockpitTabId) => void + nextTab: () => void + prevTab: () => void + moveRow: (delta: number) => void + toggleDetail: () => void + exportReplay: () => void + refresh: () => void + close: () => void + } + | undefined +const [cockpitOpen, setCockpitOpen] = createSignal(false) + +function collectLiveChildren(context: any, rootSessionID?: string): CockpitChildEntry[] { + try { + const rawList = context?.data?.session?.list?.() + if (!Array.isArray(rawList)) return [] + return rawList + .filter( + (s: any) => + s && typeof s.id === 'string' && (!rootSessionID || s.parentID === rootSessionID), + ) + .slice(0, 20) + .map((s: any) => { + const statusRaw = context?.data?.session?.status?.(s.id) + const status: CockpitChildEntry['status'] = + statusRaw === 'busy' || statusRaw === 'running' + ? 'running' + : statusRaw === 'error' + ? 'failed' + : statusRaw === 'interrupted' + ? 'interrupted' + : 'completed' + const created = typeof s.time?.created === 'number' ? s.time.created : Date.now() + const updated = typeof s.time?.updated === 'number' ? s.time.updated : created + return { + id: s.id, + agent: String(s.agent ?? s.title ?? 'specialist').split(/\s+/)[0] ?? 'specialist', + kind: String(s.kind ?? 'task'), + status, + cost: typeof s.cost === 'number' ? s.cost : 0, + startedAt: created, + updatedAt: updated, + tokens: + typeof s.tokens?.input === 'number' ? s.tokens.input + (s.tokens?.output ?? 0) : 0, + model: typeof s.model === 'string' ? s.model : undefined, + } + }) + } catch { + return [] + } +} + +function collectHostLogs(): CockpitLogEntry[] { + const g = globalThis as { __pantheonCockpitLogs?: CockpitLogEntry[] } + if (!Array.isArray(g.__pantheonCockpitLogs)) return [] + return g.__pantheonCockpitLogs +} + +function collectSessionTelemetry( + context: any, + sessionID?: string, +): { + title?: string + modelName?: string + contextTokens: number + contextWindow: number + sessionCost?: number +} { + const sInfo = sessionID ? context?.data?.session?.info?.(sessionID) : undefined + const messages: any[] = sessionID ? (context?.data?.session?.messages?.(sessionID) ?? []) : [] + let contextTokens = typeof sInfo?.tokens?.input === 'number' ? sInfo.tokens.input : 0 + let modelName: string | undefined = typeof sInfo?.model === 'string' ? sInfo.model : undefined + let totalCost = typeof sInfo?.cost === 'number' ? sInfo.cost : 0 + let sawMsgCost = false + if (Array.isArray(messages) && messages.length > 0) { + for (const msg of messages) { + if (!msg || typeof msg !== 'object') continue + if (typeof msg.cost === 'number' && Number.isFinite(msg.cost)) { + totalCost += msg.cost + sawMsgCost = true + } + } + for (let i = messages.length - 1; i >= 0; i--) { + const msg = messages[i] + if (msg?.role === 'assistant' || msg?.type === 'assistant') { + const t = msg.tokens + if (t && typeof t === 'object') { + const total = + (Number(t.input) || 0) + + (Number(t.output) || 0) + + (Number(t.reasoning) || 0) + + (Number(t.cache?.read) || 0) + + (Number(t.cache?.write) || 0) + if (total > 0) { + contextTokens = total + if (!modelName && typeof msg.modelID === 'string') modelName = msg.modelID + break + } + } + } + } + } + const modelsCatalog = context?.data?.provider?.models?.() ?? [] + let contextWindow = 1_000_000 + if (Array.isArray(modelsCatalog) && modelName) { + const hit = modelsCatalog.find((m: any) => m?.id === modelName || m?.modelID === modelName) + if (typeof hit?.limit?.context === 'number' && hit.limit.context > 0) { + contextWindow = hit.limit.context + } + } + return { + title: typeof sInfo?.title === 'string' ? sInfo.title : undefined, + modelName, + contextTokens, + contextWindow, + sessionCost: sawMsgCost || typeof sInfo?.cost === 'number' ? totalCost : undefined, + } +} + +export function CockpitView(props: { + readonly context: any + readonly workspaceDir: string + readonly sessionID?: string + readonly onClose: () => void +}) { + const isPt = () => resolveLanguage(tuiPrefs().layout?.language) === 'pt-BR' + const [tab, setTab] = createSignal('overview') + const [selectedRow, setSelectedRow] = createSignal(0) + const [showDetail, setShowDetail] = createSignal(false) + const [exportNote, setExportNote] = createSignal(null) + const [tick, setTick] = createSignal(0) + + const activeSid = () => + props.sessionID ?? + (props.context?.ui?.router?.current?.()?.type === 'session' + ? props.context.ui.router.current().sessionID + : undefined) + + const snapshot = () => { + tick() + const sid = activeSid() + const telemetry = collectSessionTelemetry(props.context, sid) + return buildCockpitSnapshot({ + workspaceDir: props.workspaceDir, + sessionTitle: telemetry.title, + modelName: telemetry.modelName, + contextTokens: telemetry.contextTokens, + contextWindow: telemetry.contextWindow, + sessionCost: telemetry.sessionCost, + children: collectLiveChildren(props.context, sid), + events: collectHostLogs(), + isPt: isPt(), + }) + } + + const fg = () => props.context?.theme?.text?.base + const muted = () => props.context?.theme?.text?.muted ?? fg() + const accent = () => resolveAccentColor(tuiPrefs().theme?.accent, props.context?.theme) + const success = () => props.context?.theme?.text?.feedback?.success?.base ?? accent() + const errFg = () => props.context?.theme?.text?.feedback?.error?.base ?? accent() + + onMount(() => { + setCockpitOpen(true) + let popMode: (() => void) | undefined + try { + popMode = props.context?.keymap?.mode?.push?.(ROUTE_MODE) + } catch { + /* ignore */ + } + const timer = setInterval(() => setTick((t) => t + 1), 1500) + cockpitController = { + setTab: (id) => { + setTab(id) + setSelectedRow(0) + }, + nextTab: () => { + const idx = TABS.findIndex((t) => t.id === tab()) + const next = TABS[(idx + 1) % TABS.length] + if (next) setTab(next.id) + }, + prevTab: () => { + const idx = TABS.findIndex((t) => t.id === tab()) + const prev = TABS[(idx - 1 + TABS.length) % TABS.length] + if (prev) setTab(prev.id) + }, + moveRow: (delta) => { + const snap = snapshot() + const max = + tab() === 'swarm' + ? snap.swarm.rows.length + : tab() === 'flightdeck' + ? Math.max(snap.flightdeck.steps.length, snap.flightdeck.logs.length) + : 0 + if (max <= 0) return + setSelectedRow((cur) => Math.max(0, Math.min(max - 1, cur + delta))) + }, + toggleDetail: () => setShowDetail((v) => !v), + exportReplay: () => { + try { + const relPath = writeCockpitReplayArtifact(props.workspaceDir, snapshot()) + setExportNote(relPath) + setTick((t) => t + 1) + } catch { + setExportNote('export_failed') + } + }, + refresh: () => setTick((t) => t + 1), + close: props.onClose, + } + onCleanup(() => { + clearInterval(timer) + cockpitController = undefined + setCockpitOpen(false) + try { + popMode?.() + } catch { + /* ignore */ + } + }) + }) + + return ( + + {/* Header Bar */} + + + + {'◈ PANTHEON COCKPIT '} + + {`· ${snapshot().sessionTitle} (${snapshot().modelName})`} + + + {'[ Esc / Q ]'} + + + + {/* Tab Row */} + + + {(t) => { + const active = () => tab() === t.id + return ( + setTab(t.id)}> + {`[${t.label}]`} + + ) + }} + + + + {'─'.repeat(72)} + + {/* Page 1: Overview */} + + + + {'Token Meter & Context'} + + + {`Velocity: ${snapshot().overview.velocityBars} Context: ${snapshot().overview.contextGauge} Spend: $${snapshot().overview.sessionCost.toFixed(4)}`} + + + + + {'Runtime Surfaces & Health'} + + + {(item) => {` ● ${item.label.padEnd(28)} ${item.status}`}} + + + + + + {'Work Map (Topology)'} + + + {(line) => {line}} + + + + + + {/* Page 2: Swarm */} + + + + {`● ${snapshot().swarm.activeCount} active ✓ ${snapshot().swarm.completedCount} done ✗ ${snapshot().swarm.failedCount} failed · $${snapshot().swarm.totalCost.toFixed(4)}`} + + + 0} + fallback={ + + {isPt() + ? 'Nenhum subagente registrado nesta sessão ainda.' + : 'No subagent delegations recorded in this session yet.'} + + } + > + + {(row, idx) => { + const sel = () => idx() === selectedRow() + const marker = + row.status === 'running' ? '●' : row.status === 'failed' ? '✗' : '✓' + return ( + { + setSelectedRow(idx()) + setShowDetail((v) => !v) + }} + > + + {`${sel() ? '▸' : ' '} ${marker} @${row.agent.padEnd(11)} ${row.ganttBar} ${String(row.durationSec).padStart(5)}s $${row.cost.toFixed(3)}`} + + + + {` id=${row.id} kind=${row.kind} tokens=${row.tokens} model=${row.model ?? 'inherited'}`} + + + + ) + }} + + + + + + + {/* Page 3: Flightdeck */} + + + + {'GATE (Safety, Guardrails & Step-Ledger)'} + + {` ${snapshot().flightdeck.gateGlyphs}`} + {` ${snapshot().flightdeck.gateSummary}`} + + + + {'Step-Ledger & Active Tasks'} + + 0} + fallback={{' (no active step-ledger entries)'}} + > + + {(st) => ( + + {` ▸ ${st.stepKey.padEnd(20)} [${st.state.padEnd(11)}] @${st.agent} ${st.objective.slice(0, 36)}`} + + )} + + + + + + + {'Semantic Event Stream'} + + 0} + fallback={{' (no bus telemetry events captured yet)'}} + > + + {(ev) => ( + + {` [${ev.kind}] @${ev.agent}: ${ev.detail.slice(0, 56)}`} + + )} + + + + + + cockpitController?.exportReplay()}> + + {'[ x Export Replay Trace ]'} + + + {(note) => {`✓ ${note()}`}} + + + + + + {'─'.repeat(72)} + + + { + '1-3 tabs · Tab/Shift+Tab switch · ↑↓ select · Enter detail · x replay · r refresh · Esc/q close' + } + + + ) +} + +function plainReturnRoute(cur: any): WindowRoute | undefined { + if (!cur || typeof cur.type !== 'string') return undefined + if (cur.type === 'session' && typeof cur.sessionID === 'string') { + return { type: 'session', sessionID: cur.sessionID } + } + if (cur.type === 'home') return { type: 'home' } + return undefined +} + +export function setupPantheonCockpit(context: Context, resolveCwd: () => string): void { + const ui = (context as any)?.ui + if (typeof ui?.router?.register === 'function') { + try { + ui.router.register({ + name: ROUTE_NAME, + render: ({ data }: { data?: { returnRoute?: WindowRoute } }) => { + const ret = data?.returnRoute + const onClose = () => { + if (ret) ui.router.navigate(ret) + else ui.router.navigate({ type: 'home' }) + } + return ( + + ) + }, + }) + routerReady = true + } catch { + routerReady = false + } + } + + const routeGated = () => { + try { + const r = ui?.router?.current?.() + return r?.type === 'plugin' && r.name === ROUTE_NAME + } catch { + return false + } + } + + const commands = [ + { + id: 'pantheon.cockpit.tab1', + title: 'Overview tab', + bind: '1', + run: () => { + cockpitController?.setTab('overview') + return undefined + }, + }, + { + id: 'pantheon.cockpit.tab2', + title: 'Swarm tab', + bind: '2', + run: () => { + cockpitController?.setTab('swarm') + return undefined + }, + }, + { + id: 'pantheon.cockpit.tab3', + title: 'Flightdeck tab', + bind: '3', + run: () => { + cockpitController?.setTab('flightdeck') + return undefined + }, + }, + { + id: 'pantheon.cockpit.next', + title: 'Next Cockpit tab', + bind: 'tab', + run: () => { + cockpitController?.nextTab() + return undefined + }, + }, + { + id: 'pantheon.cockpit.prev', + title: 'Previous Cockpit tab', + bind: 'shift+tab', + run: () => { + cockpitController?.prevTab() + return undefined + }, + }, + { + id: 'pantheon.cockpit.up', + title: 'Previous row', + bind: 'up,k', + run: () => { + cockpitController?.moveRow(-1) + return undefined + }, + }, + { + id: 'pantheon.cockpit.down', + title: 'Next row', + bind: 'down,j', + run: () => { + cockpitController?.moveRow(1) + return undefined + }, + }, + { + id: 'pantheon.cockpit.detail', + title: 'Toggle row detail', + bind: 'enter', + run: () => { + cockpitController?.toggleDetail() + return undefined + }, + }, + { + id: 'pantheon.cockpit.export', + title: 'Export Flightdeck replay trace', + bind: 'x', + run: () => { + cockpitController?.exportReplay() + return undefined + }, + }, + { + id: 'pantheon.cockpit.refresh', + title: 'Refresh Cockpit', + bind: 'r', + run: () => { + cockpitController?.refresh() + return undefined + }, + }, + { + id: 'pantheon.cockpit.close', + title: 'Close Cockpit', + bind: 'escape,q', + run: () => { + cockpitController?.close() + return undefined + }, + }, + ] + + try { + ;(context as any).keymap?.layer?.(() => ({ + mode: ROUTE_MODE, + priority: 1, + enabled: () => routeGated() || cockpitOpen(), + commands, + })) + ;(context as any).keymap?.layer?.(() => ({ + mode: 'global' as const, + priority: 1, + enabled: () => cockpitOpen(), + commands, + })) + } catch { + /* keymap unavailable */ + } +} + +export function openPantheonCockpit(context: Context, workspaceDir: string): void { + const ui = (context as any)?.ui + if (routerReady && typeof ui?.router?.navigate === 'function') { + let returnRoute: WindowRoute | undefined + try { + const cur = ui.router.current() + if (!(cur?.type === 'plugin' && cur.name === ROUTE_NAME)) { + returnRoute = plainReturnRoute(cur) + } + } catch { + returnRoute = undefined + } + ui.router.navigate({ + type: 'plugin', + name: ROUTE_NAME, + ...(returnRoute ? { data: { returnRoute } } : {}), + }) + return + } + + try { + const curSid = + ui?.router?.current?.()?.type === 'session' ? ui.router.current().sessionID : undefined + ui?.dialog?.show?.( + () => ( + ui?.dialog?.clear?.()} + /> + ), + () => {}, + ) + ui?.dialog?.set?.({ size: 'large', centered: true }) + } catch { + /* ignore */ + } +} diff --git a/src/plugins/tui/src/index.tsx b/src/plugins/tui/src/index.tsx index bc03d9fe..3be0f3bc 100644 --- a/src/plugins/tui/src/index.tsx +++ b/src/plugins/tui/src/index.tsx @@ -21,6 +21,9 @@ import { onMount, Show, } from 'solid-js' +import { openArtifactsDialog } from './artifacts' +import { type PantheonArtifactEntry, scanPantheonArtifacts } from './artifacts-state.ts' +import { openPantheonCockpit, setupPantheonCockpit } from './cockpit' import { CONTEXT_BAR_CELLS, type ContextProgressTone, @@ -129,6 +132,18 @@ export const SIDEBAR_REFRESH_EVENTS = [ 'session.idle', 'session.status', 'session.deleted', + 'session.execution.started', + 'session.execution.succeeded', + 'session.execution.failed', + 'session.execution.interrupted', + 'session.message.content.updated', + 'session.tool.input.started', + 'session.tool.called', + 'session.tool.success', + 'session.tool.failed', + 'session.step.ended', + 'session.usage.updated', + 'session.permissions', ] as const satisfies readonly SidebarDataEvent[] /* ─── Active Preset Detection ────────────────────────────── @@ -892,30 +907,202 @@ export type ToolCallSummary = { failures: number } -/** Conta chamadas de ferramentas e eventuais falhas/erros. Pure. */ -export function countToolCalls(messages: readonly any[] | null | undefined): ToolCallSummary { - if (!Array.isArray(messages)) return { total: 0, failures: 0 } +export type ToolDomain = 'mem' | 'ctx' | 'code' | 'edit' | 'read' | 'shell' | 'agent' | 'mcp' + +export type ToolDomainSummary = ToolCallSummary & { + byDomain: Partial> + activeTool: string | null +} + +const TOOL_DOMAIN_ORDER: readonly ToolDomain[] = [ + 'mem', + 'ctx', + 'code', + 'edit', + 'read', + 'shell', + 'agent', + 'mcp', +] + +function normalizeToolName(part: any): string { + const raw = + typeof part?.name === 'string' ? part.name : typeof part?.tool === 'string' ? part.tool : '' + return raw.trim() +} + +/** Extrai chamadas `tools.(...)` de dentro do Code Mode (`execute` / `search`) + * para revelar a tool real do Pantheon/OpenCode usada. Pure. */ +function resolveEffectiveToolNames(part: any): string[] { + const outer = normalizeToolName(part) + if (outer === '') return [] + if (outer.toLowerCase() === 'execute') { + const code = part?.state?.input?.code + if (typeof code === 'string' && code !== '') { + const inner: string[] = [] + for (const match of code.matchAll(/\btools\.([a-zA-Z0-9_]+)\s*\(/g)) { + if (match[1]) inner.push(match[1]) + } + if (inner.length > 0) return inner + } + } + return [outer] +} + +function extractToolFilePaths(part: any): string[] { + const found: string[] = [] + const input = part?.state?.input && typeof part.state.input === 'object' ? part.state.input : null + if (!input) return found + for (const candidate of [input.file, input.path, input.filePath, input.target]) { + const base = fileBasename(candidate) + if (base && !found.includes(base)) found.push(base) + } + if (typeof input.code === 'string' && input.code !== '') { + for (const match of input.code.matchAll( + /\b(?:file|path|filePath|target)\s*:\s*["']([^"']+)["']/g, + )) { + const base = fileBasename(match[1]) + if (base && !found.includes(base)) found.push(base) + } + } + return found +} + +function isToolFailureState(state: any): boolean { + return ( + state?.status === 'error' || + state?.status === 'failed' || + state?.error !== undefined || + (typeof state?.exitCode === 'number' && state.exitCode !== 0) + ) +} + +function isToolActiveState(state: any): boolean { + return state?.status === 'running' || state?.status === 'pending' || state?.status === 'streaming' +} + +/** Classifica uma tool (nativa, OpenCode ou MCP externa) em domínio curto e + * verbo de 3–4 caracteres para Sidebar/Dispatch. Pure. */ +export function classifyToolPart(rawName: unknown): { domain: ToolDomain; verb: string } { + const name = typeof rawName === 'string' ? rawName.trim().toLowerCase() : '' + if (name === '') return { domain: 'agent', verb: 'tool' } + if (name === 'question') return { domain: 'agent', verb: 'ask' } + if (name.startsWith('memory_')) return { domain: 'mem', verb: 'mem' } + if ( + name.startsWith('context_') || + name.startsWith('goal_') || + name === 'pantheon_step_ledger' || + name === 'todowrite' || + name === 'todoread' + ) { + return { domain: 'ctx', verb: name.startsWith('todo') ? 'todo' : 'ctx' } + } + if (name.startsWith('code_')) return { domain: 'code', verb: 'code' } + if ( + name === 'hashline_edit' || + name === 'edit' || + name === 'edit_file' || + name === 'write' || + name === 'write_file' || + name === 'patch' + ) { + return { domain: 'edit', verb: 'edit' } + } + if ( + name === 'read' || + name === 'read_file' || + name === 'glob' || + name === 'grep' || + name === 'list' + ) { + return { domain: 'read', verb: 'read' } + } + if (name === 'shell' || name === 'bash' || name === 'run_command' || name === 'execute') { + return { domain: 'shell', verb: name === 'execute' ? 'exec' : 'bash' } + } + if (name === 'pantheon_deepwork') return { domain: 'agent', verb: 'plan' } + if ( + name === 'subagent' || + name.startsWith('pantheon_') || + name === 'vision' || + name === 'webfetch' || + name === 'websearch' || + name === 'search' + ) { + return { domain: 'agent', verb: name.startsWith('web') ? 'web' : 'agnt' } + } + if (name.includes('_') && !name.startsWith('pantheon_')) { + return { domain: 'mcp', verb: 'mcp' } + } + return { domain: 'agent', verb: 'tool' } +} + +/** Resume chamadas de ferramentas por domínio nativo + tool em execução. Pure. */ +export function summarizeToolDomains( + messages: readonly any[] | null | undefined, +): ToolDomainSummary { + const byDomain: Partial> = {} + if (!Array.isArray(messages)) return { total: 0, failures: 0, byDomain, activeTool: null } let total = 0 let failures = 0 + let activeTool: string | null = null for (const message of messages) { if (message?.type !== 'assistant' || !Array.isArray(message.content)) continue for (const part of message.content) { if (part?.type !== 'tool') continue total++ const state = part.state - if ( - state?.status === 'error' || - state?.status === 'failed' || - state?.error !== undefined || - (typeof state?.exitCode === 'number' && state.exitCode !== 0) - ) { - failures++ + if (isToolFailureState(state)) failures++ + const effectiveNames = resolveEffectiveToolNames(part) + for (const toolName of effectiveNames) { + const { domain } = classifyToolPart(toolName) + byDomain[domain] = (byDomain[domain] ?? 0) + 1 + } + if (isToolActiveState(state) && effectiveNames.length > 0) { + activeTool = effectiveNames[effectiveNames.length - 1] ?? null } } } + return { total, failures, byDomain, activeTool } +} + +/** Conta chamadas de ferramentas e eventuais falhas/erros. Pure. */ +export function countToolCalls(messages: readonly any[] | null | undefined): ToolCallSummary { + const { total, failures } = summarizeToolDomains(messages) return { total, failures } } +/** Formata a quebra compacta por domínio (`mem:2 ctx:1 code:1 · ✦ memory_search`) + * para caber na largura da sidebar. Retorna null sem dados. Pure. */ +export function formatToolDomainLine( + summary: ToolDomainSummary | null | undefined, + max = SIDEBAR_CONTENT_WIDTH, +): string | null { + if (!summary) return null + const chunks: string[] = [] + for (const domain of TOOL_DOMAIN_ORDER) { + const count = summary.byDomain?.[domain] ?? 0 + if (count > 0) chunks.push(`${domain}:${count}`) + } + const active = + typeof summary.activeTool === 'string' && summary.activeTool.trim() !== '' + ? `\u2726 ${summary.activeTool.trim()}` + : null + if (chunks.length === 0 && !active) return null + const joined = chunks.join(' ') + const raw = active ? (joined ? `${joined} \u00B7 ${active}` : active) : joined + if (cellWidth(raw) <= max) return raw + if (active) { + const activeFit = truncateLabel(active, max) + const remaining = max - cellWidth(activeFit) - 3 + if (remaining >= 5 && joined !== '') { + return `${truncateLabel(joined, remaining)} \u00B7 ${activeFit}` + } + return activeFit + } + return truncateLabel(raw, max) +} + export function formatToolCallLine( summary: ToolCallSummary | null | undefined, locale = 'en', @@ -1307,10 +1494,16 @@ export function latestTodoItems(messages: readonly any[] | null | undefined): To const parts = message.content for (let position = parts.length - 1; position >= 0; position--) { const part = parts[position] - if (part?.type !== 'tool' || part?.name !== 'todowrite') continue + if (part?.type !== 'tool') continue if (part?.state?.status !== 'completed') continue - const items = parseTodoItems(part.state.input) - return items.length === 0 ? null : items + if (part?.name === 'todowrite') { + const items = parseTodoItems(part.state.input) + return items.length === 0 ? null : items + } + if (part?.name === 'execute' && resolveEffectiveToolNames(part).includes('todowrite')) { + const fromOutput = parseTodoItems(part.state.output) + if (fromOutput.length > 0) return fromOutput + } } } return null @@ -1891,6 +2084,112 @@ export function collectSubagentCalls( export type DelegationState = 'running' | 'completed' | 'failed' | 'interrupted' export type DelegationTone = 'warning' | 'error' | 'success' +export type ChildAttention = 'question' | 'permission' | 'error' + +/** Atividade em tempo real extraída das mensagens em cache de um subagente. */ +export type ChildActivity = { + activeVerb: string | null + activeTool: string | null + attention: ChildAttention | null + recentTools: string[] + filesTouched: string[] + lastSnippet: string | null +} + +function fileBasename(raw: unknown): string | null { + if (typeof raw !== 'string') return null + const trimmed = raw.trim() + if (trimmed === '') return null + const normalized = trimmed.replaceAll('\\', '/') + const parts = normalized.split('/').filter(Boolean) + return parts.length > 0 ? (parts[parts.length - 1] ?? null) : null +} + +/** Extrai atividade ao vivo, alertas de bloqueio e histórico recente de um filho + * a partir de suas mensagens em cache. Pure, fail-open. */ +export function extractChildActivity( + messages: readonly any[] | null | undefined, + status?: string, + hostAttention?: { permission?: boolean; question?: boolean }, +): ChildActivity | null { + let activeTool: string | null = null + let activeVerb: string | null = null + let latestTool: string | null = null + let latestVerb: string | null = null + let attention: ChildAttention | null = hostAttention?.permission + ? 'permission' + : hostAttention?.question + ? 'question' + : status === 'error' || status === 'failed' + ? 'error' + : null + const recentTools: string[] = [] + const filesTouched: string[] = [] + let lastSnippet: string | null = null + + if (Array.isArray(messages)) { + for (const message of messages) { + if (message?.type !== 'assistant' || !Array.isArray(message.content)) continue + for (const part of message.content) { + if (part?.type === 'text' && typeof part.text === 'string') { + const clean = part.text.replace(/\s+/g, ' ').trim() + if (clean !== '') lastSnippet = clean + continue + } + if (part?.type !== 'tool') continue + const effectiveNames = resolveEffectiveToolNames(part) + if (effectiveNames.length === 0) continue + const name = effectiveNames[effectiveNames.length - 1] ?? '' + const state = part.state + const { verb } = classifyToolPart(name) + latestTool = name + latestVerb = verb + for (const toolName of effectiveNames) { + const existingIdx = recentTools.indexOf(toolName) + if (existingIdx !== -1) recentTools.splice(existingIdx, 1) + recentTools.unshift(toolName) + if (recentTools.length > 4) recentTools.pop() + } + for (const base of extractToolFilePaths(part)) { + if (!filesTouched.includes(base)) { + filesTouched.unshift(base) + if (filesTouched.length > 3) filesTouched.pop() + } + } + if (isToolActiveState(state)) { + activeTool = name + activeVerb = verb + if (name.toLowerCase() === 'question') attention = 'question' + } else if ( + attention === null && + isToolFailureState(state) && + (status === 'error' || status === 'failed' || status === 'retry') + ) { + attention = 'error' + } + } + } + } + + if (attention === 'question' || attention === 'permission') activeVerb = 'ask' + else if (attention === 'error') activeVerb = 'err' + else if (activeVerb === null && (status === 'running' || status === 'busy')) { + activeVerb = latestVerb + activeTool = latestTool + } + + if ( + activeVerb === null && + activeTool === null && + attention === null && + recentTools.length === 0 && + filesTouched.length === 0 && + lastSnippet === null + ) { + return null + } + return { activeVerb, activeTool, attention, recentTools, filesTouched, lastSnippet } +} /** Grace window for a child that has not started yet. V2's `session.status()` * returns `idle` both for "created but not started" and for "finished", so an @@ -1927,6 +2226,8 @@ export type DelegationView = { kindOrigin: DispatchKindOrigin /** The parent asked for this child to run in the background. */ background: boolean + /** Atividade ao vivo extraída do filho (quando em cache). */ + activity?: ChildActivity | null } /** Map the host's live session status to a display state. V2 exposes only @@ -2065,6 +2366,8 @@ export type DispatchEntry = { export type CollectDispatchOptions = { now?: number calls?: Map + activities?: Map + includeChildActivity?: boolean } /** `message.list` of one session, degrades to an empty list. The host's list is @@ -2111,14 +2414,16 @@ export function toDispatchEntry( status: string | undefined, now = Date.now(), call?: SubagentCall | null, + activity?: ChildActivity | null, ): DispatchEntry { const title = typeof child?.title === 'string' && child.title !== '' ? child.title : null const parentID = typeof child?.parentID === 'string' && child.parentID !== '' ? child.parentID : null const description = typeof call?.description === 'string' && call.description !== '' ? call.description : null + const baseView = toDelegationView(child, status, now, call) return { - view: toDelegationView(child, status, now, call), + view: activity ? { ...baseView, activity } : baseView, title, description, parentID, @@ -2165,13 +2470,54 @@ export function collectDispatch( continue } if (!child) continue - entries.push( - toDispatchEntry(child, sessionStatusOf(context, childID), now, calls.get(childID) ?? null), - ) + const status = sessionStatusOf(context, childID) + let hasPerm = false + let hasQuest = false + try { + const perms = context?.data?.session?.permission?.(childID) + if (Array.isArray(perms) && perms.length > 0) hasPerm = true + } catch { + /* host may omit permission accessor */ + } + try { + const quests = context?.data?.session?.question?.(childID) + if (Array.isArray(quests) && quests.length > 0) hasQuest = true + } catch { + /* host may omit question accessor */ + } + let activity = options.activities?.get(childID) ?? null + if (activity === null && options.includeChildActivity === true) { + activity = extractChildActivity(readSessionMessages(context, childID), status, { + permission: hasPerm, + question: hasQuest, + }) + } else if (hasPerm || hasQuest) { + activity = + extractChildActivity(undefined, status, { + permission: hasPerm, + question: hasQuest, + }) ?? activity + } + entries.push(toDispatchEntry(child, status, now, calls.get(childID) ?? null, activity)) } return entries.sort((a, b) => compareDelegations(a.view, b.view)) } +/** Enrich pre-collected dispatch entries with live child activity from cached + * child transcripts (used by the full-width dispatch panel). */ +export function enrichDispatchEntries( + context: any, + entries: readonly DispatchEntry[], +): DispatchEntry[] { + return entries.map((entry) => { + if (entry.view.activity) return entry + const childMsgs = readSessionMessages(context, entry.view.id) + const status = sessionStatusOf(context, entry.view.id) + const activity = extractChildActivity(childMsgs, status) + return activity ? { ...entry, view: { ...entry.view, activity } } : entry + }) +} + /* ─── Block layout ───────────────────────────────────────── */ /** Sidebar blocks in render order. Spacing is derived from this list instead of @@ -2346,6 +2692,36 @@ export function dispatchTotalCost(views: readonly DelegationView[]): number { return total } +function effectiveChildPresentation( + view: Pick, + frame = 0, +): { marker: string; suffix: string; tone: DelegationTone } { + const act = view.activity + const attention = act?.attention ?? null + const tone: DelegationTone = + attention === 'error' + ? 'error' + : attention === 'question' || attention === 'permission' + ? 'warning' + : 'success' + const marker = + attention === 'error' + ? '! ' + : attention === 'question' || attention === 'permission' + ? '? ' + : `${spinnerFrame(frame)} ` + + let suffix = dispatchKindSuffix(view.kind, view.background) + if (attention === 'question' || attention === 'permission') { + suffix = `${DISPATCH_KIND_SEPARATOR}ask${view.background === true ? DISPATCH_BACKGROUND_MARKER : ''}` + } else if (attention === 'error') { + suffix = `${DISPATCH_KIND_SEPARATOR}err${view.background === true ? DISPATCH_BACKGROUND_MARKER : ''}` + } else if ((view.kind === null || view.kind === 'oth') && act?.activeVerb) { + suffix = `${DISPATCH_KIND_SEPARATOR}${act.activeVerb}${view.background === true ? DISPATCH_BACKGROUND_MARKER : ''}` + } + return { marker, suffix, tone } +} + /** One live child: `⠸ · `, with the model as a * fourth column only when the row still fits and the child is unclassified — * the kind is the stronger evidence at this width, so it takes the model's @@ -2359,11 +2735,10 @@ export function runningChildRowText( frame = 0, max = DISPATCH_MAX_WIDTH, ): string { - const marker = `${spinnerFrame(frame)} ` + const { marker, suffix } = effectiveChildPresentation(view, frame) const duration = dispatchElapsed(view, now).padStart(DISPATCH_DURATION_WIDTH) const cost = formatDispatchCost(view.cost).padStart(DISPATCH_COST_WIDTH) const model = dispatchModelText(view) - const suffix = dispatchKindSuffix(view.kind, view.background) const limit = Math.max(1, max) const row = (agentWidth: number, withModel: boolean, withSuffix = true): string => { const kind = withSuffix ? suffix : '' @@ -2515,8 +2890,8 @@ export function failedSuffixText(failures: number | null | undefined): string | return `${rounded} ${rounded === 1 ? 'falha' : 'falhas'}` } -/** One rendered live row: its text plus the session it navigates to. */ -export type DispatchRunningLine = { id: string; text: string } +/** One rendered live row: its text, attention tone and session id. */ +export type DispatchRunningLine = { id: string; text: string; tone?: DelegationTone } /** Everything the `Dispatch` block renders, already joined and capped. */ export type DispatchBlockView = { @@ -2569,6 +2944,7 @@ export function buildDispatchBlock( const runningLines = running.map((view) => ({ id: view.id, text: runningChildRowText(view, now, frame, max), + tone: effectiveChildPresentation(view, frame).tone, })) const summary = completedSummaryText(finished.length, finishedCost, groups.length) @@ -2765,9 +3141,22 @@ export function dispatchPanelRowText( DISPATCH_PANEL_MIN_AGENT_WIDTH, Math.min(DISPATCH_PANEL_AGENT_WIDTH, width - (DISPATCH_PANEL_ROW_FIXED_WIDTH + costWidth)), ) - const marker = dispatchPanelMarker(view.state, frame) + const marker = + view.activity?.attention === 'error' + ? '! ' + : view.activity?.attention === 'question' || view.activity?.attention === 'permission' + ? '? ' + : dispatchPanelMarker(view.state, frame) const agent = dispatchPanelCell(dispatchAgentText(view, DISPATCH_PANEL_AGENT_WIDTH), agentWidth) - const kind = dispatchPanelCell(view.kind, DISPATCH_PANEL_KIND_WIDTH) + const effectiveKind = + view.activity?.attention === 'question' || view.activity?.attention === 'permission' + ? 'ask' + : view.activity?.attention === 'error' + ? 'err' + : (view.kind === null || view.kind === 'oth') && view.activity?.activeVerb + ? view.activity.activeVerb + : view.kind + const kind = dispatchPanelCell(effectiveKind, DISPATCH_PANEL_KIND_WIDTH) const cost = costText.padStart(costWidth) const duration = truncateLabel( dispatchElapsed(view, now), @@ -2830,6 +3219,27 @@ export function dispatchPanelDetail( max, ), ) + const activity = view.activity + if (activity) { + if (activity.attention === 'question') { + lines.push(truncateLabel('status ? aguardando resposta do usuário', max)) + } else if (activity.attention === 'permission') { + lines.push(truncateLabel('status ? aguardando permissão', max)) + } else if (activity.attention === 'error') { + lines.push(truncateLabel('status ! erro na execução', max)) + } else if (activity.activeTool) { + lines.push(truncateLabel(`status \u2726 ${activity.activeTool}`, max)) + } + const toolsText = activity.recentTools.length > 0 ? activity.recentTools.join(', ') : '' + const filesText = activity.filesTouched.length > 0 ? activity.filesTouched.join(', ') : '' + if (toolsText || filesText) { + const joined = [toolsText, filesText].filter(Boolean).join(SPEND_LINE_SEPARATOR) + lines.push(truncateLabel(`tools ${joined}`, max)) + } + if (activity.lastSnippet) { + lines.push(truncateLabel(`\u21B3 ${activity.lastSnippet}`, max)) + } + } return lines } @@ -3126,7 +3536,7 @@ export function createDispatchPanelModel( const entries = createMemo(() => { revision() if (!isOpen()) return [] - return collectDispatch(context, activeSessionID()) + return enrichDispatchEntries(context, collectDispatch(context, activeSessionID())) }) const layout = createMemo(() => dispatchPanelLayout(panel().width)) @@ -3652,6 +4062,8 @@ export type SidebarModel = { tokenAnatomyLine: Accessor /** Contagem de chamadas de ferramentas e falhas. */ toolCallsLine: Accessor + /** Quebra por domínio de tools nativas + tool ativa. */ + toolCallsDetailLine: Accessor /** Badge de compactação (ex: "1x compact"). */ compactionBadge: Accessor /** Badge de turnos da sessão (ex: "↻ 4 turns"). */ @@ -3950,6 +4362,7 @@ export function createSidebarModel( const rootID = activeSessionID() const collected: any[] = [] let todo: TodoItem[] = [] + const activities = new Map() for (const id of familySessionIDs()) { let list: any[] = [] try { @@ -3959,9 +4372,14 @@ export function createSidebarModel( /* one unreadable session must not hide the others */ } collected.push(...list.slice(-MODEL_USAGE_MESSAGE_LIMIT)) - if (id === rootID) todo = latestTodoItems(list) ?? [] + if (id === rootID) { + todo = latestTodoItems(list) ?? [] + } else { + const activity = extractChildActivity(list, sessionStatusOf(context, id)) + if (activity) activities.set(id, activity) + } } - return { messages: collected, todo } + return { messages: collected, todo, activities } }) const usageMessages = createMemo(() => transcript().messages) // Ordered + capped todo rows; empty when the transcript has no `todowrite`, @@ -4147,7 +4565,11 @@ export function createSidebarModel( revision() const id = activeSessionID() if (id === '') return [] - return collectDispatch(context, id, { now: Date.now(), calls: subagentCalls() }) + return collectDispatch(context, id, { + now: Date.now(), + calls: subagentCalls(), + activities: transcript().activities, + }) }) /** What the sidebar block renders: the collector's rows, nothing else. */ @@ -4174,10 +4596,13 @@ export function createSidebarModel( }) const tokenAnatomyLine = createMemo(() => formatTokenAnatomyLine(tokenAnatomy())) const tokenAnatomySplit = createMemo(() => formatTokenAnatomySplit(tokenAnatomy())) - const toolCalls = createMemo(() => countToolCalls(messages())) + const toolCalls = createMemo(() => summarizeToolDomains(messages())) const toolCallsLine = createMemo(() => formatToolCallLine(toolCalls(), tuiPrefs().layout.language), ) + const toolCallsDetailLine = createMemo(() => + formatToolDomainLine(toolCalls(), SIDEBAR_CONTENT_WIDTH), + ) const compactions = createMemo(() => extractCompactionInfo(messages())) const compactionBadge = createMemo(() => { const info = compactions() @@ -4327,6 +4752,7 @@ export function createSidebarModel( turnCostLine, tokenAnatomyLine, toolCallsLine, + toolCallsDetailLine, compactionBadge, turnsBadge, tokenAnatomySplit, @@ -4492,10 +4918,13 @@ function SidebarInner(props: SidebarProps): JSX.Element { // session each drop independently; nothing reflows — the column just shortens. const header = () => tuiPrefs().sidebar.header const availableUpdate = useAvailableUpdate(__PANTHEON_VERSION__) + const isPt = () => resolveLanguage(tuiPrefs().layout?.language) === 'pt-BR' const updateBadge = () => formatUpdateBadge(__PANTHEON_VERSION__, availableUpdate(), { - isPt: resolveLanguage(tuiPrefs().layout?.language) === 'pt-BR', + isPt: isPt(), }) + const artifacts = useWorkspaceArtifacts(context) + const activePlan = () => artifacts().find((entry) => entry.kind === 'plan') return ( - {(badge) => {badge()}} + {(badge) => ( + { + void openPantheonSettings(context, { initialTab: 'updates' }) + }} + > + {badge()} + + )} {/* Preset plus the provider of the model in use — both derived from host @@ -4753,6 +5190,9 @@ function SidebarInner(props: SidebarProps): JSX.Element { {model.gateStatus()} + + {(line) => {line()}} + 0}> Session · reported cost @@ -4848,7 +5288,7 @@ function SidebarInner(props: SidebarProps): JSX.Element { {(row: DispatchRunningLine) => ( - {row.text} + {row.text} )} @@ -4878,6 +5318,37 @@ function SidebarInner(props: SidebarProps): JSX.Element { + + 0}> + + + {(plan) => ( + { + openArtifactsDialog(context, resolveSidebarCwd(context), { + initialArtifactId: plan().id, + }) + }} + flexShrink={0} + > + {`▸ Plan: ${truncateLabel(plan().title, 22)}`} + + )} + + { + openArtifactsDialog(context, resolveSidebarCwd(context)) + }} + flexShrink={0} + > + + {isPt() + ? `◈ Artefatos (${artifacts().length})` + : `◈ Artifacts (${artifacts().length})`} + + + + ) } @@ -5085,17 +5556,79 @@ function PantheonSettingsCommandLayer(props: { context: any }) { void openPantheonSettings(props.context) }, }, + { + id: 'pantheon.updates.open', + title: 'Pantheon: Updates & Cleanup', + group: 'Pantheon', + palette: true, + slash: { name: 'pantheon-updates' }, + run: () => { + void openPantheonSettings(props.context, { initialTab: 'updates' }) + }, + }, + { + id: 'pantheon.whats-new.open', + title: "Pantheon: What's New", + group: 'Pantheon', + palette: true, + slash: { name: 'pantheon-whats-new', aliases: ['whats-new'] }, + run: () => { + void maybeShowWhatsNew(props.context, { force: true }) + }, + }, + { + id: 'pantheon.artifacts.open', + title: 'Pantheon: Artifacts', + group: 'Pantheon', + palette: true, + slash: { name: 'pantheon-artifacts', aliases: ['artifacts'] }, + run: () => { + openArtifactsDialog(props.context, resolveSidebarCwd(props.context)) + }, + }, + { + id: 'pantheon.cockpit.open', + title: 'Pantheon: Mission Control Cockpit', + group: 'Pantheon', + palette: true, + slash: { name: 'pantheon-cockpit', aliases: ['cockpit'] }, + run: () => { + openPantheonCockpit(props.context, resolveSidebarCwd(props.context)) + }, + }, ], })) return null } +function useWorkspaceArtifacts(context: any): () => PantheonArtifactEntry[] { + const [entries, setEntries] = createSignal( + scanPantheonArtifacts(resolveSidebarCwd(context)), + ) + let lastScan = Date.now() + const refresh = () => { + const now = Date.now() + if (now - lastScan < 1500) return + lastScan = now + setEntries(scanPantheonArtifacts(resolveSidebarCwd(context))) + } + onMount(() => { + setEntries(scanPantheonArtifacts(resolveSidebarCwd(context))) + const stop = subscribeSidebarRefresh(context, refresh) + onCleanup(stop) + }) + return entries +} + /** Home-screen status contribution. The sidebar slot is session-scoped, so * before the first prompt the sidebar may not mount at all (Known Issue) — * this keeps a compact Pantheon line visible on the home footer meanwhile. */ function HomeStatus(props: { context: any }) { const preset = useActivePreset(props.context).preset const availableUpdate = useAvailableUpdate(__PANTHEON_VERSION__) + const artifacts = useWorkspaceArtifacts(props.context) + const activePlan = () => artifacts().find((entry) => entry.kind === 'plan') + const isPt = () => resolveLanguage(tuiPrefs().layout?.language) === 'pt-BR' const accent = () => resolveAccentColor( tuiDraftPreview()?.theme?.accent ?? tuiPrefs().theme?.accent, @@ -5104,7 +5637,7 @@ function HomeStatus(props: { context: any }) { const muted = () => props.context.theme?.text?.muted ?? props.context.theme?.text?.base const updateBadge = () => formatUpdateBadge(__PANTHEON_VERSION__, availableUpdate(), { - isPt: resolveLanguage(tuiPrefs().layout?.language) === 'pt-BR', + isPt: isPt(), compact: true, }) return ( @@ -5113,7 +5646,50 @@ function HomeStatus(props: { context: any }) { {`Pantheon v${__PANTHEON_VERSION__}${preset().name ? ` ${PRESET_MARKER} ${preset().name}` : ''}`} - {(badge) => {` · ${badge()}`}} + + {(badge) => ( + { + void openPantheonSettings(props.context, { initialTab: 'updates' }) + }} + > + {` · ${badge()}`} + + )} + + + {(plan) => ( + { + openArtifactsDialog(props.context, resolveSidebarCwd(props.context), { + initialArtifactId: plan().id, + }) + }} + > + {` · ▸ Plan: ${truncateLabel(plan().title, 20)}`} + + )} + + 0}> + { + openArtifactsDialog(props.context, resolveSidebarCwd(props.context)) + }} + > + + {isPt() + ? ` · Artefatos (${artifacts().length})` + : ` · Artifacts (${artifacts().length})`} + + + + { + openPantheonCockpit(props.context, resolveSidebarCwd(props.context)) + }} + > + {' · ◈ Cockpit'} + ) @@ -5267,6 +5843,11 @@ const plugin = Plugin.define({ } catch { /* settings unavailable on this host — the command toasts/fails open */ } + try { + setupPantheonCockpit(context, () => resolveSidebarCwd(context)) + } catch { + /* cockpit unavailable on this host */ + } // In-session settings docked above prompt (session.composer.top) const unregisterSettingsSlot = context.ui.slot({ append: 'session.composer.top', diff --git a/src/plugins/tui/src/legacy-audit.ts b/src/plugins/tui/src/legacy-audit.ts index 0c3c3b15..fa0965ca 100644 --- a/src/plugins/tui/src/legacy-audit.ts +++ b/src/plugins/tui/src/legacy-audit.ts @@ -65,7 +65,9 @@ export interface LegacyCleanResult { export interface LegacyAuditOptions { readonly workspaceDir?: string readonly globalConfigDir?: string + readonly cacheDir?: string readonly runningVersion?: string + readonly activeBundlePath?: string readonly includeRedundantCopiedAssets?: boolean readonly env?: Record } @@ -135,6 +137,124 @@ const LEGACY_INSTRUCTION_FILES: readonly string[] = Object.freeze([ 'zeus-workflow.instructions.md', ]) +export function resolveAuditCacheDir( + env: Record = process.env, +): string | undefined { + if (env.NODE_TEST_CONTEXT) return undefined + if (env.XDG_CACHE_HOME?.trim()) return join(resolve(env.XDG_CACHE_HOME.trim()), 'opencode', 'npm') + const home = env.HOME?.trim() + return home ? join(resolve(home), '.cache', 'opencode', 'npm') : undefined +} + +function readCachedPackageVersion(candidateDir: string): string | null { + for (const manifest of [ + join(candidateDir, 'node_modules', 'pantheon-opencode', 'package.json'), + join(candidateDir, 'package.json'), + ]) { + try { + if (!existsSync(manifest)) continue + const parsed = JSON.parse(readFileSync(manifest, 'utf8')) as { version?: unknown } + if (typeof parsed.version === 'string' && parsed.version.trim() !== '') { + return parsed.version.trim() + } + } catch { + /* ignore */ + } + } + return null +} + +function isUnderPath(parentDir: string, targetPath: string): boolean { + try { + const parentReal = realpathSync(parentDir) + const targetReal = realpathSync(targetPath) + return targetReal === parentReal || targetReal.startsWith(`${parentReal}/`) + } catch { + return false + } +} + +function collectCacheAudit(cacheNpmDir: string, options: LegacyAuditOptions): LegacyAuditItem[] { + const items: LegacyAuditItem[] = [] + if (!existsSync(cacheNpmDir) || cacheNpmDir === '/') return items + + const activeBundlePath = options.activeBundlePath ?? '' + const runningVersion = options.runningVersion ? String(options.runningVersion).trim() : '' + const runningIsStable = runningVersion !== '' && !/-(?:beta|rc)\./i.test(runningVersion) + const seen = new Set() + + const pushCacheItem = (targetPath: string, reason: string) => { + const resolved = resolve(targetPath) + if (seen.has(resolved) || !existsSync(resolved)) return + if (activeBundlePath && isUnderPath(resolved, activeBundlePath)) return + seen.add(resolved) + items.push({ + path: resolved, + scope: 'global', + category: 'drift', + reason, + bytes: measurePathBytes(resolved), + }) + } + + let channelEntries: Array<{ name: string; isDirectory: () => boolean }> = [] + try { + channelEntries = readdirSync(cacheNpmDir, { withFileTypes: true }) + } catch { + return items + } + + for (const entry of channelEntries) { + if (!entry.isDirectory()) continue + if (entry.name !== 'pantheon-opencode' && !entry.name.startsWith('pantheon-opencode@')) { + continue + } + const channelDir = join(cacheNpmDir, entry.name) + + // Flag coexisting @beta channel cache once user runs a stable install. + if (runningIsStable && entry.name === 'pantheon-opencode@beta') { + pushCacheItem(channelDir, 'Stale @beta plugin cache coexisting with stable install') + continue + } + + // Keep only the active (or newest) timestamp/version revision inside a channel directory. + try { + const revisions = readdirSync(channelDir, { withFileTypes: true }) + .filter( + (sub) => sub.isDirectory() && sub.name !== 'node_modules' && !sub.name.startsWith('.'), + ) + .map((sub) => { + const full = join(channelDir, sub.name) + let mtime = 0 + try { + mtime = statSync(full).mtimeMs + } catch {} + return { + path: full, + mtime, + active: Boolean(activeBundlePath && isUnderPath(full, activeBundlePath)), + } + }) + if (revisions.length > 1) { + revisions.sort((a, b) => Number(b.active) - Number(a.active) || b.mtime - a.mtime) + for (const stale of revisions.slice(1)) { + const ver = readCachedPackageVersion(stale.path) + pushCacheItem( + stale.path, + ver + ? `Stale cached Pantheon plugin revision (v${ver})` + : 'Stale cached Pantheon plugin revision', + ) + } + } + } catch { + /* ignore unreadable cache dir */ + } + } + + return items +} + export function resolveAuditGlobalDir( env: Record = process.env, ): string | undefined { @@ -616,6 +736,9 @@ export function scanLegacyArtifacts(options: LegacyAuditOptions = {}): LegacyAud const globalConfigDir = options.globalConfigDir ? resolve(options.globalConfigDir) : resolveAuditGlobalDir(options.env) + const cacheNpmDir = options.cacheDir + ? resolve(options.cacheDir) + : resolveAuditCacheDir(options.env) const items: LegacyAuditItem[] = [] let unmigratedStores = 0 @@ -626,6 +749,10 @@ export function scanLegacyArtifacts(options: LegacyAuditOptions = {}): LegacyAud unmigratedStores += res.unmigratedStores } + if (cacheNpmDir && existsSync(cacheNpmDir) && cacheNpmDir !== '/') { + items.push(...collectCacheAudit(cacheNpmDir, options)) + } + if ( workspaceDir && existsSync(workspaceDir) && @@ -665,6 +792,9 @@ export function cleanLegacyArtifacts( const globalConfigDir = options.globalConfigDir ? resolve(options.globalConfigDir) : resolveAuditGlobalDir(options.env) + const cacheNpmDir = options.cacheDir + ? resolve(options.cacheDir) + : resolveAuditCacheDir(options.env) const scopeFilter = options.scope && options.scope !== 'all' ? options.scope : null const scan = scanLegacyArtifacts(options) @@ -699,7 +829,11 @@ export function cleanLegacyArtifacts( continue } const scopeRoot = item.scope === 'global' ? globalConfigDir : workspaceDir - if (!scopeRoot || !isConfinedWithin(scopeRoot, item.path)) { + const confineRoot = + item.scope === 'global' && cacheNpmDir && isConfinedWithin(cacheNpmDir, item.path) + ? cacheNpmDir + : scopeRoot + if (!confineRoot || !isConfinedWithin(confineRoot, item.path)) { errors.push({ path: item.path, reason: 'Path escapes target scope root' }) continue } @@ -712,7 +846,7 @@ export function cleanLegacyArtifacts( if (item.path.endsWith('.db')) { for (const suffix of ['-wal', '-shm', '-journal']) { const sidecar = `${item.path}${suffix}` - if (existsSync(sidecar) && isConfinedWithin(scopeRoot, sidecar)) { + if (existsSync(sidecar) && isConfinedWithin(confineRoot, sidecar)) { const sidecarBytes = measurePathBytes(sidecar) rmSync(sidecar, { force: true }) removed.push(sidecar) diff --git a/src/plugins/tui/src/mermaid-ascii.ts b/src/plugins/tui/src/mermaid-ascii.ts new file mode 100644 index 00000000..437ac6df --- /dev/null +++ b/src/plugins/tui/src/mermaid-ascii.ts @@ -0,0 +1,540 @@ +/** + * mermaid-ascii.ts — Zero-dependency Unicode diagram renderer for Mermaid + * code blocks displayed inside the `/pantheon-artifacts` terminal reader. + */ + +interface FlowNode { + readonly id: string + label: string +} + +interface FlowEdge { + readonly from: string + readonly to: string + readonly label?: string + readonly dashed: boolean +} + +function cleanLabel(raw: string): string { + return raw + .replace(//gi, ' / ') + .replace(/^["'`]|["'`]$/g, '') + .replace(/\s+/g, ' ') + .trim() +} + +function splitOperandsOutsideDelimiters(text: string): string[] { + const out: string[] = [] + let cur = '' + let quote: string | null = null + let bracketDepth = 0 + for (let i = 0; i < text.length; i += 1) { + const ch = text[i] ?? '' + if (quote) { + if (ch === quote) quote = null + cur += ch + continue + } + if (ch === '"' || ch === "'") { + quote = ch + cur += ch + continue + } + if (ch === '[' || ch === '(' || ch === '{') { + bracketDepth += 1 + cur += ch + continue + } + if ((ch === ']' || ch === ')' || ch === '}') && bracketDepth > 0) { + bracketDepth -= 1 + cur += ch + continue + } + if (ch === '&' && bracketDepth === 0) { + const part = cur.trim() + if (part) out.push(part) + cur = '' + continue + } + cur += ch + } + const tail = cur.trim() + if (tail) out.push(tail) + return out +} + +function parseNodeToken(token: string): { id: string; label?: string } { + const trimmed = token.trim() + if (trimmed === '[*]') return { id: '__star__', label: '●' } + + const match = + /^([A-Za-z0-9_.:-]+)\s*(?:\[\[([^\]]*)\]\]|\(\(([^)]*)\)\)|\(\[([^\]]*)\]\)|\{\{([^}]*)\}\}|\[([^\]]*)\]|\(([^)]*)\)|\{([^}]*)\})?$/.exec( + trimmed, + ) + if (!match) { + const idOnly = trimmed.replace(/[^A-Za-z0-9_.:-]/g, '') || trimmed + return { id: idOnly, label: cleanLabel(trimmed) } + } + const id = match[1] ?? trimmed + const rawLabel = match[2] ?? match[3] ?? match[4] ?? match[5] ?? match[6] ?? match[7] ?? match[8] + return rawLabel !== undefined ? { id, label: cleanLabel(rawLabel) } : { id } +} + +function truncateText(text: string, maxLen: number): string { + if (maxLen <= 1) return text.slice(0, Math.max(0, maxLen)) + if (text.length <= maxLen) return text + return `${text.slice(0, maxLen - 1)}…` +} + +function drawBox(label: string, maxWidth: number, indent = ''): string[] { + const innerLimit = Math.max(8, maxWidth - indent.length - 4) + const text = truncateText(label, innerLimit) + const bar = '─'.repeat(text.length + 2) + return [`${indent}╭${bar}╮`, `${indent}│ ${text} │`, `${indent}╰${bar}╯`] +} + +const ARROW_PATTERN = String.raw`(?:(?:-->|-\.->|==>)\|([^|]+)\||--\s+([^->\n]+?)\s+-->|-\.\s*([^.]+?)\s*\.->|==\s*([^=]+?)\s*==>|-->|-\.->|==>|---)` +const EDGE_RE = new RegExp(String.raw`^(.*?)\s+${ARROW_PATTERN}\s+(.*)$`) + +function splitChainOperands(line: string): { + parts: string[] + connectors: Array<{ label?: string; dashed: boolean }> +} { + // Walk left-to-right extracting arrow connectors between operand groups + const arrowTokenRe = new RegExp(String.raw`\s+(${ARROW_PATTERN})\s+`, 'g') + const parts: string[] = [] + const connectors: Array<{ label?: string; dashed: boolean }> = [] + let lastIdx = 0 + for (const m of line.matchAll(arrowTokenRe)) { + const idx = m.index ?? 0 + parts.push(line.slice(lastIdx, idx).trim()) + const arrow = m[1] ?? '' + const labelRaw = m[2] ?? m[3] ?? m[4] ?? m[5] + connectors.push({ + label: labelRaw ? cleanLabel(labelRaw) : undefined, + dashed: arrow.includes('-.'), + }) + lastIdx = idx + m[0].length + } + parts.push(line.slice(lastIdx).trim()) + return { parts, connectors } +} + +function parseFlowchart(lines: readonly string[]): { + direction: 'LR' | 'TD' + nodes: Map + edges: FlowEdge[] +} { + const nodes = new Map() + const edges: FlowEdge[] = [] + let direction: 'LR' | 'TD' = 'TD' + + const ensureNode = (id: string, label?: string): void => { + const existing = nodes.get(id) + if (existing) { + if (label && existing.label === existing.id) existing.label = label + return + } + nodes.set(id, { id, label: label ?? id }) + } + + for (const rawLine of lines) { + const stripped = rawLine.trim() + if (!stripped || stripped.startsWith('%%')) continue + if (/^(flowchart|graph)\s+/i.test(stripped)) { + if (/\bLR\b|\bRL\b/i.test(stripped)) direction = 'LR' + continue + } + if (/^(classDef|style|linkStyle|click|class|direction|subgraph|end)\b/i.test(stripped)) { + continue + } + + for (const stmt of stripped.split(';')) { + const s = stmt.trim() + if (!s) continue + if (EDGE_RE.test(` ${s} `) || ['-->', '-.->', '==>', '---'].some((tok) => s.includes(tok))) { + const { parts, connectors } = splitChainOperands(s) + if (parts.length >= 2 && connectors.length === parts.length - 1) { + for (let i = 0; i < connectors.length; i += 1) { + const leftGroup = splitOperandsOutsideDelimiters(parts[i] ?? '') + const rightGroup = splitOperandsOutsideDelimiters(parts[i + 1] ?? '') + const conn = connectors[i] + for (const lTok of leftGroup) { + const left = parseNodeToken(lTok) + ensureNode(left.id, left.label) + for (const rTok of rightGroup) { + const right = parseNodeToken(rTok) + ensureNode(right.id, right.label) + edges.push({ + from: left.id, + to: right.id, + label: conn?.label, + dashed: Boolean(conn?.dashed), + }) + } + } + } + continue + } + } + + const single = parseNodeToken(s) + if (single.id) ensureNode(single.id, single.label) + } + } + + return { direction, nodes, edges } +} + +function renderHorizontalChain( + chain: readonly FlowNode[], + edges: readonly FlowEdge[], + maxWidth: number, +): string[] | null { + if (chain.length < 2 || chain.length > 5) return null + const boxes = chain.map((n) => drawBox(n.label, 28)) + const edgeWidths = edges.map((e) => (e.label ? Math.max(5, e.label.length + 4) : 4)) + const totalW = + boxes.reduce((sum, b) => sum + (b[0]?.length ?? 0), 0) + + edgeWidths.reduce((sum, w) => sum + w, 0) + if (totalW > maxWidth) return null + + const top: string[] = [] + const mid: string[] = [] + const bot: string[] = [] + for (let i = 0; i < boxes.length; i += 1) { + const box = boxes[i] + if (!box) continue + top.push(box[0] ?? '') + mid.push(box[1] ?? '') + bot.push(box[2] ?? '') + if (i < edges.length) { + const ew = edgeWidths[i] ?? 4 + const lbl = edges[i]?.label + const stem = edges[i]?.dashed ? '╌' : '─' + const arrowMid = `${stem.repeat(ew - 1)}►` + const arrowTop = lbl ? ` ${lbl}`.padEnd(ew, ' ') : ' '.repeat(ew) + top.push(arrowTop) + mid.push(arrowMid) + bot.push(' '.repeat(ew)) + } + } + return [top.join(''), mid.join(''), bot.join('')] +} + +function renderFlowchart(lines: readonly string[], maxWidth: number): string[] | null { + const { direction, nodes, edges } = parseFlowchart(lines) + if (nodes.size === 0) return null + + const outEdges = new Map() + const inDegree = new Map() + const incomingSources = new Map() + for (const id of nodes.keys()) { + outEdges.set(id, []) + inDegree.set(id, 0) + incomingSources.set(id, []) + } + for (const e of edges) { + outEdges.get(e.from)?.push(e) + inDegree.set(e.to, (inDegree.get(e.to) ?? 0) + 1) + incomingSources.get(e.to)?.push(e.from) + } + + // Try horizontal side-by-side rendering for concise LR chains + const isSimpleChain = + edges.length === nodes.size - 1 && + [...outEdges.values()].every((list) => list.length <= 1) && + [...inDegree.values()].every((deg) => deg <= 1) + if (direction === 'LR' && isSimpleChain) { + const startId = [...nodes.keys()].find((id) => (inDegree.get(id) ?? 0) === 0) + if (startId) { + const chain: FlowNode[] = [] + const chainEdges: FlowEdge[] = [] + let cur: string | undefined = startId + const seen = new Set() + while (cur && !seen.has(cur)) { + seen.add(cur) + const node = nodes.get(cur) + if (!node) break + chain.push(node) + const nextEdge = outEdges.get(cur)?.[0] + if (!nextEdge) break + chainEdges.push(nextEdge) + cur = nextEdge.to + } + const horiz = renderHorizontalChain(chain, chainEdges, maxWidth) + if (horiz) return horiz + } + } + + // General vertical DAG/tree box renderer + const out: string[] = [] + const visited = new Set() + const renderedJoin = new Set() + + const renderSubtree = ( + nodeId: string, + prefix: string, + isRoot: boolean, + edgeFromParent?: FlowEdge, + ): void => { + const node = nodes.get(nodeId) + if (!node) return + const deg = inDegree.get(nodeId) ?? 0 + + if (!isRoot && deg > 1 && !renderedJoin.has(nodeId)) { + const sources = incomingSources.get(nodeId) ?? [] + const remaining = sources.some((src) => !visited.has(src) && src !== edgeFromParent?.from) + if (remaining) { + const lbl = edgeFromParent?.label ? ` (${edgeFromParent.label})` : '' + out.push( + `${prefix} ╰─► converges at ${truncateText(node.label, Math.max(12, maxWidth - prefix.length - 20))}${lbl}`, + ) + return + } + renderedJoin.add(nodeId) + } + + if (visited.has(nodeId)) { + const lbl = edgeFromParent?.label ? ` (${edgeFromParent.label})` : '' + out.push( + `${prefix} ╰─► ↺ ${truncateText(node.label, Math.max(12, maxWidth - prefix.length - 10))}${lbl}`, + ) + return + } + visited.add(nodeId) + + if (!isRoot && deg > 1) { + const sources = (incomingSources.get(nodeId) ?? []) + .map((s) => nodes.get(s)?.id ?? s) + .filter((v, i, arr) => arr.indexOf(v) === i) + out.push(`${prefix} (from ${sources.join(', ')})`) + } + + const box = drawBox(node.label, maxWidth, prefix) + out.push(...box) + + const children = outEdges.get(nodeId) ?? [] + if (children.length === 0) return + + if (children.length === 1 && children[0]) { + const child = children[0] + const stemX = `${prefix} ` + const lineChar = child.dashed ? '┆' : '│' + const lbl = child.label ? ` ${child.label}` : '' + out.push(`${stemX}${lineChar}${lbl}`) + out.push(`${stemX}▼`) + renderSubtree(child.to, prefix, false, child) + return + } + + for (let i = 0; i < children.length; i += 1) { + const child = children[i] + if (!child) continue + const isLast = i === children.length - 1 + const branch = isLast ? '└──►' : '├──►' + const edgeTag = child.label ? `[${child.label}] ` : '' + const childPrefix = `${prefix} ${isLast ? ' ' : '│ '}` + out.push( + `${prefix} ${branch} ${edgeTag}${truncateText(nodes.get(child.to)?.label ?? child.to, Math.max(12, maxWidth - prefix.length - edgeTag.length - 8))}`, + ) + const grandChildren = outEdges.get(child.to) ?? [] + if (!visited.has(child.to)) { + visited.add(child.to) + if (grandChildren.length > 0) { + for (let j = 0; j < grandChildren.length; j += 1) { + const gc = grandChildren[j] + if (!gc) continue + const gcDeg = inDegree.get(gc.to) ?? 0 + if (gcDeg > 1) { + const srcs = incomingSources.get(gc.to) ?? [] + const pending = srcs.some((s) => !visited.has(s)) + if (pending) { + out.push( + `${childPrefix} ╰─► converges at ${truncateText(nodes.get(gc.to)?.label ?? gc.to, Math.max(12, maxWidth - childPrefix.length - 20))}`, + ) + continue + } + } + out.push(`${childPrefix} │`) + out.push(`${childPrefix} ▼`) + renderSubtree(gc.to, childPrefix, false, gc) + } + } + } + } + } + + const roots = [...nodes.keys()].filter((id) => (inDegree.get(id) ?? 0) === 0) + const queue = roots.length > 0 ? roots : [...nodes.keys()].slice(0, 1) + for (let i = 0; i < queue.length; i += 1) { + const rootId = queue[i] + if (!rootId || visited.has(rootId)) continue + if (out.length > 0) out.push('') + renderSubtree(rootId, '', true) + } + + for (const id of nodes.keys()) { + if (!visited.has(id)) { + if (out.length > 0) out.push('') + renderSubtree(id, '', true) + } + } + + return out +} + +function renderSequence(lines: readonly string[], maxWidth: number): string[] | null { + const participants = new Map() + const messages: Array<{ from: string; to: string; text: string; dashed: boolean }> = [] + + const addParticipant = (id: string, label?: string): void => { + if (!participants.has(id)) participants.set(id, cleanLabel(label ?? id)) + else if (label) participants.set(id, cleanLabel(label)) + } + + for (const raw of lines) { + const s = raw.trim() + if (!s || s.startsWith('%%') || /^sequenceDiagram\b/i.test(s)) continue + const partMatch = /^(?:participant|actor)\s+([A-Za-z0-9_.-]+)(?:\s+as\s+(.+))?$/i.exec(s) + if (partMatch?.[1]) { + addParticipant(partMatch[1], partMatch[2]) + continue + } + const msgMatch = /^([A-Za-z0-9_.-]+)\s*(-->>|->>|-->|->)\s*([A-Za-z0-9_.-]+)\s*:\s*(.*)$/.exec( + s, + ) + if (msgMatch?.[1] && msgMatch[2] && msgMatch[3]) { + addParticipant(msgMatch[1]) + addParticipant(msgMatch[3]) + messages.push({ + from: msgMatch[1], + to: msgMatch[3], + text: cleanLabel(msgMatch[4] ?? ''), + dashed: msgMatch[2].startsWith('--'), + }) + } + } + + if (participants.size === 0 || messages.length === 0) return null + const ids = [...participants.keys()] + const count = ids.length + const colStep = Math.floor((maxWidth - 4) / Math.max(1, count - 1)) + + // Render full aligned lifelines when 2-4 participants fit comfortably + if (count >= 2 && count <= 4 && colStep >= 18) { + const centers = ids.map((_, idx) => 5 + idx * Math.min(colStep, 22)) + const totalW = (centers[count - 1] ?? 10) + 8 + const out: string[] = [] + const topLine = Array(totalW).fill(' ') + const midLine = Array(totalW).fill(' ') + const botLine = Array(totalW).fill(' ') + + for (let i = 0; i < count; i += 1) { + const id = ids[i] + if (!id) continue + const label = truncateText(participants.get(id) ?? id, 12) + const boxW = label.length + 4 + const start = Math.max(0, (centers[i] ?? 0) - Math.floor(boxW / 2)) + const top = `╭${'─'.repeat(label.length + 2)}╮` + const mid = `│ ${label} │` + const bot = `╰${'─'.repeat(label.length + 2)}╯` + for (let k = 0; k < boxW; k += 1) { + if (start + k < totalW) { + topLine[start + k] = top[k] + midLine[start + k] = mid[k] + botLine[start + k] = k === (centers[i] ?? 0) - start ? '┬' : bot[k] + } + } + } + out.push(topLine.join('').trimEnd(), midLine.join('').trimEnd(), botLine.join('').trimEnd()) + + const emptyLifelines = (): string[] => { + const arr = Array(totalW).fill(' ') + for (const c of centers) arr[c] = '│' + return arr + } + + for (const msg of messages) { + const iFrom = ids.indexOf(msg.from) + const iTo = ids.indexOf(msg.to) + if (iFrom < 0 || iTo < 0) continue + const cFrom = centers[iFrom] ?? 0 + const cTo = centers[iTo] ?? 0 + const left = Math.min(cFrom, cTo) + const right = Math.max(cFrom, cTo) + + const labelRow = emptyLifelines() + const msgText = truncateText(msg.text, Math.max(6, right - left - 2)) + for (let k = 0; k < msgText.length; k += 1) { + if (left + 2 + k < totalW) labelRow[left + 2 + k] = msgText[k] + } + out.push(labelRow.join('').trimEnd()) + + const arrowRow = emptyLifelines() + const wire = msg.dashed ? '┄' : '─' + for (let x = left + 1; x < right; x += 1) arrowRow[x] = wire + if (cFrom < cTo) { + arrowRow[left] = '├' + arrowRow[right - 1] = '►' + } else { + arrowRow[left + 1] = '◄' + arrowRow[right] = '┤' + } + out.push(arrowRow.join('').trimEnd()) + } + out.push(emptyLifelines().join('').trimEnd()) + return out + } + + // Fallback compact sequence list + return messages.map((m, idx) => { + const arrow = m.dashed ? '╌╌►' : '──►' + const fromLbl = participants.get(m.from) ?? m.from + const toLbl = participants.get(m.to) ?? m.to + return truncateText(`${idx + 1}. [${fromLbl}] ${arrow} [${toLbl}]: ${m.text}`, maxWidth) + }) +} + +function renderStateDiagram(lines: readonly string[], maxWidth: number): string[] | null { + const normalized = lines.map((line) => { + const trimmed = line.trim() + if (/^stateDiagram(?:-v2)?$/i.test(trimmed)) return 'flowchart TD' + // Convert "A --> B : label" into "A -->|label| B" + const arrowWithLabel = /^(.+?)\s*-->\s*(.+?)\s*:\s*(.+)$/.exec(trimmed) + if (arrowWithLabel?.[1] && arrowWithLabel[2] && arrowWithLabel[3]) { + return `${arrowWithLabel[1].trim()} -->|${arrowWithLabel[3].trim()}| ${arrowWithLabel[2].trim()}` + } + return line + }) + return renderFlowchart(normalized, maxWidth) +} + +export function renderMermaidToUnicode( + rawLines: readonly string[], + maxWidth = 76, +): { header: string; lines: string[] } { + const firstMeaningful = rawLines.map((l) => l.trim()).find((l) => l && !l.startsWith('%%')) ?? '' + + if (/^(?:flowchart|graph)\b/i.test(firstMeaningful)) { + const rendered = renderFlowchart(rawLines, maxWidth) + if (rendered && rendered.length > 0) { + return { header: '[Diagram: Flowchart]', lines: rendered } + } + } else if (/^sequenceDiagram\b/i.test(firstMeaningful)) { + const rendered = renderSequence(rawLines, maxWidth) + if (rendered && rendered.length > 0) { + return { header: '[Diagram: Sequence]', lines: rendered } + } + } else if (/^stateDiagram/i.test(firstMeaningful)) { + const rendered = renderStateDiagram(rawLines, maxWidth) + if (rendered && rendered.length > 0) { + return { header: '[Diagram: State]', lines: rendered } + } + } + + return { + header: '[Mermaid Diagram]', + lines: rawLines.map((l) => ` ${l.trim()}`).filter((l) => l.trim().length > 0), + } +} diff --git a/src/plugins/tui/src/pantheon-settings-state.ts b/src/plugins/tui/src/pantheon-settings-state.ts index 7c08ec80..90f44449 100644 --- a/src/plugins/tui/src/pantheon-settings-state.ts +++ b/src/plugins/tui/src/pantheon-settings-state.ts @@ -481,11 +481,48 @@ export function buildAboutTab(version: string, extra?: AboutTabExtra): SettingsT }, ] + const toolRows: SettingsRow[] = [ + { + id: 'about.tools.memory', + name: isPt ? 'Memória FTS5' : 'FTS5 Memory', + value: isPt ? 'ativo · 6 tools' : 'active · 6 tools', + note: 'memory_store, memory_recall, memory_search, memory_forget, memory_list, memory_stats', + }, + { + id: 'about.tools.persistence', + name: isPt ? 'Checkpoints & Metas' : 'Checkpoints & Goals', + value: isPt ? 'ativo · 6 tools' : 'active · 6 tools', + note: 'context_save, context_get, goal_create, goal_get, goal_update, goal_done', + }, + { + id: 'about.tools.codemap', + name: isPt ? 'Codemap & AST' : 'Codemap & AST', + value: isPt ? 'ativo · 5 tools' : 'active · 5 tools', + note: 'code_index, code_query, code_neighbors, ast_search, ast_rewrite', + }, + { + id: 'about.tools.edit', + name: isPt ? 'Edição & Execução' : 'Edit & Execution', + value: isPt ? 'ativo · 4 tools' : 'active · 4 tools', + note: 'hashline_edit, shell, todowrite, todoread', + }, + { + id: 'about.tools.governance', + name: isPt ? 'Orquestração & Custos' : 'Orchestration & Cost', + value: isPt ? 'ativo · 9 tools' : 'active · 9 tools', + note: 'pantheon_cost, pantheon_model, pantheon_skill_search, pantheon_deepwork, pantheon_step_ledger, pantheon_agent_forge, pantheon_local_decision, pantheon_review_verdict, pantheon_worktree', + }, + ] + const groups = [{ title: isPt ? 'Sistema & Plataforma' : 'System & Platform', rows: sysRows }] if (extra?.preset !== undefined || extra?.decisionEnabled !== undefined) { groups.push({ title: isPt ? 'Governança & Roteamento' : 'Governance & Routing', rows: govRows }) } groups.push({ title: isPt ? 'Projeto & Referências' : 'Project & References', rows: refRows }) + groups.push({ + title: isPt ? 'Ferramentas Nativas (30)' : 'Native Tools (30)', + rows: toolRows, + }) return { id: 'about', diff --git a/src/plugins/tui/src/pantheon-settings.tsx b/src/plugins/tui/src/pantheon-settings.tsx index 247457fe..2c050018 100644 --- a/src/plugins/tui/src/pantheon-settings.tsx +++ b/src/plugins/tui/src/pantheon-settings.tsx @@ -26,6 +26,7 @@ import { execFile } from 'node:child_process' import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs' import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' import type { Context } from '@opencode/plugin/tui/context' import { createEffect, createSignal, For, onCleanup, onMount, Show } from 'solid-js' import { @@ -93,7 +94,6 @@ import { writeActivePreset, writeConfiguredVisionModel, } from './preset-state.ts' -import { applyQuotaRow, buildQuotaTab, readQuotaPrefs, writeQuotaPrefs } from './quota-state.ts' import { resolveLanguage } from './settings-i18n.ts' import { applyTuiRow, @@ -423,7 +423,7 @@ function resolveRunningVersion(): string { // ── The window view (presentational; both surfaces render it) ────────── const NAME_WIDTH = 24 -const VALUE_WIDTH = 30 +const VALUE_WIDTH = 32 export function SettingsWindow(props: { version: string @@ -501,6 +501,8 @@ export function SettingsWindow(props: { {...(props.boxRef !== undefined ? { ref: props.boxRef } : {})} focusable flexDirection="column" + width="100%" + {...(props.isDialog ? { minWidth: 80 } : {})} {...(props.height !== undefined ? { height: props.height } : { flexGrow: 1, flexBasis: 0 })} minHeight={0} border={!props.isDialog} @@ -536,7 +538,8 @@ export function SettingsWindow(props: { flexDirection="row" flexWrap="wrap" flexGrow={1} - flexShrink={0} + flexShrink={1} + minWidth={0} columnGap={1} rowGap={1} > @@ -594,10 +597,16 @@ export function SettingsWindow(props: { const gutter = () => (isSelected() ? '▸ ' : ' ') const valueCell = () => { const formatted = formatValueDisplay(display()) - if (row.cycle !== undefined) return `< ${formatted} >` - if (row.action !== undefined) return `[ ${formatted} ]` - if (row.id.startsWith('autonomy.gradient.')) return `[ref] ${formatted}` - return formatted + const raw = + row.cycle !== undefined + ? `< ${formatted} >` + : row.action !== undefined + ? `[ ${formatted} ]` + : row.id.startsWith('autonomy.gradient.') + ? `[ref] ${formatted}` + : formatted + const maxLen = VALUE_WIDTH - (staged() ? 2 : 0) + return raw.length > maxLen ? `${raw.slice(0, maxLen - 1)}…` : raw } return ( - + {`${gutter()}${row.name}`.padEnd(NAME_WIDTH + 2)} + { props.onSelectRow?.(row.id) props.onCycleValue?.(row.id, 1) }} > + @@ -825,6 +839,7 @@ interface PageApi { } let pageApi: PageApi | undefined +let pendingInitialTabId: string | undefined function createWindowController( context: Context, @@ -869,9 +884,20 @@ function createWindowController( const [confirmExit, setConfirmExit] = createSignal(false) // Initial non-blocking audit scan for Updates & Maintenance panel + const activeBundlePath = (() => { + try { + return fileURLToPath(import.meta.url) + } catch { + return undefined + } + })() queueMicrotask(() => { try { - const scan = scanLegacyArtifacts({ workspaceDir, runningVersion: currentVersion }) + const scan = scanLegacyArtifacts({ + workspaceDir, + runningVersion: currentVersion, + ...(activeBundlePath ? { activeBundlePath } : {}), + }) setLegacyAudit(scan.summary) } catch { /* fail-open */ @@ -939,7 +965,6 @@ function createWindowController( buildGatesTab(load(), lang, activeScope), buildDecisionTab(decision(), process.env, readAuthProviders(), readConfigProviders(), lang), buildPresetTab(presetInput(), lang), - buildQuotaTab(undefined, lang, readQuotaPrefs()), buildTuiTab(tuiPrefs(), lang), buildAutonomyTab({ goalLoop: goalLoop(), @@ -970,6 +995,13 @@ function createWindowController( ] } + if (pendingInitialTabId !== undefined) { + const requestedTab = pendingInitialTabId + pendingInitialTabId = undefined + const targetIdx = tabs().findIndex((tab) => tab.id === requestedTab) + if (targetIdx >= 0) setPage(targetIdx) + } + const rows = () => tabRows(tabs()[page()] ?? tabs()[0] ?? EMPTY_TAB) const move = (delta: number) => { @@ -1073,7 +1105,11 @@ function createWindowController( setLegacyScanning(true) setLegacyNotice(undefined) try { - const scan = scanLegacyArtifacts({ workspaceDir, runningVersion: currentVersion }) + const scan = scanLegacyArtifacts({ + workspaceDir, + runningVersion: currentVersion, + ...(activeBundlePath ? { activeBundlePath } : {}), + }) setLegacyAudit(scan.summary) const isPt = resolveLanguage(tuiPrefs().layout?.language) === 'pt-BR' setNotice( @@ -1097,8 +1133,13 @@ function createWindowController( setLegacyCleaning(true) const isPt = resolveLanguage(tuiPrefs().layout?.language) === 'pt-BR' try { - const res = cleanLegacyArtifacts({ workspaceDir, runningVersion: currentVersion }) - const after = scanLegacyArtifacts({ workspaceDir, runningVersion: currentVersion }) + const auditOpts = { + workspaceDir, + runningVersion: currentVersion, + ...(activeBundlePath ? { activeBundlePath } : {}), + } + const res = cleanLegacyArtifacts(auditOpts) + const after = scanLegacyArtifacts(auditOpts) setLegacyAudit(after.summary) setLoad(readOverridesLoad(workspaceDir)) const summaryMsg = isPt @@ -1287,16 +1328,6 @@ function createWindowController( return { ok: false, reason: 'tui prefs storage unavailable' } } } - if (id.startsWith('quota.')) { - try { - const current = readQuotaPrefs() - const updated = applyQuotaRow(current, id, value) - writeQuotaPrefs(updated) - return { ok: true } - } catch { - return { ok: false, reason: 'quota prefs disk write failed' } - } - } return { ok: false, reason: 'unknown staged row' } } @@ -1598,7 +1629,7 @@ function openSettingsDialog(context: Context): void { setDialogOpen(true) pageApi = controller.api const rendererHeight = () => (context as any).renderer?.height ?? 30 - const maxHeight = () => Math.min(16, Math.max(8, Math.floor(rendererHeight() * 0.55))) + const maxHeight = () => Math.min(28, Math.max(14, Math.floor(rendererHeight() * 0.78))) try { context.ui.dialog.show( () => ( @@ -1628,7 +1659,7 @@ function openSettingsDialog(context: Context): void { ), close, ) - context.ui.dialog.set({ size: 'medium', centered: true }) + context.ui.dialog.set({ size: 'large', centered: true }) } catch { /* dialog stack unavailable — fail-open */ } @@ -1897,7 +1928,7 @@ export function setupPantheonSettings( { id: 'pantheon.settings.next.tab', title: 'Next settings tab', - bind: 'tab', + bind: 'tab,]', run: () => { pageApi?.nextTab() return undefined @@ -1906,7 +1937,7 @@ export function setupPantheonSettings( { id: 'pantheon.settings.prev.tab', title: 'Previous settings tab', - bind: 'shift+tab', + bind: 'shift+tab,[', run: () => { pageApi?.prevTab?.() return undefined @@ -1979,11 +2010,20 @@ export function setupPantheonSettings( // ── The entry point (command run) ────────────────────────────────────── -export async function openPantheonSettings(context: Context): Promise { +export async function openPantheonSettings( + context: Context, + options: { initialTab?: string } = {}, +): Promise { + if (options.initialTab) { + pendingInitialTabId = options.initialTab + } + const sessionID = (context as any)?.sessionID ?? routeSessionID(context) ?? activeSessionId() try { const prefs = tuiPrefs() const viewMode = prefs.layout?.settingsView ?? 'docked' - if (viewMode === 'fullscreen' && routerAvailable && context.ui?.router?.navigate) { + const shouldUseRoute = + viewMode !== 'dialog' && (viewMode === 'fullscreen' || !sessionID) && routerAvailable + if (shouldUseRoute && context.ui?.router?.navigate) { let returnRoute: WindowRoute | undefined try { const current = context.ui.router.current() @@ -2010,20 +2050,33 @@ export async function openPantheonSettings(context: Context): Promise { /* preferences check failed — fall through to docked */ } - // Primary mode: docked in session.composer.top - const sessionID = (context as any)?.sessionID ?? routeSessionID(context) ?? activeSessionId() + // Primary mode: docked in session.composer.top (fall back to dialog if no router/session) if (!sessionID) { - try { - context.ui?.toast?.show?.({ - variant: 'info', - title: 'Pantheon', - message: 'Open a session first: Pantheon settings opens above the prompt box.', - }) - } catch {} + openSettingsDialog(context) return } if (settingsOpen()) { + if (options.initialTab && pageApi) { + const tabOrder = [ + 'gates', + 'decision', + 'preset', + 'tui', + 'autonomy', + 'j1', + 'updates', + 'changelog', + 'doctor', + 'about', + ] + const targetIdx = tabOrder.indexOf(options.initialTab) + if (targetIdx >= 0) { + pendingInitialTabId = undefined + pageApi.jumpTab(targetIdx) + return + } + } closePantheonSettings() return } diff --git a/src/plugins/tui/src/quota-state.ts b/src/plugins/tui/src/quota-state.ts deleted file mode 100644 index 08181bf5..00000000 --- a/src/plugins/tui/src/quota-state.ts +++ /dev/null @@ -1,190 +0,0 @@ -/** - * quota-state.ts — the Quotas & Spend tab (inspired by opencode-quota). - * - * Exposes live model token spending, daily budgets, rate-limits per provider, - * and context token telemetry in a dedicated tab in the Pantheon Settings window. - */ -import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs' -import { homedir } from 'node:os' -import { dirname, join } from 'node:path' -import type { SettingsTab } from './pantheon-settings-state.ts' -import { resolveLanguage } from './settings-i18n.ts' - -export interface QuotaSnapshot { - todaySpend?: string - monthSpend?: string - sessionSpend?: string - sessionTokens?: string - cacheHit?: string - speed?: string -} - -export interface QuotaPrefs { - sessionCap: string - alertThreshold: 'enabled' | 'disabled' - autoCompact: 'enabled' | 'disabled' -} - -export const DEFAULT_QUOTA_PREFS: QuotaPrefs = { - sessionCap: '$5.00', - alertThreshold: 'enabled', - autoCompact: 'enabled', -} - -export function resolveQuotaPrefsPath(): string { - const xdg = process.env.XDG_CONFIG_HOME - const base = xdg?.startsWith('/') ? xdg : join(homedir(), '.config') - return join(base, 'opencode', 'pantheon-quota.json') -} - -export function readQuotaPrefs(filePath = resolveQuotaPrefsPath()): QuotaPrefs { - try { - if (!existsSync(filePath)) return { ...DEFAULT_QUOTA_PREFS } - const raw = JSON.parse(readFileSync(filePath, 'utf8')) as Partial - return { - sessionCap: - typeof raw.sessionCap === 'string' && - ['$1.00', '$2.00', '$5.00', '$10.00', 'unlimited'].includes(raw.sessionCap) - ? raw.sessionCap - : DEFAULT_QUOTA_PREFS.sessionCap, - alertThreshold: raw.alertThreshold === 'disabled' ? 'disabled' : 'enabled', - autoCompact: raw.autoCompact === 'disabled' ? 'disabled' : 'enabled', - } - } catch { - return { ...DEFAULT_QUOTA_PREFS } - } -} - -export function writeQuotaPrefs(prefs: QuotaPrefs, filePath = resolveQuotaPrefsPath()): void { - mkdirSync(dirname(filePath), { recursive: true }) - writeFileSync(filePath, `${JSON.stringify(prefs, null, 2)}\n`, 'utf8') -} - -export function applyQuotaRow(prefs: QuotaPrefs, id: string, value: string): QuotaPrefs { - const next = { ...prefs } - if (id === 'quota.budget.sessionCap') { - if (['$1.00', '$2.00', '$5.00', '$10.00', 'unlimited'].includes(value)) { - next.sessionCap = value - } - } else if (id === 'quota.budget.alertThreshold') { - next.alertThreshold = value === 'disabled' ? 'disabled' : 'enabled' - } else if (id === 'quota.compaction.auto') { - next.autoCompact = value === 'disabled' ? 'disabled' : 'enabled' - } - return next -} - -export function buildQuotaTab( - snapshot?: QuotaSnapshot, - languagePref?: string, - prefs: QuotaPrefs = readQuotaPrefs(), -): SettingsTab { - const isPt = resolveLanguage(languagePref) === 'pt-BR' - - return { - id: 'quota', - title: isPt ? 'Cotas & Gastos' : 'Quotas & Spend', - groups: [ - { - title: isPt ? 'Consumo & Gastos de Sessão' : 'Session Spend & Tokens', - rows: [ - { - id: 'quota.spend.today', - name: isPt ? 'Gasto hoje (00h-agora)' : 'Spend today (00h-now)', - value: snapshot?.todaySpend ?? '—', - note: isPt ? 'Calculado a partir de opencode.db' : 'Derived from opencode.db ledger', - }, - { - id: 'quota.spend.month', - name: isPt ? 'Gasto acumulado (30d)' : 'Spend last 30 days', - value: snapshot?.monthSpend ?? '—', - note: isPt ? 'Janela móvel de 30 dias' : 'Rolling 30-day window', - }, - { - id: 'quota.spend.session', - name: isPt ? 'Gasto na sessão ativa' : 'Active session spend', - value: snapshot?.sessionSpend ?? '—', - note: isPt ? 'Custo de todas as mensagens do turno' : 'Sum of turn assistant messages', - }, - { - id: 'quota.tokens.context', - name: isPt ? 'Tokens de contexto' : 'Context tokens', - value: snapshot?.sessionTokens ?? '—', - note: isPt - ? 'Tokens consumidos vs janela do modelo' - : 'Tokens used vs model context limit', - }, - { - id: 'quota.tokens.cache', - name: isPt ? 'Eficiência de cache' : 'Prompt cache hit', - value: snapshot?.cacheHit ?? '—', - note: isPt ? 'Desconto de leitura em cache aplicado' : 'Cache read discount applied', - }, - ], - }, - { - title: isPt ? 'Limites & Teto de Orçamento' : 'Rate Limits & Budget Caps', - rows: [ - { - id: 'quota.budget.sessionCap', - name: isPt ? 'Teto por sessão' : 'Session budget cap', - value: prefs.sessionCap, - cycle: ['$1.00', '$2.00', '$5.00', '$10.00', 'unlimited'], - note: isPt - ? 'Avisa ou pausa ao atingir o teto' - : 'Warns or pauses when session spend reaches cap', - }, - { - id: 'quota.budget.alertThreshold', - name: isPt ? 'Alerta em 80% do teto' : 'Alert at 80% of cap', - value: prefs.alertThreshold, - cycle: ['enabled', 'disabled'], - note: isPt - ? 'Emite aviso visual no footer da TUI' - : 'Shows visual notice in TUI footer', - }, - { - id: 'quota.compaction.auto', - name: isPt ? 'Auto-compactar em 80% do contexto' : 'Auto-compact at 80% context', - value: prefs.autoCompact, - cycle: ['enabled', 'disabled'], - note: isPt - ? 'Aciona compressão automática de histórico' - : 'Triggers automatic context compaction', - }, - ], - }, - { - title: isPt - ? 'Provedores & Janelas de Cota (Referência)' - : 'Providers & Quota Windows (Reference)', - rows: [ - { - id: 'quota.ref.anthropic', - name: 'Anthropic (Claude 3.7)', - value: 'Tier 4', - note: isPt - ? '400k TPM · Reset diário às 00:00 UTC' - : '400k TPM · Daily reset at 00:00 UTC', - }, - { - id: 'quota.ref.openai', - name: 'OpenAI (GPT-4o)', - value: 'Tier 4', - note: isPt - ? '800k TPM · Reset por janela móvel de 1 min' - : '800k TPM · 1-minute rolling window', - }, - { - id: 'quota.ref.google', - name: 'Google (Gemini 2.5)', - value: 'Pay-as-you-go', - note: isPt - ? '4M TPM · Alta capacidade com cota flexível' - : '4M TPM · High capacity with flexible quota', - }, - ], - }, - ], - } -} diff --git a/src/plugins/tui/src/update-status.ts b/src/plugins/tui/src/update-status.ts index 7b6caf96..1236e1dd 100644 --- a/src/plugins/tui/src/update-status.ts +++ b/src/plugins/tui/src/update-status.ts @@ -152,8 +152,8 @@ export function buildUpdatesTab(input: UpdatesSectionInput): SettingsTab { name: isPt ? 'Comando no terminal' : 'CLI Command', value: 'opencode plugin update', note: isPt - ? `sem npx: \`${pluginCommand} && opencode reload\`` - : `native CLI (no npx): \`${pluginCommand} && opencode reload\``, + ? `rode \`${pluginCommand} && opencode reload\` (sem npx)` + : `run \`${pluginCommand} && opencode reload\` (no npx)`, }) const audit = input.legacyAudit @@ -174,8 +174,8 @@ export function buildUpdatesTab(input: UpdatesSectionInput): SettingsTab { ? 'limpo (0 obsoletos)' : 'clean (0 obsolete)' : isPt - ? `${audit.total} arquivo(s) (${formatBytes(audit.totalBytes)})` - : `${audit.total} file(s) (${formatBytes(audit.totalBytes)})`, + ? `${audit.total} item(ns) (${formatBytes(audit.totalBytes)})` + : `${audit.total} item(s) (${formatBytes(audit.totalBytes)})`, note: input.legacyNotice ? input.legacyNotice : audit && audit.total > 0 @@ -183,8 +183,8 @@ export function buildUpdatesTab(input: UpdatesSectionInput): SettingsTab { ? `global: ${audit.byScope.global} · projeto: ${audit.byScope.project}${audit.unmigratedStores > 0 ? ` · ${audit.unmigratedStores} store(s) p/ migrar` : ''}` : `global: ${audit.byScope.global} · project: ${audit.byScope.project}${audit.unmigratedStores > 0 ? ` · ${audit.unmigratedStores} store(s) to migrate` : ''}` : isPt - ? 'verifica hooks V1, bancos não migrados e cópias redundantes' - : 'checks V1 hooks, unmigrated stores & redundant plugin copies', + ? 'verifica caches npm antigos, hooks V1, bancos e cópias redundantes' + : 'checks stale npm caches, V1 hooks, unmigrated stores & copied files', }, { id: 'legacy.scan', @@ -198,8 +198,8 @@ export function buildUpdatesTab(input: UpdatesSectionInput): SettingsTab { : 'scan global + project', action: 'legacy-scan', note: isPt - ? 'enter escaneia sem modificar ou apagar nenhum arquivo' - : 'enter scans read-only without deleting anything', + ? 'enter verifica global, projeto e cache npm sem apagar nada' + : 'enter scans global, project & npm cache read-only', }, { id: 'legacy.clean', @@ -210,14 +210,14 @@ export function buildUpdatesTab(input: UpdatesSectionInput): SettingsTab { : 'cleaning…' : audit && audit.total > 0 ? isPt - ? `remover ${audit.total} (${formatBytes(audit.totalBytes)})` + ? `limpar ${audit.total} (${formatBytes(audit.totalBytes)})` : `remove ${audit.total} (${formatBytes(audit.totalBytes)})` : isPt - ? 'nada para remover' + ? 'nada a remover' : 'nothing to remove', action: 'legacy-clean', note: isPt - ? 'migra memória/contexto/goals antes e preserva agentes/skills custom' + ? 'migra memória/contexto/goals antes; preserva agentes/skills custom' : 'migrates memory/context/goals first · preserves custom agents/skills', }, ] diff --git a/src/plugins/tui/src/whats-new-open.ts b/src/plugins/tui/src/whats-new-open.ts index 64b31c99..67c99c70 100644 --- a/src/plugins/tui/src/whats-new-open.ts +++ b/src/plugins/tui/src/whats-new-open.ts @@ -84,6 +84,8 @@ export interface WhatsNewOpenInput { changelogText: string | null /** Host dialog opener; `onClose` fires on host dismissal (ESC / chrome). */ show: WhatsNewShowFn + /** Re-open even when the version was already dismissed. */ + force?: boolean } /** @@ -92,9 +94,9 @@ export interface WhatsNewOpenInput { * (both host-initiated and local close binds) must funnel into marking seen. */ export async function openWhatsNew(input: WhatsNewOpenInput): Promise { - const { version, statePath, changelogText, show } = input + const { version, statePath, changelogText, show, force = false } = input if (typeof version !== 'string' || version.trim() === '') return false - if (!(await shouldShowWhatsNew(version, statePath))) return false + if (!force && !(await shouldShowWhatsNew(version, statePath))) return false const highlights: WhatsNewHighlights = changelogText ? extractHighlights(changelogText, version) diff --git a/src/plugins/tui/src/whats-new.tsx b/src/plugins/tui/src/whats-new.tsx index 36bcca0f..287b1280 100644 --- a/src/plugins/tui/src/whats-new.tsx +++ b/src/plugins/tui/src/whats-new.tsx @@ -33,6 +33,8 @@ */ import type { Context } from '@opencode/plugin/tui/context' import { createSignal, For, Show } from 'solid-js' +import { resolveLanguage } from './settings-i18n' +import { tuiPrefs } from './tui-prefs' import { readChangelogForBundle, resolveRunningVersion } from './whats-new-highlights.ts' import { openWhatsNew, type WhatsNewViewData, wrapWhatsNewLine } from './whats-new-open.ts' import { defaultWhatsNewStatePath } from './whats-new-state.ts' @@ -42,6 +44,7 @@ export function WhatsNewContent(props: { data: WhatsNewViewData page: () => number pageCount: () => number + isPt?: boolean fg?: any muted?: any warn?: any @@ -49,6 +52,7 @@ export function WhatsNewContent(props: { onNext?: () => void onPrev?: () => void }) { + const isPt = () => props.isPt ?? resolveLanguage(tuiPrefs().layout?.language) === 'pt-BR' const rows = () => { const current = props.data.pages[Math.min(props.page(), props.pageCount() - 1)] ?? [] const wrapped: string[] = [] @@ -73,17 +77,20 @@ export function WhatsNewContent(props: { paddingLeft={1} paddingRight={1} marginRight={1} + flexShrink={0} > - + {'NOVIDADES'} - + {props.data.title} - props.onClose?.()}> - {'[ Esc / Q ]'} + props.onClose?.()}> + + {'[ Esc / Q ]'} + @@ -122,7 +129,7 @@ export function WhatsNewContent(props: { marginRight={1} onMouseDown={() => props.onPrev?.()} > - {'‹ Prev'} + {isPt() ? '‹ Anterior' : '‹ Prev'} {`${props.page() + 1} / ${props.pageCount()}`} @@ -134,10 +141,12 @@ export function WhatsNewContent(props: { marginRight={1} onMouseDown={() => props.onNext?.()} > - {'Next ›'} + {isPt() ? 'Próxima ›' : 'Next ›'} - {'Enter / Esc / Q close'} + + {isPt() ? 'Enter / Esc / Q fechar' : 'Enter / Esc / Q close'} + {/* Prominent OK Button */} @@ -148,7 +157,7 @@ export function WhatsNewContent(props: { onMouseDown={() => props.onClose?.()} > - {'OK, Got it'} + {isPt() ? 'OK, Entendido' : 'OK, Got it'} @@ -158,9 +167,13 @@ export function WhatsNewContent(props: { /** * Entry glue: resolve version + shipped CHANGELOG.md, then show the window - * through the host dialog stack once. Never throws. + * through the host dialog stack once (or on demand when `options.force` is set). + * Never throws. */ -export async function maybeShowWhatsNew(context: Context): Promise { +export async function maybeShowWhatsNew( + context: Context, + options: { force?: boolean } = {}, +): Promise { try { const version = await resolveRunningVersion(import.meta.url) if (!version) return @@ -228,6 +241,7 @@ export async function maybeShowWhatsNew(context: Context): Promise { version, statePath, changelogText, + force: options.force === true, show: (render, onClose) => { const close = () => { setOpen(false) @@ -263,6 +277,7 @@ export async function maybeShowWhatsNew(context: Context): Promise { ), close, ) + context.ui.dialog.set({ size: 'large', centered: true }) } catch { /* dialog stack unavailable — fail-open, retried on the next start */ } diff --git a/src/skills/artifact-management/SKILL.md b/src/skills/artifact-management/SKILL.md index 19a8b257..9d0cc4b3 100644 --- a/src/skills/artifact-management/SKILL.md +++ b/src/skills/artifact-management/SKILL.md @@ -28,20 +28,21 @@ Note: Files in `.pantheon/deepwork/` are gitignored by default, while `.pantheon When generating plans, executive reports, or ADRs, agents must format documents using high density, visual clarity, and concrete data: ### 1. GitHub-Flavored Markdown (GFM) Alerts -Use alerts to highlight background context, efficiency gains, and safety gates: +Use alerts to highlight background context, efficiency gains, and safety gates (never nest or place alerts consecutively): - `> [!NOTE]` Background context, technical assumptions, and architecture decisions. - `> [!TIP]` Performance optimizations, token footprint savings, and latency wins. - `> [!IMPORTANT]` Mandatory requirements, verification gates, and human approval checkpoints. - `> [!WARNING]` Potential breaking changes, deprecation notices, or environment constraints. +- `> [!CAUTION]` High-risk actions that could cause data loss or security vulnerabilities. ### 2. Native Mermaid Diagrams -Include a visual flowchart (`flowchart TD` or `graph LR`) visualizing the execution graph, agent handoffs, and verification gates before code changes begin. +Include a visual flowchart (`flowchart TD` / `graph LR` / `sequenceDiagram` / `stateDiagram-v2` / `erDiagram`) visualizing the execution graph, agent handoffs, and verification gates before code changes begin. Quote node labels containing parentheses or brackets (e.g., `B["Phase 1 (@hermes)"]`) and avoid HTML tags inside labels so both CLI and OpenCode Desktop render cleanly. -### 3. Quantitative Diagnostics & Comparison Tables -Provide real metrics rather than vague qualitative statements: -- Tokens / context footprint (before vs after) -- Test execution latency (e.g. global vs sliced test) -- File counts and lines affected +### 3. Quantitative Diagnostics, Clickable Links & No Chat Duplication +Provide real metrics and direct navigation rather than vague prose: +- Tokens / context footprint (before vs after) and sliced test latency. +- Clickable file links using basenames and line ranges (`[tool.ts](file:///abs/path/to/tool.ts#L12-L40)`) for instant jump in OpenCode Desktop and readable paths in CLI. +- **No chat duplication:** after saving an artifact, link to it and present only the concise executive decision summary (≤ 15 lines) and approval gate in chat instead of repeating the full document. ### 4. Sliced Actionable Phases Every implementation phase lists: diff --git a/src/skills/artifact-management/references/artifact-templates.md b/src/skills/artifact-management/references/artifact-templates.md index 7fc8497b..a0a6ac1c 100644 --- a/src/skills/artifact-management/references/artifact-templates.md +++ b/src/skills/artifact-management/references/artifact-templates.md @@ -14,6 +14,8 @@ Produced by `@athena`. Opens with an immediate Mermaid diagram and follows with > [!NOTE] > High-level context, background problem, and target outcome. +Overview paragraph separating consecutive alerts cleanly (never nest or stack alerts back-to-back). + > [!IMPORTANT] > Non-negotiable safety constraints, auth boundaries, or database schema requirements. @@ -38,13 +40,13 @@ flowchart TD ## 3. Implementation Phases ### Phase 1: Core Implementation (@hermes) -- **Target Files:** `src/server/auth.ts`, `tests/auth.test.ts` +- **Target Files:** [`auth.ts`](file:///abs/path/to/src/server/auth.ts#L1-L40), [`auth.test.ts`](file:///abs/path/to/tests/auth.test.ts#L1-L30) - **Actions:** RED -> GREEN -> REFACTOR implementation of the auth handler. - **Validation Gate:** `node --test tests/auth.test.ts` - **Exit Criteria:** All tests green; no Biome/Ruff lint warnings. ### Phase 2: Interface & Client (@aphrodite) -- **Target Files:** `src/ui/login.tsx` +- **Target Files:** [`login.tsx`](file:///abs/path/to/src/ui/login.tsx#L1-L50) - **Actions:** Connect UI state to new auth endpoint; ensure WCAG AA keyboard access. - **Validation Gate:** `npx biome check src/ui/login.tsx` @@ -68,6 +70,8 @@ Produced by `@apollo` (deep discovery) or `@themis` (quality/security audits): > [!NOTE] > Summary of findings and systemic conclusions. +Concise executive takeaway before optimization guidance. + > [!TIP] > Key optimization opportunities and quick wins. diff --git a/src/skills/instruction-forge/SKILL.md b/src/skills/instruction-forge/SKILL.md index b0df76b7..707cb187 100644 --- a/src/skills/instruction-forge/SKILL.md +++ b/src/skills/instruction-forge/SKILL.md @@ -22,12 +22,12 @@ Do NOT fire for one-shot task instructions given in conversation; those stay in | Rule kind | Home | Loaded when | |---|---|---| -| Repo setup (commands, layout, gates of THIS repo) | `AGENTS.md` managed region | Every session in the repo | +| Repo setup (commands, layout, gates of THIS repo) | `AGENTS.md` (managed region inside Pantheon; direct root `AGENTS.md` in external repos) | Every session in the repo | | Repo-agnostic behavior every session must pay for | `AGENTS.global.md` / shared instruction (`agents: ["*"]`) | Every session | | Behavior scoped to one agent | `src/instructions/*.instructions.md` with `agents:` selector | That agent's prompt, at build | | A recurring workflow a specialist executes | A skill (`SKILL.md`, ≤120-line core + `references/`) | On demand via grant | | A runtime gate the plugin owns | `behaviors:` registry in `routing.yml` (then env/override), never prose | Plugin setup | -| Generated region content | `scripts/build-agents-md.mjs` (source of truth) — NEVER hand-edited | Regenerated | +| Generated region content (Pantheon repo only) | `scripts/build-agents-md.mjs` (source of truth) — NEVER hand-edited | Regenerated | Two artifacts, zero overlap: the project `AGENTS.md` carries repo setup; `AGENTS.global.md` carries repo-agnostic rules. A session pays for global + project exactly once — a rule in both is a defect (`tests/eval/instruction-golden.test.mjs` pins this). @@ -50,7 +50,8 @@ A missing reference interrupts the action — read nothing in its place, never i ## Rules -- Generated regions (`pantheon:generated`) are machine-written: change the generator, never the output. +- Generated regions (`pantheon:generated`) are machine-written: change the generator, never the output (applies inside the Pantheon repo; external projects without `scripts/build-agents-md.mjs` edit their committed root `AGENTS.md` directly). +- For solo-dev external projects: keep project setup, verification commands, and worktree/branch boundaries in committed `AGENTS.md`, versioned architecture decisions in `docs/decisions/`, and personal cross-session notes in `.pantheon/memory/`. - Existing conventions of the codebase outrank personal preference — a rule that fights the grain gets rejected, not encoded. - Frontmatter contracts are enforced by tests (`tests/agent-skills-contract.test.mjs`); never add unlisted keys. - An instruction that says "always" but has a known exception must state the exception or it is a defect, not a style choice. diff --git a/src/skills/instruction-forge/references/agents-md-doctrine.md b/src/skills/instruction-forge/references/agents-md-doctrine.md index 2eb8c192..cb7b03b0 100644 --- a/src/skills/instruction-forge/references/agents-md-doctrine.md +++ b/src/skills/instruction-forge/references/agents-md-doctrine.md @@ -30,6 +30,13 @@ for global + project exactly once; overlap is a defect pinned by that agent's prompt at build (`generateAgentPrompt`); it never rides another agent's. +## External Projects & Solo-Dev Repositories + +When working outside the Pantheon repository (where `scripts/build-agents-md.mjs` does not exist): +- Author or update the project's committed root `AGENTS.md` directly — keep it concise (stack, layout, exact test/lint/build commands, and worktree ownership rules). +- Keep team/project architecture decisions in committed `docs/decisions/` rather than ignored `.pantheon/` artifacts so git history stays complete even across clones or worktrees. +- Keep `.pantheon/memory/` for local operational recall (linked worktrees automatically share the main repository's `.pantheon/memory/memory.db` unless `PANTHEON_ISOLATE_WORKTREE_MEMORY=1` is set). + ## Writing rules that survive - One imperative per line where possible; a threshold is a number, not "fast". diff --git a/tests/pantheon-settings-state.test.mjs b/tests/pantheon-settings-state.test.mjs index b6469753..9773fecd 100644 --- a/tests/pantheon-settings-state.test.mjs +++ b/tests/pantheon-settings-state.test.mjs @@ -141,6 +141,30 @@ describe('about tab', () => { assert.equal(rows[0].value, 'v2.0.0-beta.2') assert.ok(rows.some((row) => row.note.includes('V1 contract is removed'))) }) + + it('exposes the native 2.2 tool inventory in EN and pt-BR', () => { + const enTab = buildAboutTab('2.2.0', { languagePref: 'en' }) + const enRows = tabRows(enTab) + const memEn = enRows.find((r) => r.id === 'about.tools.memory') + const codeEn = enRows.find((r) => r.id === 'about.tools.codemap') + const govEn = enRows.find((r) => r.id === 'about.tools.governance') + assert.ok( + enTab.groups.some((g) => g.title === 'Native Tools (30)'), + 'EN inventory group displays Native Tools (30)', + ) + assert.ok(memEn?.value.includes('6 tools'), 'EN memory tools row present') + assert.ok(codeEn?.value.includes('5 tools'), 'EN codemap & AST tools row present') + assert.ok(codeEn?.note.includes('ast_search'), 'EN codemap & AST row lists ast_search') + assert.ok( + govEn?.note.includes('pantheon_review_verdict') && govEn?.note.includes('pantheon_worktree'), + 'EN governance row lists review verdict and worktree tool', + ) + assert.ok(enRows.some((r) => r.id === 'about.tools.edit' && r.note.includes('hashline_edit'))) + + const ptRows = tabRows(buildAboutTab('2.2.0', { languagePref: 'pt-BR' })) + const memPt = ptRows.find((r) => r.id === 'about.tools.memory') + assert.ok(memPt?.note.includes('memory_search'), 'pt-BR memory row lists native tools') + }) }) function load_fixture(global, project, corruptGlobal = false) { diff --git a/tests/pantheon/codemap-and-ledger.test.ts b/tests/pantheon/codemap-and-ledger.test.ts index 8a54b06a..f028aa74 100644 --- a/tests/pantheon/codemap-and-ledger.test.ts +++ b/tests/pantheon/codemap-and-ledger.test.ts @@ -190,3 +190,41 @@ test('step-ledger enforces mechanical completion gate and invalidates verificati rmSync(dir, { recursive: true, force: true }) } }) + +test('codemap prunes deleted files on query, neighbors, and re-index', async () => { + const dir = mkdtempSync(join(tmpdir(), 'pantheon-codemap-prune-')) + try { + const fileA = join(dir, 'probe.mjs') + const fileB = join(dir, 'probe.test.mjs') + writeFileSync(fileA, 'export function orphanSum(a, b) { return a + b }\n', 'utf8') + writeFileSync(fileB, "import { orphanSum } from './probe.mjs'\n", 'utf8') + + const tools = new Map(createCodemapTools(dir).map((t) => [t.name, t])) + const ctx = { directory: dir } + const idx1 = await callTool(tools, 'code_index', {}, ctx) + assert.equal(idx1.indexed, 2) + + // Delete probe.mjs and probe.test.mjs from disk + rmSync(fileA) + rmSync(fileB) + + // Query and neighbors must prune missing files instead of returning stale symbols + const q = await callTool(tools, 'code_query', { query: 'orphanSum' }, ctx) + assert.equal(q.count, 0) + assert.deepEqual(q.results, []) + + const n = await callTool(tools, 'code_neighbors', { target: 'probe.mjs' }, ctx) + assert.deepEqual(n.outgoing, []) + assert.deepEqual(n.incoming, []) + + // Re-create one file, delete it, then verify code_index reports pruned >= 1 + writeFileSync(fileA, 'export function orphanSum2(a, b) { return a + b }\n', 'utf8') + await callTool(tools, 'code_index', {}, ctx) + rmSync(fileA) + const idx2 = await callTool(tools, 'code_index', {}, ctx) + assert.equal(idx2.ok, true) + assert.ok((idx2.pruned as number) >= 1, `expected pruned >= 1, got ${String(idx2.pruned)}`) + } finally { + rmSync(dir, { recursive: true, force: true }) + } +}) diff --git a/tests/pantheon/delegation-enforce.test.ts b/tests/pantheon/delegation-enforce.test.ts index 6f1c1d75..79e0d15b 100644 --- a/tests/pantheon/delegation-enforce.test.ts +++ b/tests/pantheon/delegation-enforce.test.ts @@ -483,8 +483,18 @@ async function main() { assert.deepEqual( [...DEFAULT_BLOCKED_TOOLS].sort(), - ['bash', 'edit', 'hashline_edit', 'pantheon_model', 'shell', 'task', 'write'], - 'host covers edit/write/bash/task — hashline_edit, pantheon_model, and shell are the plugin ' + + [ + 'ast_rewrite', + 'bash', + 'edit', + 'hashline_edit', + 'pantheon_model', + 'pantheon_worktree', + 'shell', + 'task', + 'write', + ], + 'host covers edit/write/bash/task — ast_rewrite, hashline_edit, pantheon_model, and shell are the plugin ' + 'tools the guard must add (all are write/execution surfaces)', ) diff --git a/tests/pantheon/hashline.test.ts b/tests/pantheon/hashline.test.ts index b17ebeb5..2dcda283 100644 --- a/tests/pantheon/hashline.test.ts +++ b/tests/pantheon/hashline.test.ts @@ -39,6 +39,7 @@ import { import { createReadEnhancer } from '../../src/pantheon/hashline/read-enhancer.ts' import { createHashlineEditTool } from '../../src/pantheon/hashline/tool.ts' import { HASHLINE_DICT, hashTag } from '../../src/pantheon/hashline/xxhash.ts' +import { createV2ToolDefinitions } from '../../src/pantheon/tools.ts' // ─── Harness ─────────────────────────────────────────────────────────── @@ -368,6 +369,62 @@ async function main() { assert.match(threw.message, /read-only/i) }) + // ── fallbackDir / hostLocationDirectory ────────────────────────────── + await testAsync( + 'tool: relative path resolves against fallbackDir when ctx.directory/worktree are omitted', + async () => { + const tmp = mkdtempSync(join(tmpdir(), 'hashline-fallback-')) + try { + const target = join(tmp, 'probe.mjs') + writeFileSync(target, 'export function soma(a, b) {\n return a + b\n}\n') + const tool = createHashlineEditTool(tmp) + const res = await tool.execute( + { + file: 'probe.mjs', + edits: [ + { + op: 'prepend', + ref: `1#${hashTag('export function soma(a, b) {', 1)}`, + content: '// fallback probe', + }, + ], + }, + { sessionID: 'ses_hl_fallback', agent: 'zeus' }, + ) + assert.notEqual(typeof res, 'string', `expected success object, got: ${String(res)}`) + assert.equal( + readFileSync(target, 'utf8'), + '// fallback probe\nexport function soma(a, b) {\n return a + b\n}\n', + ) + + // End-to-end via createV2ToolDefinitions(..., hostLocationDirectory) + const defs = createV2ToolDefinitions(undefined, {}, undefined, tmp) + const def = defs.find((d) => d.name === 'hashline_edit') + assert.ok(def, 'hashline_edit definition must exist') + const v2Res = await def.execute( + { + file: 'probe.mjs', + edits: [ + { + op: 'replace', + ref: `1#${hashTag('// fallback probe', 1)}`, + lines: ['// v2 hostLocationDirectory ok'], + }, + ], + }, + { sessionID: 'ses_hl_fallback', agent: 'zeus' }, + ) + assert.match(v2Res.output, /^Updated /) + assert.equal( + readFileSync(target, 'utf8'), + '// v2 hostLocationDirectory ok\nexport function soma(a, b) {\n return a + b\n}\n', + ) + } finally { + rmSync(tmp, { recursive: true, force: true }) + } + }, + ) + // ── golden sanity ──────────────────────────────────────────────────── await testAsync('golden: sha256 tag is stable across runs (same input → same tag)', async () => { const input = 'the quick brown fox jumps over the lazy dog' diff --git a/tests/pantheon/lsp-and-ast.test.ts b/tests/pantheon/lsp-and-ast.test.ts new file mode 100644 index 00000000..4b4397e9 --- /dev/null +++ b/tests/pantheon/lsp-and-ast.test.ts @@ -0,0 +1,292 @@ +import assert from 'node:assert/strict' +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { createServer } from 'node:net' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import test from 'node:test' +import { pathToFileURL } from 'node:url' +import { createAstTools } from '../../src/pantheon/ast-tools.ts' +import { createV2ExecuteAfter } from '../../src/pantheon/execute-after.ts' +import { + encodeLspMessage, + getLspTcpPoolSize, + parseLspMessages, + parseLspTcpEndpoints, + queryTcpLspDiagnostics, + runPostEditDiagnostics, + shutdownLspTcpPool, +} from '../../src/pantheon/lsp-diagnostics.ts' +import { createV2ToolDefinitions } from '../../src/pantheon/tools.ts' + +test('LSP JSON-RPC framing encodes and decodes multiple Content-Length payloads', () => { + const m1 = encodeLspMessage({ jsonrpc: '2.0', id: 1, method: 'initialize', params: {} }) + const m2 = encodeLspMessage({ + jsonrpc: '2.0', + method: 'textDocument/publishDiagnostics', + params: { diagnostics: [] }, + }) + const combined = Buffer.concat([Buffer.from(m1), Buffer.from(m2)]) + const decoded = parseLspMessages(combined) + assert.equal(decoded.messages.length, 2) + assert.equal((decoded.messages[0] as { id: number }).id, 1) + assert.equal( + (decoded.messages[1] as { method: string }).method, + 'textDocument/publishDiagnostics', + ) + assert.equal(decoded.remainder.length, 0) +}) + +test('runPostEditDiagnostics surfaces TypeScript type diagnostics for edited files and skips clean ones', async () => { + const dir = mkdtempSync(join(tmpdir(), 'pantheon-lsp-')) + try { + mkdirSync(join(dir, 'src'), { recursive: true }) + const broken = join(dir, 'src', 'broken.ts') + writeFileSync( + broken, + ['export function add(a: number, b: number): number {', ' return a + "bad"', '}'].join('\n'), + ) + const diag = await runPostEditDiagnostics(broken, { cwd: dir }) + assert.ok(diag, 'expected TS semantic diagnostic output') + assert.match(diag, /\[LSP-Diagnostics\]/) + assert.match(diag, /broken\.ts:2:/) + + const clean = join(dir, 'src', 'clean.ts') + writeFileSync(clean, 'export function add(a: number, b: number): number { return a + b }\n') + const cleanDiag = await runPostEditDiagnostics(clean, { cwd: dir }) + assert.equal(cleanDiag, null) + } finally { + rmSync(dir, { recursive: true, force: true }) + } +}) + +test('execute.after wires LSP diagnostics after edits alongside editLint', async () => { + const dir = mkdtempSync(join(tmpdir(), 'pantheon-exec-after-lsp-')) + try { + const file = join(dir, 'sample.ts') + writeFileSync(file, 'const x: number = "oops"\nexport default x\n') + const after = createV2ExecuteAfter({ editLint: false }) + const event = { + tool: 'write', + sessionID: 'ses_test', + id: 'call_1', + status: 'completed', + input: { filePath: file }, + result: { output: 'Wrote file.' }, + } + await after(event) + assert.match(event.result.output, /\[LSP-Diagnostics\]/) + } finally { + rmSync(dir, { recursive: true, force: true }) + } +}) + +test('ast_search finds structural matches with metavariables and ast_rewrite rewrites cleanly', async () => { + const dir = mkdtempSync(join(tmpdir(), 'pantheon-ast-')) + try { + mkdirSync(join(dir, 'src'), { recursive: true }) + const target = join(dir, 'src', 'legacy.ts') + writeFileSync( + target, + [ + 'export function loadUser(id: string) {', + ' // console.log("ignored in comment")', + ' console.log("loading", id)', + ' console.log("done", id)', + '}', + ].join('\n'), + ) + + const tools = new Map(createAstTools(dir).map((t) => [t.name, t])) + const search = tools.get('ast_search') + const rewrite = tools.get('ast_rewrite') + assert.ok(search && rewrite) + + const found = JSON.parse( + (await search.execute({ pattern: 'console.log($$$ARGS)', path: 'src' }, { directory: dir })) + .output, + ) as { + ok: boolean + total: number + matches: Array<{ line: number; captures: Record }> + } + assert.equal(found.ok, true) + assert.equal(found.total, 2, 'comments must not count as AST call matches') + assert.equal(found.matches[0]?.line, 3) + + const preview = JSON.parse( + ( + await rewrite.execute( + { + pattern: 'console.log($$$ARGS)', + replacement: 'logger.debug($$$ARGS)', + path: 'src', + dryRun: true, + }, + { directory: dir }, + ) + ).output, + ) as { ok: boolean; replacements: number; dryRun: boolean } + assert.equal(preview.ok, true) + assert.equal(preview.replacements, 2) + assert.equal(preview.dryRun, true) + assert.match(readFileSync(target, 'utf8'), /console\.log\("loading"/) + + const applied = JSON.parse( + ( + await rewrite.execute( + { + pattern: 'console.log($$$ARGS)', + replacement: 'logger.debug($$$ARGS)', + path: 'src', + dryRun: false, + }, + { directory: dir }, + ) + ).output, + ) as { ok: boolean; replacements: number; filesModified: string[] } + assert.equal(applied.ok, true) + assert.equal(applied.replacements, 2) + assert.equal(applied.filesModified.length, 1) + const afterText = readFileSync(target, 'utf8') + assert.match(afterText, /logger\.debug\("loading", id\)/) + assert.match(afterText, /\/\/ console\.log\("ignored in comment"\)/) + } finally { + rmSync(dir, { recursive: true, force: true }) + } +}) + +test('ast_search and ast_rewrite are exposed via createV2ToolDefinitions', () => { + const names = new Set(createV2ToolDefinitions().map((t) => t.name)) + assert.ok(names.has('ast_search')) + assert.ok(names.has('ast_rewrite')) +}) + +test('multi-IDE TCP LSP proxy pool parses endpoints and reuses initialized socket across queries', async () => { + const parsed = parseLspTcpEndpoints('typescript=127.0.0.1:4101,python=localhost:4102') + assert.equal(parsed.length, 2) + assert.equal(parsed[0]?.language, 'typescript') + assert.equal(parsed[1]?.port, 4102) + + let connections = 0 + let didOpenCount = 0 + let didChangeCount = 0 + const server = createServer((socket) => { + connections += 1 + let buf = Buffer.alloc(0) + socket.on('data', (chunk) => { + buf = Buffer.concat([buf, chunk]) + const decoded = parseLspMessages(buf) + buf = Buffer.from(decoded.remainder) + for (const raw of decoded.messages) { + const msg = raw as { + id?: number + method?: string + params?: { textDocument?: { uri?: string } } + } + if (msg.method === 'initialize') { + socket.write( + encodeLspMessage({ jsonrpc: '2.0', id: msg.id, result: { capabilities: {} } }), + ) + } else if ( + msg.method === 'textDocument/didOpen' || + msg.method === 'textDocument/didChange' + ) { + if (msg.method === 'textDocument/didOpen') didOpenCount += 1 + else didChangeCount += 1 + socket.write( + encodeLspMessage({ + jsonrpc: '2.0', + method: 'textDocument/publishDiagnostics', + params: { + uri: msg.params?.textDocument?.uri, + diagnostics: [ + { + severity: 1, + code: 'LSP99', + message: 'Pooled proxy type mismatch', + range: { start: { line: 0, character: 2 } }, + }, + ], + }, + }), + ) + } + } + }) + }) + + await new Promise((res) => server.listen(0, '127.0.0.1', res)) + const addr = server.address() as { port: number } + const dir = mkdtempSync(join(tmpdir(), 'pantheon-lsp-tcp-')) + try { + const file = join(dir, 'sample.ts') + writeFileSync(file, 'const x: number = "bad"\n') + + const first = await queryTcpLspDiagnostics(file, { + host: '127.0.0.1', + port: addr.port, + cwd: dir, + timeoutMs: 2000, + }) + assert.equal(first.length, 1) + assert.equal(first[0]?.code, 'LSP99') + assert.equal(getLspTcpPoolSize(), 1) + + const second = await runPostEditDiagnostics(file, { + cwd: dir, + tcpEndpoint: { host: '127.0.0.1', port: addr.port }, + timeoutMs: 2000, + }) + assert.match(second ?? '', /Pooled proxy type mismatch/) + assert.equal(connections, 1, 'pooled TCP LSP client must reuse the single initialized socket') + assert.equal(didOpenCount, 1) + assert.equal(didChangeCount, 1) + assert.equal(pathToFileURL(file).href.startsWith('file://'), true) + } finally { + shutdownLspTcpPool() + await new Promise((res) => server.close(() => res())) + rmSync(dir, { recursive: true, force: true }) + } +}) + +test('execute.after resolves relative paths and ast_rewrite filesModified against options.cwd', async () => { + const dir = mkdtempSync(join(tmpdir(), 'pantheon-exec-after-cwd-')) + try { + mkdirSync(join(dir, 'src'), { recursive: true }) + const file = join(dir, 'src', 'broken.ts') + writeFileSync(file, 'export const bad: number = "still_broken"\n') + + const handler = createV2ExecuteAfter({ + cwd: dir, + editLint: false, + editLsp: true, + }) + + const rewriteEvent = { + tool: 'ast_rewrite', + sessionID: 'ses_after', + status: 'completed', + input: { path: 'src', pattern: 'foo', replacement: 'bar' }, + result: { + output: JSON.stringify({ + ok: true, + filesModified: ['src/broken.ts'], + }), + }, + } + await handler(rewriteEvent) + assert.match(rewriteEvent.result.output, /\[LSP-Diagnostics\]/) + + const hashlineEvent = { + tool: 'hashline_edit', + sessionID: 'ses_after', + status: 'completed', + input: { file: 'src/broken.ts', edits: [] }, + result: { output: 'Applied 1 edit.' }, + } + await handler(hashlineEvent) + assert.match(hashlineEvent.result.output, /\[LSP-Diagnostics\]/) + } finally { + rmSync(dir, { recursive: true, force: true }) + } +}) diff --git a/tests/pantheon/memory-federation.test.ts b/tests/pantheon/memory-federation.test.ts new file mode 100644 index 00000000..a3b092cd --- /dev/null +++ b/tests/pantheon/memory-federation.test.ts @@ -0,0 +1,80 @@ +import assert from 'node:assert/strict' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { basename, join } from 'node:path' +import test from 'node:test' +import { resolveFederatedRepoDirs } from '../../src/pantheon/memory-federation.ts' +import { createNativeMemoryAndPersistenceTools } from '../../src/pantheon/native-memory-tools.ts' + +test('multi-repo knowledge federation searches peer memory stores read-only with provenance', async () => { + const isoHome = mkdtempSync(join(tmpdir(), 'pantheon-fed-home-')) + const repoA = mkdtempSync(join(tmpdir(), 'pantheon-fed-a-')) + const repoB = mkdtempSync(join(tmpdir(), 'pantheon-fed-b-')) + const prevHome = process.env.HOME + const prevXdg = process.env.XDG_CONFIG_HOME + const prevEnv = process.env.PANTHEON_FEDERATED_REPOS + try { + process.env.HOME = isoHome + process.env.XDG_CONFIG_HOME = join(isoHome, '.config') + const toolsB = new Map(createNativeMemoryAndPersistenceTools(repoB).map((t) => [t.name, t])) + const storeB = toolsB.get('memory_store') + assert.ok(storeB) + await storeB.execute( + { + namespace: 'architecture', + key: 'fed-rule-jwt', + value: 'Always rotate asymmetric RS256 signing keys every 30 days', + }, + { directory: repoB }, + ) + + process.env.PANTHEON_FEDERATED_REPOS = repoB + const peers = resolveFederatedRepoDirs(repoA) + assert.equal(peers.length, 1) + + const toolsA = new Map(createNativeMemoryAndPersistenceTools(repoA).map((t) => [t.name, t])) + const searchA = toolsA.get('memory_search') + const statsA = toolsA.get('memory_stats') + assert.ok(searchA && statsA) + + const resFed = JSON.parse( + (await searchA.execute({ query: 'RS256 signing', federated: true }, { directory: repoA })) + .output, + ) as { + ok: boolean + count: number + results: Array<{ key: string; sourceRepo?: string }> + } + assert.equal(resFed.ok, true) + assert.equal(resFed.count, 1) + assert.equal(resFed.results[0]?.key, 'fed-rule-jwt') + assert.equal(resFed.results[0]?.sourceRepo, basename(repoB)) + + const resLocalOnly = JSON.parse( + (await searchA.execute({ query: 'RS256 signing', federated: false }, { directory: repoA })) + .output, + ) as { ok: boolean; count: number } + assert.equal(resLocalOnly.ok, true) + assert.equal(resLocalOnly.count, 0) + + const statsOut = JSON.parse((await statsA.execute({}, { directory: repoA })).output) as { + ok: boolean + total: number + federated?: { total: number; repos: Array<{ repo: string; total: number }> } + } + assert.equal(statsOut.ok, true) + assert.equal(statsOut.total, 0) + assert.equal(statsOut.federated?.total, 1) + assert.equal(statsOut.federated?.repos[0]?.repo, basename(repoB)) + } finally { + if (prevHome === undefined) delete process.env.HOME + else process.env.HOME = prevHome + if (prevXdg === undefined) delete process.env.XDG_CONFIG_HOME + else process.env.XDG_CONFIG_HOME = prevXdg + if (prevEnv === undefined) delete process.env.PANTHEON_FEDERATED_REPOS + else process.env.PANTHEON_FEDERATED_REPOS = prevEnv + rmSync(isoHome, { recursive: true, force: true }) + rmSync(repoA, { recursive: true, force: true }) + rmSync(repoB, { recursive: true, force: true }) + } +}) diff --git a/tests/pantheon/native-memory-tools.test.ts b/tests/pantheon/native-memory-tools.test.ts index 24022798..7e4044f0 100644 --- a/tests/pantheon/native-memory-tools.test.ts +++ b/tests/pantheon/native-memory-tools.test.ts @@ -1,5 +1,6 @@ import assert from 'node:assert/strict' -import { mkdtempSync, rmSync } from 'node:fs' +import { execFileSync } from 'node:child_process' +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import test from 'node:test' @@ -173,3 +174,73 @@ test('native persistence and goal tools save/load state and block path traversal rmSync(dir, { recursive: true, force: true }) } }) + +test('worktree sessions share the main repository memory, checkpoints, and goals store', async () => { + const base = mkdtempSync(join(tmpdir(), 'pantheon-wt-mem-')) + const mainRepo = join(base, 'repo') + const worktreeDir = join(base, 'wt-task') + const prevHome = process.env.HOME + const prevXdg = process.env.XDG_CONFIG_HOME + process.env.HOME = join(base, 'home') + process.env.XDG_CONFIG_HOME = join(base, 'home', '.config') + mkdirSync(mainRepo, { recursive: true }) + try { + execFileSync('git', ['init'], { cwd: mainRepo, stdio: 'ignore' }) + execFileSync('git', ['config', 'user.email', 'test@example.com'], { + cwd: mainRepo, + stdio: 'ignore', + }) + execFileSync('git', ['config', 'user.name', 'Test'], { cwd: mainRepo, stdio: 'ignore' }) + writeFileSync(join(mainRepo, 'README.md'), '# test\n') + execFileSync('git', ['add', '.'], { cwd: mainRepo, stdio: 'ignore' }) + execFileSync('git', ['commit', '-m', 'init'], { cwd: mainRepo, stdio: 'ignore' }) + execFileSync('git', ['worktree', 'add', '-b', 'feat/wt', worktreeDir], { + cwd: mainRepo, + stdio: 'ignore', + }) + + const mainTools = new Map( + createNativeMemoryAndPersistenceTools(mainRepo).map((tool) => [tool.name, tool]), + ) + const wtTools = new Map( + createNativeMemoryAndPersistenceTools(worktreeDir).map((tool) => [tool.name, tool]), + ) + + await callTool( + mainTools, + 'memory_store', + { namespace: 'arch', key: 'solo-rule', value: 'Share memory across worktrees' }, + { directory: mainRepo, sessionID: 'ses_main' }, + ) + + const recalledFromWt = await callTool( + wtTools, + 'memory_recall', + { namespace: 'arch', key: 'solo-rule' }, + { directory: worktreeDir, worktree: worktreeDir, sessionID: 'ses_wt' }, + ) + assert.equal(recalledFromWt.key, 'solo-rule') + assert.equal(recalledFromWt.value, 'Share memory across worktrees') + + await callTool( + wtTools, + 'goal_create', + { id: 'wt-goal-1', title: 'Keep goals visible from main', criteria: ['Shared root'] }, + { directory: worktreeDir, worktree: worktreeDir, sessionID: 'ses_wt' }, + ) + const goalFromMain = await callTool( + mainTools, + 'goal_get', + { id: 'wt-goal-1' }, + { directory: mainRepo, sessionID: 'ses_main' }, + ) + assert.equal(goalFromMain.id, 'wt-goal-1') + assert.equal(goalFromMain.title, 'Keep goals visible from main') + } finally { + if (prevHome === undefined) delete process.env.HOME + else process.env.HOME = prevHome + if (prevXdg === undefined) delete process.env.XDG_CONFIG_HOME + else process.env.XDG_CONFIG_HOME = prevXdg + rmSync(base, { recursive: true, force: true }) + } +}) diff --git a/tests/pantheon/pillars-3-4-5.test.ts b/tests/pantheon/pillars-3-4-5.test.ts new file mode 100644 index 00000000..83c53a66 --- /dev/null +++ b/tests/pantheon/pillars-3-4-5.test.ts @@ -0,0 +1,257 @@ +import assert from 'node:assert/strict' +import { execFileSync } from 'node:child_process' +import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import test from 'node:test' +import { createAgentForgeTool } from '../../src/pantheon/agent-forge-tool.ts' +import { getSharedBus } from '../../src/pantheon/bus.ts' +import { evaluateReproductionGate } from '../../src/pantheon/reproduction-gate.ts' +import { createReviewVerdictTool } from '../../src/pantheon/review-verdict.ts' +import { detectRepositoryStacks } from '../../src/pantheon/stack-detector.ts' +import { createStepLedgerTool } from '../../src/pantheon/step-ledger.ts' +import { + createPantheonWorktreeDefinition, + createWorktreeTool, + resolvePantheonWorktreePath, +} from '../../src/pantheon/worktree-orchestrator.ts' + +test('worktree-orchestrator enforces sibling .pantheon-worktrees path and manages git worktree lifecycle', async () => { + const root = mkdtempSync(join(tmpdir(), 'pantheon-wt-orch-')) + try { + const repo = join(root, 'my-app') + mkdirSync(repo, { recursive: true }) + execFileSync('git', ['init', '-q'], { cwd: repo }) + execFileSync('git', ['config', 'user.email', 'test@pantheon.dev'], { cwd: repo }) + execFileSync('git', ['config', 'user.name', 'Pantheon Test'], { cwd: repo }) + writeFileSync(join(repo, 'README.md'), '# My App\n') + execFileSync('git', ['add', 'README.md'], { cwd: repo }) + execFileSync('git', ['commit', '-q', '-m', 'init'], { cwd: repo }) + + const canonicalTarget = resolvePantheonWorktreePath(repo, 'feat-auth') + assert.ok(canonicalTarget.includes('.pantheon-worktrees')) + assert.equal(canonicalTarget.startsWith(repo), false, 'worktree must live outside main project') + + const def = createPantheonWorktreeDefinition() + assert.equal(def.id, 'pantheon-worktree') + const ac = new AbortController() + const created = await def.create( + { sourceDirectory: repo, directory: join(repo, '.pantheon', 'bad') }, + { signal: ac.signal }, + ) + assert.equal( + created.directory.startsWith(repo), + false, + 'never place worktree inside .pantheon or repo', + ) + assert.ok(existsSync(join(created.directory, 'README.md'))) + + const entries = await def.list(repo, { signal: ac.signal }) + assert.equal(entries.length, 2) + assert.ok(entries.some((e) => realpathSync(e.directory) === realpathSync(created.directory))) + + await def.remove({ directory: created.directory, force: true }, { signal: ac.signal }) + assert.equal(existsSync(created.directory), false) + + // Also test direct agent tool interface `pantheon_worktree` + const wtTool = createWorktreeTool(repo) + const wtCreated = JSON.parse( + (await wtTool.execute({ action: 'create', task: 'feat-tool' }, { directory: repo })).output, + ) as { ok: boolean; directory: string } + assert.equal(wtCreated.ok, true) + assert.ok(existsSync(wtCreated.directory)) + assert.equal(wtCreated.directory.startsWith(repo), false) + const wtRemoved = JSON.parse( + ( + await wtTool.execute( + { action: 'remove', directory: wtCreated.directory, force: true }, + { directory: repo }, + ) + ).output, + ) as { ok: boolean } + assert.equal(wtRemoved.ok, true) + } finally { + rmSync(root, { recursive: true, force: true }) + } +}) + +test('pantheon_review_verdict emits bus event and routes bounded SessionSyntheticInput to parent session on BLOCK', async () => { + const syntheticCalls: Array> = [] + const busVerdicts: string[] = [] + const off = getSharedBus().on('review:verdict', (e) => busVerdicts.push(e.verdict)) + + try { + const tool = createReviewVerdictTool({ + get: async ({ sessionID }) => + sessionID === 'ses_review_1' ? { parentID: 'ses_parent_zeus' } : undefined, + synthetic: async (input) => { + syntheticCalls.push(input as Record) + }, + }) + const res1 = JSON.parse( + ( + await tool.execute( + { + verdict: 'BLOCK', + summary: 'Missing null guard in auth callback', + targetAgent: 'hermes', + findings: [ + { severity: 'critical', file: 'src/auth.ts', message: 'Unhandled null user' }, + ], + }, + { sessionID: 'ses_review_1', agent: 'themis' }, + ) + ).output, + ) as { + ok: boolean + verdict: string + syntheticTriggered: boolean + syntheticSessionID?: string + } + + assert.equal(res1.ok, true) + assert.equal(res1.verdict, 'BLOCK') + assert.equal(res1.syntheticTriggered, true) + assert.equal(res1.syntheticSessionID, 'ses_parent_zeus') + assert.equal(busVerdicts[0], 'BLOCK') + assert.equal(syntheticCalls.length, 1) + assert.equal(syntheticCalls[0]?.sessionID, 'ses_parent_zeus') + assert.equal(syntheticCalls[0]?.resume, true) + assert.equal( + 'agent' in (syntheticCalls[0] ?? {}), + false, + 'SessionSyntheticInput forbids bare agent field', + ) + assert.match(String(syntheticCalls[0]?.text ?? ''), /BLOCK/) + assert.match(String(syntheticCalls[0]?.text ?? ''), /src\/auth\.ts/) + + // Bounded at 2 per session+agent so a third consecutive BLOCK stops auto-looping + await tool.execute( + { verdict: 'BLOCK', summary: 'Still failing', targetAgent: 'hermes' }, + { sessionID: 'ses_review_1', agent: 'themis' }, + ) + const res3 = JSON.parse( + ( + await tool.execute( + { verdict: 'BLOCK', summary: 'Still failing x3', targetAgent: 'hermes' }, + { sessionID: 'ses_review_1', agent: 'themis' }, + ) + ).output, + ) as { syntheticTriggered: boolean } + assert.equal(syntheticCalls.length, 2, 'remediation synthetic dispatch must stay bounded') + assert.equal(res3.syntheticTriggered, false) + } finally { + off() + } +}) + +test('reproduction gate blocks production edits in bugfix steps until a failing RED test is recorded', async () => { + const dir = mkdtempSync(join(tmpdir(), 'pantheon-repro-gate-')) + try { + const ledger = createStepLedgerTool(dir) + await ledger.execute( + { + action: 'init_step', + stepKey: 'fix-login-500', + objective: 'Fix login null crash', + agent: 'hermes', + taskType: 'bugfix', + }, + { directory: dir }, + ) + + // Test file edits ARE allowed before reproduction so specialist can write RED repro + const allowTest = evaluateReproductionGate({ + cwd: dir, + tool: 'write', + agent: 'hermes', + args: { filePath: join(dir, 'tests', 'login.test.ts') }, + }) + assert.equal(allowTest.allowed, true) + + // Production file edit is BLOCKED before failing reproduction is recorded + const blockProd = evaluateReproductionGate({ + cwd: dir, + tool: 'hashline_edit', + agent: 'hermes', + args: { file: 'src/login.ts' }, + }) + assert.equal(blockProd.allowed, false) + assert.match(blockProd.message ?? '', /\[Reproduction-Gate\]/) + + // Recording exitCode === 0 must be rejected as a bugfix reproduction + const badRepro = JSON.parse( + ( + await ledger.execute( + { + action: 'record_reproduction', + stepKey: 'fix-login-500', + command: 'node --test tests/login.test.ts', + exitCode: 0, + }, + { directory: dir }, + ) + ).output, + ) as { ok: boolean } + assert.equal(badRepro.ok, false) + + // Recording failing RED reproduction unlocks production edits + const goodRepro = JSON.parse( + ( + await ledger.execute( + { + action: 'record_reproduction', + stepKey: 'fix-login-500', + command: 'node --test tests/login.test.ts', + exitCode: 1, + }, + { directory: dir }, + ) + ).output, + ) as { ok: boolean } + assert.equal(goodRepro.ok, true) + + const allowProd = evaluateReproductionGate({ + cwd: dir, + tool: 'hashline_edit', + agent: 'hermes', + args: { file: 'src/login.ts' }, + }) + assert.equal(allowProd.allowed, true) + } finally { + rmSync(dir, { recursive: true, force: true }) + } +}) + +test('stack-detector and agent_forge detect_stack identify polyglot manifests cleanly', async () => { + const dir = mkdtempSync(join(tmpdir(), 'pantheon-stack-')) + try { + writeFileSync( + join(dir, 'package.json'), + JSON.stringify({ + name: 'web', + dependencies: { react: '^19.0.0' }, + devDependencies: { typescript: '^5.0.0' }, + }), + ) + writeFileSync(join(dir, 'pyproject.toml'), '[project]\ndependencies = ["fastapi", "pytest"]\n') + writeFileSync(join(dir, 'go.mod'), 'module example.com/svc\n\ngo 1.23\n') + + const detected = detectRepositoryStacks(dir) + const ids = detected.stacks.map((s) => s.id) + assert.ok(ids.includes('node-typescript')) + assert.ok(ids.includes('python')) + assert.ok(ids.includes('go')) + assert.ok(detected.suggestedSpecialists.length >= 2) + + const forge = createAgentForgeTool(dir) + const forgeOut = JSON.parse( + (await forge.execute({ action: 'detect_stack' }, { directory: dir })).output, + ) as { ok: boolean; stacks: Array<{ id: string }>; suggestedSpecialists: unknown[] } + assert.equal(forgeOut.ok, true) + assert.ok(forgeOut.stacks.some((s) => s.id === 'python')) + assert.ok(forgeOut.suggestedSpecialists.length >= 2) + } finally { + rmSync(dir, { recursive: true, force: true }) + } +}) diff --git a/tests/pantheon/plugin-contract.test.ts b/tests/pantheon/plugin-contract.test.ts index a7bb1df2..2552d1c1 100644 --- a/tests/pantheon/plugin-contract.test.ts +++ b/tests/pantheon/plugin-contract.test.ts @@ -406,6 +406,27 @@ async function main(): Promise { assert.equal(agents[0].mode, 'primary') }) + test('CANONICAL_SLASH_COMMANDS does not duplicate TUI-only commands', () => { + const blockMatch = /const CANONICAL_SLASH_COMMANDS[\s\S]*?=\s*\[([\s\S]*?)\n\]/.exec( + pluginSource, + ) + assert.ok(blockMatch !== null, 'CANONICAL_SLASH_COMMANDS must exist in plugin.ts') + for (const tuiCmd of [ + 'pantheon-settings', + 'pantheon-updates', + 'pantheon-whats-new', + 'pantheon-artifacts', + 'pantheon-cockpit', + 'dispatch', + ]) { + assert.doesNotMatch( + blockMatch[1], + new RegExp(`name:\\s*'${tuiCmd}'`), + `server CANONICAL_SLASH_COMMANDS must not duplicate TUI command /${tuiCmd}`, + ) + } + }) + test('V2 agent transform applies only manual per-agent overrides and ignores preset markers', () => { assert.equal(typeof agentTransformCallback, 'function') const root = mkdtempSync(join(tmpdir(), 'pantheon-v2-agent-transform-')) @@ -2878,6 +2899,8 @@ async function main(): Promise { // V2_UNSUPPORTED_FEATURES. // beta.29 adds `todowrite` (pass-through) so the TUI todo panel renders. assert.deepEqual(registered.map((t) => t.name).sort(), [ + 'ast_rewrite', + 'ast_search', 'code_index', 'code_neighbors', 'code_query', @@ -2899,14 +2922,44 @@ async function main(): Promise { 'pantheon_deepwork', 'pantheon_local_decision', 'pantheon_model', + 'pantheon_review_verdict', 'pantheon_skill_search', 'pantheon_step_ledger', + 'pantheon_worktree', 'shell', 'todoread', 'todowrite', ]) }) + test('V2 preserves host-provided native todowrite/todoread instead of shadowing them', async () => { + const registeredNames: string[] = [] + await plugin.setup( + makeBaseContext({ + tool: { + transform: async (callback: (draft: unknown) => void) => { + callback({ + list: () => [{ id: 'todowrite' }, { id: 'todoread' }, { id: 'read' }], + get: (id: string) => (id === 'todowrite' || id === 'todoread' ? { id } : undefined), + namespace: () => {}, + add: (tool: { name: string }) => { + registeredNames.push(tool.name) + }, + }) + return { dispose: async () => {} } + }, + }, + }) as never, + ) + assert.equal(registeredNames.includes('todowrite'), false, 'must not shadow native todowrite') + assert.equal(registeredNames.includes('todoread'), false, 'must not shadow native todoread') + assert.equal( + registeredNames.includes('hashline_edit'), + true, + 'native pantheon tools still register', + ) + }) + test('every draft.add declares output — removing it fails this test', async () => { const registered = await registerToolsThroughHostMock() assert.ok(registered.length > 0, 'expected at least one registered tool') @@ -3026,6 +3079,8 @@ async function main(): Promise { const registered = await registerToolsThroughHostMock() const names = registered.map((t) => t.name).sort() assert.deepEqual(names, [ + 'ast_rewrite', + 'ast_search', 'code_index', 'code_neighbors', 'code_query', @@ -3047,8 +3102,10 @@ async function main(): Promise { 'pantheon_deepwork', 'pantheon_local_decision', 'pantheon_model', + 'pantheon_review_verdict', 'pantheon_skill_search', 'pantheon_step_ledger', + 'pantheon_worktree', 'shell', 'todoread', 'todowrite', @@ -3603,7 +3660,7 @@ async function main(): Promise { const v2WriteTools = [...DEFAULT_BLOCKED_TOOLS].filter((tool) => registeredNames.has(tool)) assert.deepEqual( v2WriteTools.sort(), - ['hashline_edit', 'pantheon_model', 'shell'], + ['ast_rewrite', 'hashline_edit', 'pantheon_model', 'pantheon_worktree', 'shell'], 'the V2 surface exposes mutating tools; all must be in the blocked set', ) for (const tool of v2WriteTools) { diff --git a/tests/pantheon/step-runner-and-checkpoint.test.ts b/tests/pantheon/step-runner-and-checkpoint.test.ts new file mode 100644 index 00000000..399eb22b --- /dev/null +++ b/tests/pantheon/step-runner-and-checkpoint.test.ts @@ -0,0 +1,194 @@ +import assert from 'node:assert/strict' +import { execFileSync } from 'node:child_process' +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import test from 'node:test' +import { getSharedBus } from '../../src/pantheon/bus.ts' +import { captureGitCheckpoint, restoreGitCheckpoint } from '../../src/pantheon/git-checkpoint.ts' +import { createStepLedgerTool } from '../../src/pantheon/step-ledger.ts' +import { runAtomicStepSubSession } from '../../src/pantheon/step-runner.ts' + +function initGitRepo(dir: string): void { + execFileSync('git', ['init', '-q'], { cwd: dir }) + execFileSync('git', ['config', 'user.email', 'test@pantheon.dev'], { cwd: dir }) + execFileSync('git', ['config', 'user.name', 'Pantheon Test'], { cwd: dir }) + writeFileSync(join(dir, 'app.ts'), 'export const version = 1\n') + execFileSync('git', ['add', 'app.ts'], { cwd: dir }) + execFileSync('git', ['commit', '-q', '-m', 'init'], { cwd: dir }) +} + +test('captureGitCheckpoint and restoreGitCheckpoint snapshot and roll back without touching real staged index', async () => { + const dir = mkdtempSync(join(tmpdir(), 'pantheon-git-ckpt-')) + try { + initGitRepo(dir) + const snap = await captureGitCheckpoint(dir, 'step-1') + assert.equal(snap.ok, true) + assert.match(snap.treeHash ?? '', /^[0-9a-f]{40}$/) + + // Mutate tracked file and add a new untracked file + writeFileSync(join(dir, 'app.ts'), 'export const version = 999\n') + writeFileSync(join(dir, 'stray.ts'), 'export const stray = true\n') + + assert.ok(snap.treeHash) + const rollback = await restoreGitCheckpoint(dir, snap.treeHash) + assert.equal(rollback.ok, true) + assert.equal(readFileSync(join(dir, 'app.ts'), 'utf8'), 'export const version = 1\n') + assert.equal( + existsSync(join(dir, 'stray.ts')), + false, + 'newly created untracked file must be cleaned', + ) + } finally { + rmSync(dir, { recursive: true, force: true }) + } +}) + +test('step_ledger captures baselineTree on init_step and auto-rolls back on themis:reflex:escalated', async () => { + const dir = mkdtempSync(join(tmpdir(), 'pantheon-ledger-rollback-')) + try { + initGitRepo(dir) + const ledger = createStepLedgerTool(dir) + const escalated: string[] = [] + const rolledBack: string[] = [] + const bus = getSharedBus() + const offEsc = bus.on('themis:reflex:escalated', (e) => escalated.push(e.taskID)) + const offRb = bus.on('step:rollback', (e) => rolledBack.push(e.stepKey)) + + try { + const initRes = JSON.parse( + ( + await ledger.execute( + { + action: 'init_step', + stepKey: 'step-auto-rb', + objective: 'Fix regression cleanly', + agent: 'hermes', + }, + { directory: dir }, + ) + ).output, + ) as { ok: boolean; step: { baselineTree?: string } } + assert.equal(initRes.ok, true) + assert.match(initRes.step.baselineTree ?? '', /^[0-9a-f]{40}$/) + + writeFileSync(join(dir, 'app.ts'), 'export const version = -1 // broken\n') + await ledger.execute( + { action: 'record_mutation', stepKey: 'step-auto-rb', files: ['app.ts'] }, + { directory: dir }, + ) + + // 3 failing verifications exhaust maxRetries (2) -> escalate -> auto-rollback + for (let i = 0; i < 3; i += 1) { + await ledger.execute( + { + action: 'record_verification', + stepKey: 'step-auto-rb', + command: 'npm test', + exitCode: 1, + }, + { directory: dir }, + ) + } + + assert.ok(escalated.includes('step-auto-rb')) + assert.ok(rolledBack.includes('step-auto-rb')) + assert.equal(readFileSync(join(dir, 'app.ts'), 'utf8'), 'export const version = 1\n') + } finally { + offEsc() + offRb() + } + } finally { + rmSync(dir, { recursive: true, force: true }) + } +}) + +test('runAtomicStepSubSession and pantheon_step_ledger execute_step use real SDK shapes and clean up child session', async () => { + const dir = mkdtempSync(join(tmpdir(), 'pantheon-step-runner-')) + try { + initGitRepo(dir) + const calls: string[] = [] + const removed: string[] = [] + const ledger = createStepLedgerTool(dir) + + const fakeSessionDomain = { + create: async (opts?: { title?: string; agent?: string; parentID?: string }) => { + calls.push(`create:${opts?.agent ?? ''}:${opts?.title ?? ''}`) + assert.ok(opts?.agent, 'create must specify target agent matching SessionCreateInput') + return { id: 'ses_atomic_1' } + }, + prompt: async (input: { + sessionID: string + text: string + agents?: ReadonlyArray<{ readonly name: string }> + }) => { + const keyMatch = /stepKey:\s*(\S+)/.exec(input.text) + const targetKey = keyMatch?.[1] ?? 'sub-step-1' + calls.push(`prompt:${input.sessionID}:${targetKey}`) + assert.equal( + input.agents?.[0]?.name, + 'hermes', + 'prompt must pass SessionPromptInput agents[]', + ) + // Simulate sub-session completing verification & ledger + await ledger.execute( + { action: 'record_mutation', stepKey: targetKey, files: ['app.ts'] }, + { directory: dir }, + ) + await ledger.execute( + { + action: 'record_verification', + stepKey: targetKey, + command: 'node --test', + exitCode: 0, + }, + { directory: dir }, + ) + await ledger.execute({ action: 'complete_step', stepKey: targetKey }, { directory: dir }) + return { ok: true } + }, + wait: async (input: { readonly sessionID: string }) => { + calls.push(`wait:${input.sessionID}`) + return { status: 'completed' } + }, + remove: async (input: { readonly sessionID: string }) => { + removed.push(input.sessionID) + }, + } + + const res = await runAtomicStepSubSession({ + sessionDomain: fakeSessionDomain, + cwd: dir, + stepKey: 'sub-step-1', + objective: 'Implement health route', + agent: 'hermes', + }) + assert.equal(res.ok, true) + assert.equal(res.sessionID, 'ses_atomic_1') + assert.equal(res.stepState, 'done') + assert.deepEqual(removed, ['ses_atomic_1']) + assert.ok(calls.some((c) => c.startsWith('create:hermes:'))) + assert.ok(calls.includes('wait:ses_atomic_1')) + + // Now invoke directly via pantheon_step_ledger(action="execute_step") + const wiredLedger = createStepLedgerTool(dir, fakeSessionDomain) + const toolOut = JSON.parse( + ( + await wiredLedger.execute( + { + action: 'execute_step', + stepKey: 'sub-step-2', + objective: 'Add readiness check', + agent: 'hermes', + }, + { directory: dir, sessionID: 'ses_parent_zeus' }, + ) + ).output, + ) as { ok: boolean; stepState?: string; receiptId?: string } + assert.equal(toolOut.ok, true) + assert.equal(toolOut.stepState, 'done') + assert.ok(toolOut.receiptId) + } finally { + rmSync(dir, { recursive: true, force: true }) + } +}) diff --git a/tests/release-body.test.mjs b/tests/release-body.test.mjs new file mode 100644 index 00000000..d3d1f47a --- /dev/null +++ b/tests/release-body.test.mjs @@ -0,0 +1,186 @@ +import assert from 'node:assert/strict' +import { execFileSync } from 'node:child_process' +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, test } from 'node:test' +import { fileURLToPath } from 'node:url' + +const ROOT = fileURLToPath(new URL('..', import.meta.url)) +const SCRIPT = join(ROOT, 'scripts/release-body.mjs') +const tempDirs = [] + +function makeTempDir() { + const dir = mkdtempSync(join(tmpdir(), 'pantheon-release-body-')) + tempDirs.push(dir) + return dir +} + +afterEach(() => { + while (tempDirs.length > 0) { + rmSync(tempDirs.pop(), { recursive: true, force: true }) + } +}) + +describe('scripts/release-body.mjs', () => { + test('uses canonical changelog notes untouched when no curated release page exists', async () => { + const { composeReleaseBody } = await import(SCRIPT) + const dir = makeTempDir() + const releasesDir = join(dir, 'docs', 'releases') + mkdirSync(releasesDir, { recursive: true }) + + const changelogNotes = "### 🆕 What's New\n\n- **core** — Added widget.\n" + const body = composeReleaseBody({ + version: '2.2.0', + channel: 'stable', + recovery: false, + changelogNotes, + repoRoot: dir, + releasesDir, + repo: 'ils15/pantheon-opencode', + ref: 'v2.2.0', + }) + + assert.equal(body, "### 🆕 What's New\n\n- **core** — Added widget.\n") + }) + + test('passes through canonical changelog notes for beta channel and recovery mode even if curated page exists', async () => { + const { composeReleaseBody } = await import(SCRIPT) + const dir = makeTempDir() + const releasesDir = join(dir, 'docs', 'releases') + mkdirSync(releasesDir, { recursive: true }) + writeFileSync(join(releasesDir, 'v2.2.0.md'), '# Rich Release Page\n', 'utf8') + + const changelogNotes = "### 🆕 What's New\n\n- **beta** — Snapshot.\n" + + assert.equal( + composeReleaseBody({ + version: '2.2.0-beta.1', + channel: 'beta', + recovery: false, + changelogNotes, + repoRoot: dir, + releasesDir, + repo: 'ils15/pantheon-opencode', + ref: 'v2.2.0-beta.1', + }), + "### 🆕 What's New\n\n- **beta** — Snapshot.\n", + ) + + assert.equal( + composeReleaseBody({ + version: '2.2.0', + channel: 'stable', + recovery: true, + changelogNotes, + repoRoot: dir, + releasesDir, + repo: 'ils15/pantheon-opencode', + ref: 'v2.2.0', + }), + "### 🆕 What's New\n\n- **beta** — Snapshot.\n", + ) + }) + + test('composes rich GitHub release body with rewritten asset/doc URLs and collapsible changelog ledger', async () => { + const { composeReleaseBody } = await import(SCRIPT) + const dir = makeTempDir() + const releasesDir = join(dir, 'docs', 'releases') + const assetsDir = join(dir, 'docs', 'assets', 'tui') + mkdirSync(releasesDir, { recursive: true }) + mkdirSync(assetsDir, { recursive: true }) + writeFileSync(join(dir, 'docs', 'INSTALLATION.md'), '# Install\n', 'utf8') + writeFileSync(join(assetsDir, 'cockpit-overview.png'), 'png', 'utf8') + + const curated = [ + '# Pantheon `v2.2.0`', + '', + '![Cockpit Overview](../assets/tui/cockpit-overview.png "Live Cockpit")', + '', + 'See [Installation](../INSTALLATION.md#quickstart) and [Highlights](./highlights.md).', + '', + '```markdown', + '![Inside Code](../assets/tui/ignored.png)', + '```', + '', + 'Inline code `![Inline](../assets/tui/ignored.png)` stays untouched.', + '', + ].join('\n') + writeFileSync(join(releasesDir, 'v2.2.0.md'), curated, 'utf8') + + const changelogNotes = "### 🆕 What's New\n\n- **cockpit** — 3-page mission control.\n" + const result = composeReleaseBody({ + version: 'v2.2.0', + channel: 'stable', + recovery: false, + changelogNotes, + repoRoot: dir, + releasesDir, + repo: 'ils15/pantheon-opencode', + ref: 'v2.2.0', + }) + + assert.match( + result, + /!\[Cockpit Overview\]\(https:\/\/raw\.githubusercontent\.com\/ils15\/pantheon-opencode\/v2\.2\.0\/docs\/assets\/tui\/cockpit-overview\.png "Live Cockpit"\)/, + ) + assert.match( + result, + /\[Installation\]\(https:\/\/github\.com\/ils15\/pantheon-opencode\/blob\/v2\.2\.0\/docs\/INSTALLATION\.md#quickstart\)/, + ) + assert.match( + result, + /\[Highlights\]\(https:\/\/github\.com\/ils15\/pantheon-opencode\/blob\/v2\.2\.0\/docs\/releases\/highlights\.md\)/, + ) + assert.match(result, /!\[Inside Code\]\(\.\.\/assets\/tui\/ignored\.png\)/) + assert.match(result, /`!\[Inline\]\(\.\.\/assets\/tui\/ignored\.png\)`/) + assert.match(result, /
/) + assert.match(result, /Full Keep a Changelog Ledger \(v2\.2\.0\)/) + assert.match(result, /\*\*cockpit\*\* — 3-page mission control\./) + }) + + test('CLI writes composed output to --out cleanly', () => { + const dir = makeTempDir() + const releasesDir = join(dir, 'docs', 'releases') + mkdirSync(releasesDir, { recursive: true }) + writeFileSync( + join(releasesDir, 'v2.2.0.md'), + '# Pantheon `v2.2.0`\n\n![Img](../assets/tui/home-status.png)\n', + 'utf8', + ) + const notesPath = join(dir, 'changelog-notes.md') + const outPath = join(dir, 'release-notes.md') + writeFileSync(notesPath, "### 🆕 What's New\n\n- **core** — Shipped.\n", 'utf8') + + execFileSync( + process.execPath, + [ + SCRIPT, + '--version', + '2.2.0', + '--channel', + 'stable', + '--changelog-notes', + notesPath, + '--repo-root', + dir, + '--releases-dir', + releasesDir, + '--repo', + 'ils15/pantheon-opencode', + '--ref', + 'v2.2.0', + '--out', + outPath, + ], + { cwd: ROOT, stdio: 'pipe' }, + ) + + const written = readFileSync(outPath, 'utf8') + assert.match( + written, + /https:\/\/raw\.githubusercontent\.com\/ils15\/pantheon-opencode\/v2\.2\.0\/docs\/assets\/tui\/home-status\.png/, + ) + assert.match(written, /\*\*core\*\* — Shipped\./) + }) +}) diff --git a/tests/release-workflow-security.test.mjs b/tests/release-workflow-security.test.mjs index 996da343..b3719ec5 100644 --- a/tests/release-workflow-security.test.mjs +++ b/tests/release-workflow-security.test.mjs @@ -193,6 +193,9 @@ test('beta gate trusts the committed X.Y.Z-beta.N and notes come from the change assert.match(validate, /Expected a committed X\.Y\.Z-beta\.N version/) // Both channels extract release notes from the committed CHANGELOG section. assert.match(validate, /node scripts\/changelog-extract\.mjs "\$BASE_VERSION"/) + // Stable releases with a curated docs/releases/vX.Y.Z.md compose via release-body.mjs. + assert.match(validate, /node scripts\/release-body\.mjs/) + assert.match(validate, /"\$RELEASE_CHANNEL" = "stable"/) }) test('tag and release provenance remains bound to TARGET_SHA', () => { diff --git a/tests/tui-artifacts.test.mjs b/tests/tui-artifacts.test.mjs new file mode 100644 index 00000000..fef7c618 --- /dev/null +++ b/tests/tui-artifacts.test.mjs @@ -0,0 +1,142 @@ +import assert from 'node:assert/strict' +import { mkdirSync, mkdtempSync, readFileSync, rmSync, utimesSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import test from 'node:test' +import { fileURLToPath } from 'node:url' +import { + artifactKindLabel, + formatArtifactLines, + paginateArtifactLines, + scanPantheonArtifacts, +} from '../src/plugins/tui/src/artifacts-state.ts' + +const root = fileURLToPath(new URL('..', import.meta.url)) + +test('scanPantheonArtifacts finds plans, reports, and ADRs across main repo and worktrees', () => { + const tmp = mkdtempSync(join(tmpdir(), 'pantheon-artifacts-')) + try { + const repo = join(tmp, 'main-repo') + const wt = join(tmp, 'wt-feature') + mkdirSync(join(repo, '.git', 'worktrees', 'wt-feature'), { recursive: true }) + mkdirSync(join(repo, '.pantheon', 'deepwork', 'auth-oauth'), { recursive: true }) + mkdirSync(join(repo, '.pantheon', 'reports'), { recursive: true }) + mkdirSync(join(repo, 'docs', 'adr'), { recursive: true }) + mkdirSync(wt, { recursive: true }) + + writeFileSync(join(repo, '.git', 'HEAD'), 'ref: refs/heads/main\n') + writeFileSync(join(repo, '.git', 'worktrees', 'wt-feature', 'commondir'), '../..\n') + writeFileSync(join(wt, '.git'), `gitdir: ${join(repo, '.git', 'worktrees', 'wt-feature')}\n`) + + const planPath = join(repo, '.pantheon', 'deepwork', 'auth-oauth', 'PLAN.md') + const reportPath = join(repo, '.pantheon', 'reports', '2026-11-19-security.md') + const adrPath = join(repo, 'docs', 'adr', '001-native-tools.md') + const adrReadme = join(repo, 'docs', 'adr', 'README.md') + + writeFileSync(planPath, '# Architectural Plan: OAuth2 PKCE\n\nDetails\n') + writeFileSync(reportPath, '# Executive Report: Security Audit\n\nAll clean.\n') + writeFileSync(adrPath, '# ADR-001: Native Tools\n\nAccepted.\n') + writeFileSync(adrReadme, '# ADR Index\n') + + utimesSync(adrPath, new Date(1000), new Date(1000)) + utimesSync(reportPath, new Date(2000), new Date(2000)) + utimesSync(planPath, new Date(3000), new Date(3000)) + + const fromWorktree = scanPantheonArtifacts(wt) + assert.equal( + fromWorktree.length, + 3, + 'worktree must see main repo artifacts and ignore README.md', + ) + assert.deepEqual( + fromWorktree.map((e) => [e.kind, e.title]), + [ + ['plan', 'Architectural Plan: OAuth2 PKCE'], + ['report', 'Executive Report: Security Audit'], + ['adr', 'ADR-001: Native Tools'], + ], + ) + assert.equal(artifactKindLabel('plan', true), 'Plano') + assert.equal(artifactKindLabel('report', false), 'Report') + } finally { + rmSync(tmp, { recursive: true, force: true }) + } +}) + +test('formatArtifactLines renders GFM alerts, Mermaid blocks, links, and paginates cleanly', () => { + const md = [ + '# Plan Title', + '', + '> [!IMPORTANT]', + '> Verify [`auth.ts`](file:///repo/src/auth.ts#L10-L20) before merge.', + '', + '```mermaid', + 'flowchart TD', + ' A["Start"] --> B["Gate"]', + '```', + '', + '- Bullet item one', + ].join('\n') + + const lines = formatArtifactLines(md, 60) + assert.ok(lines.includes('PLAN TITLE')) + assert.ok(lines.includes('[IMPORTANT]')) + assert.ok(lines.some((l) => l.includes('auth.ts#L10-L20'))) + assert.ok(lines.includes('[Diagram: Flowchart]')) + assert.ok(lines.some((l) => l.includes('│ Start │'))) + assert.ok(lines.some((l) => l.includes('│ Gate │'))) + assert.ok(lines.some((l) => l.includes('▼'))) + assert.ok(lines.includes('• Bullet item one')) + + const pages = paginateArtifactLines(lines, 4) + assert.ok(pages.length >= 2) + assert.ok(pages.every((p) => p.length <= 4)) +}) + +test('formatArtifactLines renders branching/converging DAG, sequenceDiagram, and stateDiagram as Unicode boxes', () => { + const md = [ + '```mermaid', + 'flowchart TD', + ' T1["T1: Schema & Migrations"] -->|ready| T2["T2: API"] & T3["T3: UI"]', + ' T2 & T3 --> T4["T4: Audit"]', + '```', + '', + '```mermaid', + 'sequenceDiagram', + ' participant Z as Zeus', + ' participant A as Athena', + ' Z->>A: plan task', + ' A-->>Z: PLAN.md', + '```', + '', + '```mermaid', + 'stateDiagram-v2', + ' [*] --> Draft', + ' Draft --> Approved : user confirm', + '```', + ].join('\n') + + const lines = formatArtifactLines(md, 76) + assert.ok(lines.includes('[Diagram: Flowchart]')) + assert.ok(lines.some((l) => l.includes('│ T1: Schema & Migrations │'))) + assert.ok(lines.some((l) => l.includes('├──► [ready] T2: API'))) + assert.ok(lines.some((l) => l.includes('│ T4: Audit │'))) + assert.ok(lines.includes('[Diagram: Sequence]')) + assert.ok(lines.some((l) => l.includes('│ Zeus │') && l.includes('│ Athena │'))) + assert.ok(lines.some((l) => l.includes('├───────'))) + assert.ok(lines.includes('[Diagram: State]')) + assert.ok(lines.some((l) => l.includes('user confirm'))) +}) + +test('index.tsx wires /pantheon-artifacts command, Sidebar/Home artifact links, and initialArtifactId', () => { + const indexSrc = readFileSync(join(root, 'src/plugins/tui/src/index.tsx'), 'utf8') + const artifactsSrc = readFileSync(join(root, 'src/plugins/tui/src/artifacts.tsx'), 'utf8') + const settingsSrc = readFileSync(join(root, 'src/plugins/tui/src/pantheon-settings.tsx'), 'utf8') + assert.match(indexSrc, /import \{ openArtifactsDialog \} from '\.\/artifacts'/) + assert.match(indexSrc, /id: 'pantheon\.artifacts\.open'/) + assert.match(indexSrc, /name: 'pantheon-artifacts'/) + assert.match(indexSrc, /useWorkspaceArtifacts/) + assert.match(indexSrc, /initialArtifactId:\s*plan\(\)\.id/) + assert.match(artifactsSrc, /initialArtifactId\?: string/) + assert.match(settingsSrc, /\(viewMode === 'fullscreen' \|\| !sessionID\) && routerAvailable/) +}) diff --git a/tests/tui-cockpit.test.mjs b/tests/tui-cockpit.test.mjs new file mode 100644 index 00000000..c6aea8ab --- /dev/null +++ b/tests/tui-cockpit.test.mjs @@ -0,0 +1,160 @@ +import assert from 'node:assert/strict' +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import test from 'node:test' +import { fileURLToPath } from 'node:url' +import { getSharedBus } from '../src/pantheon/bus.ts' +import { wireCockpitBusRecorder } from '../src/pantheon/cockpit-events.ts' +import { + buildCockpitSnapshot, + formatCockpitReplayArtifact, + formatGanttBar, + formatGateMatrixGlyphs, + renderWorkMapLines, + writeCockpitReplayArtifact, +} from '../src/plugins/tui/src/cockpit-state.ts' + +const root = fileURLToPath(new URL('..', import.meta.url)) + +test('cockpit-state builds Overview, Swarm Gantt bars, Work Map, and Flightdeck Gate Matrix cleanly', () => { + const dir = mkdtempSync(join(tmpdir(), 'pantheon-cockpit-')) + try { + mkdirSync(join(dir, '.pantheon', 'ledger'), { recursive: true }) + writeFileSync( + join(dir, '.pantheon', 'ledger', 'step-ledger.json'), + JSON.stringify({ + version: 1, + steps: { + 'step-auth': { + stepKey: 'step-auth', + objective: 'Implement OAuth PKCE handler', + agent: 'hermes', + state: 'done', + mutatedFiles: ['src/auth.ts'], + lastMutationAt: 1000, + lastVerifiedAt: 2000, + verificationExitCode: 0, + receiptId: 'rcpt_1234', + updatedAt: new Date(2000).toISOString(), + }, + 'step-fix': { + stepKey: 'step-fix', + objective: 'Fix session timeout bug', + agent: 'talos', + state: 'in_progress', + taskType: 'bugfix', + mutatedFiles: [], + lastMutationAt: null, + lastVerifiedAt: null, + updatedAt: new Date(3000).toISOString(), + }, + }, + }), + ) + + const snapshot = buildCockpitSnapshot({ + workspaceDir: dir, + sessionTitle: 'OAuth Refactor', + modelName: 'claude-sonnet-4.5', + contextTokens: 48_000, + contextWindow: 200_000, + sessionCost: 0.42, + cacheRate: 92, + children: [ + { + id: 'ses_c1', + agent: 'athena', + kind: 'plan', + status: 'completed', + cost: 0.08, + startedAt: 1000, + updatedAt: 5000, + tokens: 12_000, + }, + { + id: 'ses_c2', + agent: 'hermes', + kind: 'oth', + status: 'running', + cost: 0.19, + startedAt: 4000, + updatedAt: 9000, + tokens: 24_000, + }, + ], + events: [ + { + kind: 'lsp:diagnostics', + timestamp: 4500, + agent: 'hermes', + detail: 'src/auth.ts clean (0 errors)', + severity: 'ok', + }, + { + kind: 'review:verdict', + timestamp: 5500, + agent: 'themis', + detail: 'BLOCK: Missing rate limit on token exchange', + severity: 'error', + }, + ], + }) + + assert.equal(snapshot.overview.contextPercent, 24) + assert.equal(snapshot.overview.subagentCount, 2) + assert.ok(snapshot.overview.workMap.some((line) => line.includes('[Zeus]'))) + + assert.equal(snapshot.swarm.rows.length, 2) + assert.ok(snapshot.swarm.rows[0]?.ganttBar.includes('█')) + + assert.equal(snapshot.flightdeck.steps.length, 2) + assert.equal(snapshot.flightdeck.logs.length, 2) + assert.ok(snapshot.flightdeck.gateSummary.includes('allowed')) + assert.match(formatGateMatrixGlyphs(3, 1, 1, 1), /■.*▣.*□.*✗/) + + const gantt = formatGanttBar(2000, 6000, 1000, 9000, 16) + assert.equal(gantt.length, 16) + assert.ok(gantt.includes('█')) + + const mapLines = renderWorkMapLines({ subagents: 2, artifacts: 3, stepsDone: 1, stepsTotal: 2 }) + assert.ok(mapLines.length >= 3) + + const replay = formatCockpitReplayArtifact(snapshot, new Date('2026-11-19T18:00:00Z')) + assert.match(replay.filename, /^cockpit-replay-2026-11-19T18-00-00\.md$/) + assert.match(replay.markdown, /```mermaid\nsequenceDiagram/) + assert.match(replay.markdown, /athena/) + const relWritten = writeCockpitReplayArtifact(dir, snapshot, new Date('2026-11-19T18:00:00Z')) + assert.equal(relWritten, `.pantheon/reports/${replay.filename}`) + const saved = readFileSync(join(dir, relWritten), 'utf8') + assert.ok(saved.includes('## Execution Replay Diagram')) + } finally { + rmSync(dir, { recursive: true, force: true }) + } +}) + +test('index.tsx wires /pantheon-cockpit command to openCockpit', () => { + const indexSrc = readFileSync(join(root, 'src/plugins/tui/src/index.tsx'), 'utf8') + assert.match(indexSrc, /import \{[\s\S]*openPantheonCockpit[\s\S]*\} from '\.\/cockpit'/) + assert.match(indexSrc, /id:\s*'pantheon\.cockpit\.open'/) + assert.match(indexSrc, /name:\s*'pantheon-cockpit'/) +}) + +test('wireCockpitBusRecorder persists PantheonBus events for cross-process TUI Flightdeck stream', () => { + const dir = mkdtempSync(join(tmpdir(), 'pantheon-cockpit-bus-')) + const stop = wireCockpitBusRecorder(dir) + try { + getSharedBus().emit('review:verdict', { + verdict: 'APPROVE_WITH_NOTES', + targetAgent: 'hermes', + summary: 'Looks clean with minor naming note', + findingsCount: 1, + timestamp: 12_345, + }) + const snap = buildCockpitSnapshot({ workspaceDir: dir, children: [] }) + assert.ok(snap.flightdeck.logs.some((e) => e.kind === 'review:verdict' && e.agent === 'hermes')) + } finally { + stop() + rmSync(dir, { recursive: true, force: true }) + } +}) diff --git a/tests/tui-dispatch-panel.test.mjs b/tests/tui-dispatch-panel.test.mjs index 2de25e1b..5d2338a6 100644 --- a/tests/tui-dispatch-panel.test.mjs +++ b/tests/tui-dispatch-panel.test.mjs @@ -1083,3 +1083,78 @@ test('render: empty, mixed and narrow panels keep their documented shape', async 'a narrow row keeps its columns instead of wrapping', ) }) + +test('peek & live activity: panel detail shows active tool, files touched and snippet when present', async () => { + const { collectDispatch, dispatchPanelDetail, dispatchPanelRowText } = await loadV2() + const host = createPanelHost({ + children: [ + ['ses_root', { id: 'ses_root' }], + [ + 'ses_child_live', + { + id: 'ses_child_live', + parentID: 'ses_root', + agent: 'hermes', + model: 'hy4-flash-free', + cost: 0.01, + time: { created: 1000, updated: 5000 }, + }, + ], + ], + statuses: [['ses_child_live', 'running']], + messages: [ + [ + 'ses_root', + [ + { + type: 'assistant', + content: [ + { + type: 'tool', + name: 'subagent', + state: { + status: 'running', + metadata: { sessionID: 'ses_child_live' }, + input: { agent: 'hermes', description: 'Criar helper' }, + }, + }, + ], + }, + ], + ], + [ + 'ses_child_live', + [ + { + type: 'assistant', + content: [ + { type: 'tool', name: 'code_query', state: { status: 'completed' } }, + { + type: 'tool', + name: 'hashline_edit', + state: { status: 'running', input: { file: 'src/soma.mjs' } }, + }, + { type: 'text', text: 'Atualizando função soma em src/soma.mjs' }, + ], + }, + ], + ], + ], + }) + + const entries = collectDispatch(host.context, 'ses_root', { + now: 6000, + includeChildActivity: true, + }) + assert.equal(entries.length, 1) + assert.equal(entries[0].view.activity?.activeVerb, 'edit') + const rowText = dispatchPanelRowText(entries[0], { now: 6000, max: 50 }) + assert.ok(rowText.includes('edit'), `live panel row should surface active verb: ${rowText}`) + + const detail = dispatchPanelDetail(entries[0], { max: 60 }) + assert.ok(detail.length >= 5, `expected peek detail lines, got ${detail.length}`) + const joined = detail.slice(4).join('\n') + assert.match(joined, /hashline_edit/) + assert.match(joined, /soma\.mjs/) + assert.match(joined, /Atualizando função soma/) +}) diff --git a/tests/tui-legacy-audit.test.mjs b/tests/tui-legacy-audit.test.mjs index e39463ce..1601d1e1 100644 --- a/tests/tui-legacy-audit.test.mjs +++ b/tests/tui-legacy-audit.test.mjs @@ -1,5 +1,5 @@ import assert from 'node:assert/strict' -import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { existsSync, mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { DatabaseSync } from 'node:sqlite' @@ -97,4 +97,79 @@ describe('tui legacy-audit scanner & cleaner', () => { rmSync(tmp, { recursive: true, force: true }) } }) + + it('detects and cleans stale coexisting OpenCode plugin caches while keeping the active bundle', () => { + const tmp = mkdtempSync(join(tmpdir(), 'pantheon-tui-cache-')) + try { + const globalDir = join(tmp, 'global-opencode') + const cacheNpmDir = join(tmp, 'cache', 'opencode', 'npm') + const oldRev = join(cacheNpmDir, 'pantheon-opencode', '1000000') + const activeRev = join(cacheNpmDir, 'pantheon-opencode', '2000000') + const betaCache = join(cacheNpmDir, 'pantheon-opencode@beta', '1500000') + + mkdirSync(globalDir, { recursive: true }) + mkdirSync(join(oldRev, 'node_modules', 'pantheon-opencode'), { recursive: true }) + mkdirSync( + join(activeRev, 'node_modules', 'pantheon-opencode', 'src', 'plugins', 'tui', 'dist'), + { + recursive: true, + }, + ) + mkdirSync(join(betaCache, 'node_modules', 'pantheon-opencode'), { recursive: true }) + + writeFileSync( + join(oldRev, 'node_modules', 'pantheon-opencode', 'package.json'), + JSON.stringify({ name: 'pantheon-opencode', version: '2.1.6' }), + ) + writeFileSync( + join(activeRev, 'node_modules', 'pantheon-opencode', 'package.json'), + JSON.stringify({ name: 'pantheon-opencode', version: '2.2.0' }), + ) + writeFileSync( + join(betaCache, 'node_modules', 'pantheon-opencode', 'package.json'), + JSON.stringify({ name: 'pantheon-opencode', version: '2.2.0-beta.11' }), + ) + const activeBundlePath = join( + activeRev, + 'node_modules', + 'pantheon-opencode', + 'src', + 'plugins', + 'tui', + 'dist', + 'tui.js', + ) + writeFileSync(activeBundlePath, '// active tui bundle') + + utimesSync(oldRev, new Date(1000), new Date(1000)) + utimesSync(activeRev, new Date(2000), new Date(2000)) + + const scan = scanLegacyArtifacts({ + globalConfigDir: globalDir, + cacheDir: cacheNpmDir, + runningVersion: '2.2.0', + activeBundlePath, + }) + assert.equal(scan.summary.total, 2) + assert.equal(scan.summary.byCategory.drift, 2) + assert.equal( + scan.items.some((item) => item.path === activeRev), + false, + 'active running cache revision must never be flagged', + ) + + const cleaned = cleanLegacyArtifacts({ + globalConfigDir: globalDir, + cacheDir: cacheNpmDir, + runningVersion: '2.2.0', + activeBundlePath, + }) + assert.equal(cleaned.errors.length, 0) + assert.equal(existsSync(oldRev), false) + assert.equal(existsSync(join(cacheNpmDir, 'pantheon-opencode@beta')), false) + assert.equal(existsSync(activeBundlePath), true) + } finally { + rmSync(tmp, { recursive: true, force: true }) + } + }) }) diff --git a/tests/tui-sidebar.test.mjs b/tests/tui-sidebar.test.mjs index 328fd315..3ecfdccc 100644 --- a/tests/tui-sidebar.test.mjs +++ b/tests/tui-sidebar.test.mjs @@ -824,7 +824,7 @@ test('refresh subscription uses only names from the OpenCode V2 event union', as }) test('createSidebarModel: subscription, toast, spinner and teardown (fake host)', async () => { - const { createSidebarModel } = await loadV2() + const { createSidebarModel, SIDEBAR_REFRESH_EVENTS } = await loadV2() const now = Date.now() const host = createSidebarHost({ children: [ @@ -863,18 +863,7 @@ test('createSidebarModel: subscription, toast, spinner and teardown (fake host)' try { // The fake host throws on any name outside the union, so a passing mount // proves every subscription is a real V2 event. - assert.deepEqual( - [...host.registered.keys()], - [ - 'session.created', - 'session.renamed', - 'session.metadata.updated', - 'session.moved', - 'session.idle', - 'session.status', - 'session.deleted', - ], - ) + assert.deepEqual([...host.registered.keys()], [...SIDEBAR_REFRESH_EVENTS]) assert.deepEqual(host.toasts, [], 'mounting must not toast') // The sidebar no longer lists other sessions — only the active one. @@ -5231,4 +5220,160 @@ test('v2.1.7 TUI enhancements: turn cost delta, token anatomy, tool health and c } finally { dispose() } + + // 8. Native tool domain breakdown & live tool indicator (Slice 2) + const msgsNative = [ + { + type: 'assistant', + content: [ + { type: 'tool', name: 'memory_store', state: { status: 'completed' } }, + { type: 'tool', name: 'memory_search', state: { status: 'running' } }, + { type: 'tool', name: 'context_save', state: { status: 'completed' } }, + { type: 'tool', name: 'code_query', state: { status: 'completed' } }, + { type: 'tool', name: 'hashline_edit', state: { status: 'completed' } }, + ], + }, + ] + const domains = v2.summarizeToolDomains(msgsNative) + assert.equal(domains.total, 5) + assert.equal(domains.activeTool, 'memory_search') + assert.deepEqual(domains.byDomain, { mem: 2, ctx: 1, code: 1, edit: 1 }) + const detailLine = v2.formatToolDomainLine(domains, 31) + assert.ok(detailLine?.includes('mem:2'), `expected mem:2 in ${detailLine}`) + assert.ok(detailLine.includes('✦'), `expected live marker in ${detailLine}`) + assert.ok( + v2.cellWidth(detailLine) <= 31, + `detail line fits 31 cols (${v2.cellWidth(detailLine)})`, + ) + + const hostNative = createSidebarHost({ + children: [['ses_native_tools', { id: 'ses_native_tools', title: 'Native', agent: 'zeus' }]], + messages: [['ses_native_tools', msgsNative]], + }) + let modelNative + const disposeNative = createRoot((disposeRoot) => { + modelNative = v2.createSidebarModel(hostNative.context, () => 'ses_native_tools') + return disposeRoot + }) + try { + assert.equal(typeof modelNative.toolCallsDetailLine, 'function') + assert.ok(modelNative.toolCallsDetailLine()?.includes('mem:2')) + } finally { + disposeNative() + } + + // 9. Dispatch 2026 live child activity & attention badges (Slice 4) + const childMsgsEdit = [ + { + type: 'assistant', + content: [ + { + type: 'tool', + name: 'hashline_edit', + state: { status: 'running', input: { file: 'src/probe.mjs' } }, + }, + { type: 'text', text: 'Applying edit to probe helper.' }, + ], + }, + ] + const actEdit = v2.extractChildActivity(childMsgsEdit, 'running') + assert.equal(actEdit.activeVerb, 'edit') + assert.equal(actEdit.activeTool, 'hashline_edit') + assert.equal(actEdit.attention, null) + assert.deepEqual(actEdit.filesTouched, ['probe.mjs']) + + const childRowLive = v2.runningChildRowText( + { + id: 'ses_h', + label: 'hermes', + state: 'running', + startedAt: 1000, + updatedAt: 5000, + agent: 'hermes', + model: 'hy4-flash-free', + cost: 0, + kind: 'oth', + kindOrigin: 'agent', + background: false, + activity: actEdit, + }, + 13_400, + 0, + ) + assert.ok(childRowLive.includes('hermes·edit'), `live verb replaces ·oth: ${childRowLive}`) + assert.ok(v2.cellWidth(childRowLive) <= 34) + + const actAsk = v2.extractChildActivity( + [ + { + type: 'assistant', + content: [{ type: 'tool', name: 'question', state: { status: 'pending' } }], + }, + ], + 'running', + ) + assert.equal(actAsk.attention, 'question') + assert.equal(actAsk.activeVerb, 'ask') + const blockAsk = v2.buildDispatchBlock([ + { + id: 'ses_ask', + label: 'prometheus', + state: 'running', + startedAt: 1000, + updatedAt: 5000, + agent: 'prometheus', + model: 'kimi', + cost: 0, + kind: 'oth', + kindOrigin: 'agent', + background: false, + activity: actAsk, + }, + ]) + assert.equal(blockAsk?.running[0]?.tone, 'warning') + assert.ok(blockAsk?.running[0]?.text.startsWith('? ')) + assert.ok(blockAsk?.running[0]?.text.includes('·ask')) + + // 10. Code Mode `execute` unwrapping + separate `read` domain + live refresh events + assert.ok(v2.SIDEBAR_REFRESH_EVENTS.includes('session.tool.called')) + assert.ok(v2.SIDEBAR_REFRESH_EVENTS.includes('session.message.content.updated')) + assert.ok(v2.SIDEBAR_REFRESH_EVENTS.includes('session.usage.updated')) + + const msgsCodeMode = [ + { + type: 'assistant', + content: [ + { type: 'tool', name: 'read', state: { status: 'completed', input: { path: 'a.js' } } }, + { + type: 'tool', + name: 'execute', + state: { + status: 'completed', + input: { code: 'await tools.memory_store({ namespace: "a", key: "b", value: "c" })' }, + }, + }, + { + type: 'tool', + name: 'execute', + state: { + status: 'running', + input: { + code: 'await tools.hashline_edit({ file: "src/probe.mjs", edits: [] })', + }, + }, + }, + ], + }, + ] + const cmDomains = v2.summarizeToolDomains(msgsCodeMode) + assert.equal(cmDomains.total, 3) + assert.equal(cmDomains.byDomain.read, 1) + assert.equal(cmDomains.byDomain.mem, 1) + assert.equal(cmDomains.byDomain.edit, 1) + assert.equal(cmDomains.activeTool, 'hashline_edit') + + const cmChild = v2.extractChildActivity(msgsCodeMode, 'running') + assert.equal(cmChild?.activeVerb, 'edit') + assert.equal(cmChild?.activeTool, 'hashline_edit') + assert.deepEqual(cmChild?.filesTouched, ['probe.mjs', 'a.js']) }) diff --git a/wiki/Deepwork-Guide.md b/wiki/Deepwork-Guide.md index e562f36c..87b392f5 100644 --- a/wiki/Deepwork-Guide.md +++ b/wiki/Deepwork-Guide.md @@ -1,17 +1,18 @@ -# Guia de Deepwork: Planejamento Rigoroso +# Guia de Deepwork: Planejamento Rigoroso & Artefatos -O **Deepwork** é o sistema de planejamento disciplinado do Pantheon. +O **Deepwork** é o sistema de planejamento canônico e execução auditada do Pantheon. --- ## 1. Princípios 1. **O plano vive em `.pantheon/deepwork//`:** - - `plan.json`: O estado canônico estrito. - - `journal.ndjson`: O histórico auditável de eventos. - - `PLAN.md`: A projeção visual em Markdown com grafo Mermaid. + - `plan.json`: O estado canônico estrito validado por schema. + - `journal.ndjson`: O histórico append-only auditável de eventos e decisões. + - `PLAN.md`: A projeção visual em Markdown com grafo Mermaid e links clicáveis `file://`. 2. **Zero HTML:** O Pantheon utiliza diálogos interativos nativos (`question` tool) no próprio OpenCode para decisões e aprovações. -3. **Decisões Humanas Primeiro:** Incertezas técnicas e escolhas de escopo são apresentadas com opções recomendadas `(Recomendado)` para aprovação com 1 clique. +3. **Decisões Humanas Primeiro:** Trade-offs técnicos (`decisions_needed`) são resolvidos antes da execução dos especialistas. +4. **Progresso Verificado (`pantheon_step_ledger`):** Mutações precisam registrar verificação objetiva (testes/lint) antes de concluir cada etapa. --- @@ -28,3 +29,15 @@ Ou delegando ao Zeus: ```text @zeus elabore um plano de deepwork para a issue #42 ``` + +--- + +## 3. Lendo e Revisando Planos (`/pantheon-artifacts`) + +Depois que a `@athena` cria `.pantheon/deepwork//PLAN.md`, você pode inspecionar no chat do **OpenCode Desktop** ou abrir o leitor interativo paginado direto no terminal via `/pantheon-artifacts` (`/artifacts`): + +![Lista de artefatos no OpenCode TUI](../docs/assets/tui/artifacts-list.png) + +![Leitor paginado de artefatos no OpenCode TUI](../docs/assets/tui/artifacts-reader.png) + +> Veja todos os atalhos de teclado e mouse em [Artefatos & `/pantheon-artifacts`](../docs/pt-BR/ARTIFACTS.md). diff --git a/wiki/FAQ.md b/wiki/FAQ.md index f7842b6a..f12b4ee1 100644 --- a/wiki/FAQ.md +++ b/wiki/FAQ.md @@ -1,20 +1,37 @@ # Perguntas Frequentes (FAQ) -### 1. Por que o @zeus não edita código diretamente? -O Zeus é o orquestrador central. Sua função é analisar o problema, dividir o escopo e delegar para os especialistas certos (`@hermes`, `@aphrodite`, `@talos`). Ter o orquestrador isolado de escrita garante disciplina e evita que um único modelo alucine em código sem revisão. +### 1. Qual a melhor forma de instalar o Pantheon no OpenCode 2.x? +Use o gerenciador nativo de plugins do próprio OpenCode: -### 2. Como resolver um bug urgente rapidamente sem cerimônia de planejamento? -Chame diretamente o **@talos**: -```text -@talos corrija o typo na mensagem de erro do arquivo auth.ts +```bash +opencode plugin add pantheon-opencode ``` -### 3. Como ver quanto gastei na sessão? -Execute no chat: +Isso carrega os 14 agentes, 25 skills, comandos slash e as 26 ferramentas nativas em memória **sem copiar arquivos para o repositório**, funcionando em qualquer diretório ou worktree. Use `npx pantheon-opencode init` apenas se quiser gerar `.opencode/` ou `AGENTS.md` em disco. + +### 2. Como atualizar e remover caches ou arquivos antigos (evitar dados stale)? +Dentro do OpenCode, rode `/pantheon-settings` e vá na aba **Atualizações** (`/pantheon-updates`). Lá você pode checar o canal (`latest` vs `beta`), atualizar o plugin e clicar em **Escanear obsoletos** / **Migrar & limpar** para remover cópias antigas em `.opencode/` e caches coexistentes em `~/.cache/opencode/npm/pantheon-opencode*` sem tocar no bundle ativo nem nos seus agentes/skills customizados. + +### 3. Como ler planos Deepwork e relatórios grandes no terminal? +Execute `/pantheon-artifacts` (ou `/artifacts`). O visualizador lista `PLAN.md` (`.pantheon/deepwork/*/PLAN.md`), relatórios (`.pantheon/reports/*.md`) e ADRs (`docs/adr/*.md`) com leitura paginada e suporte a teclado e mouse — inclusive quando você está trabalhando dentro de uma git worktree. + +### 4. Memória FTS5 e artefatos funcionam dentro de `git worktree`? +Sim! Tanto a memória SQLite FTS5 (`.pantheon/memory/memory.db`) quanto o visualizador `/pantheon-artifacts` detectam `--git-common-dir` e resolvem automaticamente para a raiz do repositório principal, mantendo memória e planos compartilhados entre worktrees (você pode isolar memória por worktree definindo `PANTHEON_ISOLATE_WORKTREE_MEMORY=1`). + +### 5. Como usar no Windows + OpenCode Desktop? +O ambiente totalmente suportado hoje no Windows é rodar via **WSL2 (Linux)** (inclusive conectando o OpenCode Desktop ao workspace WSL2). No Windows nativo (`win32`) sem WSL2 há limitações conhecidas por chamadas POSIX e shell `/bin/bash`; veja [Plataformas](../docs/PLATFORMS.md). + +### 6. Por que o `@zeus` não edita código diretamente? +O Zeus é o orquestrador central (fail-closed: sem acesso de escrita ou shell direto). Ele analisa o pedido, planeja com `@athena`/`@apollo` e delega a execução para especialistas (`@hermes`, `@aphrodite`, `@demeter`, `@prometheus`, `@talos`) com revisão da `@themis`. + +### 7. Como resolver um bug urgente rapidamente sem planejamento longo? +Chame diretamente o **`@talos`**: + ```text -/pantheon_cost +@talos corrija o typo na mensagem de erro do arquivo auth.ts ``` -Ou acompanhe o gauge de contexto e spend diretamente no painel lateral da TUI (`pantheon tui`). -### 4. Onde posso ler a documentação completa? -Acesse o portal oficial no GitHub Pages: **[https://ils15.github.io/pantheon-opencode/](https://ils15.github.io/pantheon-opencode/)**. +### 8. Onde vejo custos da sessão, subagentes e documentações completas? +- **Sidebar ao vivo & `/dispatch`:** mostram tokens, cache, tool calls e custo agregado por subagente. +- **Tool `pantheon_cost`:** consulta detalhada por período/sessão. +- **Guias completos:** [Documentação PT-BR](../docs/pt-BR/index.md) · [English Docs](../docs/index.md) · [Site Oficial](https://ils15.github.io/pantheon-opencode/). diff --git a/wiki/Home.md b/wiki/Home.md index 87486f93..baf0fd78 100644 --- a/wiki/Home.md +++ b/wiki/Home.md @@ -1,6 +1,6 @@ # 🏛️ Bem-vindo à Wiki do Pantheon -> **Pantheon** é um framework de orquestração multi-agente para o **OpenCode**: 14 agentes especializados, 25 skills canônicas e um fluxo guiado do planejamento à mudança revisada e testada. +> **Pantheon v2.2.0** é um framework de orquestração multi-agente nativo para o **OpenCode 2.x**: 14 agentes especializados, 25 skills canônicas, 30 ferramentas TypeScript nativas, `/pantheon-cockpit` (3 páginas) e uma TUI completa no terminal e Desktop. --- @@ -8,31 +8,46 @@ | Página da Wiki | Descrição | |---|---| -| [Matriz de Agentes](Agent-Matrix.md) | Quem é quem no Olimpo: permissões, ferramentas e papéis de cada um dos 14 agentes | -| [Guia do Deepwork](Deepwork-Guide.md) | Como funciona o planejamento arquitetural em JSON, DAGs em Mermaid e aprovação interativa | -| [Pantheon Vision](Pantheon-Vision.md) | Como colar imagens e depurar interfaces sem poluir o chat | -| [Perguntas Frequentes (FAQ)](FAQ.md) | Respostas para dúvidas comuns e boas práticas | +| [Tour Visual: TUI, Settings & Artefatos](TUI-and-Artifacts.md) | Prints reais do `/pantheon-settings`, `/pantheon-artifacts`, `/dispatch` e Sidebar | +| [Matriz de Agentes](Agent-Matrix.md) | Quem é quem no Olimpo: permissões, ferramentas e papéis dos 14 agentes | +| [Guia do Deepwork](Deepwork-Guide.md) | Planejamento arquitetural em JSON, DAGs Mermaid, step ledger e `/pantheon-artifacts` | +| [Pantheon Vision](Pantheon-Vision.md) | Como colar imagens e configurar o modelo de visão sem poluir o chat | +| [Perguntas Frequentes (FAQ)](FAQ.md) | Instalação nativa, atualização sem lixo legado, worktrees e Windows/WSL2 | -> 📖 **Portal Oficial de Documentação:** Para guias interativos completos, pesquisa em tempo real e changelog detalhado, acesse nosso site oficial no GitHub Pages: **[https://ils15.github.io/pantheon-opencode/](https://ils15.github.io/pantheon-opencode/)**. +> 📖 **Documentação Completa:** [Mapa em Português](../docs/pt-BR/index.md) · [English Docs](../docs/index.md) · [Site GitHub Pages](https://ils15.github.io/pantheon-opencode/) --- -## ⚡ Início Rápido em 3 Comandos +## ⚡ Início Rápido em 3 Passos ```bash -# 1. Instale o Pantheon no seu projeto -npx pantheon-opencode init +# 1. Instale o plugin nativo no OpenCode 2.x (zero arquivos copiados, funciona em qualquer pasta) +opencode plugin add pantheon-opencode # 2. Inicie o OpenCode com a TUI opencode -# 3. Dispare sua primeira tarefa no chat -/pantheon Adicionar exportação de dados em CSV com testes unitários +# 3. Explore os comandos ou dispare sua primeira tarefa +/pantheon-settings ``` +![Tela inicial do OpenCode com Pantheon v2.2.0](../docs/assets/tui/home-status.png) + +--- + +## 💬 Paleta de Comandos & Sidebar ao Vivo + +Digite `/pantheon` no compositor (ou pressione `Ctrl+P`) para acessar ajustes, novidades, inspeção de artefatos, despacho de subagentes e governança: + +![Autocomplete de comandos /pantheon](../docs/assets/tui/commands-autocomplete.png) + +Durante a execução, a barra lateral exibe contexto, uso de cache, ferramentas, status do portão `J1` e o resumo consolidado do **Dispatch** por especialista: + +![Sidebar ao vivo com Dispatch e telemetria de sessão](../docs/assets/tui/session-sidebar.png) + --- -## 👥 Os Especialistas do Pantheon +## 👥 Arquitetura dos Especialistas ```mermaid flowchart TD diff --git a/wiki/Pantheon-Vision.md b/wiki/Pantheon-Vision.md index 1bd24b6b..cd1fe7b4 100644 --- a/wiki/Pantheon-Vision.md +++ b/wiki/Pantheon-Vision.md @@ -1,6 +1,6 @@ # Pantheon Vision: Análise Visual -O **Pantheon Vision** permite inspecionar interfaces visuais e designs colando imagens diretamente no OpenCode. +O **Pantheon Vision** permite inspecionar interfaces visuais, prints de erro e layouts colando imagens diretamente no OpenCode — mantendo o contexto da conversa enxuto via `vision_describe`. --- @@ -8,16 +8,21 @@ O **Pantheon Vision** permite inspecionar interfaces visuais e designs colando i 1. Copie qualquer imagem para a área de transferência (`Ctrl+C` ou captura de tela). 2. Cole no chat do OpenCode (`Ctrl+V`). -3. Digite sua instrução: +3. Descreva o objetivo: ```text - ajustar isso daqui, criar um menu lateral responsivo e atualizar os cards + ajustar o alinhamento do cabeçalho, melhorar o contraste do botão primário e revisar a responsividade ``` --- ## Configuração do Modelo Visual -Você pode configurar o modelo que faz a análise de imagem: -* **Na TUI:** `pantheon tui` ➔ **Settings** ➔ **Preset** ➔ **Vision Model**. +Você pode configurar qual modelo analisa as imagens sem alterar seu modelo principal de código: + +* **Na TUI:** `/pantheon-settings` ➔ aba **Preset** ➔ **Modelo de Visão** (`< automático >` ou modelo específico). * **No arquivo:** `.opencode/opencode-vision.json`. * **Por variável de ambiente:** `export PANTHEON_VISION_MODEL="opencode-go/mimo-v2.6-flash"`. + +![Aba Preset com seleção de Modelo de Visão](../docs/assets/tui/settings-preset.png) + +> 📖 Guia completo: [Visão Multimodal](../docs/pt-BR/guides/vision.md) · [English Vision Guide](../docs/guides/vision.md) diff --git a/wiki/TUI-and-Artifacts.md b/wiki/TUI-and-Artifacts.md new file mode 100644 index 00000000..9d5f1ec2 --- /dev/null +++ b/wiki/TUI-and-Artifacts.md @@ -0,0 +1,65 @@ +# 🖥️ Tour Visual: TUI, Configurações & Artefatos + +> Guia visual completo das interfaces nativas do Pantheon `v2.2.0` no OpenCode 2.x. +> Documentação de referência: [Configurações & TUI](../docs/pt-BR/SETTINGS.md) · [Artefatos](../docs/pt-BR/ARTIFACTS.md). + +--- + +## 1. Painel de Configurações (`/pantheon-settings`) + +Abre via `/pantheon-settings` (também funciona direto na tela inicial, pela paleta `Ctrl+P`, ou clicando no selo `↑ vX.Y.Z` na Home/Sidebar). Navegação completa por teclado (`Tab`, setas, `Enter`, `Ctrl+S`) ou mouse. + +### `Gates` — Regras & Portões em Tempo Real +Ative/desative skills (`Auto-continue`, `TDD with agents`, `Code review checklist`, `Prompt refinery`) e portões de execução (`Idle todo enforcer`, `Context pruner`, `J1 risk gate`) no escopo **global** ou do **projeto**: + +![Aba Gates no Pantheon Settings](../docs/assets/tui/settings-gates.png) + +### `Decisão`, `Preset`, `TUI` & `Autonomia` +Configure arbitragem Jev, tier global de modelos + modelo de visão, idioma (`pt-BR`/`en`/`auto`), barras da sidebar e tetos de autonomia/orçamento: + +![Aba Decisão no Pantheon Settings](../docs/assets/tui/settings-decision.png) + +![Aba TUI no Pantheon Settings](../docs/assets/tui/settings-tui.png) + +![Aba Autonomia no Pantheon Settings](../docs/assets/tui/settings-autonomy.png) + +### `Atualizações`, `Doctor` & `Sobre` +Verifique canal npm (`latest`/`beta`), execute limpeza segura de caches antigos e legado V1 (`~/.cache/opencode/npm/pantheon-opencode*`), cheque saúde do ambiente e consulte as **30 Native Tools** no inventário ao vivo: + +![Atualizações e Limpeza de Legado](../docs/assets/tui/settings-updates.png) + +![Doctor no Pantheon Settings](../docs/assets/tui/settings-doctor.png) + +![Aba Sobre listando as 30 ferramentas nativas](../docs/assets/tui/settings-about.png) + +--- + +## 2. Mission Control Cockpit (`/pantheon-cockpit`) + +Painel de observabilidade ao vivo em 3 abas (`1–3` ou `Tab`), com `Overview` (tokens/velocidade, gauges, health/work map), `Swarm` (árvore de delegação, barras Gantt concorrentes e stream semântico) e `Flightdeck` (matriz de permissões/gates J1 e telemetria): + +![Cockpit Overview](../docs/assets/tui/cockpit-overview.png) + +![Cockpit Swarm](../docs/assets/tui/cockpit-swarm.png) + +![Cockpit Flightdeck](../docs/assets/tui/cockpit-flightdeck.png) + +--- + +## 2. Visualizador de Artefatos (`/pantheon-artifacts`) + +Liste e leia planos Deepwork (`.pantheon/deepwork/*/PLAN.md`), relatórios (`.pantheon/reports/*.md`) e ADRs (`docs/adr/*.md`) com paginação no terminal — inclusive a partir de git worktrees ligadas ao repositório principal: + +![Lista de artefatos no /pantheon-artifacts](../docs/assets/tui/artifacts-list.png) + +![Leitor paginado no /pantheon-artifacts](../docs/assets/tui/artifacts-reader.png) + +--- + +## 3. Painel `/dispatch` & `What's New` + +Acompanhe cada subagente filho (`hermes`, `prometheus`, `athena`, `themis`) com tokens e custo individual em `/dispatch`, e reveja destaques da versão a qualquer momento em `/pantheon-whats-new` (`/whats-new`): + +![Painel /dispatch em fullscreen](../docs/assets/tui/dispatch-panel.png) + +![Janela What's New no OpenCode](../docs/assets/tui/whats-new.png)