pantheon-opencode 2.0.3 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/AGENTS.global.md +1 -1
  2. package/AGENTS.md +1 -1
  3. package/CHANGELOG.md +68 -0
  4. package/README.md +13 -6
  5. package/README.pt-BR.md +12 -5
  6. package/commands/pantheon-deepwork.md +11 -2
  7. package/package.json +2 -1
  8. package/plugin.json +1 -1
  9. package/prompts/orchestrate-with-zeus.prompt.md +2 -0
  10. package/pyproject.toml +1 -1
  11. package/scripts/cost.mjs +4 -5
  12. package/scripts/decision-router-budget.mjs +27 -6
  13. package/scripts/decision-router.mjs +76 -34
  14. package/scripts/doctor.mjs +74 -0
  15. package/scripts/install/decision-router-config.mjs +32 -7
  16. package/src/agents/apollo.md +6 -53
  17. package/src/agents/athena.md +1 -0
  18. package/src/agents/talos.md +10 -40
  19. package/src/agents/themis.md +9 -0
  20. package/src/agents/zeus.md +29 -2
  21. package/src/mcp/pantheon_vision.py +33 -2
  22. package/src/pantheon/background-job-board.ts +33 -0
  23. package/src/pantheon/bus.ts +190 -0
  24. package/src/pantheon/cost-command.ts +4 -1
  25. package/src/pantheon/deepwork/deepwork-tool.ts +370 -0
  26. package/src/pantheon/deepwork/plan-projection.ts +274 -0
  27. package/src/pantheon/deepwork/plan-schema.ts +93 -0
  28. package/src/pantheon/deepwork/plan-tracker.ts +336 -0
  29. package/src/pantheon/execution-receipt.ts +113 -0
  30. package/src/pantheon/jev-decision-tool.ts +8 -2
  31. package/src/pantheon/local-decision-budget.ts +36 -6
  32. package/src/pantheon/model-command.ts +2 -4
  33. package/src/pantheon/native-vision.ts +3 -1
  34. package/src/pantheon/prompt-cache-order.ts +89 -0
  35. package/src/pantheon/skill-search-tool.ts +2 -2
  36. package/src/pantheon/themis-reflex.ts +164 -0
  37. package/src/pantheon/tools.ts +2 -0
  38. package/src/plugin/index.js +979 -60
  39. package/src/plugins/tui/dist/tui.js +461 -289
  40. package/src/plugins/tui/dist/tui.js.map +1 -1
  41. package/src/plugins/tui/package-lock.json +2 -2
  42. package/src/plugins/tui/package.json +1 -1
  43. package/src/plugins/tui/src/autonomy-state.ts +14 -16
  44. package/src/plugins/tui/src/decision-router-state.ts +22 -10
  45. package/src/plugins/tui/src/pantheon-settings-state.ts +119 -35
  46. package/src/plugins/tui/src/pantheon-settings.tsx +142 -48
  47. package/src/plugins/tui/src/preset-state.ts +96 -6
  48. package/src/plugins/tui/src/update-status.ts +62 -22
@@ -334,7 +334,7 @@ export function readUserDecisionRouterConfig({ env = process.env } = {}) {
334
334
  const filePath = resolveUserDecisionRouterConfigPath(env)
335
335
  try {
336
336
  assertNoSymlinkAncestors(filePath)
337
- assertTrustedDirectoryChain(dirname(filePath))
337
+ assertTrustedDirectoryChain(dirname(filePath), { env })
338
338
  const stat = lstatSync(filePath)
339
339
  assertPrivatePath(stat, true)
340
340
  const parsed = JSON.parse(readFileSync(filePath, 'utf8'))
@@ -356,7 +356,7 @@ export function writeUserDecisionRouterConfig(config, { env = process.env } = {}
356
356
  assertNoSymlinkAncestors(directory, { includeLeaf: false })
357
357
  mkdirSync(directory, { recursive: true, mode: 0o700 })
358
358
  assertNoSymlinkAncestors(directory)
359
- assertTrustedDirectoryChain(directory)
359
+ assertTrustedDirectoryChain(directory, { env })
360
360
  assertPrivateDirectory(directory)
361
361
  try {
362
362
  const existing = lstatSync(filePath)
@@ -535,7 +535,24 @@ function assertPrivateDirectory(directory) {
535
535
  assertPrivatePath(stat, false)
536
536
  }
537
537
 
538
- function assertTrustedDirectoryChain(directory) {
538
+ function isPermittedGroupWritable(_current, env = process.env) {
539
+ if (env.PANTHEON_ALLOW_GROUP_WRITABLE === '1' || env.PANTHEON_ALLOW_GROUP_WRITABLE === 'true') {
540
+ return true
541
+ }
542
+ if (
543
+ env.JUPYTERHUB_USER ||
544
+ env.JUPYTER_IMAGE ||
545
+ env.JUPYTER_SERVER_ROOT ||
546
+ env.KUBERNETES_SERVICE_HOST ||
547
+ env.container ||
548
+ existsSync('/.dockerenv')
549
+ ) {
550
+ return true
551
+ }
552
+ return false
553
+ }
554
+
555
+ function assertTrustedDirectoryChain(directory, { env = process.env } = {}) {
539
556
  const absolute = resolve(directory)
540
557
  const root = parse(absolute).root
541
558
  const parts = absolute.slice(root.length).split(sep).filter(Boolean)
@@ -555,14 +572,22 @@ function assertTrustedDirectoryChain(directory) {
555
572
  if (!stat.isDirectory() || stat.isSymbolicLink()) {
556
573
  throw new Error('Decision-router configuration path contains a non-directory component')
557
574
  }
558
- if (stat.uid !== uid && stat.uid !== 0) {
575
+ const mode = stat.mode & 0o7777
576
+ const isSticky = (mode & 0o1000) !== 0
577
+ const isSystemOrUser = stat.uid === uid || stat.uid === 0 || (isSticky && stat.uid === 65534)
578
+ if (!isSystemOrUser) {
559
579
  throw new Error('Decision-router configuration path has an untrusted owner')
560
580
  }
561
- const mode = stat.mode & 0o7777
562
- const rootStickyDirectory = stat.uid === 0 && (mode & 0o1000) !== 0
563
- if ((mode & 0o022) !== 0 && !rootStickyDirectory) {
581
+ const worldWritable = (mode & 0o002) !== 0
582
+ const groupWritable = (mode & 0o020) !== 0
583
+ if (worldWritable && !isSticky) {
564
584
  throw new Error('Decision-router configuration path is writable by other users')
565
585
  }
586
+ if (groupWritable && !isSticky && !isPermittedGroupWritable(current, env)) {
587
+ throw new Error(
588
+ `Decision-router configuration path "${current}" is group-writable (mode ${(mode & 0o777).toString(8)}). In containers or JupyterHub, set PANTHEON_ALLOW_GROUP_WRITABLE=1 to permit group-writable ancestors, or run: chmod +t "${current}"`,
589
+ )
590
+ }
566
591
  }
567
592
  }
568
593
 
@@ -59,57 +59,10 @@ mcp_tools:
59
59
  - **Code-mode / infrastructure reads** — cheap and on demand; never for
60
60
  decisions the ladder already answers.
61
61
 
62
- ## Core Capabilities
62
+ ## Discovery Rules & Boundaries
63
63
 
64
- ### 1. Codebase Discovery
65
- - Use direct targeted searches for straightforward questions; batch independent searches only when the discovery scope benefits from it
66
- - Search boundaries: NEVER search or read files in `.pantheon/**`, `.pantheon/deepwork/**`, `.git/**`, `node_modules/**`, or `.pantheon-worktrees/**`
67
- - Search for files, patterns, symbols, imports in application source (`src/`, `lib/`, `tests/`, `docs/`)
68
- - Generate structured summaries (not raw dumps)
69
-
70
- ### 2. External Research
71
- - Web search through whatever web-search MCP the USER has configured — Pantheon
72
- bundles none and does not assume one. If no search tool is available, skip
73
- external search and say so; never present an unverified recollection as a
74
- citation.
75
- - Context7 for library documentation
76
- - Read URLs with webfetch for known resource URLs
77
-
78
- ### 3. Codemap Generation
79
- - Map project structure: top-level directories, entry points, key modules
80
- - Identify architecture patterns and tech debt signals
81
- - Return hierarchical summaries (60-70% token savings vs raw file reads)
82
-
83
- ## TOOLS NOT AVAILABLE
84
- - bash - forbidden (cannot run commands)
85
- - edit - forbidden (read-only agent)
86
- - Web search by default - no search MCP is bundled or pre-configured. Use one
87
- ONLY if the user's own config exposes it; otherwise state that external search
88
- was unavailable instead of improvising.
89
-
90
- ## Pragmatism and Non-Destructive Inspection
91
- - Diagnostic operations (reading files, targeted webfetch for documentation/status, symbol search) are inherently safe and non-destructive.
92
- - Do not debate hypothetical side-effects (e.g. click counting, redirect chains) or invent reasons to avoid inspecting what was requested.
93
- - Focus on returning objective findings directly, without paralysis over capabilities.
94
-
95
- ## MCP Security
96
- - Never embed credentials in URLs (grep for token=, key=, secret=)
97
- - Use environment variables for auth
98
- - Scrub URLs before logging
99
- - URL allowlist: official docs, public RFCs, package registries, public GitHub
100
- - Response content never stored to disk
101
-
102
- ## Output Format
103
- Return structured findings with:
104
- - **files_changed:** [paths]
105
- - **summary:** What was found
106
- - **confidence:** high | medium | low
107
-
108
- ## Auto-Continue (Embedded: Discovery)
109
-
110
- - Continue through independent discovery queries when more evidence is needed; use only the breadth justified by the request
111
- - Partial results OK on timeout — return whatever is found
112
- - No checkpoint needed (read-only, idempotent operations)
113
- - If timeout occurs, return partial findings with confidence score
114
- - Do NOT loop back for more searches — return what you have
115
- - Never auto-continue past 3 search rounds without fresh context
64
+ - **Strictly read-only scout**: search with grep/glob/read and `pantheon-memory` (`memory_search`, `code_query`). Never modify files, never run shell commands.
65
+ - **Search order**: session context first, direct targeted searches second. Batch independent queries only when discovery scope benefits from parallel search.
66
+ - **Boundaries**: NEVER search or read inside `.pantheon/**`, `.pantheon/deepwork/**`, `.git/**`, `node_modules/**`, or `.pantheon-worktrees/**`.
67
+ - **External research**: Use configured web search MCP or `webfetch` for documentation URLs. Never invent citations.
68
+ - **Output format**: Return hierarchical structured findings (`files_changed`, `summary`, `confidence`). No raw dumps.
@@ -26,6 +26,7 @@ permission:
26
26
  grep: allow
27
27
  glob: allow
28
28
  webfetch: allow
29
+ pantheon_deepwork: allow
29
30
  question: allow
30
31
  task:
31
32
  "*": deny
@@ -51,32 +51,11 @@ mcp_tools:
51
51
  - **Code-mode / infrastructure reads** — cheap and on demand; never for
52
52
  decisions the ladder already answers.
53
53
 
54
- ## Verification Tiers
54
+ ## Fast-Path Execution Contract
55
55
 
56
- Small bounded fix → change + one targeted proof, no ceremony. Material change → full test discipline. Match the tier to the change.
57
-
58
-
59
- ## Core Capabilities
60
-
61
- ### 1. Rapid Repairs
62
- - Single-file fixes (< 10 lines)
63
- - Multi-file fixes (max 2 files)
64
- - CSS, typo, import, and minor logic fixes
65
-
66
- ### 2. No TDD Ceremony
67
- - Hotfixes skip the RED->GREEN->REFACTOR cycle
68
- - Fix and run the narrowest relevant existing test/check; do not run a full suite for a micro-edit
69
- - Document the root cause inline
70
-
71
- ### 3. Escalation Rules
72
- Escalate to @zeus if:
73
- - Fix requires > 2 files or > 10 lines changed
74
- - Has security implications
75
- - Requires database migration
76
- - Touches authentication, security-sensitive behavior, production data, global configuration, or broad permissions
77
- - Breaks existing tests unexpectedly
78
-
79
- Full-auto does not permit Talos to perform push/merge/deploy, destructive/global changes, or sensitive work; escalate for required specialist review and explicit human approval.
56
+ - **Micro-scope only**: single-file (< 10 lines) or max 2 files (CSS, typos, imports, isolated logic fixes).
57
+ - **Zero ceremony**: skip RED->GREEN->REFACTOR; run only the narrowest relevant test slice via `test-slicing`.
58
+ - **Standalone execution**: no subagents, no orchestration overhead. Return `## subtask_summary` directly.
80
59
 
81
60
  ## Requested Artifact Completion
82
61
 
@@ -84,19 +63,10 @@ Full-auto does not permit Talos to perform push/merge/deploy, destructive/global
84
63
  - Searching the MCP Code Mode catalog only discovers MCP tools. A missing MCP match does not mean native file tools are unavailable.
85
64
  - 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.
86
65
 
87
- ## Constraints
88
- - No orchestration: you work standalone
89
- - No Themis review needed (low-risk)
90
- - Return subtask_summary format
91
- - If complexity exceeds threshold, escalate immediately
92
-
93
- ## Auto-Continue (Embedded: Hotfix)
94
-
95
- - Auto-continue through quick fix cycles (identify → fix → verify)
96
- - No checkpoint needed (single-file fixes, low complexity)
97
- - Escalate to Zeus if fix takes > 3 turns or requires > 2 files / > 10 lines
98
- - If fix breaks existing tests, stop immediately and escalate
99
- - No partial results — either fix is applied or escalate
66
+ ## Escalation Boundaries
100
67
 
101
- ## Skills
102
- `code-review-checklist`, `git-workflow-and-versioning`
68
+ Escalate to @zeus immediately if:
69
+ - Change requires > 2 files or > 10 lines
70
+ - Touches security, authentication, credentials, migrations, or broad permissions
71
+ - Fix takes > 3 turns or causes unexpected test regression
72
+ - Full-auto never permits push/merge/deploy or destructive operations without specialist review and human approval.
@@ -10,6 +10,7 @@ permission:
10
10
  shell: allow
11
11
  edit: deny
12
12
  hashline_edit: deny
13
+ pantheon_deepwork: allow
13
14
  task:
14
15
  "*": deny
15
16
  temperature: 0.1
@@ -183,6 +184,14 @@ Estimated time: ~60% of review effort
183
184
  - [ ] IntentGate passed (code solves the right problem)
184
185
  - [ ] Auth/security, data/schema, and sensitive actions preserve applicable tests, specialist review, and human approval
185
186
 
187
+ ## Local Reflex Loop (Self-Healing)
188
+
189
+ When Layer 1 (lint/formatting/style) or Layer 2 (narrow test slice) fails:
190
+ - Themis executes a direct local reflex loop with the implementer (up to 2 retry attempts).
191
+ - Emits `themis:reflex:discrepancy` with the exact failing slice/rules.
192
+ - Does NOT escalate to Zeus unless the 2-retry reflex budget is exhausted or an architectural/IntentGate mismatch occurs.
193
+ - On successful remediation, emits `themis:reflex:resolved` and issues PASS / PASS_WITH_NOTES.
194
+
186
195
  ## Verdict
187
196
 
188
197
  After review, return one of these:
@@ -11,6 +11,7 @@ permission:
11
11
  vision_describe: allow
12
12
  pantheon_jev_decide: allow
13
13
  pantheon_skill_search: allow
14
+ pantheon_deepwork: allow
14
15
  question: allow
15
16
  task:
16
17
  "*": allow
@@ -45,6 +46,20 @@ skills:
45
46
  - **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.**
46
47
  - **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.
47
48
 
49
+ ## Prompt Refinery & Request Disambiguation (`prompt-refinery`)
50
+
51
+ - **Prefix `>>` (Tier 2 Visual Contract):**
52
+ - When the user's prompt begins with `>>`: DO NOT execute immediately. Trigger Tier 2 Visual Contract.
53
+ - Present the structured engineering brief:
54
+ - Slices table (`Slice | Focus Area | Target Files | Verification Gate`)
55
+ - In Scope, Out of Scope & Negative Constraints
56
+ - Acceptance Criteria
57
+ - Open Questions with Recommended Defaults
58
+ - **MANDATORY `question` tool:** Always invoke the native `question` tool with structured choices (e.g. `["Aprovar escopo e iniciar execução", "Ajustar escopo/premissas"]`) to obtain explicit user confirmation before dispatching implementers.
59
+ - **Ambiguous or Multi-Concern Prompts (Tier 1 Silent Lean):**
60
+ - When a request mixes refactor/fix/redesign without clear acceptance criteria, extract internal lean brief (Target, Slices, Constraints, Verification, Defaults).
61
+ - If ambiguity blocks safe execution or presents critical trade-offs, **always invoke the native `question` tool** with concrete options rather than making blind assumptions or writing plain-text questions.
62
+
48
63
  ## Fast-Path Direct Implementation (Default Coding Workflow)
49
64
 
50
65
  - **Direct coding requests (features, bug fixes, refactoring, tests, hotfixes)**:
@@ -71,17 +86,29 @@ These rules are economic, measured against the 2026-11-05 usage audit. They appl
71
86
  - **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.
72
87
  - **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.
73
88
  - **pantheon-vision** (`vision_describe`): One pass per image; forward results in prompt to specialists.
89
+ - **pantheon_deepwork**: Structured Deepwork plans (.pantheon/deepwork/<slug>/plan.json, journal.ndjson, PLAN.md). Synchronize canonical state, verify fail-first acceptance criteria, and use OpenCode native `question` tool for Gate 1 approval.
74
90
 
75
91
  ## Local advisory routing before native delegation
76
92
 
77
93
  - 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.
78
94
  - Bounded, reversible, low-uncertainty, and non-sensitive tasks: route directly to the specialist; do not force planning or plan approval.
79
95
  - Ambiguous routing: prefer one typed `pantheon_jev_decide` with `mode: "delegation"` or `pantheon_local_decision`. Build `candidateAgents` from available subagent targets.
80
- - Missing capability: run `pantheon_skill_search` or `node scripts/skill-search.mjs` (read-only, never installs). Propose `npx skills add <skill>` for user review.
96
+ - Missing capability & Proactive Project Skill Decision Flow:
97
+ - 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.
98
+ - Arbitration: If multiple or ambiguous external candidates are returned, arbitrate relevance with `pantheon_jev_decide` (`mode: "choice"` or `"rank"`).
99
+ - Proactive Interactive Question Gate (MANDATORY `question` tool):
100
+ - NEVER ask the user to type terminal commands (`bash: deny`, `shell: deny`).
101
+ - 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/`).
102
+ - ALWAYS proactively invoke the native `question` tool immediately after discovery/ranking to offer 1-click installation options:
103
+ * Recommended choice: `"(Recomendado) Instalar skills prioritárias no projeto (.agents/skills/)"` (curated candidates).
104
+ * Granular choice: `"Selecionar skills específicas para instalar"` (or checkbox list if multiselect).
105
+ * Skip choice: `"Prosseguir sem instalar skills adicionais"`.
106
+ - 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 `npx skills add <skill1> [skill2...] -a opencode -y` in the project root (batching multiple skills in a single run).
107
+ - Verification: Specialist verifies directory creation in `<project>/.agents/skills/<skill-name>/` and reports completion; subsequent `pantheon_skill_search` confirms `installed: true`.
81
108
 
82
109
  ## Visual Context for Implementation
83
110
 
84
- - When a request includes an image or screenshot, use image content already available in the conversation. Call `vision_describe` only if it appears in the active root tool list; otherwise state the limitation instead of guessing.
111
+ - 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.
85
112
  - 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.
86
113
  - 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.
87
114
 
@@ -389,6 +389,37 @@ def _key_from_credential_db(provider: str) -> str | None:
389
389
  return None
390
390
 
391
391
 
392
+ def _opencode_config_dir() -> Path:
393
+ """Locate the OpenCode configuration directory."""
394
+ xdg = os.getenv("XDG_CONFIG_HOME")
395
+ if xdg and xdg.strip():
396
+ return Path(xdg.strip()) / "opencode"
397
+ return Path.home() / ".config" / "opencode"
398
+
399
+
400
+ def _configured_vision_model() -> str:
401
+ """Resolve configured vision model from env or opencode-vision.json."""
402
+ env_model = os.getenv("PANTHEON_VISION_MODEL")
403
+ if env_model and env_model.strip():
404
+ return env_model.strip()
405
+ candidates = [
406
+ Path.cwd() / ".opencode" / "opencode-vision.json",
407
+ _opencode_config_dir() / "opencode-vision.json",
408
+ Path.home() / ".opencode" / "opencode-vision.json",
409
+ ]
410
+ for path in candidates:
411
+ if path.is_file():
412
+ try:
413
+ data = json.loads(path.read_text(encoding="utf-8"))
414
+ if isinstance(data, dict):
415
+ val = data.get("visionModel")
416
+ if isinstance(val, str) and val.strip() and val.strip() != "auto":
417
+ return val.strip()
418
+ except (OSError, json.JSONDecodeError):
419
+ pass
420
+ return DEFAULT_MODEL
421
+
422
+
392
423
  def _resolve_auth() -> tuple[str | None, str]:
393
424
  """Resolve auth in env-first, then OpenCode credential-store order.
394
425
 
@@ -404,7 +435,7 @@ def _resolve_auth() -> tuple[str | None, str]:
404
435
  graceful callers (``vision_describe`` / ``vision_ocr``) degrade to local
405
436
  extraction, and only the fatal gateway path logs the paths/env vars tried.
406
437
  """
407
- model = os.getenv("PANTHEON_VISION_MODEL") or DEFAULT_MODEL
438
+ model = _configured_vision_model()
408
439
  env_key = os.getenv("PANTHEON_OPENCODE_API_KEY") or os.getenv("OPENCODE_API_KEY")
409
440
  if env_key:
410
441
  return env_key, _endpoint_for_model(model)
@@ -437,7 +468,7 @@ def _resolve_auth() -> tuple[str | None, str]:
437
468
 
438
469
  def _model() -> str:
439
470
  """Return the configured model without exposing configuration secrets."""
440
- return os.getenv("PANTHEON_VISION_MODEL") or DEFAULT_MODEL
471
+ return _configured_vision_model()
441
472
 
442
473
 
443
474
  def _metadata(image: ImageInput) -> dict[str, Any]:
@@ -13,6 +13,7 @@
13
13
  import { mkdir, rename, unlink, writeFile } from 'node:fs/promises'
14
14
  import { dirname, join } from 'node:path'
15
15
 
16
+ import { getSharedBus } from './bus.ts'
16
17
  import { createPantheonLogger } from './logger.ts'
17
18
 
18
19
  // Silence-by-default TUI policy (pantheon-hooks L42-58): console output in a
@@ -292,6 +293,14 @@ export class BackgroundJobBoard {
292
293
 
293
294
  this.jobs.set(input.taskID, record)
294
295
  await this.persistRecord(record)
296
+ getSharedBus().emit('job:created', {
297
+ taskID: record.taskID,
298
+ alias: record.alias,
299
+ agent: record.agent,
300
+ parentSessionID: record.parentSessionID,
301
+ state: record.state,
302
+ timestamp: now,
303
+ })
295
304
  return record
296
305
  }
297
306
 
@@ -364,6 +373,14 @@ export class BackgroundJobBoard {
364
373
 
365
374
  // --- write-ahead log: persist before notify ---
366
375
  await this.persistRecord(job)
376
+ getSharedBus().emit('job:updated', {
377
+ taskID: job.taskID,
378
+ alias: job.alias,
379
+ agent: job.agent,
380
+ state: job.state,
381
+ resultSummary: job.resultSummary,
382
+ timestamp: job.updatedAt,
383
+ })
367
384
 
368
385
  // --- signal on terminal states ---
369
386
  if (willBeTerminal) {
@@ -463,6 +480,11 @@ export class BackgroundJobBoard {
463
480
  // cycle deleted them. Instead, remove any still-pending wake signal so
464
481
  // reconcile leaves no `<alias>.signal.json` behind.
465
482
  await this.deleteSignal(job.alias)
483
+ getSharedBus().emit('job:reconciled', {
484
+ taskID: job.taskID,
485
+ alias: job.alias,
486
+ timestamp: job.updatedAt,
487
+ })
466
488
 
467
489
  return job
468
490
  }
@@ -728,6 +750,17 @@ export class BackgroundJobBoard {
728
750
  }
729
751
 
730
752
  private notifyTerminal(taskID: string): void {
753
+ const job = this.jobs.get(taskID)
754
+ if (job) {
755
+ getSharedBus().emit('job:terminal', {
756
+ taskID: job.taskID,
757
+ alias: job.alias,
758
+ agent: job.agent,
759
+ state: job.state,
760
+ resultSummary: job.resultSummary,
761
+ timestamp: job.completedAt ?? Date.now(),
762
+ })
763
+ }
731
764
  for (const listener of this.terminalListeners) {
732
765
  try {
733
766
  listener(taskID)
@@ -0,0 +1,190 @@
1
+ /**
2
+ * Pantheon Event Bus (pantheon-bus) — In-memory reactive event system.
3
+ *
4
+ * Eliminates disk I/O and polling loops for inter-agent communication,
5
+ * background job tracking, and reactive verification.
6
+ *
7
+ * Process-global singleton anchored in globalThis.__pantheonSharedBus,
8
+ * matching the dual-plugin deduplication architecture in shared-board.ts.
9
+ *
10
+ * Pure TypeScript — zero external dependencies.
11
+ *
12
+ * @module bus
13
+ */
14
+
15
+ export interface JobEventPayload {
16
+ readonly taskID: string
17
+ readonly alias: string
18
+ readonly agent: string
19
+ readonly timestamp: number
20
+ readonly parentSessionID?: string | undefined
21
+ readonly state?: string | undefined
22
+ readonly resultSummary?: string | null | undefined
23
+ }
24
+
25
+ export interface ThemisReflexEventPayload {
26
+ readonly taskID: string
27
+ readonly agent: string
28
+ readonly file: string
29
+ readonly error: string
30
+ readonly attempt: number
31
+ readonly maxAttempts: number
32
+ readonly timestamp: number
33
+ readonly resolved?: boolean | undefined
34
+ }
35
+
36
+ export interface ExecutionReceiptPayload {
37
+ readonly receiptId: string
38
+ readonly taskID: string
39
+ readonly agent: string
40
+ readonly status: 'VERIFIED' | 'UNVERIFIED' | 'FAILED'
41
+ readonly files: ReadonlyArray<{
42
+ readonly path: string
43
+ readonly hash: string
44
+ readonly sizeBytes: number
45
+ }>
46
+ readonly testSlice?:
47
+ | { readonly command: string; readonly exitCode: number; readonly durationMs: number }
48
+ | undefined
49
+ readonly timestamp: number
50
+ readonly signature: string
51
+ }
52
+
53
+ export interface PantheonEventMap {
54
+ 'job:created': JobEventPayload
55
+ 'job:updated': JobEventPayload
56
+ 'job:terminal': JobEventPayload
57
+ 'job:reconciled': { readonly taskID: string; readonly alias: string; readonly timestamp: number }
58
+ 'themis:reflex:discrepancy': ThemisReflexEventPayload
59
+ 'themis:reflex:resolved': ThemisReflexEventPayload
60
+ 'agent:execution:receipt': ExecutionReceiptPayload
61
+ }
62
+
63
+ export type PantheonEventName = keyof PantheonEventMap
64
+
65
+ // biome-ignore lint/suspicious/noExplicitAny: internal heterogeneous event listener storage
66
+ type AnyListener = (payload: any) => void | Promise<void>
67
+
68
+ export class PantheonBus {
69
+ private readonly listeners: Map<string, Set<AnyListener>> = new Map()
70
+
71
+ /**
72
+ * Register a persistent listener for an event.
73
+ * Returns an unsubscribe callback for easy cleanup.
74
+ */
75
+ on<E extends PantheonEventName>(
76
+ event: E,
77
+ listener: (payload: PantheonEventMap[E]) => void | Promise<void>,
78
+ ): () => void {
79
+ let set = this.listeners.get(event)
80
+ if (!set) {
81
+ set = new Set()
82
+ this.listeners.set(event, set)
83
+ }
84
+ set.add(listener)
85
+ return () => {
86
+ set?.delete(listener)
87
+ if (set?.size === 0) {
88
+ this.listeners.delete(event)
89
+ }
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Register a one-shot listener that unregisters itself after firing once.
95
+ */
96
+ once<E extends PantheonEventName>(
97
+ event: E,
98
+ listener: (payload: PantheonEventMap[E]) => void | Promise<void>,
99
+ ): () => void {
100
+ const unsubscribe = this.on(event, (payload) => {
101
+ unsubscribe()
102
+ return listener(payload)
103
+ })
104
+ return unsubscribe
105
+ }
106
+
107
+ /**
108
+ * Synchronously emit an event to all registered listeners.
109
+ * Listener rejections are logged safely without throwing.
110
+ */
111
+ emit<E extends PantheonEventName>(event: E, payload: PantheonEventMap[E]): void {
112
+ const set = this.listeners.get(event)
113
+ if (!set || set.size === 0) return
114
+ for (const listener of Array.from(set)) {
115
+ try {
116
+ const result = listener(payload)
117
+ if (result instanceof Promise) {
118
+ result.catch(() => {})
119
+ }
120
+ } catch {
121
+ // Safe swallow: an in-memory listener crash must not fail the emitter
122
+ }
123
+ }
124
+ }
125
+
126
+ /**
127
+ * Wait asynchronously for a specific event matching a predicate, with an optional timeout.
128
+ */
129
+ waitFor<E extends PantheonEventName>(
130
+ event: E,
131
+ predicate: (payload: PantheonEventMap[E]) => boolean,
132
+ timeoutMs = 30_000,
133
+ ): Promise<PantheonEventMap[E]> {
134
+ return new Promise((resolve, reject) => {
135
+ let timer: NodeJS.Timeout | null = null
136
+ let unsubscribe: (() => void) | null = null
137
+
138
+ if (timeoutMs > 0 && Number.isFinite(timeoutMs)) {
139
+ timer = setTimeout(() => {
140
+ unsubscribe?.()
141
+ reject(new Error(`Timed out waiting for bus event "${event}" after ${timeoutMs}ms`))
142
+ }, timeoutMs)
143
+ }
144
+
145
+ unsubscribe = this.on(event, (payload) => {
146
+ try {
147
+ if (predicate(payload)) {
148
+ if (timer) clearTimeout(timer)
149
+ unsubscribe?.()
150
+ resolve(payload)
151
+ }
152
+ } catch (err) {
153
+ if (timer) clearTimeout(timer)
154
+ unsubscribe?.()
155
+ reject(err)
156
+ }
157
+ })
158
+ })
159
+ }
160
+
161
+ /** Number of active listeners for a specific event or in total. */
162
+ listenerCount(event?: PantheonEventName): number {
163
+ if (event) {
164
+ return this.listeners.get(event)?.size ?? 0
165
+ }
166
+ let total = 0
167
+ for (const set of this.listeners.values()) {
168
+ total += set.size
169
+ }
170
+ return total
171
+ }
172
+
173
+ /** Clear all listeners (primarily for unit tests). */
174
+ clear(): void {
175
+ this.listeners.clear()
176
+ }
177
+ }
178
+
179
+ const BUS_KEY = '__pantheonSharedBus'
180
+
181
+ /**
182
+ * Access the process-global PantheonBus singleton.
183
+ */
184
+ export function getSharedBus(): PantheonBus {
185
+ const host = globalThis as { [BUS_KEY]?: PantheonBus }
186
+ if (host[BUS_KEY] instanceof PantheonBus) return host[BUS_KEY]
187
+ const bus = new PantheonBus()
188
+ host[BUS_KEY] = bus
189
+ return bus
190
+ }
@@ -296,7 +296,10 @@ const COST_AGGREGATE_SQL: Record<CostSource, (sessionId: boolean) => string> = {
296
296
  session_message: (sessionId) => `
297
297
  WITH valid AS (
298
298
  SELECT json_extract(data, '$.agent') AS agent,
299
- 'unknown' AS phase,
299
+ COALESCE(NULLIF(json_extract(data, '$.phase'), ''),
300
+ NULLIF(json_extract(data, '$.metadata.phase'), ''),
301
+ NULLIF(json_extract(data, '$.subtask.phase'), ''),
302
+ 'unknown') AS phase,
300
303
  COALESCE(json_extract(data, '$.model.providerID'),
301
304
  json_extract(data, '$.providerID')) AS provider,
302
305
  COALESCE(json_extract(data, '$.model.id'),