pantheon-opencode 1.4.3 → 1.5.0-beta.2

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 (99) hide show
  1. package/.pantheon/code-mode/README.md +93 -0
  2. package/.pantheon/code-mode/checkpoint-session.py +7 -0
  3. package/.pantheon/code-mode/checkpoint-session.sh +11 -0
  4. package/.pantheon/code-mode/checkpoint_session.py +481 -0
  5. package/.pantheon/code-mode/compress-inline.py +450 -0
  6. package/.pantheon/code-mode/eval-llm-judge.py +255 -0
  7. package/.pantheon/code-mode/eval-monte-carlo.py +368 -0
  8. package/.pantheon/code-mode/eval-run.py +197 -0
  9. package/.pantheon/code-mode/eval-static.py +321 -0
  10. package/.pantheon/code-mode/example-sync.sh +5 -0
  11. package/.pantheon/code-mode/session-end-save.py +186 -0
  12. package/.pantheon/code-mode/session-end-save.sh +18 -0
  13. package/.pantheon/code-mode/test-allowed.sh +5 -0
  14. package/.pantheon/code-mode/test-auto-continue-checkpoint.sh +179 -0
  15. package/.pantheon/code-mode/test-env.sh +7 -0
  16. package/.pantheon/code-mode/test-prlimit.sh +9 -0
  17. package/.pantheon/code-mode/test-timeout.sh +6 -0
  18. package/README.md +161 -1101
  19. package/README.pt-BR.md +222 -0
  20. package/bin/pantheon-init.mjs +30 -11
  21. package/opencode.json +1 -0
  22. package/package.json +14 -3
  23. package/plugin.json +15 -0
  24. package/scripts/_pantheon_paths.py +48 -7
  25. package/scripts/ci-validate-yaml.py +7 -2
  26. package/scripts/code_mode_server.py +33 -2
  27. package/scripts/cost.mjs +30 -14
  28. package/scripts/doctor.mjs +135 -127
  29. package/scripts/generate-preset-docs.mjs +127 -66
  30. package/scripts/generate-prompts.sh +2 -2
  31. package/scripts/install/cli-ui.mjs +8 -1
  32. package/scripts/install/config-migration.mjs +401 -0
  33. package/scripts/install/health-check.mjs +3 -3
  34. package/scripts/install/model-picker.mjs +72 -23
  35. package/scripts/install/opencode-version.mjs +47 -0
  36. package/scripts/install/opencode.mjs +261 -88
  37. package/scripts/install/plugin.mjs +112 -42
  38. package/scripts/install/shared.mjs +13 -158
  39. package/scripts/install-mcp.mjs +44 -232
  40. package/scripts/mcp_persistence_server.py +382 -16
  41. package/scripts/mcp_resources_server.py +144 -40
  42. package/scripts/memory_mcp_server.py +2 -2
  43. package/scripts/probe-context-rehydrate.mjs +240 -0
  44. package/scripts/probe-pantheon-cost.mjs +304 -0
  45. package/scripts/recover-zenodo-deposition.mjs +146 -0
  46. package/scripts/sync-tui.mjs +32 -7
  47. package/scripts/test-opencode-v1-v2-sandbox.sh +944 -0
  48. package/scripts/uninstall.mjs +298 -954
  49. package/scripts/validate-zenodo-release.mjs +154 -0
  50. package/scripts/zenodo-artifact.mjs +21 -0
  51. package/scripts/zenodo-release-state.mjs +53 -0
  52. package/src/agents/zeus.md +25 -14
  53. package/src/mcp/_pantheon_paths.py +48 -7
  54. package/src/mcp/code_mode_server.py +33 -2
  55. package/src/mcp/eval_store.py +1 -1
  56. package/src/mcp/mcp_persistence_server.py +382 -16
  57. package/src/mcp/mcp_resources_server.py +144 -40
  58. package/src/mcp/pantheon_vision_server.py +1 -1
  59. package/src/mcp/toon_codec.py +491 -0
  60. package/src/pantheon/background-job-board.ts +67 -1
  61. package/src/pantheon/cost-command.ts +60 -39
  62. package/src/pantheon/delegate-manager.ts +669 -0
  63. package/src/pantheon/delegation-classifier.ts +307 -0
  64. package/src/pantheon/delegation-enforce.ts +13 -12
  65. package/src/pantheon/delegation-finalize.ts +374 -0
  66. package/src/pantheon/delegation-notify.ts +212 -0
  67. package/src/pantheon/delegation-toast.ts +73 -0
  68. package/src/pantheon/delegation.ts +1120 -0
  69. package/src/pantheon/goal-loop.ts +2 -2
  70. package/src/pantheon/goal-store.ts +1 -1
  71. package/src/pantheon/hashline/tool.ts +2 -2
  72. package/src/pantheon/model-command.ts +2 -1
  73. package/src/pantheon/permission-eval.ts +284 -0
  74. package/src/pantheon/step-cap.ts +110 -0
  75. package/src/pantheon/token-opt.ts +781 -0
  76. package/src/pantheon/toon-codec.ts +481 -0
  77. package/src/pantheon/tui-version-check.ts +1 -3
  78. package/src/pantheon/v2-bridge.ts +129 -0
  79. package/src/pantheon/v2-events.ts +131 -0
  80. package/src/pantheon/v2-hooks.ts +287 -0
  81. package/src/pantheon/v2-tool-definitions.ts +331 -0
  82. package/src/pantheon/zeus-delegate-with-retry.ts +406 -0
  83. package/src/plugin-v2/index.ts +21 -0
  84. package/src/plugin-v2.ts +824 -0
  85. package/src/plugin.ts +236 -42
  86. package/src/plugins/tui/dist/server.d.ts +1 -1
  87. package/src/plugins/tui/dist/server.d.ts.map +1 -1
  88. package/src/plugins/tui/dist/server.js +1 -1
  89. package/src/plugins/tui/dist/server.js.map +1 -1
  90. package/src/plugins/tui/dist/tui.d.ts +10 -7
  91. package/src/plugins/tui/dist/tui.d.ts.map +1 -1
  92. package/src/plugins/tui/dist/tui.js +11 -8
  93. package/src/plugins/tui/dist/tui.js.map +1 -1
  94. package/src/plugins/tui/dist/tui.tsx +22 -16
  95. package/src/plugins/tui/package-lock.json +51 -51
  96. package/src/plugins/tui/package.json +7 -7
  97. package/src/plugins/tui/src/index.tsx +28 -24
  98. package/src/skills/README.md +0 -2
  99. package/src/pantheon/tool-context.ts +0 -41
@@ -17,7 +17,7 @@ from pathlib import Path
17
17
  from typing import Any
18
18
 
19
19
  import yaml
20
- from _pantheon_paths import pantheon_home, pantheon_project
20
+ from _pantheon_paths import has_symlink_component, pantheon_home, pantheon_project
21
21
  from eval_store import get_latest_eval, list_evals
22
22
  from mcp.server.fastmcp import FastMCP
23
23
 
@@ -25,6 +25,88 @@ from mcp.server.fastmcp import FastMCP
25
25
  _PANTHEON_HOME: Path = pantheon_home()
26
26
  _PANTHEON_PROJECT: Path | None = pantheon_project()
27
27
 
28
+
29
+ def _within(path: Path, parent: Path) -> bool:
30
+ """Return whether ``path`` is contained by ``parent`` after resolution."""
31
+ try:
32
+ path.relative_to(parent)
33
+ except ValueError:
34
+ return False
35
+ return True
36
+
37
+
38
+ def _safe_root(root: Path, parent: Path) -> Path | None:
39
+ """Return a physical resource root only when its layout is trusted.
40
+
41
+ Local ``.opencode`` and ``.pantheon`` directories are trust boundaries:
42
+ accepting either as a symlink would make all resources below it
43
+ untrusted, even when the link happens to point inside the project.
44
+ """
45
+ if parent.is_symlink() or has_symlink_component(parent):
46
+ return None
47
+ # Keep the project root lexical until this trust-boundary check. This
48
+ # rejects PANTHEON_PROJECT/cwd symlinks instead of resolving them away.
49
+ if parent.name in {".opencode", ".pantheon"} and parent.parent.is_symlink():
50
+ return None
51
+ if root.is_symlink():
52
+ return None
53
+ if not root.exists() or not root.is_dir():
54
+ return None
55
+ parent_resolved = parent.resolve()
56
+ resolved = root.resolve()
57
+ if parent.name in {".opencode", ".pantheon"} and not _within(
58
+ parent_resolved, parent.parent.resolve()
59
+ ):
60
+ return None
61
+ return resolved if _within(resolved, parent_resolved) else None
62
+
63
+
64
+ def _resource_root(name: str) -> Path | None:
65
+ """Choose a project-local root before the global installation root.
66
+
67
+ A present but unsafe project root is ignored rather than followed; this
68
+ preserves the global fallback while preventing symlink escapes.
69
+ """
70
+ candidates: list[tuple[Path, Path]] = []
71
+ if _PANTHEON_PROJECT is not None:
72
+ if name in {"agents", "skills"}:
73
+ local = _PANTHEON_PROJECT / ".opencode"
74
+ candidates.append((local / name, local))
75
+ elif name in {"deepwork", "memory-bank"}:
76
+ local = _PANTHEON_PROJECT / ".pantheon"
77
+ candidates.append((local / name, local))
78
+ candidates.append((_PANTHEON_HOME / name, _PANTHEON_HOME))
79
+ for root, parent in candidates:
80
+ safe = _safe_root(root, parent)
81
+ if safe is not None:
82
+ return safe
83
+ return None
84
+
85
+
86
+ def _resource_roots(name: str) -> list[Path]:
87
+ """Return safe resource roots in local-first precedence order."""
88
+ roots: list[Path] = []
89
+ if _PANTHEON_PROJECT is not None:
90
+ base_name = ".opencode" if name in {"agents", "skills"} else ".pantheon"
91
+ base = _PANTHEON_PROJECT / base_name
92
+ local = _safe_root(base / name, base)
93
+ if local is not None:
94
+ roots.append(local)
95
+ global_root = _safe_root(_PANTHEON_HOME / name, _PANTHEON_HOME)
96
+ if global_root is not None:
97
+ roots.append(global_root)
98
+ return roots
99
+
100
+
101
+ def _safe_child(root: Path, relative: str) -> Path | None:
102
+ """Resolve a child while rejecting every lexical symlink component."""
103
+ candidate = root / relative
104
+ if has_symlink_component(candidate):
105
+ return None
106
+ resolved = candidate.resolve()
107
+ return resolved if _within(resolved, root.resolve()) else None
108
+
109
+
28
110
  # ── FastMCP App ───────────────────────────────────────────────────────────────
29
111
  mcp = FastMCP(
30
112
  "Pantheon Resources",
@@ -67,17 +149,27 @@ def _get_role_from_frontmatter(frontmatter: dict[str, Any]) -> str:
67
149
  )
68
150
  async def list_agents() -> str:
69
151
  """Return a markdown list of all agents with their roles."""
70
- agents_dir = _PANTHEON_HOME / "agents"
71
- if not agents_dir.is_dir():
152
+ agents_dirs = _resource_roots("agents")
153
+ if not agents_dirs:
72
154
  return "Agents directory not found."
73
155
 
74
156
  agents: list[str] = []
75
- for f in sorted(agents_dir.iterdir()):
76
- if f.suffix == ".md" and f.stem.lower() != "readme":
77
- frontmatter = _parse_yaml_frontmatter(f)
78
- name = frontmatter.get("name", f.stem)
79
- role = _get_role_from_frontmatter(frontmatter)
80
- agents.append(f"- **{name}** — {role}")
157
+ seen: set[str] = set()
158
+ for agents_dir in agents_dirs:
159
+ for entry in sorted(agents_dir.iterdir()):
160
+ f = _safe_child(agents_dir, entry.name)
161
+ if (
162
+ f is not None
163
+ and f.is_file()
164
+ and f.suffix == ".md"
165
+ and f.stem.lower() != "readme"
166
+ and f.name not in seen
167
+ ):
168
+ seen.add(f.name)
169
+ frontmatter = _parse_yaml_frontmatter(f)
170
+ name = frontmatter.get("name", f.stem)
171
+ role = _get_role_from_frontmatter(frontmatter)
172
+ agents.append(f"- **{name}** — {role}")
81
173
 
82
174
  return "\n".join(agents) if agents else "No agents found."
83
175
 
@@ -88,19 +180,23 @@ async def list_agents() -> str:
88
180
  )
89
181
  async def list_skills() -> str:
90
182
  """Return a markdown list of all skills with descriptions."""
91
- skills_dir = _PANTHEON_HOME / "skills"
92
- if not skills_dir.is_dir():
183
+ skills_dirs = _resource_roots("skills")
184
+ if not skills_dirs:
93
185
  return "Skills directory not found."
94
186
 
95
187
  skills: list[str] = []
96
- for f in sorted(skills_dir.iterdir()):
97
- if f.is_dir():
98
- skill_file = f / "SKILL.md"
99
- if skill_file.exists():
100
- frontmatter = _parse_yaml_frontmatter(skill_file)
101
- name = frontmatter.get("name", f.name)
102
- desc = frontmatter.get("description", "No description")
103
- skills.append(f"- **{name}** — {desc}")
188
+ seen: set[str] = set()
189
+ for skills_dir in skills_dirs:
190
+ for entry in sorted(skills_dir.iterdir()):
191
+ f = _safe_child(skills_dir, entry.name)
192
+ if f is not None and f.is_dir() and f.name not in seen:
193
+ skill_file = _safe_child(f, "SKILL.md")
194
+ if skill_file is not None and skill_file.is_file():
195
+ seen.add(f.name)
196
+ frontmatter = _parse_yaml_frontmatter(skill_file)
197
+ name = frontmatter.get("name", f.name)
198
+ desc = frontmatter.get("description", "No description")
199
+ skills.append(f"- **{name}** — {desc}")
104
200
 
105
201
  return "\n".join(skills) if skills else "No skills found."
106
202
 
@@ -111,10 +207,10 @@ async def list_skills() -> str:
111
207
  )
112
208
  async def get_routing() -> str:
113
209
  """Return the full content of routing.yml."""
114
- routing_file = _PANTHEON_HOME / "routing.yml"
115
- if not routing_file.exists() and _PANTHEON_PROJECT:
116
- routing_file = _PANTHEON_PROJECT / "src" / "routing.yml"
117
- if not routing_file.exists():
210
+ routing_file = _safe_child(_PANTHEON_HOME, "routing.yml")
211
+ if routing_file is None and _PANTHEON_PROJECT:
212
+ routing_file = _safe_child(_PANTHEON_PROJECT / "src", "routing.yml")
213
+ if routing_file is None or not routing_file.exists():
118
214
  return "routing.yml not found."
119
215
  return routing_file.read_text(encoding="utf-8")
120
216
 
@@ -128,11 +224,17 @@ async def get_routing() -> str:
128
224
  )
129
225
  async def get_agent(agent_name: str) -> str:
130
226
  """Return the full content of an agent file, case-insensitively."""
131
- agents_dir = _PANTHEON_HOME / "agents"
132
227
  name_lower = agent_name.lower()
133
- for f in agents_dir.iterdir():
134
- if f.suffix == ".md" and f.stem.lower() == name_lower:
135
- return f.read_text(encoding="utf-8")
228
+ for agents_dir in _resource_roots("agents"):
229
+ for entry in agents_dir.iterdir():
230
+ f = _safe_child(agents_dir, entry.name)
231
+ if (
232
+ f is not None
233
+ and f.is_file()
234
+ and f.suffix == ".md"
235
+ and f.stem.lower() == name_lower
236
+ ):
237
+ return f.read_text(encoding="utf-8")
136
238
  return f"Agent '{agent_name}' not found."
137
239
 
138
240
 
@@ -142,10 +244,11 @@ async def get_agent(agent_name: str) -> str:
142
244
  )
143
245
  async def get_deepwork_plan(slug: str) -> str:
144
246
  """Return PLAN.md content for a deepwork slug."""
145
- if _PANTHEON_PROJECT is None:
247
+ deepwork_dir = _resource_root("deepwork")
248
+ if deepwork_dir is None:
146
249
  return f"Deepwork '{slug}' not found. (PANTHEON_PROJECT not set)"
147
- plan_file = _PANTHEON_PROJECT / ".pantheon" / "deepwork" / slug / "PLAN.md"
148
- if not plan_file.exists():
250
+ plan_file = _safe_child(deepwork_dir, f"{slug}/PLAN.md")
251
+ if plan_file is None or not plan_file.is_file():
149
252
  return f"Deepwork '{slug}' not found."
150
253
  return plan_file.read_text(encoding="utf-8")
151
254
 
@@ -157,10 +260,11 @@ async def get_deepwork_plan(slug: str) -> str:
157
260
  )
158
261
  async def get_deepwork_status(slug: str) -> str:
159
262
  """Return STATUS.md content for a deepwork slug, or a default message."""
160
- if _PANTHEON_PROJECT is None:
263
+ deepwork_dir = _resource_root("deepwork")
264
+ if deepwork_dir is None:
161
265
  return "STATUS.md not found. (PANTHEON_PROJECT not set)"
162
- status_file = _PANTHEON_PROJECT / ".pantheon" / "deepwork" / slug / "STATUS.md"
163
- if not status_file.exists():
266
+ status_file = _safe_child(deepwork_dir, f"{slug}/STATUS.md")
267
+ if status_file is None or not status_file.is_file():
164
268
  return "STATUS.md not found. Current state: IN PROGRESS"
165
269
  return status_file.read_text(encoding="utf-8")
166
270
 
@@ -171,8 +275,9 @@ async def get_deepwork_status(slug: str) -> str:
171
275
  )
172
276
  async def get_skill(name: str) -> str:
173
277
  """Return SKILL.md content for a skill directory."""
174
- skill_file = _PANTHEON_HOME / "skills" / name / "SKILL.md"
175
- if not skill_file.exists():
278
+ skills_dir = _resource_root("skills")
279
+ skill_file = _safe_child(skills_dir, f"{name}/SKILL.md") if skills_dir else None
280
+ if skill_file is None or not skill_file.is_file():
176
281
  return f"Skill '{name}' not found."
177
282
  return skill_file.read_text(encoding="utf-8")
178
283
 
@@ -188,12 +293,11 @@ async def get_memory_bank(path: str) -> str:
188
293
  Security: resolves absolute path and verifies it stays within
189
294
  .pantheon/memory-bank/ to prevent directory traversal attacks.
190
295
  """
191
- if _PANTHEON_PROJECT is None:
296
+ memory_dir = _resource_root("memory-bank")
297
+ if memory_dir is None:
192
298
  return "Memory bank not available. (PANTHEON_PROJECT not set)"
193
- resolved = (_PANTHEON_PROJECT / ".pantheon" / "memory-bank" / path).resolve()
194
- mb_dir = (_PANTHEON_PROJECT / ".pantheon" / "memory-bank").resolve()
195
-
196
- if not str(resolved).startswith(str(mb_dir)):
299
+ resolved = _safe_child(memory_dir, path)
300
+ if resolved is None:
197
301
  return "Path traversal blocked: access denied."
198
302
 
199
303
  if not resolved.exists() or not resolved.is_file():
@@ -25,7 +25,7 @@ import json
25
25
  import os
26
26
  import sqlite3
27
27
  import time
28
- from datetime import datetime, timezone
28
+ from datetime import UTC, datetime
29
29
  from pathlib import Path
30
30
  from typing import Any
31
31
 
@@ -198,7 +198,7 @@ def _parse_iso_ts(value: str) -> float:
198
198
  """
199
199
  dt = datetime.fromisoformat(value.replace("Z", "+00:00"))
200
200
  if dt.tzinfo is None:
201
- dt = dt.replace(tzinfo=timezone.utc)
201
+ dt = dt.replace(tzinfo=UTC)
202
202
  return dt.timestamp()
203
203
 
204
204
 
@@ -0,0 +1,240 @@
1
+ #!/usr/bin/env node
2
+ import { spawnSync } from 'node:child_process'
3
+ /**
4
+ * Offline/ambiental probe for context_rehydrate and context_session_summary.
5
+ *
6
+ * The Python child imports the installed persistence server and exercises the
7
+ * real FastMCP tools against a temporary SQLite database. No OpenCode command,
8
+ * network call, LLM, or user database is involved. Missing package/runtime is
9
+ * NOT_TESTED/AMBIENTAL rather than a false PASS.
10
+ */
11
+ import { existsSync, mkdtempSync, rmSync } from 'node:fs'
12
+ import { tmpdir } from 'node:os'
13
+ import { join } from 'node:path'
14
+ import { fileURLToPath } from 'node:url'
15
+
16
+ const requestedVersion = valueFor('--version')
17
+ const jsonOutput = process.argv.includes('--json')
18
+ const runtime = fileURLToPath(new URL('./mcp_persistence_server.py', import.meta.url))
19
+
20
+ function valueFor(name) {
21
+ const index = process.argv.indexOf(name)
22
+ return index >= 0 ? process.argv[index + 1] : undefined
23
+ }
24
+
25
+ function emit(status, detail, checks = []) {
26
+ const result = { status, version: requestedVersion, detail, checks }
27
+ if (jsonOutput) process.stdout.write(JSON.stringify(result))
28
+ else process.stdout.write(`${status}: ${detail}\n`)
29
+ if (status === 'FAIL') process.exitCode = 1
30
+ }
31
+
32
+ function unavailable(detail) {
33
+ emit('NOT_TESTED', detail)
34
+ }
35
+
36
+ function pythonCandidates() {
37
+ const venvPython = process.env.HOME
38
+ ? join(process.env.HOME, '.config', 'opencode', '.venv', 'bin', 'python')
39
+ : undefined
40
+ return [process.env.PANTHEON_PYTHON, venvPython, 'python3'].filter(Boolean)
41
+ }
42
+
43
+ const PYTHON_HARNESS = `
44
+ import asyncio
45
+ import importlib.util
46
+ import json
47
+ import os
48
+ import sys
49
+ from pathlib import Path
50
+
51
+ runtime_path = Path(sys.argv[1]).resolve()
52
+ db_root = Path(sys.argv[2]).resolve()
53
+ sys.path.insert(0, str(runtime_path.parent))
54
+ sys.argv = [str(runtime_path), "--global-db", str(db_root / "global.db"),
55
+ "--project-db", str(db_root / "project.db")]
56
+
57
+ spec = importlib.util.spec_from_file_location("probe_mcp_persistence", runtime_path)
58
+ if spec is None or spec.loader is None:
59
+ raise RuntimeError("could not load persistence runtime")
60
+ module = importlib.util.module_from_spec(spec)
61
+ spec.loader.exec_module(module)
62
+
63
+
64
+ async def call(name, arguments):
65
+ result = await module.mcp.call_tool(name, arguments)
66
+ if isinstance(result, tuple):
67
+ structured = result[1]
68
+ if structured is not None:
69
+ if isinstance(structured, dict) and "result" in structured:
70
+ return structured["result"]
71
+ return structured
72
+ result = result[0]
73
+ if isinstance(result, dict):
74
+ return result
75
+ if not result:
76
+ return None
77
+ text = getattr(result[0], "text", str(result[0]))
78
+ try:
79
+ return json.loads(text)
80
+ except (TypeError, ValueError, json.JSONDecodeError):
81
+ return text
82
+
83
+
84
+ async def main():
85
+ checks = []
86
+ slug = "context-rehydrate-probe"
87
+ session_id = "synthetic-session"
88
+ checkpoint = {
89
+ "version": 1,
90
+ "goal": {"id": "probe-goal", "objective": "verify context recovery",
91
+ "status": "in_progress"},
92
+ "phase": {"current": 2, "total": 3, "name": "offline validation"},
93
+ "delegations": {"in_flight": [{"alias": "apo-probe", "agent": "apollo",
94
+ "task_id": "probe-task"}]},
95
+ }
96
+ tail = ["phase 1 complete", "phase 2 payload validated"]
97
+
98
+ # context_save creates the real session-qualified latest pointer. Keeping
99
+ # tail under its own key also tests the runtime's latest/tail fallback.
100
+ await call("context_save", {"slug": slug, "key": "tail",
101
+ "content": json.dumps(tail),
102
+ "session_id": session_id})
103
+ await call("context_save", {"slug": slug, "key": "phase:2",
104
+ "content": json.dumps(checkpoint),
105
+ "session_id": session_id})
106
+ latest = await call("context_get", {"slug": slug, "key": "latest",
107
+ "session_id": session_id})
108
+ stored_tail = await call("context_get", {"slug": slug, "key": "tail",
109
+ "session_id": session_id})
110
+ if latest is None or stored_tail is None:
111
+ raise AssertionError("synthetic latest/tail checkpoint payload is null")
112
+ checks.append("synthetic latest/tail/goal/phase/delegation checkpoint: PASS")
113
+
114
+ os.environ.pop("PANTHEON_COMPACTION", None)
115
+ os.environ.pop("PANTHEON_SESSION_END_SUMMARY", None)
116
+ blocks = await call("context_rehydrate", {"slug": slug})
117
+ summary = await call("context_session_summary", {"slug": slug})
118
+ if not isinstance(blocks, list) or not blocks:
119
+ raise AssertionError("context_rehydrate returned a null/empty payload")
120
+ if not isinstance(summary, str) or not summary:
121
+ raise AssertionError("context_session_summary returned a null/empty payload")
122
+ for fragment in ("verify context recovery", "phase 2/3", "apo-probe",
123
+ "phase 2 payload validated"):
124
+ if not any(fragment in block for block in blocks) and fragment not in summary:
125
+ raise AssertionError(f"payload is missing {fragment!r}")
126
+ checks.append("context_rehydrate non-null payload: PASS")
127
+ checks.append("context_session_summary non-null payload: PASS")
128
+
129
+ missing_blocks = await call("context_rehydrate", {"slug": "probe-absent"})
130
+ missing_summary = await call("context_session_summary", {"slug": "probe-absent"})
131
+ if missing_blocks is not None or missing_summary is not None:
132
+ raise AssertionError("absent checkpoint must return null payloads")
133
+ checks.append("absence returns null: PASS")
134
+
135
+ expired_slug = "context-expired-probe"
136
+ await call("context_save", {"slug": expired_slug, "key": "phase:1",
137
+ "content": json.dumps(checkpoint), "ttl": -1,
138
+ "session_id": session_id})
139
+ expired_blocks = await call("context_rehydrate", {"slug": expired_slug})
140
+ expired_summary = await call("context_session_summary", {"slug": expired_slug})
141
+ if expired_blocks is not None or expired_summary is not None:
142
+ raise AssertionError("expired checkpoint must return null payloads")
143
+ checks.append("expiration returns null: PASS")
144
+
145
+ invalid_slug = "context-invalid-probe"
146
+ await call("context_save", {"slug": invalid_slug, "key": "phase:1",
147
+ "content": "not-json", "session_id": session_id})
148
+ invalid_blocks = await call("context_rehydrate", {"slug": invalid_slug})
149
+ invalid_summary = await call("context_session_summary", {"slug": invalid_slug})
150
+ if invalid_blocks is not None or invalid_summary is not None:
151
+ raise AssertionError("invalid checkpoint must return null payloads")
152
+ checks.append("invalid payload returns null: PASS")
153
+
154
+ os.environ["PANTHEON_COMPACTION"] = "off"
155
+ switched_blocks = await call("context_rehydrate", {"slug": slug})
156
+ if switched_blocks is not None:
157
+ raise AssertionError("PANTHEON_COMPACTION=off must return null")
158
+ os.environ.pop("PANTHEON_COMPACTION", None)
159
+ os.environ["PANTHEON_SESSION_END_SUMMARY"] = "off"
160
+ switched_summary = await call("context_session_summary", {"slug": slug})
161
+ if switched_summary is not None:
162
+ raise AssertionError("PANTHEON_SESSION_END_SUMMARY=off must return null")
163
+ checks.append("kill-switches return null: PASS")
164
+ print(json.dumps({"checks": checks}))
165
+
166
+
167
+ asyncio.run(main())
168
+ `
169
+
170
+ async function main() {
171
+ if (requestedVersion !== 'v1' && requestedVersion !== 'v2') {
172
+ emit('FAIL', 'usage: --version v1|v2 [--json]')
173
+ return
174
+ }
175
+ if (!existsSync(runtime)) {
176
+ unavailable('installed package does not include mcp_persistence_server.py')
177
+ return
178
+ }
179
+
180
+ const root = mkdtempSync(join(tmpdir(), 'pantheon-context-probe-'))
181
+ const dbRoot = join(root, 'db')
182
+ const python = pythonCandidates().find((candidate) =>
183
+ candidate.includes('/') ? existsSync(candidate) : true,
184
+ )
185
+ if (!python) {
186
+ rmSync(root, { recursive: true, force: true })
187
+ unavailable('Python persistence runtime is not available')
188
+ return
189
+ }
190
+
191
+ try {
192
+ const child = spawnSync(python, ['-c', PYTHON_HARNESS, runtime, dbRoot], {
193
+ encoding: 'utf8',
194
+ timeout: 30000,
195
+ env: process.env,
196
+ })
197
+ if (child.error) {
198
+ const detail = child.error instanceof Error ? child.error.message : String(child.error)
199
+ if (/EACCES|permission denied|not found/i.test(detail)) {
200
+ emit('AMBIENTAL', `persistence runtime unavailable: ${detail}`)
201
+ } else {
202
+ unavailable(`persistence runtime unavailable: ${detail}`)
203
+ }
204
+ return
205
+ }
206
+ if (child.signal === 'SIGTERM') {
207
+ emit('AMBIENTAL', 'persistence probe timed out after 30s')
208
+ return
209
+ }
210
+ if (child.status !== 0) {
211
+ const detail = `${child.stderr || child.stdout || 'persistence probe failed'}`.trim()
212
+ if (
213
+ /No module named|ModuleNotFoundError|can't open file|No such file|importerror/i.test(detail)
214
+ ) {
215
+ unavailable(`persistence runtime unavailable: ${detail.slice(0, 320)}`)
216
+ } else {
217
+ emit('FAIL', `offline persistence checks failed: ${detail.slice(0, 320)}`)
218
+ }
219
+ return
220
+ }
221
+
222
+ const lines = child.stdout.trim().split('\n').filter(Boolean)
223
+ const payload = JSON.parse(lines.at(-1) || '')
224
+ if (!Array.isArray(payload.checks) || payload.checks.length < 6) {
225
+ emit('FAIL', 'offline persistence probe returned incomplete checks')
226
+ return
227
+ }
228
+ emit(
229
+ 'PASS',
230
+ 'offline synthetic persistence checks passed; no LLM or user DB was used',
231
+ payload.checks,
232
+ )
233
+ } catch (error) {
234
+ emit('FAIL', error instanceof Error ? error.message : String(error))
235
+ } finally {
236
+ rmSync(root, { recursive: true, force: true })
237
+ }
238
+ }
239
+
240
+ await main()