pantheon-opencode 1.6.0-beta.14 → 1.6.0-beta.17

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 (50) hide show
  1. package/AGENTS.global.md +8 -10
  2. package/AGENTS.md +1 -1
  3. package/CHANGELOG.md +62 -3
  4. package/README.md +155 -24
  5. package/README.pt-BR.md +14 -14
  6. package/package.json +3 -3
  7. package/plugin.json +1 -1
  8. package/pyproject.toml +1 -1
  9. package/scripts/_pantheon_paths.py +24 -0
  10. package/scripts/doctor.mjs +7 -2
  11. package/scripts/install-mcp.mjs +1 -1
  12. package/scripts/mcp_persistence.py +1260 -1017
  13. package/scripts/memory_mcp.py +12 -843
  14. package/scripts/test-opencode-v2-sandbox.sh +2 -115
  15. package/skills-lock.json +3 -3
  16. package/src/agents/aphrodite.md +11 -10
  17. package/src/agents/apollo.md +1 -2
  18. package/src/agents/athena.md +13 -13
  19. package/src/agents/demeter.md +10 -7
  20. package/src/agents/gaia.md +0 -1
  21. package/src/agents/hephaestus.md +4 -3
  22. package/src/agents/hermes.md +10 -9
  23. package/src/agents/iris.md +0 -1
  24. package/src/agents/mnemosyne.md +3 -2
  25. package/src/agents/nyx.md +4 -4
  26. package/src/agents/prometheus.md +12 -11
  27. package/src/agents/zeus.md +27 -2
  28. package/src/instructions/agent-return-format.instructions.md +7 -9
  29. package/src/instructions/zeus-council-synthesis.instructions.md +2 -2
  30. package/src/instructions/zeus-memory-operations.instructions.md +9 -1
  31. package/src/instructions/zeus-timeout-retry.instructions.md +8 -1
  32. package/src/mcp/_pantheon_paths.py +24 -0
  33. package/src/mcp/mcp_codemap_module.py +86 -18
  34. package/src/mcp/mcp_persistence.py +1260 -1017
  35. package/src/mcp/memory_mcp.py +101 -57
  36. package/src/pantheon/goal-loop.ts +11 -8
  37. package/src/pantheon/task-result-guard.ts +50 -14
  38. package/src/pantheon/v2-execute-after.ts +135 -24
  39. package/src/pantheon/v2-tools.ts +10 -1
  40. package/src/plugin-v2.ts +6 -4
  41. package/src/plugin.ts +3 -2
  42. package/src/plugins/tui/dist/tui-v2.js +2 -2
  43. package/src/plugins/tui/dist/tui.js +1 -1
  44. package/src/plugins/tui/package-lock.json +2 -2
  45. package/src/plugins/tui/package.json +1 -1
  46. package/src/routing.yml +4 -4
  47. package/src/skills/codemap/SKILL.md +1 -1
  48. package/src/skills/memory-bank/SKILL.md +17 -13
  49. package/src/skills/session-goal/SKILL.md +12 -22
  50. package/scripts/probe-context-rehydrate.mjs +0 -263
@@ -17,6 +17,9 @@ Tools:
17
17
  memory_forget — Delete by ID or key
18
18
  memory_list — Chronological listing
19
19
  memory_stats — DB statistics
20
+ code_index — Index code entities
21
+ code_query — Search indexed code entities
22
+ code_neighbors — Find related code entities
20
23
 
21
24
  Usage:
22
25
  python scripts/memory_mcp.py
@@ -27,13 +30,14 @@ from __future__ import annotations
27
30
  import contextlib
28
31
  import functools
29
32
  import json
33
+ import logging
30
34
  import sqlite3
31
35
  import time
32
36
  from datetime import UTC, datetime
33
37
  from pathlib import Path
34
- from typing import Annotated, Any
38
+ from typing import Annotated, Any, Literal, TypedDict
35
39
 
36
- from _pantheon_paths import pantheon_home
40
+ from _pantheon_paths import pantheon_home, trusted_project_root
37
41
  from fastmcp import FastMCP
38
42
  from pydantic import BeforeValidator, Field
39
43
 
@@ -119,6 +123,20 @@ mcp = FastMCP(
119
123
  "index, so a query must share a token with the stored text to match."
120
124
  ),
121
125
  )
126
+ _LOGGER = logging.getLogger(__name__)
127
+
128
+
129
+ class MemorySearchErrorDetail(TypedDict):
130
+ """Safe, typed error detail returned when a memory search cannot run."""
131
+
132
+ type: Literal["DatabaseUnavailableError", "MemorySearchError"]
133
+ message: str
134
+
135
+
136
+ class MemorySearchError(TypedDict):
137
+ """Structured error envelope for ``memory_search``."""
138
+
139
+ error: MemorySearchErrorDetail
122
140
 
123
141
 
124
142
  # ── Database ──────────────────────────────────────────────────────────────────
@@ -304,22 +322,21 @@ def _build_fts_query(query: str) -> str:
304
322
 
305
323
  Tokens surviving both filters are still prefix-matched, so a query term
306
324
  retrieves documents containing a longer word that starts with it. If every
307
- token is a stopword the unfiltered tokens are matched exactly, so an
308
- all-stopword query degrades to a literal lookup rather than to no results.
325
+ token is a stopword, the query is empty and returns no results.
309
326
 
310
327
  Args:
311
328
  query: Raw, user-supplied search text.
312
329
 
313
330
  Returns:
314
- An FTS5 expression (terms joined with ``OR``), or ``""`` for an empty
315
- query.
331
+ An FTS5 expression (terms joined with ``OR``), or ``""`` when there are
332
+ no searchable terms.
316
333
  """
317
334
  words = [word for word in query.split() if word]
318
335
  if not words:
319
336
  return ""
320
337
  content = [word for word in words if word.lower() not in _STOPWORDS]
321
338
  if not content:
322
- content = words
339
+ return ""
323
340
  return " OR ".join(
324
341
  f'"{word}"*' if len(word) >= _MIN_PREFIX_LEN else f'"{word}"'
325
342
  for word in content
@@ -376,20 +393,17 @@ def _fetch_created_at_map(db: sqlite3.Connection, ids: list[int]) -> dict[int, s
376
393
  ids: Memory row IDs to look up.
377
394
 
378
395
  Returns:
379
- Mapping of id -> created_at ISO string. Empty on failure.
396
+ Mapping of id -> created_at ISO string.
380
397
  """
381
398
  created_at_map: dict[int, str] = {}
382
399
  if not ids:
383
400
  return created_at_map
384
- try:
385
- placeholders = ",".join("?" * len(ids))
386
- rows = db.execute(
387
- f"SELECT id, created_at FROM memories WHERE id IN ({placeholders})",
388
- ids,
389
- ).fetchall()
390
- created_at_map = {r["id"]: r["created_at"] for r in rows}
391
- except Exception:
392
- created_at_map = {}
401
+ placeholders = ",".join("?" * len(ids))
402
+ rows = db.execute(
403
+ f"SELECT id, created_at FROM memories WHERE id IN ({placeholders})",
404
+ ids,
405
+ ).fetchall()
406
+ created_at_map = {r["id"]: r["created_at"] for r in rows}
393
407
  return created_at_map
394
408
 
395
409
 
@@ -584,14 +598,15 @@ def memory_store(
584
598
  "prefix-matched, so a query must share a token with the stored text — "
585
599
  "there is no semantic/vector retrieval. Optional decay_days applies a "
586
600
  "freshness half-life (2^(-days/decay_days)) so recent entries rank "
587
- "higher; default None keeps the raw BM25 order.",
601
+ "higher; default None keeps the raw BM25 order. An empty result means "
602
+ "nothing matched; an error means the memory store could not be read.",
588
603
  )
589
604
  def memory_search(
590
605
  query: str,
591
606
  namespace: str | None = None,
592
607
  top_k: int = 5,
593
608
  decay_days: float | None = None,
594
- ) -> list[dict[str, Any]]:
609
+ ) -> list[dict[str, Any]] | MemorySearchError:
595
610
  """Search memories with FTS5 BM25.
596
611
 
597
612
  Args:
@@ -604,17 +619,31 @@ def memory_search(
604
619
 
605
620
  Returns:
606
621
  List of memory entries with a ``score`` (BM25, higher is better,
607
- freshness-decayed when ``decay_days`` is set) and parsed metadata.
622
+ freshness-decayed when ``decay_days`` is set) and parsed metadata, or a
623
+ typed error when the memory store cannot be read.
608
624
  """
609
625
  if not query or not query.strip():
610
626
  return []
611
627
 
612
- top_k = max(1, min(50, int(top_k)))
613
- db = _get_conn()
614
628
  fts_query = _build_fts_query(query)
615
629
  if not fts_query:
616
630
  return []
617
631
 
632
+ top_k = max(1, min(50, int(top_k)))
633
+ try:
634
+ db = _get_conn()
635
+ except Exception:
636
+ _LOGGER.warning("memory_search failed: memory database could not be opened")
637
+ return {
638
+ "error": {
639
+ "type": "DatabaseUnavailableError",
640
+ "message": (
641
+ "Memory database could not be opened. Check its configured "
642
+ "location and permissions, then retry."
643
+ ),
644
+ }
645
+ }
646
+
618
647
  try:
619
648
  params: list[Any] = [fts_query]
620
649
  namespace_clause = ""
@@ -634,46 +663,51 @@ def memory_search(
634
663
  params,
635
664
  ).fetchall()
636
665
  hits = [(r["rowid"], r["bm25"]) for r in rows]
637
- except Exception:
638
- return []
639
-
640
- if not hits:
641
- return []
642
-
643
- candidate_ids = [doc_id for doc_id, _ in hits]
644
- created_at_map = (
645
- _fetch_created_at_map(db, candidate_ids)
646
- if decay_days is not None and decay_days > 0
647
- else {}
648
- )
649
- ranked = _score_hits(hits, top_k, created_at_map, decay_days)
666
+ if not hits:
667
+ return []
650
668
 
651
- results: list[dict[str, Any]] = []
652
- if ranked:
653
- # 5. Fetch full entries
654
- id_list = [doc_id for doc_id, _ in ranked]
655
- score_map = {doc_id: score for doc_id, score in ranked}
669
+ candidate_ids = [doc_id for doc_id, _ in hits]
670
+ created_at_map = (
671
+ _fetch_created_at_map(db, candidate_ids)
672
+ if decay_days is not None and decay_days > 0
673
+ else {}
674
+ )
675
+ ranked = _score_hits(hits, top_k, created_at_map, decay_days)
656
676
 
657
- try:
677
+ results: list[dict[str, Any]] = []
678
+ if ranked:
679
+ # 5. Fetch full entries
680
+ id_list = [doc_id for doc_id, _ in ranked]
681
+ score_map = {doc_id: score for doc_id, score in ranked}
658
682
  placeholders = ",".join("?" * len(id_list))
659
683
  rows = db.execute(
660
684
  f"""SELECT id, namespace, key, value, metadata, created_at
661
685
  FROM memories WHERE id IN ({placeholders})""",
662
686
  id_list,
663
687
  ).fetchall()
664
- except Exception:
665
- return []
666
688
 
667
- # Preserve ranking order
668
- row_map = {r["id"]: r for r in rows}
669
- for doc_id in id_list:
670
- row = row_map.get(doc_id)
671
- if row is None:
672
- continue
673
- entry = dict(row)
674
- entry = _parse_metadata(entry)
675
- entry["score"] = round(score_map.get(doc_id, 0.0), 4)
676
- results.append(entry)
689
+ # Preserve ranking order
690
+ row_map = {r["id"]: r for r in rows}
691
+ for doc_id in id_list:
692
+ row = row_map.get(doc_id)
693
+ if row is None:
694
+ continue
695
+ entry = dict(row)
696
+ entry = _parse_metadata(entry)
697
+ entry["score"] = round(score_map.get(doc_id, 0.0), 4)
698
+ results.append(entry)
699
+ except Exception:
700
+ _LOGGER.warning("memory_search failed: FTS or stored-entry read failed")
701
+ return {
702
+ "error": {
703
+ "type": "MemorySearchError",
704
+ "message": (
705
+ "Memory search failed while reading the SQLite FTS index "
706
+ "or stored entries. Check the memory store and FTS index, "
707
+ "then retry."
708
+ ),
709
+ }
710
+ }
677
711
 
678
712
  return results
679
713
 
@@ -870,8 +904,8 @@ def memory_stats() -> dict[str, Any]:
870
904
 
871
905
 
872
906
  @mcp.tool(
873
- description="Index codebase files incrementally (hash-based skip). "
874
- "Parses Python (ast) and TypeScript (regex) to build knowledge graph.",
907
+ description="Index supported files inside the host-bound project root only. "
908
+ "Parses Python (ast) and TypeScript (regex) into the shared Memory DB.",
875
909
  )
876
910
  def code_index(
877
911
  path: str | None = None,
@@ -880,7 +914,7 @@ def code_index(
880
914
  """Index code files into knowledge graph.
881
915
 
882
916
  Args:
883
- path: File or directory to index; None = cwd.
917
+ path: File or directory within the trusted project root; None = project root.
884
918
  force: Re-parse even if hash unchanged.
885
919
 
886
920
  Returns:
@@ -888,8 +922,18 @@ def code_index(
888
922
  """
889
923
  if _codemap is None:
890
924
  return {"error": "codemap module not available"}
925
+ project_root = trusted_project_root()
926
+ if project_root is None:
927
+ return {
928
+ "error": (
929
+ "Trusted project root unavailable; code_index requires the MCP "
930
+ "host to set PANTHEON_PROJECT to an absolute project directory"
931
+ ),
932
+ "indexed": 0,
933
+ "skipped": 0,
934
+ }
891
935
  db = _get_conn()
892
- return _codemap.code_index(db, path, force)
936
+ return _codemap.code_index(db, path, force, project_root=project_root)
893
937
 
894
938
 
895
939
  @mcp.tool(
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Full-auto Goal Loop (Wave 3, PR #46) — one active goal per session,
2
+ * Goal Loop (Wave 3, PR #46) — when enabled, one active goal per session is
3
3
  * continued automatically while idle. `pantheon_goal_create` starts a goal;
4
4
  * `pantheon_goal_update` moves it pending → in_progress → done; while
5
5
  * active, `GoalLoop.onIdle` re-injects the continuation prompt (objective
@@ -7,7 +7,8 @@
7
7
  * completion-audit prompt — the state machine is the source of truth.
8
8
  *
9
9
  * Persistence: FILE-based GoalStore (`.pantheon/goals/<sessionID>.json`,
10
- * atomic tmp+rename). Opt-in `full_auto.enabled: false` default. Guards:
10
+ * atomic tmp+rename). The plugin uses hard-coded defaults; no runtime config
11
+ * enables the loop in this build. Guards:
11
12
  * board-running skip, in-flight Set, cooldown, max_continuations cap (25).
12
13
  * Injectable now() clock. Pure TypeScript — zero runtime deps.
13
14
  *
@@ -35,7 +36,7 @@ export { GoalStore }
35
36
  /** Continuation text injected into idle sessions. `{objective}` is substituted. */
36
37
  export const GOAL_CONTINUATION_PROMPT = 'Continue goal: {objective}'
37
38
 
38
- /** Defaults matching routing.yml `full_auto`. */
39
+ /** Hard-coded runtime defaults; routing.yml is documentation-only. */
39
40
  export const GOAL_LOOP_DEFAULTS = {
40
41
  enabled: false,
41
42
  cooldownMs: 5000,
@@ -93,7 +94,7 @@ function toolFailure(prefix: string, err: unknown): string {
93
94
  // ─── Args schemas ──────────────────────────────────────────────────────
94
95
 
95
96
  const goalCreateArgs = {
96
- objective: z.string().min(1).describe('The goal objective the session keeps working toward.'),
97
+ objective: z.string().min(1).describe('The objective recorded in this legacy session goal.'),
97
98
  } satisfies z.ZodRawShape
98
99
 
99
100
  const goalUpdateArgs = {
@@ -149,8 +150,9 @@ export class GoalLoop {
149
150
  this.warn = deps.logger?.warn ?? ((message: string) => log.warn(message))
150
151
  }
151
152
 
152
- /** True when the session has an active (non-done) goal. Used by the idle dispatcher. */
153
+ /** True when the enabled loop can own idle for this session. */
153
154
  async hasActiveGoal(sessionID: string): Promise<boolean> {
155
+ if (!this.options.enabled) return false
154
156
  return this.store.hasActive(sessionID)
155
157
  }
156
158
 
@@ -243,7 +245,7 @@ export class GoalLoop {
243
245
  return {
244
246
  pantheon_goal_create: {
245
247
  description:
246
- 'Create the single active goal for this session. The goal loop then continues the session automatically on idle until the goal is marked done.',
248
+ 'Deprecated legacy V1 tool. Create and store the single active goal for this session. Goals are stored but are not automatically continued in the current build. For durable manual goals, use the Persistence MCP `goal_*` tools available in this branch.',
247
249
  args: goalCreateArgs,
248
250
  execute: async (args, ctx) => {
249
251
  try {
@@ -270,7 +272,7 @@ export class GoalLoop {
270
272
  },
271
273
  pantheon_goal_update: {
272
274
  description:
273
- 'Update the active goal: set status (pending/in_progress/done) and/or rewrite the objective. Setting status to done stops all further continuations.',
275
+ 'Deprecated legacy V1 tool. Update the stored active goal: set status (pending/in_progress/done) and/or rewrite the objective. Goal records are not automatically continued in the current build. For durable manual goals, use the Persistence MCP `goal_*` tools available in this branch.',
274
276
  args: goalUpdateArgs,
275
277
  execute: async (args, ctx) => {
276
278
  try {
@@ -292,7 +294,8 @@ export class GoalLoop {
292
294
  },
293
295
  },
294
296
  pantheon_goal_get: {
295
- description: 'Return the active goal for this session (status, objective, continuations).',
297
+ description:
298
+ 'Deprecated legacy V1 tool. Return the stored active V1 goal (status, objective, continuation count). Goals are not automatically continued in the current build. For durable manual goals, use the Persistence MCP `goal_*` tools available in this branch.',
296
299
  args: goalGetArgs,
297
300
  execute: async (_args, ctx) => {
298
301
  try {
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Task Result Guard — detects empty task() results from native opencode
3
- * subagent calls and converts them to explicit errors.
2
+ * Task Result Guard — detects empty `task`/`subagent` tool results and converts
3
+ * them to explicit errors. Accepted labels do not prove live-host event mapping.
4
4
  *
5
5
  * Bug context (reproduced 2026-09-10): task() native creates a child session
6
6
  * that inherits the parent transcript. When the payload exceeds the provider's
@@ -11,9 +11,9 @@
11
11
  * task as `completed` with empty content. The parent LLM receives an empty
12
12
  * result and proceeds as if the task succeeded.
13
13
  *
14
- * The guard intercepts this in the `tool.execute.after` hook: when the tool
15
- * is `task` and the output is empty/whitespace-only, it replaces the output
16
- * with an explicit error message so the parent sees a failure, not silence.
14
+ * The guard intercepts empty results for either `task` or `subagent` tool
15
+ * labels in `tool.execute.after` and replaces them with an explicit error.
16
+ * This adapter compatibility does not establish which label a live host emits.
17
17
  *
18
18
  * Pure TypeScript — zero runtime dependencies. Meant to be wired into the
19
19
  * `combinedAfter` hook chain in plugin.ts alongside the sandbox and read
@@ -57,32 +57,68 @@ export interface TaskResultGuardOptions {
57
57
  // ─── Constants ─────────────────────────────────────────────────────────
58
58
 
59
59
  /**
60
- * The error message injected when a task() result is empty.
60
+ * The error message injected when a child-dispatch result is empty.
61
61
  * Keeps the historical "no assistant or tool output" contract text.
62
62
  */
63
63
  export const EMPTY_TASK_ERROR =
64
64
  'ERROR: task() returned empty output — child session produced no assistant or tool output. ' +
65
65
  'This typically means the provider rejected the request (admission control / rate limit) ' +
66
66
  'or the child session crashed before producing any response. ' +
67
- 'Consider splitting the work into a smaller task() or retrying the child session.'
67
+ 'Consider splitting the work into a smaller task. No retry is automatic; investigate before retrying manually.'
68
+
69
+ /**
70
+ * The placeholder text the HOST substitutes into a child-dispatch tool result
71
+ * when the child produced no assistant text.
72
+ *
73
+ * Field-measured on an OpenCode V2 host: the host binary contains the literal
74
+ * `Subagent completed without a text response.` and injects it into the tool
75
+ * result, so the parent sees a success-looking string instead of silence.
76
+ *
77
+ * This MUST be re-confirmed against each host build — if a host changes the
78
+ * wording, this branch silently stops firing again.
79
+ */
80
+ export const HOST_EMPTY_RESULT_TEXT = 'Subagent completed without a text response.'
81
+
82
+ /**
83
+ * Whether a tool label is a child dispatch the guard must inspect.
84
+ *
85
+ * The accepted labels are `task` and `subagent`. Exported so the V2 adapter's
86
+ * pre-guard early return uses the SAME set: a label the guard handles must
87
+ * never be dropped before the guard sees it.
88
+ *
89
+ * @param tool - the tool label reported by the host
90
+ * @returns `true` for `task` and `subagent`
91
+ */
92
+ export function isChildDispatchTool(tool: string): boolean {
93
+ return tool === 'task' || tool === 'subagent'
94
+ }
68
95
 
69
96
  // ─── Implementation ────────────────────────────────────────────────────
70
97
 
71
98
  /**
72
99
  * Whether a result carries any text content (whitespace-only counts as empty).
100
+ *
101
+ * The host placeholder ({@link HOST_EMPTY_RESULT_TEXT}) also counts as empty:
102
+ * it means "no child text", not "the child answered".
103
+ *
104
+ * The host placeholder is matched EXACTLY (after trimming). Substring or
105
+ * prefix matching would rewrite legitimate agent messages that merely quote
106
+ * the phrase, which is worse than the defect being fixed.
73
107
  */
74
108
  function isEmptyOutput(output: unknown): boolean {
75
109
  if (output == null) return true
76
110
  if (typeof output !== 'string') return true
77
- return output.trim() === ''
111
+ const trimmed = output.trim()
112
+ if (trimmed === '') return true
113
+ return trimmed === HOST_EMPTY_RESULT_TEXT
78
114
  }
79
115
 
80
116
  /**
81
117
  * Create a task result guard handler for the `tool.execute.after` hook.
82
118
  *
83
- * When the tool is `task` and the output is empty/whitespace-only, replaces
84
- * the output with an explicit error message. All other tools pass through
85
- * untouched.
119
+ * When the tool label is `task` or `subagent` and its output is
120
+ * empty/whitespace-only, replaces the output with an explicit error message.
121
+ * All other tools pass through untouched; no child is retried automatically.
86
122
  *
87
123
  * @returns A `ToolExecuteAfterHandler`-compatible async function.
88
124
  */
@@ -90,14 +126,14 @@ export function createTaskResultGuard(options?: TaskResultGuardOptions): TaskRes
90
126
  const warn = options?.logger?.warn ?? ((message: string) => log.warn(message))
91
127
 
92
128
  return async (input: TaskGuardInput, output: TaskGuardOutput): Promise<void> => {
93
- // Only intercept the `task` tool — all others pass through untouched.
94
- if (input.tool !== 'task') return
129
+ // Accept both labels without claiming which one a live host emits.
130
+ if (!isChildDispatchTool(input.tool)) return
95
131
 
96
132
  // Only flag truly empty results — non-empty content is the happy path.
97
133
  if (!isEmptyOutput(output.output)) return
98
134
 
99
135
  warn(
100
- `[task-result-guard] Empty task() result detected on session ${input.sessionID} ` +
136
+ `[task-result-guard] Empty ${input.tool} result detected on session ${input.sessionID} ` +
101
137
  `(callID=${input.callID}). Replacing with explicit error.`,
102
138
  )
103
139