pantheon-opencode 1.6.0-beta.9 → 1.6.1

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 (140) hide show
  1. package/AGENTS.global.md +118 -0
  2. package/AGENTS.md +18 -168
  3. package/CHANGELOG.md +144 -365
  4. package/README.md +124 -607
  5. package/README.pt-BR.md +120 -345
  6. package/bin/pantheon-init.mjs +504 -141
  7. package/commands/pantheon-deepwork.md +14 -3
  8. package/commands/pantheon-vision.md +61 -12
  9. package/package.json +22 -13
  10. package/plugin.json +1 -1
  11. package/pyproject.toml +6 -2
  12. package/scripts/_pantheon_paths.py +24 -0
  13. package/scripts/build-agents-md.mjs +368 -69
  14. package/scripts/changelog-merge.mjs +161 -0
  15. package/scripts/check-plugin-v2-coverage.mjs +11 -8
  16. package/scripts/docs-check-changelog.mjs +204 -0
  17. package/scripts/docs-link-check.mjs +314 -0
  18. package/scripts/docs-media.mjs +157 -0
  19. package/scripts/doctor.mjs +850 -45
  20. package/scripts/install/agents-md.mjs +2 -2
  21. package/scripts/install/backup.mjs +648 -0
  22. package/scripts/install/cli-ui.mjs +303 -72
  23. package/scripts/install/component-selection.mjs +61 -0
  24. package/scripts/install/config-migration.mjs +583 -27
  25. package/scripts/install/exit-codes.mjs +26 -0
  26. package/scripts/install/file-inventory.mjs +555 -0
  27. package/scripts/install/health-check.mjs +31 -25
  28. package/scripts/install/interactive.mjs +99 -383
  29. package/scripts/install/interrupt.mjs +78 -0
  30. package/scripts/install/migrate.mjs +49 -25
  31. package/scripts/install/model-picker.mjs +218 -250
  32. package/scripts/install/opencode-state.mjs +91 -0
  33. package/scripts/install/opencode-version.mjs +83 -21
  34. package/scripts/install/opencode.mjs +1675 -187
  35. package/scripts/install/plan-artifact.mjs +517 -0
  36. package/scripts/install/plan.mjs +475 -0
  37. package/scripts/install/plugin.mjs +214 -27
  38. package/scripts/install/prompt-result.mjs +2 -0
  39. package/scripts/install/run-record.mjs +115 -0
  40. package/scripts/install/shared.mjs +256 -99
  41. package/scripts/install/state.mjs +63 -8
  42. package/scripts/install/strings.mjs +93 -8
  43. package/scripts/install/v2-capabilities.mjs +205 -0
  44. package/scripts/install/venv.mjs +90 -47
  45. package/scripts/install/verify.mjs +128 -0
  46. package/scripts/install/vision-prompt.mjs +173 -0
  47. package/scripts/install-mcp.mjs +2 -2
  48. package/scripts/manifest-inventory.mjs +49 -3
  49. package/scripts/mcp_persistence.py +1535 -1050
  50. package/scripts/memory_mcp.py +12 -843
  51. package/scripts/node-engine-policy.mjs +85 -0
  52. package/scripts/package-evidence.mjs +10 -2
  53. package/scripts/postinstall.mjs +26 -26
  54. package/scripts/probe-pantheon-cost.mjs +118 -19
  55. package/scripts/prune.mjs +9 -3
  56. package/scripts/reconcile.mjs +325 -0
  57. package/scripts/release-gates.mjs +687 -0
  58. package/scripts/restore.mjs +222 -0
  59. package/scripts/run-node-tests.mjs +24 -8
  60. package/scripts/sync-artifacts.mjs +19 -7
  61. package/scripts/sync-tui.mjs +5 -1
  62. package/scripts/test-opencode-v2-sandbox.sh +36 -123
  63. package/scripts/uninstall.mjs +369 -34
  64. package/scripts/update.mjs +164 -0
  65. package/scripts/validate-node-engine-policy.mjs +13 -0
  66. package/scripts/version-check.mjs +34 -1
  67. package/scripts/versioning.mjs +23 -3
  68. package/scripts/vision-status.mjs +682 -0
  69. package/skills-lock.json +8 -8
  70. package/src/agents/aphrodite.md +13 -10
  71. package/src/agents/apollo.md +4 -5
  72. package/src/agents/athena.md +74 -46
  73. package/src/agents/demeter.md +10 -7
  74. package/src/agents/gaia.md +0 -1
  75. package/src/agents/hephaestus.md +4 -3
  76. package/src/agents/hermes.md +10 -9
  77. package/src/agents/iris.md +6 -1
  78. package/src/agents/mnemosyne.md +10 -4
  79. package/src/agents/nyx.md +4 -4
  80. package/src/agents/prometheus.md +12 -11
  81. package/src/agents/talos.md +6 -0
  82. package/src/agents/zeus.md +84 -56
  83. package/src/instructions/agent-return-format.instructions.md +12 -41
  84. package/src/instructions/memory-protocol.instructions.md +5 -11
  85. package/src/instructions/test-economy.instructions.md +12 -0
  86. package/src/instructions/yagni.instructions.md +6 -15
  87. package/src/instructions/zeus-anti-stall.instructions.md +6 -6
  88. package/src/instructions/zeus-communication-rules.instructions.md +6 -6
  89. package/src/instructions/zeus-council-synthesis.instructions.md +11 -12
  90. package/src/instructions/zeus-memory-operations.instructions.md +13 -7
  91. package/src/instructions/zeus-timeout-retry.instructions.md +36 -10
  92. package/src/mcp/_pantheon_paths.py +24 -0
  93. package/src/mcp/mcp_codemap_module.py +86 -18
  94. package/src/mcp/mcp_persistence.py +1535 -1050
  95. package/src/mcp/memory_mcp.py +444 -94
  96. package/src/mcp/pantheon_vision.py +285 -41
  97. package/src/mcp/requirements-mcp.txt +6 -1
  98. package/src/mcp/requirements-vision.txt +1 -1
  99. package/src/pantheon/context-pruner.ts +541 -0
  100. package/src/pantheon/cost-command.ts +901 -60
  101. package/src/pantheon/delegation-enforce.ts +160 -23
  102. package/src/pantheon/goal-loop.ts +11 -8
  103. package/src/pantheon/guard-path.ts +162 -0
  104. package/src/pantheon/memory-context.ts +1017 -0
  105. package/src/pantheon/model-agents.ts +19 -0
  106. package/src/pantheon/model-command.ts +218 -56
  107. package/src/pantheon/model-pricing.ts +536 -0
  108. package/src/pantheon/presets.mjs +2 -0
  109. package/src/pantheon/task-result-guard.ts +50 -14
  110. package/src/pantheon/v2-bounded-read.ts +654 -0
  111. package/src/pantheon/v2-bridge.ts +27 -0
  112. package/src/pantheon/v2-delegation-enforce.ts +133 -6
  113. package/src/pantheon/v2-execute-after.ts +135 -24
  114. package/src/pantheon/v2-model-overrides.ts +275 -0
  115. package/src/pantheon/v2-shell-hooks.ts +260 -0
  116. package/src/pantheon/v2-tools.ts +89 -35
  117. package/src/pantheon/v2-unsupported.mjs +34 -7
  118. package/src/pantheon/v2-vision.ts +622 -0
  119. package/src/pantheon/vision-local.ts +531 -0
  120. package/src/pantheon/vision.ts +1166 -116
  121. package/src/plugin-v2.ts +1039 -171
  122. package/src/plugin.ts +37 -13
  123. package/src/plugins/tui/dist/tui-v2.d.ts +1029 -2
  124. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  125. package/src/plugins/tui/dist/tui-v2.js +3742 -85
  126. package/src/plugins/tui/dist/tui.js +1 -1
  127. package/src/plugins/tui/package-lock.json +15 -15
  128. package/src/plugins/tui/package.json +7 -5
  129. package/src/plugins/tui/src/index-v2.tsx +4314 -50
  130. package/src/plugins/tui/tsconfig.typecheck.json +5 -0
  131. package/src/routing.yml +50 -5
  132. package/src/skills/agent-coordination/SKILL.md +7 -2
  133. package/src/skills/artifact-management/SKILL.md +5 -1
  134. package/src/skills/auto-continue/SKILL.md +14 -6
  135. package/src/skills/codemap/SKILL.md +1 -1
  136. package/src/skills/memory-bank/SKILL.md +21 -13
  137. package/src/skills/session-goal/SKILL.md +12 -22
  138. package/src/skills/spec-driven-development/SKILL.md +3 -1
  139. package/src/skills/worktrees/SKILL.md +30 -11
  140. package/scripts/probe-context-rehydrate.mjs +0 -263
@@ -1,16 +1,18 @@
1
1
  #!/usr/bin/env python3
2
2
  """Pantheon Persistence MCP Server.
3
3
 
4
- Key-Value store with FTS5 full-text search, TTL-based expiration,
5
- and namespace isolation. Uses SQLite with zero external dependencies.
4
+ Operational-state checkpoints and manual session-scoped goal tools. The server
5
+ exposes context_save/context_get for checkpoints and four manual goal tools.
6
+ Goal tools use OpenCode session metadata and do not trigger automatic continuation.
6
7
 
7
8
  Usage:
8
- python scripts/mcp_persistence.py
9
+ <venv>/bin/python3 scripts/mcp_persistence.py
9
10
  """
10
11
 
11
12
  from __future__ import annotations
12
13
 
13
14
  import argparse
15
+ import errno
14
16
  import json
15
17
  import os
16
18
  import re
@@ -18,14 +20,22 @@ import sqlite3
18
20
  import sys
19
21
  import threading
20
22
  import time
21
- from collections.abc import Callable
22
- from contextlib import suppress
23
+ from collections.abc import Iterator, Mapping
24
+ from contextlib import contextmanager, suppress
25
+ from dataclasses import dataclass
23
26
  from datetime import UTC, datetime, timedelta
24
27
  from pathlib import Path
25
- from typing import Annotated
28
+ from typing import Annotated, Literal
29
+ from uuid import uuid4
26
30
 
27
- from _pantheon_paths import pantheon_home, pantheon_project
28
- from fastmcp import FastMCP
31
+ if os.name == "nt":
32
+ import msvcrt
33
+ else:
34
+ import fcntl
35
+
36
+ from _pantheon_paths import pantheon_home
37
+ from fastmcp import Context, FastMCP
38
+ from fastmcp.exceptions import ToolError
29
39
  from pydantic import Field
30
40
 
31
41
  # ── Schema ──────────────────────────────────────────────────────────────────────
@@ -37,7 +47,7 @@ CREATE TABLE IF NOT EXISTS kv_store (
37
47
  key TEXT NOT NULL,
38
48
  value TEXT NOT NULL,
39
49
  expires_at TEXT, -- ISO 8601, NULL = forever
40
- deleted_at TEXT, -- NULL = active, set on TTL purge
50
+ deleted_at TEXT, -- NULL = active; retained for legacy schema compatibility
41
51
  created_at TEXT NOT NULL DEFAULT (datetime('now')),
42
52
  updated_at TEXT NOT NULL DEFAULT (datetime('now')),
43
53
  revision INTEGER, -- context monotonic revision; NULL = legacy row
@@ -83,49 +93,215 @@ END;
83
93
 
84
94
  mcp = FastMCP(
85
95
  "pantheon-persistence",
86
- instructions="Key-Value store with FTS5 full-text search, "
87
- "TTL-based expiration, and namespace isolation.",
96
+ instructions="Operational-state checkpoints through context_save/context_get "
97
+ "and four manual session-scoped goal tools. Goal tools use OpenCode session "
98
+ "metadata and do not trigger automatic continuation.",
88
99
  )
89
100
 
90
101
  # ── Database Initialization ─────────────────────────────────────────────────────
91
102
 
92
103
  _global_db: sqlite3.Connection | None = None
93
104
  _project_db: sqlite3.Connection | None = None
94
- _DELETELOG_MAX_BYTES: int = 1_048_576 # 1 MB
95
- _DELETELOG_KEEP: int = 3
105
+ _global_db_path: Path | None = None
96
106
 
97
107
 
98
- def _init_db(db_path: Path) -> sqlite3.Connection:
99
- """Initialize a SQLite database with WAL mode and schema."""
100
- db_path.parent.mkdir(parents=True, exist_ok=True)
101
- conn = sqlite3.connect(str(db_path), check_same_thread=False)
102
- conn.execute("PRAGMA journal_mode=WAL")
103
- conn.execute("PRAGMA busy_timeout=5000")
104
- conn.execute("PRAGMA foreign_keys=ON")
105
- # ── FTS5 Availability Check ──────────────────────────────────────────
106
- # Check BEFORE schema creation. kv_search uses FTS5, which isn't on all systems.
107
- row = conn.execute("PRAGMA compile_options").fetchall()
108
- if not any("ENABLE_FTS5" in r[0] for r in row):
109
- print(
110
- "WARNING: SQLite FTS5 not available. kv_search will fail.", file=sys.stderr
111
- )
112
- import re as _re # noqa: PLC0415
108
+ def _has_goal_schema_objects(conn: sqlite3.Connection) -> bool:
109
+ """Check for goal tables or indexes, including migration-history remnants."""
110
+ return (
111
+ conn.execute(
112
+ "SELECT 1 FROM sqlite_master WHERE name IN ("
113
+ "'pantheon_goals', 'uq_pantheon_goals_active_session', "
114
+ "'idx_pantheon_goals_session_history', "
115
+ "'pantheon_goal_schema_migrations') LIMIT 1"
116
+ ).fetchone()
117
+ is not None
118
+ )
119
+
120
+
121
+ def _resolve_global_db_path(global_db: str | Path | None = None) -> Path:
122
+ """Resolve the global database path from its configured persistence root."""
123
+ root = (
124
+ Path(global_db).expanduser()
125
+ if global_db is not None
126
+ else pantheon_home() / "persistence"
127
+ )
128
+ return (root / "global.db").resolve()
129
+
130
+
131
+ def _assert_not_global_goal_path(db_path: str | Path) -> None:
132
+ """Keep goal schema changes categorically away from the global database."""
133
+ target = Path(db_path).expanduser().resolve()
134
+ global_path = globals().get("_global_db_path") or _resolve_global_db_path()
135
+ resolves_to_global = target == global_path
136
+ if not resolves_to_global:
137
+ try:
138
+ target_stat = target.stat()
139
+ global_stat = global_path.stat()
140
+ except FileNotFoundError:
141
+ pass
142
+ else:
143
+ resolves_to_global = (target_stat.st_dev, target_stat.st_ino) == (
144
+ global_stat.st_dev,
145
+ global_stat.st_ino,
146
+ )
113
147
 
114
- _no_fts = _re.sub(
115
- r"CREATE VIRTUAL TABLE IF NOT EXISTS kv_store_fts.*?;",
116
- "",
117
- CREATE_SQL,
118
- flags=_re.DOTALL,
148
+ if resolves_to_global:
149
+ raise GoalSchemaNotInitializedError(
150
+ "goal schema migration and DDL are prohibited for the global "
151
+ f"Persistence database ({global_path}); the target resolves to the "
152
+ "global database; choose a separate project database with --project-db"
119
153
  )
120
- conn.executescript(_no_fts)
121
- else:
122
- conn.executescript(CREATE_SQL)
123
- _ensure_revision_column(conn)
124
- conn.commit()
125
154
 
155
+
156
+ def _init_db(db_path: Path, *, project_db: bool = False) -> sqlite3.Connection:
157
+ """Initialize the KV schema and goal schema only for a pristine project DB."""
158
+ if project_db:
159
+ _assert_not_global_goal_path(db_path)
160
+ db_path.parent.mkdir(parents=True, exist_ok=True)
161
+ lock_path = db_path.with_name(f".{db_path.name}.init.lock")
162
+ lock_fd = os.open(lock_path, os.O_CREAT | os.O_RDWR, 0o600)
163
+ lock_acquired = False
164
+ try:
165
+ # Serialize initialization across processes.
166
+ _acquire_init_lock(lock_fd)
167
+ lock_acquired = True
168
+ conn = _connect_or_create_database(db_path)
169
+ try:
170
+ conn.execute("PRAGMA busy_timeout=5000")
171
+ conn.execute("PRAGMA foreign_keys=ON")
172
+ fts_available = any(
173
+ "ENABLE_FTS5" in row[0]
174
+ for row in conn.execute("PRAGMA compile_options").fetchall()
175
+ )
176
+ if not fts_available:
177
+ print(
178
+ "WARNING: SQLite FTS5 unavailable; the internal full-text index "
179
+ "was not initialized.",
180
+ file=sys.stderr,
181
+ )
182
+
183
+ # SQLite's writer lock serializes the schema inspection and every
184
+ # DDL statement. Never use executescript here: it commits implicitly.
185
+ conn.execute("BEGIN IMMEDIATE")
186
+ has_user_schema_objects = (
187
+ conn.execute(
188
+ "SELECT 1 FROM sqlite_master "
189
+ "WHERE substr(name, 1, 7) != 'sqlite_' LIMIT 1"
190
+ ).fetchone()
191
+ is not None
192
+ )
193
+ had_goal_schema_before_bootstrap = _has_goal_schema_objects(conn)
194
+ is_pristine = (
195
+ not has_user_schema_objects and not had_goal_schema_before_bootstrap
196
+ )
197
+ had_kv_store_before_bootstrap = (
198
+ conn.execute(
199
+ "SELECT 1 FROM sqlite_master WHERE type = 'table' "
200
+ "AND name = 'kv_store'"
201
+ ).fetchone()
202
+ is not None
203
+ )
204
+ skip_kv_bootstrap = (
205
+ project_db
206
+ and not had_kv_store_before_bootstrap
207
+ and had_goal_schema_before_bootstrap
208
+ )
209
+
210
+ schema_sql = CREATE_SQL
211
+ if not fts_available:
212
+ schema_sql = re.sub(
213
+ r"CREATE VIRTUAL TABLE IF NOT EXISTS kv_store_fts.*?;",
214
+ "",
215
+ schema_sql,
216
+ flags=re.DOTALL,
217
+ )
218
+ if not skip_kv_bootstrap:
219
+ _execute_sql_statements(conn, schema_sql)
220
+ _ensure_revision_column(conn)
221
+
222
+ # An empty DB has nothing to preserve, so initializing both schemas
223
+ # cannot destroy user data; any DB with user schema is never touched
224
+ # for goals. A rolled-back first init leaves no schema, so retry sees
225
+ # pristine again.
226
+ if project_db and is_pristine:
227
+ upgrade_goal_schema(
228
+ conn,
229
+ expected_path=db_path,
230
+ explicit_project_db=globals().get("_project_db_explicit", False),
231
+ _transaction_active=True,
232
+ )
233
+ conn.commit()
234
+ conn.execute("PRAGMA journal_mode=WAL")
235
+ return conn
236
+ except BaseException:
237
+ with suppress(sqlite3.Error):
238
+ conn.rollback()
239
+ conn.close()
240
+ raise
241
+ finally:
242
+ if lock_acquired:
243
+ _release_init_lock(lock_fd)
244
+ os.close(lock_fd)
245
+
246
+
247
+ def _acquire_init_lock(lock_fd: int) -> None:
248
+ """Lock the per-database initializer gate across processes."""
249
+ if os.name != "nt":
250
+ fcntl.flock(lock_fd, fcntl.LOCK_EX)
251
+ return
252
+
253
+ if os.fstat(lock_fd).st_size == 0:
254
+ os.write(lock_fd, b"\0")
255
+ os.lseek(lock_fd, 0, os.SEEK_SET)
256
+ while True:
257
+ try:
258
+ msvcrt.locking(lock_fd, msvcrt.LK_NBLCK, 1)
259
+ return
260
+ except OSError as exc:
261
+ if exc.errno not in (errno.EACCES, errno.EDEADLOCK, errno.EAGAIN):
262
+ raise
263
+ time.sleep(0.05)
264
+
265
+
266
+ def _release_init_lock(lock_fd: int) -> None:
267
+ """Release the per-database initializer gate."""
268
+ if os.name != "nt":
269
+ fcntl.flock(lock_fd, fcntl.LOCK_UN)
270
+ return
271
+ os.lseek(lock_fd, 0, os.SEEK_SET)
272
+ msvcrt.locking(lock_fd, msvcrt.LK_UNLCK, 1)
273
+
274
+
275
+ def _connect_or_create_database(db_path: Path) -> sqlite3.Connection:
276
+ """Open an existing database or create an empty SQLite file."""
277
+ database_uri = db_path.resolve().as_uri()
278
+ try:
279
+ conn = sqlite3.connect(
280
+ f"{database_uri}?mode=rw", uri=True, check_same_thread=False
281
+ )
282
+ except sqlite3.OperationalError as exc:
283
+ if "unable to open database file" not in str(exc).lower():
284
+ raise
285
+ conn = sqlite3.connect(
286
+ f"{database_uri}?mode=rwc", uri=True, check_same_thread=False
287
+ )
288
+ return conn
126
289
  return conn
127
290
 
128
291
 
292
+ def _execute_sql_statements(conn: sqlite3.Connection, script: str) -> None:
293
+ """Execute a SQL script statement-by-statement without implicit commits."""
294
+ pending = ""
295
+ for line in script.splitlines(keepends=True):
296
+ pending += line
297
+ if sqlite3.complete_statement(pending):
298
+ if pending.strip():
299
+ conn.execute(pending)
300
+ pending = ""
301
+ if pending.strip():
302
+ raise sqlite3.ProgrammingError("incomplete SQL schema statement")
303
+
304
+
129
305
  # `revision` was added after `kv_store` shipped, so an existing database has the
130
306
  # column only if it is added here. ADD COLUMN is additive and non-destructive:
131
307
  # pre-existing rows get NULL, which every reader treats as "no revision yet"
@@ -163,462 +339,1279 @@ def _db(scope: str) -> sqlite3.Connection:
163
339
  raise ValueError(f"Unknown scope: {scope!r}. Expected 'global' or 'project'.")
164
340
 
165
341
 
166
- # ── Deletelog ────────────────────────────────────────────────────────────────────
342
+ # ── Typed, session-scoped manual goal repository ────────────────────────────────
167
343
 
344
+ GOAL_SCHEMA_VERSION = 1
345
+ GOAL_SCHEMA_MIGRATION_COMMAND = "<venv-python> <installed-script> --migrate-goals"
346
+ GOAL_SCHEMA_MIGRATION_COMMAND_GUIDANCE = (
347
+ "Global install: <runtime>/.venv/bin/python3 "
348
+ "<runtime>/scripts/mcp_persistence.py --migrate-goals. "
349
+ "Project install: <project>/.venv/bin/python3 "
350
+ "<project>/.opencode/scripts/mcp_persistence.py --migrate-goals. "
351
+ "The simplest reliable source of truth is command[0] in opencode.json "
352
+ "for pantheon-persistence."
353
+ )
354
+ GOAL_TITLE_MAX_LENGTH = 512
355
+ GOAL_DESCRIPTION_MAX_LENGTH = 16_384
356
+ GOAL_SESSION_ID_MAX_LENGTH = 128
357
+ GOAL_ID_MAX_LENGTH = 64
358
+ GOAL_VERSION_MAX = 9_223_372_036_854_775_807
359
+ DELETE_CODEPOINT = 127
360
+ _DESCRIPTION_ALLOWED_CONTROLS = {"\t", "\n", "\r"}
361
+ GoalStatus = Literal["active", "done"]
362
+ _goal_write_lock = threading.RLock()
168
363
 
169
- def _rotate_deletelog(log_path: Path) -> None:
170
- """Rotate deletelog at 1MB, keep last 3 rotated files."""
171
- if not log_path.exists() or log_path.stat().st_size < _DELETELOG_MAX_BYTES:
172
- return
173
364
 
174
- # Shift existing rotated files: .3 → remove, .2 → .3, .1 → .2
175
- for i in range(_DELETELOG_KEEP, 0, -1):
176
- older = log_path.with_suffix(f".deletelog.{i}")
177
- if older.exists():
178
- if i == _DELETELOG_KEEP:
179
- older.unlink()
180
- else:
181
- older.rename(log_path.with_suffix(f".deletelog.{i + 1}"))
365
+ @dataclass(frozen=True, slots=True)
366
+ class GoalRecord:
367
+ """A manual goal persisted in the Persistence deployment database."""
182
368
 
183
- # Rename current log to .1
184
- log_path.rename(log_path.with_suffix(".deletelog.1"))
369
+ goal_id: str
370
+ session_id: str
371
+ title: str
372
+ description: str | None
373
+ status: GoalStatus
374
+ created_at: str
375
+ updated_at: str
376
+ version: int
185
377
 
186
378
 
187
- def _write_deletelog(db_path: Path, count: int, keys: list[str]) -> None:
188
- """Append a TTL purge entry to the deletelog."""
189
- log_path = db_path.with_name(db_path.name + ".deletelog")
190
- _rotate_deletelog(log_path)
379
+ class GoalStoreError(Exception):
380
+ """Base error for the typed manual-goal repository API."""
191
381
 
192
- timestamp = datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
193
- keys_str = ",".join(keys)
194
- with open(log_path, "a", encoding="utf-8") as f:
195
- f.write(f"[{timestamp}] PURGED={count} KEYS=[{keys_str}]\n")
196
382
 
383
+ class GoalSchemaNotInitializedError(GoalStoreError):
384
+ """Raised when goal operations target a DB without the goal schema."""
197
385
 
198
- # ── Resolve scope and init databases ────────────────────────────────────────────
199
386
 
200
- parser = argparse.ArgumentParser()
201
- parser.add_argument("--global-db", default=None)
202
- parser.add_argument("--project-db", default=None)
203
- args = parser.parse_args()
387
+ class GoalDatabaseInconsistentError(GoalSchemaNotInitializedError):
388
+ """Raised when the goal schema exists but the Persistence KV schema is absent."""
204
389
 
205
- _global_root = (
206
- Path(args.global_db) if args.global_db else pantheon_home() / "persistence"
390
+
391
+ _GOAL_DATABASE_INCONSISTENT_MESSAGE = (
392
+ "Persistence database is inconsistent: KV schema is missing while goal "
393
+ "schema is present; repair is required before goal operations. Stop the "
394
+ "server and restore a verified backup or have an administrator repair "
395
+ "the schema."
207
396
  )
208
- _global_db = _init_db(_global_root / "global.db")
209
397
 
210
- _project_db_instance = None
211
- _project_db_path: Path | None = None
212
- if args.project_db:
213
- _project_db_path = Path(args.project_db)
214
- _project_db_instance = _init_db(_project_db_path)
215
- else:
216
- _proj = pantheon_project()
217
- if _proj:
218
- _project_db_path = _proj / ".pantheon" / "persistence" / "project.db"
219
- _project_db_instance = _init_db(_project_db_path)
220
- _project_db = _project_db_instance
221
398
 
399
+ class GoalSchemaVersionError(GoalStoreError):
400
+ """Raised for an unsupported or inconsistent goal schema migration version."""
222
401
 
223
- # ── Tools ───────────────────────────────────────────────────────────────────────
224
402
 
403
+ class GoalValidationError(GoalStoreError, ValueError):
404
+ """Raised when a goal field or expected version is invalid."""
225
405
 
226
- @mcp.tool(
227
- name="kv_store",
228
- description="Store a key-value pair in a namespace with optional TTL (seconds). "
229
- "INSERT OR REPLACE on duplicate (namespace, key). "
230
- "ttl must be an integer between 1 and 31536000, or null/omitted. "
231
- "All invalid arguments are reported together in one message.",
232
- )
233
- async def kv_store(
234
- namespace: str,
235
- key: str,
236
- value: str,
237
- ttl: int | None = None,
238
- scope: str = "project",
239
- ) -> dict:
240
- """Store a value under namespace+key with optional TTL.
241
406
 
242
- Validates every argument before writing so a caller with both a bad ttl
243
- and a bad scope sees both violations in one message.
407
+ class ActiveGoalExistsError(GoalStoreError):
408
+ """Raised when a session already has an active goal."""
244
409
 
245
- Args:
246
- namespace: Logical grouping for keys.
247
- key: Unique key within the namespace.
248
- value: String value to store.
249
- ttl: Time-to-live in seconds (None = forever).
250
- scope: 'project' (default) or 'global'.
251
410
 
252
- Returns:
253
- Status dict with namespace and key.
254
- """
255
- errors = _ArgErrors("kv_store")
411
+ class GoalNotFoundError(GoalStoreError, LookupError):
412
+ """Raised when an update/done targets no goal owned by the session."""
413
+
414
+
415
+ class GoalVersionConflictError(GoalStoreError):
416
+ """Raised when an optimistic update uses a stale version."""
417
+
418
+
419
+ class GoalStorageError(GoalStoreError):
420
+ """Raised for SQLite errors or an invalid transaction state."""
421
+
422
+
423
+ class GoalBackupRetainedError(GoalStorageError):
424
+ """Raised when an upgrade fails after its verified backup was retained."""
425
+
426
+ def __init__(self, backup_path: Path, cause: Exception) -> None:
427
+ self.backup_path = backup_path
428
+ super().__init__(
429
+ f"goal schema upgrade failed after backup verification: {cause}"
430
+ )
431
+
432
+
433
+ class _GoalUnset:
434
+ """Sentinel distinguishing an omitted field from clearing description."""
435
+
436
+
437
+ _GOAL_UNSET = _GoalUnset()
438
+
439
+
440
+ def _assert_project_goal_connection(
441
+ conn: sqlite3.Connection,
442
+ expected_path: str | Path | None,
443
+ *,
444
+ explicit_project_db: bool = False,
445
+ ) -> None:
446
+ """Reject connections outside this server's Persistence database."""
447
+ if expected_path is None:
448
+ raise GoalSchemaNotInitializedError(
449
+ "goal operations require this server's Persistence database"
450
+ )
451
+ _assert_not_global_goal_path(expected_path)
452
+ project_path = Path(expected_path).expanduser().resolve()
453
+ if not explicit_project_db:
454
+ server_path = _resolve_project_db_path()
455
+ if project_path != server_path:
456
+ raise GoalSchemaNotInitializedError(
457
+ "migration target differs from the Persistence server database "
458
+ f"({server_path}); stop the server and rerun with --project-db "
459
+ "only when the explicitly selected database is intended"
460
+ )
256
461
  try:
257
- validated_ttl = _validate_ttl(ttl)
258
- except ValueError as exc:
259
- errors.report(str(exc), repr(ttl))
260
- errors.example(TTL_EXAMPLE)
261
- validated_ttl = None
262
- _collect_scope_error(errors, scope)
263
- errors.raise_if_any()
462
+ with _goal_write_lock:
463
+ databases = conn.execute("PRAGMA database_list").fetchall()
464
+ except sqlite3.Error as exc:
465
+ raise GoalStorageError("could not verify Persistence database") from exc
466
+ main_path = next((row[2] for row in databases if row[1] == "main"), "")
467
+ if not main_path or Path(main_path).resolve() != project_path:
468
+ raise GoalSchemaNotInitializedError(
469
+ "goal operations are restricted to this server's Persistence database"
470
+ )
471
+ try:
472
+ has_kv_store, has_goal_schema = conn.execute(
473
+ "SELECT "
474
+ "EXISTS(SELECT 1 FROM sqlite_master WHERE type = 'table' "
475
+ "AND name = 'kv_store'), "
476
+ "EXISTS(SELECT 1 FROM sqlite_master WHERE name IN ("
477
+ "'pantheon_goals', 'uq_pantheon_goals_active_session', "
478
+ "'idx_pantheon_goals_session_history', "
479
+ "'pantheon_goal_schema_migrations'))"
480
+ ).fetchone()
481
+ except sqlite3.Error as exc:
482
+ raise GoalStorageError("could not verify Persistence database schema") from exc
483
+ if not has_kv_store and has_goal_schema:
484
+ raise GoalDatabaseInconsistentError(_GOAL_DATABASE_INCONSISTENT_MESSAGE)
485
+ if not has_kv_store:
486
+ raise GoalSchemaNotInitializedError(
487
+ "goal operations require an existing Pantheon Persistence database; "
488
+ "ask the user to start the server once first"
489
+ )
264
490
 
265
- conn = _db(scope)
266
- expires_at: str | None = None
267
- if validated_ttl is not None:
268
- expires_at = (datetime.now(UTC) + timedelta(seconds=validated_ttl)).isoformat()
269
491
 
270
- conn.execute(
271
- "INSERT INTO kv_store (namespace, key, value, expires_at, "
272
- "created_at, updated_at) VALUES (?, ?, ?, ?, datetime('now'), datetime('now'))"
273
- "ON CONFLICT(namespace, key) DO UPDATE SET "
274
- " value = excluded.value, "
275
- " expires_at = excluded.expires_at, "
276
- " updated_at = datetime('now')",
277
- (namespace, key, value, expires_at),
492
+ def _project_goal_connection() -> sqlite3.Connection:
493
+ conn = globals().get("_project_db")
494
+ if conn is None:
495
+ raise GoalSchemaNotInitializedError(
496
+ "goal operations require this server's Persistence database"
497
+ )
498
+ _assert_project_goal_connection(
499
+ conn,
500
+ globals().get("_project_db_path"),
501
+ explicit_project_db=globals().get("_project_db_explicit", False),
278
502
  )
279
- conn.commit()
503
+ return conn
280
504
 
281
- # Opportunistic auto-purge: if namespace has >500 entries, purge expired
282
- _opportunistic_auto_purge(conn, namespace)
283
505
 
284
- return {"status": "stored", "namespace": namespace, "key": key}
506
+ @contextmanager
507
+ def _goal_transaction(conn: sqlite3.Connection) -> Iterator[None]:
508
+ """Serialize same-process use and acquire SQLite's cross-process write lock."""
509
+ with _goal_write_lock:
510
+ if conn.in_transaction:
511
+ raise GoalStorageError("goal connection already has an active transaction")
512
+ try:
513
+ conn.execute("BEGIN IMMEDIATE")
514
+ except sqlite3.Error as exc:
515
+ raise GoalStorageError("could not begin goal transaction") from exc
516
+ try:
517
+ yield
518
+ conn.commit()
519
+ except BaseException:
520
+ with suppress(sqlite3.Error):
521
+ conn.rollback()
522
+ raise
285
523
 
286
524
 
287
- @mcp.tool(
288
- name="kv_get",
289
- description="Retrieve a value by namespace and key. "
290
- "Returns None if not found or expired.",
291
- )
292
- async def kv_get(
293
- namespace: str,
294
- key: str,
295
- scope: str = "project",
296
- ) -> str | None:
297
- """Get a value by namespace and key.
525
+ def upgrade_goal_schema(
526
+ conn: sqlite3.Connection,
527
+ expected_path: str | Path | None = None,
528
+ *,
529
+ explicit_project_db: bool | None = None,
530
+ _transaction_active: bool = False,
531
+ ) -> None:
532
+ """Apply goal schema upgrades to the explicitly supplied Persistence DB."""
533
+ _assert_project_goal_connection(
534
+ conn,
535
+ expected_path or globals().get("_project_db_path"),
536
+ explicit_project_db=(
537
+ globals().get("_project_db_explicit", False)
538
+ if explicit_project_db is None
539
+ else explicit_project_db
540
+ ),
541
+ )
542
+ try:
543
+ if _transaction_active:
544
+ if not conn.in_transaction:
545
+ raise GoalStorageError(
546
+ "goal schema upgrade requires an active transaction"
547
+ )
548
+ _upgrade_goal_schema_in_transaction(conn)
549
+ else:
550
+ with _goal_transaction(conn):
551
+ _upgrade_goal_schema_in_transaction(conn)
552
+ except sqlite3.Error as exc:
553
+ raise GoalStorageError("could not upgrade Persistence goal schema") from exc
554
+
555
+
556
+ def _upgrade_goal_schema_in_transaction(conn: sqlite3.Connection) -> None:
557
+ """Apply goal DDL using the caller's active transaction."""
558
+ current = _inspect_goal_schema_version(conn)
559
+ if current == GOAL_SCHEMA_VERSION:
560
+ return
561
+ conn.execute(
562
+ "CREATE TABLE IF NOT EXISTS pantheon_goal_schema_migrations ("
563
+ "version INTEGER PRIMARY KEY CHECK (version > 0), "
564
+ "applied_at TEXT NOT NULL)"
565
+ )
566
+ conn.execute(
567
+ "CREATE TABLE pantheon_goals ("
568
+ "goal_id TEXT PRIMARY KEY NOT NULL, "
569
+ "session_id TEXT NOT NULL CHECK ("
570
+ "length(trim(session_id)) BETWEEN 1 AND 128 AND "
571
+ "session_id = trim(session_id)), "
572
+ "title TEXT NOT NULL CHECK ("
573
+ "length(title) BETWEEN 1 AND 512 AND length(trim(title)) > 0), "
574
+ "description TEXT CHECK (description IS NULL OR "
575
+ "length(description) <= 16384), "
576
+ "status TEXT NOT NULL CHECK (status IN ('active', 'done')), "
577
+ "created_at TEXT NOT NULL, updated_at TEXT NOT NULL, "
578
+ "version INTEGER NOT NULL CHECK (version > 0))"
579
+ )
580
+ conn.execute(
581
+ "CREATE UNIQUE INDEX uq_pantheon_goals_active_session "
582
+ "ON pantheon_goals(session_id) WHERE status = 'active'"
583
+ )
584
+ conn.execute(
585
+ "CREATE INDEX idx_pantheon_goals_session_history "
586
+ "ON pantheon_goals(session_id, created_at DESC, goal_id DESC)"
587
+ )
588
+ conn.execute(
589
+ "INSERT INTO pantheon_goal_schema_migrations(version, applied_at) "
590
+ "VALUES (?, ?)",
591
+ (GOAL_SCHEMA_VERSION, _goal_timestamp()),
592
+ )
298
593
 
299
- Args:
300
- namespace: Logical grouping for keys.
301
- key: Unique key within the namespace.
302
- scope: 'project' (default) or 'global'.
303
594
 
304
- Returns:
305
- Value string or None if not found/expired.
595
+ def downgrade_goal_schema(
596
+ conn: sqlite3.Connection,
597
+ target_version: int = 0,
598
+ *,
599
+ expected_path: str | Path | None = None,
600
+ explicit_project_db: bool | None = None,
601
+ ) -> None:
602
+ """Drop an empty goal schema; refuse rollback when goal data would be lost.
603
+
604
+ Populated goal schemas are intentionally irreversible through this helper:
605
+ callers must preserve/export their data before using any external teardown.
306
606
  """
307
- conn = _db(scope)
308
- row = conn.execute(
309
- "SELECT value FROM kv_store "
310
- "WHERE namespace = ? AND key = ? "
311
- "AND (expires_at IS NULL OR julianday(expires_at) > julianday('now')) "
312
- "AND deleted_at IS NULL",
313
- (namespace, key),
314
- ).fetchone()
315
- return str(row[0]) if row else None
607
+ _assert_project_goal_connection(
608
+ conn,
609
+ expected_path or globals().get("_project_db_path"),
610
+ explicit_project_db=(
611
+ globals().get("_project_db_explicit", False)
612
+ if explicit_project_db is None
613
+ else explicit_project_db
614
+ ),
615
+ )
616
+ if (
617
+ isinstance(target_version, bool)
618
+ or not isinstance(target_version, int)
619
+ or target_version != 0
620
+ ):
621
+ raise GoalSchemaVersionError(
622
+ "only downgrade to goal schema version 0 is supported"
623
+ )
624
+ try:
625
+ with _goal_transaction(conn):
626
+ exists = conn.execute(
627
+ "SELECT 1 FROM sqlite_master WHERE type = 'table' "
628
+ "AND name = 'pantheon_goal_schema_migrations'"
629
+ ).fetchone()
630
+ if exists is None:
631
+ return
632
+ row = conn.execute(
633
+ "SELECT COALESCE(MAX(version), 0) FROM pantheon_goal_schema_migrations"
634
+ ).fetchone()
635
+ current = int(row[0])
636
+ if current > GOAL_SCHEMA_VERSION:
637
+ raise GoalSchemaVersionError(
638
+ f"cannot downgrade unsupported goal schema version {current}"
639
+ )
640
+ goals_exist = conn.execute(
641
+ "SELECT 1 FROM sqlite_master WHERE type = 'table' "
642
+ "AND name = 'pantheon_goals'"
643
+ ).fetchone()
644
+ if (
645
+ goals_exist is not None
646
+ and conn.execute("SELECT 1 FROM pantheon_goals LIMIT 1").fetchone()
647
+ is not None
648
+ ):
649
+ raise GoalSchemaVersionError(
650
+ "cannot downgrade goal schema while goal data exists; "
651
+ "preserve or export goals before removing the schema"
652
+ )
653
+ conn.execute("DROP INDEX IF EXISTS uq_pantheon_goals_active_session")
654
+ conn.execute("DROP INDEX IF EXISTS idx_pantheon_goals_session_history")
655
+ conn.execute("DROP TABLE IF EXISTS pantheon_goals")
656
+ conn.execute("DROP TABLE pantheon_goal_schema_migrations")
657
+ except sqlite3.Error as exc:
658
+ raise GoalStorageError("could not downgrade goal schema") from exc
316
659
 
317
660
 
318
- @mcp.tool(
319
- name="kv_stats",
320
- description=(
321
- "Return storage statistics: total entries, expired count, per-namespace "
322
- "breakdown, DB file size."
323
- ),
324
- )
325
- async def kv_stats(
326
- scope: str = "project",
327
- ) -> dict:
328
- """Return storage statistics for the given scope.
661
+ def _goal_timestamp() -> str:
662
+ return datetime.now(UTC).isoformat(timespec="microseconds")
329
663
 
330
- Args:
331
- scope: 'project' (default) or 'global'.
332
664
 
333
- Returns:
334
- Dict with total_entries, expired_entries, namespaces breakdown, db_size_bytes.
335
- """
336
- conn = _db(scope)
665
+ def _validate_goal_session_id(session_id: str) -> str:
666
+ if not isinstance(session_id, str) or not session_id:
667
+ raise GoalValidationError("session_id must be a non-empty string")
668
+ if len(session_id) > GOAL_SESSION_ID_MAX_LENGTH:
669
+ raise GoalValidationError(
670
+ f"session_id exceeds the {GOAL_SESSION_ID_MAX_LENGTH}-character limit"
671
+ )
672
+ if session_id != session_id.strip() or any(
673
+ ord(char) < MIN_PRINTABLE_CODEPOINT or char == chr(DELETE_CODEPOINT)
674
+ for char in session_id
675
+ ):
676
+ raise GoalValidationError(
677
+ "session_id contains whitespace or a control character"
678
+ )
679
+ return session_id
337
680
 
338
- total = conn.execute(
339
- "SELECT COUNT(*) FROM kv_store WHERE deleted_at IS NULL"
340
- ).fetchone()[0]
341
- expired = conn.execute(
342
- "SELECT COUNT(*) FROM kv_store "
343
- "WHERE expires_at IS NOT NULL AND julianday(expires_at) < julianday('now') "
344
- "AND deleted_at IS NULL"
345
- ).fetchone()[0]
346
-
347
- ns_rows = conn.execute(
348
- "SELECT namespace, COUNT(*) as cnt, "
349
- "SUM(CASE WHEN expires_at IS NOT NULL AND julianday(expires_at) "
350
- "< julianday('now') THEN 1 ELSE 0 END) as expired_count "
351
- "FROM kv_store WHERE deleted_at IS NULL GROUP BY namespace ORDER BY cnt DESC"
352
- ).fetchall()
353
681
 
354
- namespaces = {r[0]: {"count": r[1], "expired": r[2]} for r in ns_rows}
682
+ def _validate_goal_text(
683
+ value: object, field: str, limit: int, *, allow_newlines: bool = False
684
+ ) -> str:
685
+ if not isinstance(value, str):
686
+ raise GoalValidationError(f"{field} must be a string")
687
+ if len(value) > limit:
688
+ raise GoalValidationError(f"{field} exceeds the {limit}-character limit")
689
+ if field == "title" and not value.strip():
690
+ raise GoalValidationError("title must be a non-empty string")
691
+ if any(
692
+ (
693
+ ord(char) < MIN_PRINTABLE_CODEPOINT
694
+ and not (allow_newlines and char in _DESCRIPTION_ALLOWED_CONTROLS)
695
+ )
696
+ or char == chr(DELETE_CODEPOINT)
697
+ for char in value
698
+ ):
699
+ raise GoalValidationError(f"{field} contains a control character")
700
+ return value
355
701
 
356
- db_path = _resolve_db_path(scope)
357
- db_size = db_path.stat().st_size if db_path and db_path.exists() else 0
358
702
 
359
- return {
360
- "scope": scope,
361
- "total_entries": total,
362
- "expired_entries": expired,
363
- "namespaces": namespaces,
364
- "db_size_bytes": db_size,
365
- }
703
+ def _validate_goal_version(version: int) -> int:
704
+ if (
705
+ isinstance(version, bool)
706
+ or not isinstance(version, int)
707
+ or version < 1
708
+ or version > GOAL_VERSION_MAX
709
+ ):
710
+ raise GoalValidationError(
711
+ f"expected_version must be an integer from 1 to {GOAL_VERSION_MAX}"
712
+ )
713
+ return version
366
714
 
367
715
 
368
- @mcp.tool(
369
- name="kv_delete",
370
- description="Delete a key-value pair by namespace and key. "
371
- "FTS trigger cascades automatically.",
372
- )
373
- async def kv_delete(
374
- namespace: str,
375
- key: str,
376
- scope: str = "project",
377
- ) -> dict:
378
- """Delete a key-value pair.
716
+ def _validate_goal_id(goal_id: str) -> str:
717
+ if (
718
+ not isinstance(goal_id, str)
719
+ or not goal_id
720
+ or len(goal_id) > GOAL_ID_MAX_LENGTH
721
+ or any(
722
+ ord(char) < MIN_PRINTABLE_CODEPOINT or char == chr(DELETE_CODEPOINT)
723
+ for char in goal_id
724
+ )
725
+ ):
726
+ raise GoalValidationError(
727
+ f"goal_id must be a valid string of at most {GOAL_ID_MAX_LENGTH} chars"
728
+ )
729
+ return goal_id
379
730
 
380
- Args:
381
- namespace: Logical grouping for keys.
382
- key: Unique key within the namespace.
383
- scope: 'project' (default) or 'global'.
384
731
 
385
- Returns:
386
- Status dict indicating deletion outcome.
387
- """
388
- conn = _db(scope)
389
- cursor = conn.execute(
390
- "DELETE FROM kv_store WHERE namespace = ? AND key = ?",
391
- (namespace, key),
732
+ def _inspect_goal_schema_version(conn: sqlite3.Connection) -> int | None:
733
+ """Read and validate the goal schema version without changing the DB."""
734
+ try:
735
+ tables = {
736
+ row[0]
737
+ for row in conn.execute(
738
+ "SELECT name FROM sqlite_master WHERE type = 'table' "
739
+ "AND name IN ('pantheon_goals', 'pantheon_goal_schema_migrations')"
740
+ )
741
+ }
742
+ has_goals = "pantheon_goals" in tables
743
+ has_migrations = "pantheon_goal_schema_migrations" in tables
744
+ if not has_migrations:
745
+ if has_goals:
746
+ raise GoalSchemaVersionError(
747
+ "pantheon_goals exists without goal schema migration history"
748
+ )
749
+ return None
750
+ row = conn.execute(
751
+ "SELECT MAX(version) FROM pantheon_goal_schema_migrations"
752
+ ).fetchone()
753
+ current = int(row[0] or 0)
754
+ if current == 0:
755
+ if has_goals:
756
+ raise GoalSchemaVersionError(
757
+ "pantheon_goals exists without a recorded schema version"
758
+ )
759
+ return None
760
+ if current > GOAL_SCHEMA_VERSION:
761
+ raise GoalSchemaVersionError(
762
+ f"goal schema version {current} is newer than supported "
763
+ f"version {GOAL_SCHEMA_VERSION}"
764
+ )
765
+ if current < GOAL_SCHEMA_VERSION:
766
+ raise GoalSchemaVersionError(
767
+ f"goal schema version {current} is older than supported "
768
+ f"version {GOAL_SCHEMA_VERSION}"
769
+ )
770
+ if not has_goals:
771
+ raise GoalSchemaVersionError(
772
+ "goal schema migration history exists but pantheon_goals is missing; "
773
+ "this is a half-created schema. Ask the user to preserve the current "
774
+ "database, restore a verified backup or recover the missing schema, "
775
+ "then rerun the human-approved migration."
776
+ )
777
+ indexes = {
778
+ row[0]
779
+ for row in conn.execute(
780
+ "SELECT name FROM sqlite_master WHERE type = 'index' "
781
+ "AND tbl_name = 'pantheon_goals'"
782
+ )
783
+ }
784
+ expected = {
785
+ "uq_pantheon_goals_active_session",
786
+ "idx_pantheon_goals_session_history",
787
+ }
788
+ if not expected.issubset(indexes):
789
+ raise GoalSchemaVersionError(
790
+ "goal schema migration history exists but required indexes are missing"
791
+ )
792
+ return current
793
+ except sqlite3.Error as exc:
794
+ raise GoalStorageError("could not inspect goal schema version") from exc
795
+
796
+
797
+ def _require_goal_schema(conn: sqlite3.Connection) -> None:
798
+ current = _inspect_goal_schema_version(conn)
799
+ if current is None:
800
+ raise GoalSchemaNotInitializedError(
801
+ "goal schema is not initialized. Ask the user to run "
802
+ f"`{GOAL_SCHEMA_MIGRATION_COMMAND}`; goal schema migration is a "
803
+ "human-approved operation. "
804
+ f"{GOAL_SCHEMA_MIGRATION_COMMAND_GUIDANCE}"
805
+ )
806
+
807
+
808
+ def _raw_goal_schema_version(conn: sqlite3.Connection) -> int:
809
+ """Read the recorded version for backup verification, without validation."""
810
+ try:
811
+ exists = conn.execute(
812
+ "SELECT 1 FROM sqlite_master WHERE type = 'table' "
813
+ "AND name = 'pantheon_goal_schema_migrations'"
814
+ ).fetchone()
815
+ except sqlite3.Error as exc:
816
+ raise GoalStorageError("could not inspect goal schema version") from exc
817
+ if exists is None:
818
+ return 0
819
+ try:
820
+ row = conn.execute(
821
+ "SELECT MAX(version) FROM pantheon_goal_schema_migrations"
822
+ ).fetchone()
823
+ except sqlite3.Error as exc:
824
+ raise GoalStorageError("could not read goal schema version") from exc
825
+ return int(row[0] or 0)
826
+
827
+
828
+ def _resolve_project_db_path(project_db: str | Path | None = None) -> Path:
829
+ """Resolve explicit CLI path, project override, then runtime target."""
830
+ if project_db is not None:
831
+ path = Path(project_db).expanduser()
832
+ if not path.is_absolute():
833
+ path = Path(__file__).resolve().parents[1] / path
834
+ return path.resolve()
835
+ configured_project = os.environ.get("PANTHEON_PROJECT")
836
+ if configured_project:
837
+ project_root = Path(configured_project)
838
+ if not project_root.is_absolute():
839
+ raise GoalSchemaNotInitializedError(
840
+ "PANTHEON_PROJECT must be an absolute path; set it to the "
841
+ "absolute project root or unset it."
842
+ )
843
+ return (project_root / ".pantheon" / "persistence" / "project.db").resolve()
844
+ project_root = Path(__file__).resolve().parents[1]
845
+ return (project_root / ".pantheon" / "persistence" / "project.db").resolve()
846
+
847
+
848
+ def _goal_dry_run_file_metadata(
849
+ db_path: Path,
850
+ ) -> tuple[os.stat_result | None, os.stat_result | None, os.stat_result | None]:
851
+ def optional_stat(path: Path) -> os.stat_result | None:
852
+ try:
853
+ return path.stat()
854
+ except FileNotFoundError:
855
+ return None
856
+
857
+ return (
858
+ optional_stat(db_path),
859
+ optional_stat(db_path.with_name(db_path.name + "-wal")),
860
+ optional_stat(db_path.with_name(db_path.name + "-shm")),
392
861
  )
393
- conn.commit()
394
- if cursor.rowcount > 0:
395
- return {"status": "deleted"}
396
- return {"status": "not_found"}
397
862
 
398
863
 
399
- @mcp.tool(
400
- name="kv_list",
401
- description="List keys in a namespace with optional prefix filter. "
402
- "Returns up to 'limit' entries (default 100).",
403
- )
404
- async def kv_list(
405
- namespace: str,
406
- prefix: str = "",
407
- scope: str = "project",
408
- limit: int = 100,
409
- ) -> list[dict]:
410
- """List keys in a namespace, filtered by prefix.
864
+ def _print_goal_migration_dry_run(db_path: Path) -> int:
865
+ db_path = db_path.resolve()
411
866
 
412
- Args:
413
- namespace: Logical grouping for keys.
414
- prefix: Optional key prefix filter.
415
- scope: 'project' (default) or 'global'.
416
- limit: Maximum number of results (default 100).
867
+ # Snapshot all labels before opening SQLite: opening in plain read-only mode
868
+ # can interact with existing WAL files, so its own effects must never alter
869
+ # the sidecar or size report.
870
+ try:
871
+ db_stat, wal_stat, shm_stat = _goal_dry_run_file_metadata(db_path)
872
+ except OSError as exc:
873
+ print(f"Database: {db_path}")
874
+ print("Exists: unknown")
875
+ print("Size: unknown")
876
+ print("Sidecars: unknown")
877
+ print("Goal tables exist: unknown")
878
+ print(
879
+ f"Dry-run state is unknown ({exc}); stop and investigate before "
880
+ "any migration.",
881
+ file=sys.stderr,
882
+ )
883
+ return 2
417
884
 
418
- Returns:
419
- List of dicts with key, value, created_at, expires_at.
420
- """
421
- conn = _db(scope)
422
- rows = conn.execute(
423
- "SELECT key, value, created_at, expires_at FROM kv_store "
424
- "WHERE namespace = ? AND key LIKE ? "
425
- "AND (expires_at IS NULL OR julianday(expires_at) > julianday('now')) "
426
- "AND deleted_at IS NULL "
427
- "ORDER BY key LIMIT ?",
428
- (namespace, f"{prefix}%", limit),
885
+ exists = db_stat is not None
886
+ has_wal = wal_stat is not None
887
+ has_shm = shm_stat is not None
888
+ size = (db_stat.st_size if db_stat is not None else 0) + (
889
+ wal_stat.st_size if wal_stat is not None else 0
890
+ )
891
+ size_description = " bytes (database + WAL)" if has_wal else " bytes"
892
+ print(f"Database: {db_path}")
893
+ print(f"Exists: {'yes' if exists else 'no'}")
894
+ print(f"Size: {size}{size_description}")
895
+ sidecar_description = (
896
+ f"WAL={'yes' if has_wal else 'no'}, SHM={'yes' if has_shm else 'no'}"
897
+ )
898
+ print(f"Sidecars: {sidecar_description}")
899
+
900
+ goal_tables = {"pantheon_goal_schema_migrations", "pantheon_goals"}
901
+ table_result = "no"
902
+ if exists:
903
+ connection: sqlite3.Connection | None = None
904
+ try:
905
+ uri = f"{db_path.as_uri()}?mode=ro"
906
+ if not has_wal and not has_shm:
907
+ uri += "&immutable=1"
908
+ connection = sqlite3.connect(uri, uri=True)
909
+ present = goal_tables & {
910
+ str(row[0])
911
+ for row in connection.execute(
912
+ "SELECT name FROM sqlite_master WHERE type = 'table'"
913
+ )
914
+ }
915
+ table_result = "yes" if present else "no"
916
+ if present:
917
+ table_result += f" ({', '.join(sorted(present))})"
918
+ except sqlite3.Error as exc:
919
+ table_result = "unknown"
920
+ print(
921
+ f"Dry-run state is unknown ({exc}); stop and investigate before "
922
+ "any migration.",
923
+ file=sys.stderr,
924
+ )
925
+ finally:
926
+ if connection is not None:
927
+ connection.close()
928
+ print(f"Goal tables exist: {table_result}")
929
+ print(
930
+ "Warning: stop the Persistence server for an authoritative check and "
931
+ "keep it stopped for the whole migration."
932
+ )
933
+ return 2 if table_result == "unknown" else 0
934
+
935
+
936
+ def _warn_if_symlinked_launcher() -> None:
937
+ lexical_path = Path(__file__).absolute()
938
+ resolved_path = Path(__file__).resolve()
939
+ if lexical_path != resolved_path:
940
+ print(
941
+ "Warning: this is a symlinked launcher; re-run from the installed script "
942
+ f"at {resolved_path}.",
943
+ file=sys.stderr,
944
+ )
945
+
946
+
947
+ def _print_goal_migration_failure(
948
+ error: GoalStoreError | OSError | sqlite3.Error,
949
+ ) -> None:
950
+ print(f"Goal schema migration failed: {error}", file=sys.stderr)
951
+ if isinstance(error, GoalBackupRetainedError):
952
+ print(
953
+ f"Verified backup retained at: {error.backup_path}",
954
+ file=sys.stderr,
955
+ )
956
+
957
+
958
+ def _reserve_goal_backup_path(db_path: Path) -> Path:
959
+ timestamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%S.%fZ")
960
+ backup_path = db_path.with_name(f"{db_path.name}.goal-backup-{timestamp}.sqlite3")
961
+ try:
962
+ descriptor = os.open(
963
+ backup_path,
964
+ os.O_CREAT | os.O_EXCL | os.O_WRONLY,
965
+ 0o600,
966
+ )
967
+ except OSError as exc:
968
+ raise GoalStorageError(
969
+ f"could not reserve unique goal schema backup {backup_path}"
970
+ ) from exc
971
+ os.close(descriptor)
972
+ return backup_path
973
+
974
+
975
+ def _sqlite_object_names(conn: sqlite3.Connection) -> set[str]:
976
+ return {str(row[0]) for row in conn.execute("SELECT name FROM sqlite_master")}
977
+
978
+
979
+ def _sqlite_table_row_counts(conn: sqlite3.Connection) -> dict[str, int]:
980
+ tables = conn.execute(
981
+ "SELECT name FROM sqlite_master WHERE type = 'table'"
429
982
  ).fetchall()
430
- return [
431
- {
432
- "key": r[0],
433
- "value": r[1],
434
- "created_at": r[2],
435
- "expires_at": r[3],
436
- }
437
- for r in rows
438
- ]
983
+ row_counts: dict[str, int] = {}
984
+ for (table_name,) in tables:
985
+ quoted_name = '"' + str(table_name).replace('"', '""') + '"'
986
+ row = conn.execute(f"SELECT COUNT(*) FROM {quoted_name}").fetchone()
987
+ row_counts[str(table_name)] = int(row[0])
988
+ return row_counts
439
989
 
440
990
 
441
- @mcp.tool(
442
- name="kv_search",
443
- description="Full-text search across keys and values using FTS5. "
444
- "Optionally filter by namespace.",
991
+ def _verify_goal_backup(
992
+ source: sqlite3.Connection, backup_path: Path, expected_version: int
993
+ ) -> None:
994
+ uri = f"{backup_path.as_uri()}?mode=ro&immutable=1"
995
+ backup: sqlite3.Connection | None = None
996
+ try:
997
+ backup = sqlite3.connect(uri, uri=True)
998
+ check = backup.execute("PRAGMA quick_check").fetchone()
999
+ if check is None or check[0] != "ok":
1000
+ raise GoalStorageError("goal schema backup failed SQLite integrity check")
1001
+ source_page_count = int(source.execute("PRAGMA page_count").fetchone()[0])
1002
+ backup_page_count = int(backup.execute("PRAGMA page_count").fetchone()[0])
1003
+ if source_page_count < 1 or backup_page_count != source_page_count:
1004
+ raise GoalStorageError(
1005
+ "goal schema backup page-count verification failed: "
1006
+ f"expected {source_page_count}, found {backup_page_count}"
1007
+ )
1008
+ source_objects = _sqlite_object_names(source)
1009
+ backup_objects = _sqlite_object_names(backup)
1010
+ if source_objects != backup_objects:
1011
+ raise GoalStorageError(
1012
+ "goal schema backup SQLite object-name verification failed"
1013
+ )
1014
+ if "kv_store" not in source_objects or "kv_store" not in backup_objects:
1015
+ raise GoalSchemaNotInitializedError(
1016
+ "target is not a Pantheon Persistence database: kv_store is missing; "
1017
+ "ask the user to start the server once first"
1018
+ )
1019
+ if _sqlite_table_row_counts(source) != _sqlite_table_row_counts(backup):
1020
+ raise GoalStorageError(
1021
+ "goal schema backup row-count verification failed for kv_store "
1022
+ "or another sentinel table"
1023
+ )
1024
+ actual_version = _raw_goal_schema_version(backup)
1025
+ if actual_version != expected_version:
1026
+ raise GoalStorageError(
1027
+ "goal schema backup version verification failed: "
1028
+ f"expected {expected_version}, found {actual_version}"
1029
+ )
1030
+ except sqlite3.Error as exc:
1031
+ raise GoalStorageError("could not verify goal schema backup") from exc
1032
+ finally:
1033
+ if backup is not None:
1034
+ backup.close()
1035
+
1036
+
1037
+ def _copy_goal_backup(source: sqlite3.Connection, backup_path: Path) -> None:
1038
+ """Write and durably flush the full SQLite backup before verification."""
1039
+ destination = sqlite3.connect(str(backup_path))
1040
+ try:
1041
+ source.backup(destination)
1042
+ finally:
1043
+ destination.close()
1044
+ os.chmod(backup_path, 0o600)
1045
+ with backup_path.open("rb") as backup_file:
1046
+ os.fsync(backup_file.fileno())
1047
+ directory_fd = os.open(
1048
+ backup_path.parent,
1049
+ os.O_RDONLY | getattr(os, "O_DIRECTORY", 0),
1050
+ )
1051
+ try:
1052
+ os.fsync(directory_fd)
1053
+ finally:
1054
+ os.close(directory_fd)
1055
+
1056
+
1057
+ def _remove_goal_backup_sidecars(backup_path: Path) -> None:
1058
+ for suffix in ("-wal", "-shm", "-journal"):
1059
+ with suppress(OSError):
1060
+ backup_path.with_name(backup_path.name + suffix).unlink(missing_ok=True)
1061
+
1062
+
1063
+ def _cleanup_goal_backup(backup_path: Path) -> None:
1064
+ _remove_goal_backup_sidecars(backup_path)
1065
+ with suppress(OSError):
1066
+ backup_path.unlink(missing_ok=True)
1067
+
1068
+
1069
+ def migrate_goal_schema_with_backup(
1070
+ project_db_path: str | Path,
1071
+ *,
1072
+ explicit_project_db: bool = True,
1073
+ ) -> tuple[Path, Path | None, int, bool]:
1074
+ """Back up an existing Persistence DB, then migrate its goal schema."""
1075
+ db_path = Path(project_db_path).expanduser().resolve()
1076
+ _assert_not_global_goal_path(db_path)
1077
+ if not db_path.is_file():
1078
+ raise GoalSchemaNotInitializedError(
1079
+ f"Persistence database does not exist at {db_path}; "
1080
+ "ask the user to start the server once first"
1081
+ )
1082
+ try:
1083
+ source = sqlite3.connect(f"{db_path.as_uri()}?mode=rw", uri=True, timeout=5)
1084
+ except sqlite3.Error as exc:
1085
+ raise GoalStorageError("could not open Persistence database") from exc
1086
+
1087
+ backup_path: Path | None = None
1088
+ try:
1089
+ has_kv_store = source.execute(
1090
+ "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'kv_store'"
1091
+ ).fetchone()
1092
+ if has_kv_store is None:
1093
+ if _has_goal_schema_objects(source):
1094
+ raise GoalDatabaseInconsistentError(_GOAL_DATABASE_INCONSISTENT_MESSAGE)
1095
+ raise GoalSchemaNotInitializedError(
1096
+ "target is not a Pantheon Persistence database: kv_store is missing; "
1097
+ "ask the user to start the server once first"
1098
+ )
1099
+ _assert_project_goal_connection(
1100
+ source,
1101
+ db_path,
1102
+ explicit_project_db=explicit_project_db,
1103
+ )
1104
+ current = _inspect_goal_schema_version(source)
1105
+ original_version = _raw_goal_schema_version(source)
1106
+ if current == GOAL_SCHEMA_VERSION:
1107
+ return db_path, None, original_version, True
1108
+
1109
+ backup_path = _reserve_goal_backup_path(db_path)
1110
+ try:
1111
+ _copy_goal_backup(source, backup_path)
1112
+ _remove_goal_backup_sidecars(backup_path)
1113
+ _verify_goal_backup(source, backup_path, original_version)
1114
+ except (GoalStoreError, OSError, sqlite3.Error):
1115
+ _cleanup_goal_backup(backup_path)
1116
+ raise
1117
+
1118
+ try:
1119
+ upgrade_goal_schema(
1120
+ source,
1121
+ db_path,
1122
+ explicit_project_db=explicit_project_db,
1123
+ )
1124
+ version = _raw_goal_schema_version(source)
1125
+ except Exception as exc:
1126
+ raise GoalBackupRetainedError(backup_path, exc) from exc
1127
+ return db_path, backup_path, version, False
1128
+ finally:
1129
+ source.close()
1130
+
1131
+
1132
+ _GOAL_COLUMNS = (
1133
+ "goal_id, session_id, title, description, status, created_at, updated_at, version"
445
1134
  )
446
- async def kv_search(
447
- query: str,
448
- namespace: str | None = None,
449
- scope: str = "project",
450
- limit: int = 20,
451
- ) -> list[dict]:
452
- """Full-text search across keys and values.
453
1135
 
454
- Args:
455
- query: Free-text search terms (max 10 terms quoted).
456
- namespace: Optional namespace filter.
457
- scope: 'project' (default) or 'global'.
458
- limit: Maximum number of results (default 20).
459
1136
 
460
- Returns:
461
- List of dicts with namespace, key, value, created_at, score.
1137
+ def _goal_from_row(row: sqlite3.Row | tuple[object, ...]) -> GoalRecord:
1138
+ return GoalRecord(
1139
+ goal_id=str(row[0]),
1140
+ session_id=str(row[1]),
1141
+ title=str(row[2]),
1142
+ description=row[3] if isinstance(row[3], str) else None,
1143
+ status=row[4], # type: ignore[arg-type]
1144
+ created_at=str(row[5]),
1145
+ updated_at=str(row[6]),
1146
+ version=int(row[7]),
1147
+ )
1148
+
1149
+
1150
+ def _goal_by_id(
1151
+ conn: sqlite3.Connection, session_id: str, goal_id: str
1152
+ ) -> GoalRecord | None:
1153
+ row = conn.execute(
1154
+ f"SELECT {_GOAL_COLUMNS} FROM pantheon_goals "
1155
+ "WHERE session_id = ? AND goal_id = ?",
1156
+ (session_id, goal_id),
1157
+ ).fetchone()
1158
+ return _goal_from_row(row) if row is not None else None
1159
+
1160
+
1161
+ def _goal_database_error(exc: sqlite3.Error) -> GoalStoreError:
1162
+ if "no such table: pantheon_goals" in str(exc):
1163
+ return GoalSchemaNotInitializedError(
1164
+ "goal schema is not initialized. Ask the user to run "
1165
+ f"`{GOAL_SCHEMA_MIGRATION_COMMAND}`; goal schema migration is a "
1166
+ "human-approved operation. "
1167
+ f"{GOAL_SCHEMA_MIGRATION_COMMAND_GUIDANCE}"
1168
+ )
1169
+ return GoalStorageError("goal database operation failed")
1170
+
1171
+
1172
+ def create_goal(
1173
+ *,
1174
+ session_id: str,
1175
+ title: str,
1176
+ description: str | None = None,
1177
+ ) -> GoalRecord:
1178
+ """Create one active goal; session identity must come from trusted host context.
1179
+
1180
+ The session ID is a correlation/scope key, not authentication. Callers must
1181
+ supply it internally from OpenCode ``Context`` metadata; never accept it as
1182
+ a model-controlled tool argument.
462
1183
  """
463
- conn = _db(scope)
1184
+ conn = _project_goal_connection()
1185
+ session_id = _validate_goal_session_id(session_id)
1186
+ title = _validate_goal_text(title, "title", GOAL_TITLE_MAX_LENGTH)
1187
+ if description is not None:
1188
+ description = _validate_goal_text(
1189
+ description,
1190
+ "description",
1191
+ GOAL_DESCRIPTION_MAX_LENGTH,
1192
+ allow_newlines=True,
1193
+ )
1194
+ try:
1195
+ with _goal_transaction(conn):
1196
+ _require_goal_schema(conn)
1197
+ existing = conn.execute(
1198
+ f"SELECT {_GOAL_COLUMNS} FROM pantheon_goals "
1199
+ "WHERE session_id = ? AND status = 'active'",
1200
+ (session_id,),
1201
+ ).fetchone()
1202
+ if existing is not None:
1203
+ raise ActiveGoalExistsError(
1204
+ "active goal already exists for this session"
1205
+ )
1206
+ now = _goal_timestamp()
1207
+ goal_id = uuid4().hex
1208
+ conn.execute(
1209
+ "INSERT INTO pantheon_goals(" + _GOAL_COLUMNS + ") "
1210
+ "VALUES (?, ?, ?, ?, 'active', ?, ?, 1)",
1211
+ (goal_id, session_id, title, description, now, now),
1212
+ )
1213
+ created = _goal_by_id(conn, session_id, goal_id)
1214
+ assert created is not None
1215
+ return created
1216
+ except sqlite3.IntegrityError as exc:
1217
+ try:
1218
+ with _goal_write_lock:
1219
+ _require_goal_schema(conn)
1220
+ existing = conn.execute(
1221
+ "SELECT 1 FROM pantheon_goals "
1222
+ "WHERE session_id = ? AND status = 'active'",
1223
+ (session_id,),
1224
+ ).fetchone()
1225
+ if existing is not None:
1226
+ raise ActiveGoalExistsError(
1227
+ "active goal already exists for this session"
1228
+ ) from exc
1229
+ except GoalStoreError:
1230
+ raise
1231
+ except sqlite3.Error as inspect_exc:
1232
+ raise _goal_database_error(inspect_exc) from exc
1233
+ raise GoalStorageError("goal insert violated a database constraint") from exc
1234
+ except sqlite3.Error as exc:
1235
+ raise _goal_database_error(exc) from exc
464
1236
 
465
- # Sanitize: extract up to 10 word tokens, wrap each in quotes
466
- terms = re.findall(r"\w+", query)[:10]
467
- terms = [re.escape(t) for t in terms]
468
- if not terms:
469
- return []
470
- fts_query = " OR ".join(f'"{t}"' for t in terms)
471
-
472
- sql: str = (
473
- "SELECT kv_store.namespace, kv_store.key, kv_store.value, kv_store.created_at, "
474
- "BM25(kv_store_fts) AS score "
475
- "FROM kv_store_fts "
476
- "JOIN kv_store ON kv_store_fts.rowid = kv_store.id "
477
- "WHERE kv_store_fts MATCH ? "
478
- "AND kv_store.deleted_at IS NULL "
479
- "AND (kv_store.expires_at IS NULL OR "
480
- "julianday(kv_store.expires_at) > julianday('now'))"
481
- )
482
- params: list[str | int] = [fts_query]
483
-
484
- if namespace is not None:
485
- sql += " AND kv_store.namespace = ?"
486
- params.append(namespace)
487
-
488
- sql += " ORDER BY score LIMIT ?"
489
- params.append(limit)
490
-
491
- rows = conn.execute(sql, params).fetchall()
492
- return [
493
- {
494
- "namespace": r[0],
495
- "key": r[1],
496
- "value": r[2],
497
- "created_at": r[3],
498
- "score": round(float(r[4]), 4),
499
- }
500
- for r in rows
501
- ]
502
1237
 
1238
+ def get_goal(*, session_id: str, goal_id: str | None = None) -> GoalRecord | None:
1239
+ """Get a specific goal, or its active/latest history entry.
503
1240
 
504
- @mcp.tool(
505
- name="purge_expired",
506
- description="Purge expired TTL entries. Optionally dry-run to see count "
507
- "without deleting. Logs purged keys to deletelog.",
1241
+ SQLite rowid provides an insertion-order tie-break when creation timestamps
1242
+ are equal.
1243
+ """
1244
+ conn = _project_goal_connection()
1245
+ session_id = _validate_goal_session_id(session_id)
1246
+ if goal_id is not None:
1247
+ goal_id = _validate_goal_id(goal_id)
1248
+ try:
1249
+ with _goal_write_lock:
1250
+ _require_goal_schema(conn)
1251
+ if goal_id is not None:
1252
+ return _goal_by_id(conn, session_id, goal_id)
1253
+ row = conn.execute(
1254
+ f"SELECT {_GOAL_COLUMNS} FROM pantheon_goals "
1255
+ "WHERE session_id = ? AND status = 'active' LIMIT 1",
1256
+ (session_id,),
1257
+ ).fetchone()
1258
+ if row is None:
1259
+ row = conn.execute(
1260
+ f"SELECT {_GOAL_COLUMNS} FROM pantheon_goals "
1261
+ "WHERE session_id = ? ORDER BY created_at DESC, rowid DESC "
1262
+ "LIMIT 1",
1263
+ (session_id,),
1264
+ ).fetchone()
1265
+ return _goal_from_row(row) if row is not None else None
1266
+ except sqlite3.Error as exc:
1267
+ raise _goal_database_error(exc) from exc
1268
+
1269
+
1270
+ def update_goal(
1271
+ *,
1272
+ session_id: str,
1273
+ goal_id: str,
1274
+ expected_version: int,
1275
+ title: str | None | _GoalUnset = _GOAL_UNSET,
1276
+ description: str | None | _GoalUnset = _GOAL_UNSET,
1277
+ ) -> GoalRecord:
1278
+ """CAS-update user fields only; status and version remain server-owned."""
1279
+ conn = _project_goal_connection()
1280
+ session_id = _validate_goal_session_id(session_id)
1281
+ goal_id = _validate_goal_id(goal_id)
1282
+ expected_version = _validate_goal_version(expected_version)
1283
+ if title is _GOAL_UNSET and description is _GOAL_UNSET:
1284
+ raise GoalValidationError("update must include title and/or description")
1285
+ if title is not _GOAL_UNSET:
1286
+ title = _validate_goal_text(title, "title", GOAL_TITLE_MAX_LENGTH)
1287
+ if description is not _GOAL_UNSET and description is not None:
1288
+ description = _validate_goal_text(
1289
+ description,
1290
+ "description",
1291
+ GOAL_DESCRIPTION_MAX_LENGTH,
1292
+ allow_newlines=True,
1293
+ )
1294
+ try:
1295
+ with _goal_transaction(conn):
1296
+ _require_goal_schema(conn)
1297
+ current = _goal_by_id(conn, session_id, goal_id)
1298
+ if current is None:
1299
+ raise GoalNotFoundError("goal not found for this session")
1300
+ if current.version != expected_version:
1301
+ raise GoalVersionConflictError(
1302
+ f"goal version conflict: expected {expected_version}, "
1303
+ f"current version is {current.version}"
1304
+ )
1305
+ new_title = current.title if title is _GOAL_UNSET else title
1306
+ new_description = (
1307
+ current.description if description is _GOAL_UNSET else description
1308
+ )
1309
+ conn.execute(
1310
+ "UPDATE pantheon_goals SET title = ?, description = ?, "
1311
+ "updated_at = ?, version = version + 1 "
1312
+ "WHERE goal_id = ? AND session_id = ? AND version = ?",
1313
+ (
1314
+ new_title,
1315
+ new_description,
1316
+ _goal_timestamp(),
1317
+ goal_id,
1318
+ session_id,
1319
+ expected_version,
1320
+ ),
1321
+ )
1322
+ updated = _goal_by_id(conn, session_id, goal_id)
1323
+ assert updated is not None
1324
+ if updated.version != expected_version + 1:
1325
+ raise GoalVersionConflictError(
1326
+ f"goal version conflict: expected {expected_version}, "
1327
+ f"current version is {updated.version}"
1328
+ )
1329
+ return updated
1330
+ except sqlite3.Error as exc:
1331
+ raise _goal_database_error(exc) from exc
1332
+
1333
+
1334
+ def complete_goal(
1335
+ *,
1336
+ session_id: str,
1337
+ goal_id: str,
1338
+ expected_version: int,
1339
+ ) -> GoalRecord:
1340
+ """Mark a session-owned active goal done using CAS; repeated done is idempotent."""
1341
+ conn = _project_goal_connection()
1342
+ session_id = _validate_goal_session_id(session_id)
1343
+ goal_id = _validate_goal_id(goal_id)
1344
+ expected_version = _validate_goal_version(expected_version)
1345
+ try:
1346
+ with _goal_transaction(conn):
1347
+ _require_goal_schema(conn)
1348
+ current = _goal_by_id(conn, session_id, goal_id)
1349
+ if current is None:
1350
+ raise GoalNotFoundError("goal not found for this session")
1351
+ if current.status == "done":
1352
+ return current
1353
+ if current.version != expected_version:
1354
+ raise GoalVersionConflictError(
1355
+ f"goal version conflict: expected {expected_version}, "
1356
+ f"current version is {current.version}"
1357
+ )
1358
+ conn.execute(
1359
+ "UPDATE pantheon_goals SET status = 'done', updated_at = ?, "
1360
+ "version = version + 1 WHERE goal_id = ? AND session_id = ? "
1361
+ "AND status = 'active' AND version = ?",
1362
+ (_goal_timestamp(), goal_id, session_id, expected_version),
1363
+ )
1364
+ completed = _goal_by_id(conn, session_id, goal_id)
1365
+ assert completed is not None
1366
+ if completed.status != "done" or completed.version != expected_version + 1:
1367
+ raise GoalVersionConflictError(
1368
+ f"goal version conflict: expected {expected_version}, "
1369
+ f"current version is {completed.version}"
1370
+ )
1371
+ return completed
1372
+ except sqlite3.Error as exc:
1373
+ raise _goal_database_error(exc) from exc
1374
+
1375
+
1376
+ # ── Resolve scope and init databases ────────────────────────────────────────────
1377
+
1378
+ parser = argparse.ArgumentParser()
1379
+ parser.add_argument("--global-db", default=None)
1380
+ parser.add_argument("--project-db", default=None)
1381
+ parser.add_argument(
1382
+ "--migrate-goals",
1383
+ action="store_true",
1384
+ help="back up and explicitly migrate the Persistence goal schema, then exit",
508
1385
  )
509
- async def purge_expired(
510
- scope: str = "project",
511
- dry_run: bool = False,
512
- ) -> dict:
513
- """Purge expired TTL entries from the database.
1386
+ parser.add_argument(
1387
+ "--dry-run",
1388
+ action="store_true",
1389
+ help="with --migrate-goals, report the resolved DB without changing it",
1390
+ )
1391
+ args = parser.parse_args()
514
1392
 
515
- Args:
516
- scope: 'project' (default) or 'global'.
517
- dry_run: If True, only report count without purging.
1393
+ if args.dry_run and not args.migrate_goals:
1394
+ parser.error("--dry-run requires --migrate-goals")
518
1395
 
519
- Returns:
520
- Dict with purged count and dry_run flag.
521
- """
522
- conn = _db(scope)
1396
+ _project_db_path: Path | None = None
1397
+ _project_db_explicit = args.project_db is not None
1398
+ _global_db_path = _resolve_global_db_path(args.global_db)
1399
+ if args.migrate_goals:
1400
+ _warn_if_symlinked_launcher()
1401
+ try:
1402
+ migration_db_path = _resolve_project_db_path(args.project_db)
1403
+ _assert_not_global_goal_path(migration_db_path)
1404
+ if args.dry_run:
1405
+ raise SystemExit(_print_goal_migration_dry_run(migration_db_path))
1406
+ db_path, backup_path, version, already_current = (
1407
+ migrate_goal_schema_with_backup(
1408
+ migration_db_path,
1409
+ explicit_project_db=args.project_db is not None,
1410
+ )
1411
+ )
1412
+ except (GoalStoreError, OSError, sqlite3.Error) as exc:
1413
+ _print_goal_migration_failure(exc)
1414
+ raise SystemExit(1) from exc
1415
+ print(f"Database: {db_path}")
1416
+ if backup_path is not None:
1417
+ print(f"Backup: {backup_path}")
1418
+ print(f"Goal schema version: {version}")
1419
+ if already_current:
1420
+ print("Goal schema already current; no schema changes applied.")
1421
+ else:
1422
+ print("Goal schema migration applied.")
1423
+ raise SystemExit(0)
523
1424
 
524
- # Find expired entries first
525
- expired = conn.execute(
526
- "SELECT key FROM kv_store "
527
- "WHERE expires_at IS NOT NULL "
528
- "AND julianday(expires_at) < julianday('now') "
529
- "AND deleted_at IS NULL",
530
- ).fetchall()
531
- expired_keys = [r[0] for r in expired]
532
- count = len(expired_keys)
1425
+ _global_db = _init_db(_global_db_path)
533
1426
 
534
- if dry_run:
535
- return {"purged": count, "dry_run": True}
1427
+ _project_db_path = _resolve_project_db_path(args.project_db)
1428
+ _project_db_instance = _init_db(_project_db_path, project_db=True)
1429
+ _project_db = _project_db_instance
536
1430
 
537
- if count == 0:
538
- return {"purged": 0, "dry_run": False}
539
1431
 
540
- # Mark as deleted (soft delete)
541
- conn.execute(
542
- "UPDATE kv_store SET deleted_at = datetime('now') "
543
- "WHERE expires_at IS NOT NULL "
544
- "AND julianday(expires_at) < julianday('now') "
545
- "AND deleted_at IS NULL",
546
- )
547
- conn.commit()
1432
+ # ── Tools ───────────────────────────────────────────────────────────────────────
548
1433
 
549
- # Write deletelog
550
- db_path = _resolve_db_path(scope)
551
- if db_path:
552
- _write_deletelog(db_path, count, expired_keys)
1434
+ _OPENCODE_SESSION_META_KEY = "ai.opencode/sessionID"
1435
+ _OPENCODE_SESSION_ID_PATTERN = re.compile(r"ses_[A-Za-z0-9_-]{1,124}\Z")
553
1436
 
554
- return {"purged": count, "dry_run": False}
555
1437
 
1438
+ def _session_id_from_context(context: Context) -> str:
1439
+ """Read and validate the OpenCode session ID from FastMCP request metadata.
556
1440
 
557
- def _opportunistic_auto_purge(
558
- conn: sqlite3.Connection, namespace: str, threshold: int = 500
559
- ) -> None:
560
- """Lightweight auto-purge when a namespace exceeds its threshold."""
561
- count = conn.execute(
562
- "SELECT COUNT(*) FROM kv_store WHERE namespace = ? AND deleted_at IS NULL",
563
- (namespace,),
564
- ).fetchone()[0]
565
- if count <= threshold:
566
- return
1441
+ This value is a correlation/scope key, not authentication. The supported
1442
+ boundary is OpenCode-mediated local stdio; clients able to bypass the host
1443
+ can forge metadata and are outside this check's security guarantee.
1444
+ """
1445
+ request_context = context.request_context
1446
+ if request_context is None:
1447
+ raise ToolError("Goal operations require OpenCode session metadata.")
1448
+ metadata = request_context.meta
1449
+ if not isinstance(metadata, Mapping):
1450
+ raise ToolError("Goal operations require OpenCode session metadata.")
1451
+ session_id = metadata.get(_OPENCODE_SESSION_META_KEY)
1452
+ if (
1453
+ not isinstance(session_id, str)
1454
+ or _OPENCODE_SESSION_ID_PATTERN.fullmatch(session_id) is None
1455
+ ):
1456
+ raise ToolError("Goal operations require a valid OpenCode session ID.")
1457
+ return session_id
567
1458
 
568
- conn.execute(
569
- "UPDATE kv_store SET deleted_at = datetime('now') "
570
- "WHERE namespace = ? AND expires_at IS NOT NULL "
571
- "AND datetime(expires_at) < datetime('now') AND deleted_at IS NULL",
572
- (namespace,),
573
- )
574
- conn.commit()
1459
+
1460
+ def _public_goal(record: GoalRecord | None) -> dict[str, object] | None:
1461
+ """Expose only public goal fields; omit session scope and storage details."""
1462
+ if record is None:
1463
+ return None
1464
+ return {
1465
+ "goal_id": record.goal_id,
1466
+ "title": record.title,
1467
+ "description": record.description,
1468
+ "status": record.status,
1469
+ "created_at": record.created_at,
1470
+ "updated_at": record.updated_at,
1471
+ "version": record.version,
1472
+ }
1473
+
1474
+
1475
+ def _goal_tool_error(error: GoalStoreError) -> ToolError:
1476
+ """Translate repository errors to safe, actionable MCP tool errors."""
1477
+ if isinstance(error, ActiveGoalExistsError):
1478
+ message = "This session already has an active goal. Use goal_get or update it."
1479
+ elif isinstance(error, GoalNotFoundError):
1480
+ message = "No goal with that ID exists in this session."
1481
+ elif isinstance(error, GoalVersionConflictError):
1482
+ message = (
1483
+ "The goal changed since the supplied version. Call goal_get and retry "
1484
+ "with its current version."
1485
+ )
1486
+ elif isinstance(error, GoalValidationError):
1487
+ message = f"Invalid goal request: {error}"
1488
+ elif isinstance(error, GoalSchemaNotInitializedError | GoalSchemaVersionError):
1489
+ message = str(error)
1490
+ else:
1491
+ message = "Goal storage is unavailable; no database details were exposed."
1492
+ return ToolError(message)
575
1493
 
576
1494
 
577
1495
  @mcp.tool(
578
- name="kv_delete_namespace",
1496
+ name="goal_create",
579
1497
  description=(
580
- "Delete all entries in a namespace. Optionally limit to entries older "
581
- "than N days."
1498
+ "Create one active manual goal for the current OpenCode session in this "
1499
+ "Persistence deployment database. Session identity comes from "
1500
+ "host request metadata, not tool arguments. Completed goals remain in "
1501
+ "history and allow a new goal. This does not trigger continuation."
582
1502
  ),
583
1503
  )
584
- async def kv_delete_namespace(
585
- namespace: str,
586
- scope: str = "project",
587
- older_than_days: int | None = None,
588
- ) -> dict:
589
- """Delete all entries in a namespace, optionally old entries only.
1504
+ async def goal_create(
1505
+ title: Annotated[str, Field(min_length=1, max_length=GOAL_TITLE_MAX_LENGTH)],
1506
+ context: Context,
1507
+ description: Annotated[
1508
+ str | None, Field(max_length=GOAL_DESCRIPTION_MAX_LENGTH)
1509
+ ] = None,
1510
+ ) -> dict[str, object]:
1511
+ """Create the current session's single active manual goal."""
1512
+ try:
1513
+ record = create_goal(
1514
+ session_id=_session_id_from_context(context),
1515
+ title=title,
1516
+ description=description,
1517
+ )
1518
+ except GoalStoreError as exc:
1519
+ raise _goal_tool_error(exc) from None
1520
+ return {"goal": _public_goal(record)}
590
1521
 
591
- Args:
592
- namespace: Namespace to clear.
593
- scope: 'project' (default) or 'global'.
594
- older_than_days: If set, only delete entries older than this many days.
595
1522
 
596
- Returns:
597
- Dict with deleted count.
598
- """
599
- conn = _db(scope)
1523
+ @mcp.tool(
1524
+ name="goal_get",
1525
+ description=(
1526
+ "Read a goal owned by the current OpenCode session. Omit goal_id to "
1527
+ "get its active goal, or its latest completed goal when none is active. "
1528
+ "The returned version is required for goal_update and goal_done."
1529
+ ),
1530
+ )
1531
+ async def goal_get(
1532
+ context: Context,
1533
+ goal_id: Annotated[str | None, Field(max_length=GOAL_ID_MAX_LENGTH)] = None,
1534
+ ) -> dict[str, object | None]:
1535
+ """Read the current session's active goal or retained history entry."""
1536
+ try:
1537
+ record = get_goal(session_id=_session_id_from_context(context), goal_id=goal_id)
1538
+ except GoalStoreError as exc:
1539
+ raise _goal_tool_error(exc) from None
1540
+ return {"goal": _public_goal(record)}
600
1541
 
601
- if older_than_days is not None:
602
- cursor = conn.execute(
603
- "DELETE FROM kv_store WHERE namespace = ? "
604
- "AND datetime(created_at) < datetime('now', ? || ' days')",
605
- (namespace, f"-{older_than_days}"),
606
- )
607
- else:
608
- cursor = conn.execute(
609
- "DELETE FROM kv_store WHERE namespace = ?",
610
- (namespace,),
1542
+
1543
+ @mcp.tool(
1544
+ name="goal_update",
1545
+ description=(
1546
+ "Edit title and/or description of a goal owned by the current session. "
1547
+ "Supply the version returned by goal_get; stale writes conflict. Status "
1548
+ "and timestamps are server-owned, and a completed goal cannot be reopened. "
1549
+ "Set clear_description=true to remove its optional description."
1550
+ ),
1551
+ )
1552
+ async def goal_update(
1553
+ context: Context,
1554
+ goal_id: Annotated[str, Field(min_length=1, max_length=GOAL_ID_MAX_LENGTH)],
1555
+ expected_version: Annotated[int, Field(strict=True, ge=1, le=GOAL_VERSION_MAX)],
1556
+ title: Annotated[
1557
+ str | None, Field(min_length=1, max_length=GOAL_TITLE_MAX_LENGTH)
1558
+ ] = None,
1559
+ description: Annotated[
1560
+ str | None, Field(max_length=GOAL_DESCRIPTION_MAX_LENGTH)
1561
+ ] = None,
1562
+ clear_description: bool = False,
1563
+ ) -> dict[str, object]:
1564
+ """Update only user-editable fields using the returned optimistic version."""
1565
+ if clear_description and description is not None:
1566
+ raise ToolError("Provide description or clear_description, not both.")
1567
+ changes: dict[str, object] = {}
1568
+ if title is not None:
1569
+ changes["title"] = title
1570
+ if description is not None:
1571
+ changes["description"] = description
1572
+ elif clear_description:
1573
+ changes["description"] = None
1574
+ if not changes:
1575
+ raise ToolError("Provide a title, description, or clear_description change.")
1576
+ try:
1577
+ record = update_goal(
1578
+ session_id=_session_id_from_context(context),
1579
+ goal_id=goal_id,
1580
+ expected_version=expected_version,
1581
+ **changes,
611
1582
  )
612
- conn.commit()
1583
+ except GoalStoreError as exc:
1584
+ raise _goal_tool_error(exc) from None
1585
+ return {"goal": _public_goal(record)}
1586
+
613
1587
 
614
- return {"deleted": cursor.rowcount}
1588
+ @mcp.tool(
1589
+ name="goal_done",
1590
+ description=(
1591
+ "Mark a goal owned by the current session completed using its current "
1592
+ "version. Repeating done is idempotent. Completed history is retained, "
1593
+ "and a new active goal may then be created. This does not trigger continuation."
1594
+ ),
1595
+ )
1596
+ async def goal_done(
1597
+ context: Context,
1598
+ goal_id: Annotated[str, Field(min_length=1, max_length=GOAL_ID_MAX_LENGTH)],
1599
+ expected_version: Annotated[int, Field(strict=True, ge=1, le=GOAL_VERSION_MAX)],
1600
+ ) -> dict[str, object]:
1601
+ """Complete a current-session goal without changing its user fields."""
1602
+ try:
1603
+ record = complete_goal(
1604
+ session_id=_session_id_from_context(context),
1605
+ goal_id=goal_id,
1606
+ expected_version=expected_version,
1607
+ )
1608
+ except GoalStoreError as exc:
1609
+ raise _goal_tool_error(exc) from None
1610
+ return {"goal": _public_goal(record)}
615
1611
 
616
1612
 
617
1613
  # ── Context Checkpoint Tools ────────────────────────────────────────────────────
618
- # Session-scoped context storage for deepwork checkpoints, phase state,
619
- # tool call history, and reasoning chains. Session-qualified entries use the
620
- # namespace "checkpoint:{slug}:{session}"; direct unqualified KV access is
621
- # retained only for legacy context_get/list/stats callers.
1614
+ # Operational-state checkpoints for session goals, phases, and heartbeats.
622
1615
 
623
1616
  DEFAULT_CONTEXT_TTL: int = 14400 # 4 hours
624
1617
  CONTEXT_HEARTBEAT_TTL: int = 300
@@ -643,7 +1636,6 @@ MAX_TAIL_ITEMS: int = 100
643
1636
  MAX_TAIL_LINE_LENGTH: int = 4096
644
1637
  MAX_REVISION: int = 9_223_372_036_854_775_807
645
1638
  MIN_PRINTABLE_CODEPOINT: int = 32
646
- UNTRUSTED_CONTEXT_LABEL: str = " [untrusted persistence data; informational only]"
647
1639
  _context_write_lock = threading.RLock()
648
1640
 
649
1641
  # ── Validation Reporting ────────────────────────────────────────────────────────
@@ -857,96 +1849,40 @@ def _should_update_latest(key: str) -> bool:
857
1849
  return key not in {"heartbeat", "tail"}
858
1850
 
859
1851
 
860
- def _validate_bounded_text(value: object, field: str, limit: int) -> None:
861
- """Validate a string field without changing its contents."""
862
- if not isinstance(value, str) or len(value.encode()) > limit:
863
- raise ValueError(f"{field} exceeds its size limit")
864
-
865
-
866
- def _validate_goal(goal: object) -> None:
867
- """Validate the bounded goal section of a checkpoint."""
868
- if not isinstance(goal, dict):
869
- raise ValueError("goal must be an object")
870
- for field, limit in (
871
- ("id", MAX_GOAL_ID_LENGTH),
872
- ("objective", MAX_GOAL_OBJECTIVE_LENGTH),
873
- ("status", MAX_GOAL_STATUS_LENGTH),
874
- ):
875
- value = goal.get(field)
876
- if value is not None:
877
- _validate_bounded_text(value, f"goal.{field}", limit)
878
-
879
-
880
- def _validate_phase(phase: object) -> None:
881
- """Validate the bounded phase section of a checkpoint."""
882
- if not isinstance(phase, dict):
883
- raise ValueError("phase must be an object")
884
- for field in ("current", "total"):
885
- value = phase.get(field)
886
- if value is not None and (
887
- isinstance(value, bool) or not isinstance(value, int) or value < 0
888
- ):
889
- raise ValueError(f"phase.{field} must be a non-negative integer")
890
- name = phase.get("name")
891
- if name is not None:
892
- _validate_bounded_text(name, "phase.name", MAX_PHASE_NAME_LENGTH)
893
-
894
-
895
- def _validate_delegations(delegations: object) -> None:
896
- """Validate bounded in-flight delegation records."""
897
- if not isinstance(delegations, dict):
898
- raise ValueError("delegations must be an object")
899
- in_flight = delegations.get("in_flight")
900
- if in_flight is None:
901
- return
902
- if not isinstance(in_flight, list) or len(in_flight) > MAX_DELEGATIONS:
903
- raise ValueError("delegations.in_flight exceeds its size limit")
904
- for job in in_flight:
905
- if not isinstance(job, dict):
906
- raise ValueError("delegations.in_flight entries must be objects")
907
- for field in ("alias", "agent", "task_id"):
908
- value = job.get(field)
909
- if value is not None:
910
- _validate_bounded_text(
911
- value, f"delegations.in_flight.{field}", MAX_DELEGATION_FIELD_LENGTH
912
- )
913
-
914
-
915
- def _validate_tail(tail: object, payload_bytes: int | None = None) -> list[str]:
1852
+ def _validate_tail(tail: object) -> list[str]:
916
1853
  """Validate bounded serialized tail lines."""
917
- if not isinstance(tail, list) or len(tail) > MAX_TAIL_ITEMS:
918
- raise ValueError("tail exceeds its size limit")
1854
+ if not isinstance(tail, list):
1855
+ raise ValueError("tail must be an array")
1856
+ if len(tail) > MAX_TAIL_ITEMS:
1857
+ raise ValueError(
1858
+ f"tail has {len(tail)} items; maximum is {MAX_TAIL_ITEMS}; "
1859
+ "remove tail entries or omit tail"
1860
+ )
919
1861
  for line in tail:
920
- if not isinstance(line, str) or len(line.encode()) > MAX_TAIL_LINE_LENGTH:
921
- raise ValueError("tail entries exceed their size limit")
922
- if payload_bytes is not None and payload_bytes > MAX_CONTEXT_CONTENT_BYTES:
923
- raise ValueError("tail payload exceeds its size limit")
924
- if sum(len(line.encode()) for line in tail) > MAX_CONTEXT_CONTENT_BYTES:
925
- raise ValueError("tail payload exceeds its size limit")
1862
+ if not isinstance(line, str):
1863
+ raise ValueError("tail entries must be strings")
1864
+ line_bytes = len(line.encode())
1865
+ if line_bytes > MAX_TAIL_LINE_LENGTH:
1866
+ raise ValueError(
1867
+ f"tail entries are {line_bytes:,} UTF-8 bytes; maximum is "
1868
+ f"{MAX_TAIL_LINE_LENGTH:,}; remove or shorten tail entries, "
1869
+ "or omit tail"
1870
+ )
1871
+ tail_bytes = sum(len(line.encode()) for line in tail)
1872
+ if tail_bytes > MAX_CONTEXT_CONTENT_BYTES:
1873
+ raise ValueError(
1874
+ f"tail contains {tail_bytes:,} UTF-8 bytes across strings; maximum "
1875
+ f"is {MAX_CONTEXT_CONTENT_BYTES:,} bytes; remove tail entries or "
1876
+ "omit tail"
1877
+ )
926
1878
  return tail
927
1879
 
928
1880
 
929
- def _validate_heartbeat(heartbeat: object) -> None:
930
- """Validate bounded heartbeat metadata."""
931
- if not isinstance(heartbeat, dict):
932
- raise ValueError("heartbeat must be an object")
933
- status = heartbeat.get("status")
934
- if status is not None:
935
- _validate_bounded_text(status, "heartbeat.status", MAX_GOAL_STATUS_LENGTH)
936
- turn_count = heartbeat.get("turn_count")
937
- if turn_count is not None and (
938
- isinstance(turn_count, bool)
939
- or not isinstance(turn_count, int)
940
- or turn_count < 0
941
- ):
942
- raise ValueError("heartbeat.turn_count must be a non-negative integer")
943
-
944
-
945
1881
  def _validate_version_metadata(version: object) -> None:
946
1882
  """Validate optional checkpoint ``version`` metadata leniently.
947
1883
 
948
- ``version`` is opaque application metadata (rehydrate does not consume it),
949
- not a persistence requirement. It may be a positive integer, a JSON float
1884
+ ``version`` is opaque application metadata, not a persistence requirement.
1885
+ It may be a positive integer, a JSON float
950
1886
  such as ``1.0``, or a version label like ``"1.5.0-beta.2"``. Absent/null
951
1887
  versions and any non-empty string remain valid, preserving existing integer
952
1888
  checkpoints while allowing forward-compatible labels. Only bools, empty
@@ -957,7 +1893,7 @@ def _validate_version_metadata(version: object) -> None:
957
1893
  return
958
1894
  if isinstance(version, bool):
959
1895
  raise ValueError("version must be a positive integer or version label")
960
- if isinstance(version, (int, float)):
1896
+ if isinstance(version, int | float):
961
1897
  if not 1 <= version < float("inf"):
962
1898
  raise ValueError("version must be a positive integer or version label")
963
1899
  return
@@ -965,30 +1901,74 @@ def _validate_version_metadata(version: object) -> None:
965
1901
  raise ValueError("version must be a positive integer or version label")
966
1902
 
967
1903
 
968
- # (field, validator, python type, wording) in report order. ``tail`` is the one
969
- # array section; the rest are objects. ``None`` sections are OPTIONAL and are
970
- # never reported — heartbeat checkpoints omit goal/phase by design.
971
- CHECKPOINT_SECTIONS: tuple[tuple[str, Callable[[object], object], type, str], ...] = (
972
- ("goal", _validate_goal, dict, "an object"),
973
- ("phase", _validate_phase, dict, "an object"),
974
- ("delegations", _validate_delegations, dict, "an object"),
975
- ("tail", _validate_tail, list, "an array"),
976
- ("heartbeat", _validate_heartbeat, dict, "an object"),
977
- )
1904
+ def _validate_checkpoint_text_fields(
1905
+ section: Mapping[str, object],
1906
+ section_name: str,
1907
+ limits: tuple[tuple[str, int], ...],
1908
+ ) -> None:
1909
+ for field, limit in limits:
1910
+ value = section.get(field)
1911
+ if value is not None and (
1912
+ not isinstance(value, str) or len(value.encode()) > limit
1913
+ ):
1914
+ raise ValueError(f"{section_name}.{field} exceeds its size limit")
1915
+
978
1916
 
1917
+ def _validate_checkpoint_integer_fields(
1918
+ section: Mapping[str, object], section_name: str, fields: tuple[str, ...]
1919
+ ) -> None:
1920
+ for field in fields:
1921
+ value = section.get(field)
1922
+ if value is not None and (
1923
+ isinstance(value, bool) or not isinstance(value, int) or value < 0
1924
+ ):
1925
+ raise ValueError(f"{section_name}.{field} must be a non-negative integer")
979
1926
 
980
- def _validate_checkpoint_shape(checkpoint: dict) -> None:
981
- """Validate bounded structured checkpoint fields without sanitizing them.
982
1927
 
983
- Fail-fast on purpose: the read path needs only a yes/no verdict.
984
- ``context_save`` uses ``_collect_checkpoint_errors`` so a single call
985
- reports every invalid section instead of only the first.
986
- """
987
- _validate_version_metadata(checkpoint.get("version"))
988
- for field, validator, _expected_type, _wording in CHECKPOINT_SECTIONS:
989
- value = checkpoint.get(field)
990
- if value is not None:
991
- validator(value)
1928
+ def _validate_checkpoint_delegations(section: dict) -> None:
1929
+ in_flight = section.get("in_flight")
1930
+ if in_flight is None:
1931
+ return
1932
+ if not isinstance(in_flight, list) or len(in_flight) > MAX_DELEGATIONS:
1933
+ raise ValueError("delegations.in_flight exceeds its size limit")
1934
+ for job in in_flight:
1935
+ if not isinstance(job, dict):
1936
+ raise ValueError("delegations.in_flight entries must be objects")
1937
+ _validate_checkpoint_text_fields(
1938
+ job,
1939
+ "delegations.in_flight",
1940
+ tuple(
1941
+ (field, MAX_DELEGATION_FIELD_LENGTH)
1942
+ for field in ("alias", "agent", "task_id")
1943
+ ),
1944
+ )
1945
+
1946
+
1947
+ def _validate_checkpoint_section(field: str, value: object) -> None:
1948
+ if field == "goal":
1949
+ _validate_checkpoint_text_fields(
1950
+ value,
1951
+ field,
1952
+ (
1953
+ ("id", MAX_GOAL_ID_LENGTH),
1954
+ ("objective", MAX_GOAL_OBJECTIVE_LENGTH),
1955
+ ("status", MAX_GOAL_STATUS_LENGTH),
1956
+ ),
1957
+ )
1958
+ elif field == "phase":
1959
+ _validate_checkpoint_integer_fields(value, field, ("current", "total"))
1960
+ _validate_checkpoint_text_fields(
1961
+ value, field, (("name", MAX_PHASE_NAME_LENGTH),)
1962
+ )
1963
+ elif field == "delegations":
1964
+ _validate_checkpoint_delegations(value)
1965
+ elif field == "tail":
1966
+ _validate_tail(value)
1967
+ elif field == "heartbeat":
1968
+ _validate_checkpoint_text_fields(
1969
+ value, field, (("status", MAX_GOAL_STATUS_LENGTH),)
1970
+ )
1971
+ _validate_checkpoint_integer_fields(value, field, ("turn_count",))
992
1972
 
993
1973
 
994
1974
  def _collect_checkpoint_errors(errors: _ArgErrors, parsed: dict, prefix: str) -> None:
@@ -998,7 +1978,14 @@ def _collect_checkpoint_errors(errors: _ArgErrors, parsed: dict, prefix: str) ->
998
1978
  except ValueError as exc:
999
1979
  errors.reroot(prefix, str(exc))
1000
1980
 
1001
- for field, validator, expected_type, wording in CHECKPOINT_SECTIONS:
1981
+ sections = (
1982
+ ("goal", dict, "an object"),
1983
+ ("phase", dict, "an object"),
1984
+ ("delegations", dict, "an object"),
1985
+ ("tail", list, "an array"),
1986
+ ("heartbeat", dict, "an object"),
1987
+ )
1988
+ for field, expected_type, wording in sections:
1002
1989
  value = parsed.get(field)
1003
1990
  if value is None:
1004
1991
  continue
@@ -1008,7 +1995,7 @@ def _collect_checkpoint_errors(errors: _ArgErrors, parsed: dict, prefix: str) ->
1008
1995
  )
1009
1996
  continue
1010
1997
  try:
1011
- validator(value)
1998
+ _validate_checkpoint_section(field, value)
1012
1999
  except ValueError as exc:
1013
2000
  errors.reroot(prefix, str(exc))
1014
2001
 
@@ -1020,21 +2007,25 @@ def _collect_context_content_errors(
1020
2007
  if not isinstance(content, str):
1021
2008
  errors.shape(prefix, "a string", content)
1022
2009
  return
1023
- if len(content.encode()) > MAX_CONTEXT_CONTENT_BYTES:
1024
- errors.add(prefix, f"exceeds the {MAX_CONTEXT_CONTENT_BYTES}-byte limit")
2010
+ content_bytes = len(content.encode())
2011
+ if content_bytes > MAX_CONTEXT_CONTENT_BYTES:
2012
+ errors.add(
2013
+ prefix,
2014
+ f"is {content_bytes:,} UTF-8 bytes; maximum is "
2015
+ f"{MAX_CONTEXT_CONTENT_BYTES:,} bytes. Reduce content or omit "
2016
+ "optional tail if it contributes",
2017
+ )
1025
2018
  return
1026
2019
  try:
1027
2020
  parsed = json.loads(content)
1028
2021
  except (json.JSONDecodeError, TypeError, ValueError):
1029
- # Raw text remains a compatibility format, but rehydrate never treats
1030
- # it as a checkpoint. It is still bounded above.
2022
+ # Raw text remains a compatibility format. It is still bounded above.
1031
2023
  return
1032
2024
  if isinstance(parsed, list) and key == "tail":
1033
- if len(parsed) > MAX_TAIL_ITEMS or any(
1034
- not isinstance(line, str) or len(line.encode()) > MAX_TAIL_LINE_LENGTH
1035
- for line in parsed
1036
- ):
1037
- errors.add(f"{prefix}.tail", "exceeds its size limit")
2025
+ try:
2026
+ _validate_tail(parsed)
2027
+ except ValueError as exc:
2028
+ errors.reroot(prefix, str(exc))
1038
2029
  return
1039
2030
  if not isinstance(parsed, dict):
1040
2031
  # The message already names 'content': do not prepend the path again.
@@ -1068,18 +2059,6 @@ def _collect_scope_error(errors: _ArgErrors, scope: str) -> None:
1068
2059
  errors.example(SCOPE_EXAMPLE)
1069
2060
 
1070
2061
 
1071
- def _safe_untrusted_text(value: object) -> str:
1072
- """Escape control/markup delimiters while preserving untrusted content."""
1073
- text = str(value)
1074
- return (
1075
- text.replace("<", r"\u003c")
1076
- .replace(">", r"\u003e")
1077
- .replace("\r", r"\r")
1078
- .replace("\n", r"\n")
1079
- .replace("\x00", r"\u0000")
1080
- )
1081
-
1082
-
1083
2062
  def _stored_revision(raw: object) -> int:
1084
2063
  """Parse a context revision; legacy datetime values are revision zero."""
1085
2064
  try:
@@ -1163,7 +2142,12 @@ def _upsert_context_entry(
1163
2142
  @mcp.tool(
1164
2143
  name="context_save",
1165
2144
  description="Save a context checkpoint for a session/phase. "
1166
- "Stores structured JSON in persistence KV with a key-specific TTL. "
2145
+ "Stores structured operational-state checkpoint data with key-specific expiry. "
2146
+ "The serialized content is limited to 65,536 UTF-8 bytes. An included "
2147
+ "tail may contain at most 100 strings, each at most 4,096 UTF-8 bytes, "
2148
+ "with at most 65,536 UTF-8 bytes across all tail strings. Oversized "
2149
+ "content or tail is rejected, never truncated; remove or omit optional "
2150
+ "tail data when applicable. "
1167
2151
  "content is a JSON STRING; when it parses to an object, 'goal', 'phase', "
1168
2152
  "'delegations' and 'heartbeat' must each be JSON OBJECTS and 'tail' must "
1169
2153
  "be a JSON ARRAY. 'phase' is an object {current,total,name} — NOT a phase "
@@ -1180,7 +2164,12 @@ async def context_save(
1180
2164
  str,
1181
2165
  Field(
1182
2166
  description=(
1183
- "JSON checkpoint string. When it parses to an object, 'goal', "
2167
+ "JSON checkpoint string, limited to 65,536 UTF-8 bytes. An "
2168
+ "included 'tail' may contain at most 100 strings, each at "
2169
+ "most 4,096 UTF-8 bytes, with at most 65,536 UTF-8 bytes "
2170
+ "across all tail strings. Oversized input is rejected, never "
2171
+ "truncated; remove or omit optional 'tail' when applicable. "
2172
+ "When it parses to an object, 'goal', "
1184
2173
  "'phase', 'delegations' and 'heartbeat' must be objects and "
1185
2174
  "'tail' must be an array; all are optional. 'phase' is an "
1186
2175
  "object {current,total,name}, not a counter. Example: "
@@ -1193,11 +2182,9 @@ async def context_save(
1193
2182
  scope: str = "project",
1194
2183
  revision: int | None = None,
1195
2184
  ) -> dict:
1196
- """Save a context checkpoint with session-level isolation.
2185
+ """Save an operational-state checkpoint for the supplied session ID.
1197
2186
 
1198
- Namespace is always "checkpoint:{slug}:{session_id}", preventing
1199
- cross-session reads. The session_id must be supplied by the autonomy
1200
- caller; this function never generates one.
2187
+ The caller must supply the session ID; this function never generates one.
1201
2188
 
1202
2189
  Every argument is validated before any write, and all violations are
1203
2190
  reported in a single error so the caller fixes them in one round-trip.
@@ -1206,13 +2193,13 @@ async def context_save(
1206
2193
  slug: Session identifier (e.g. "auth-refactor").
1207
2194
  key: Checkpoint key (e.g. "phase:3", "latest", "heartbeat").
1208
2195
  content: JSON-serializable string or any text content.
1209
- session_id: Required unique session ID for namespace isolation.
2196
+ session_id: Required session ID associated with this checkpoint.
1210
2197
  ttl: TTL in seconds (defaults to the key-specific context policy).
1211
2198
  scope: 'project' (default) or 'global'.
1212
2199
  revision: Optional monotonic revision. Older/equal revisions are no-ops.
1213
2200
 
1214
2201
  Returns:
1215
- Status dict with namespace, key, and session_id for subsequent calls.
2202
+ Status dict with checkpoint key and session ID for subsequent calls.
1216
2203
  """
1217
2204
  errors = _ArgErrors("context_save")
1218
2205
  valid_slug = _collect_identifier(errors, slug, "slug", MAX_CONTEXT_SLUG_LENGTH)
@@ -1305,14 +2292,13 @@ async def context_get(
1305
2292
  legacy: bool = False,
1306
2293
  scope: str = "project",
1307
2294
  ) -> str | None:
1308
- """Get a context checkpoint with session isolation.
2295
+ """Get an operational-state checkpoint by slug and key.
1309
2296
 
1310
2297
  Args:
1311
2298
  slug: Session identifier.
1312
2299
  key: Checkpoint key (default "latest").
1313
2300
  session_id: Required for session-scoped reads.
1314
- legacy: Explicitly opt into the unqualified legacy namespace when no
1315
- session_id is available.
2301
+ legacy: Explicitly opt into reading the pre-session checkpoint format.
1316
2302
  scope: 'project' (default) or 'global'.
1317
2303
 
1318
2304
  Returns:
@@ -1336,507 +2322,6 @@ async def context_get(
1336
2322
  return row[0] if row else None
1337
2323
 
1338
2324
 
1339
- @mcp.tool(
1340
- name="context_list",
1341
- description="List all context checkpoints for a session slug. "
1342
- "Returns keys, timestamps, and TTL info.",
1343
- )
1344
- async def context_list(
1345
- slug: str,
1346
- session_id: str | None = None,
1347
- legacy: bool = False,
1348
- scope: str = "project",
1349
- ) -> list[dict]:
1350
- """List all checkpoints for a session.
1351
-
1352
- Args:
1353
- slug: Session identifier.
1354
- session_id: Required for session-scoped reads.
1355
- legacy: Explicitly opt into the unqualified legacy namespace when no
1356
- session_id is available.
1357
- scope: 'project' (default) or 'global'.
1358
-
1359
- Returns:
1360
- List of dicts with key, created_at, expires_at.
1361
- """
1362
- conn = _db(scope)
1363
- ns = _context_namespace(slug, session_id, legacy=legacy)
1364
- if ns is None:
1365
- return []
1366
- rows = conn.execute(
1367
- "SELECT key, created_at, expires_at FROM kv_store "
1368
- "WHERE namespace = ? "
1369
- "AND (expires_at IS NULL OR julianday(expires_at) > julianday('now')) "
1370
- "AND deleted_at IS NULL "
1371
- "ORDER BY created_at DESC LIMIT 50",
1372
- (ns,),
1373
- ).fetchall()
1374
- return [
1375
- {
1376
- "key": r[0],
1377
- "created_at": r[1],
1378
- "expires_at": r[2],
1379
- }
1380
- for r in rows
1381
- ]
1382
-
1383
-
1384
- @mcp.tool(
1385
- name="context_stats",
1386
- description="Return session context statistics: "
1387
- "checkpoint count, TTL remaining, total size per slug.",
1388
- )
1389
- async def context_stats(
1390
- slug: str,
1391
- session_id: str | None = None,
1392
- legacy: bool = False,
1393
- scope: str = "project",
1394
- ) -> dict:
1395
- """Return storage statistics for a session's context.
1396
-
1397
- Args:
1398
- slug: Session identifier.
1399
- session_id: Required for session-scoped reads.
1400
- legacy: Explicitly opt into the unqualified legacy namespace when no
1401
- session_id is available.
1402
- scope: 'project' (default) or 'global'.
1403
-
1404
- Returns:
1405
- Dict with entry_count, total_bytes, ttl_remaining.
1406
- """
1407
- conn = _db(scope)
1408
- ns = _context_namespace(slug, session_id, legacy=legacy)
1409
- if ns is None:
1410
- return {
1411
- "slug": slug,
1412
- "namespace": None,
1413
- "entry_count": 0,
1414
- "expired_entries": 0,
1415
- "total_bytes": 0,
1416
- "ttl_remaining_seconds": None,
1417
- }
1418
-
1419
- count = conn.execute(
1420
- "SELECT COUNT(*) FROM kv_store "
1421
- "WHERE namespace = ? AND deleted_at IS NULL "
1422
- "AND (expires_at IS NULL OR julianday(expires_at) > julianday('now'))",
1423
- (ns,),
1424
- ).fetchone()[0]
1425
-
1426
- expired = conn.execute(
1427
- "SELECT COUNT(*) FROM kv_store "
1428
- "WHERE namespace = ? AND expires_at IS NOT NULL "
1429
- "AND julianday(expires_at) <= julianday('now') "
1430
- "AND deleted_at IS NULL",
1431
- (ns,),
1432
- ).fetchone()[0]
1433
-
1434
- size = conn.execute(
1435
- "SELECT COALESCE(SUM(LENGTH(value)), 0) FROM kv_store "
1436
- "WHERE namespace = ? AND deleted_at IS NULL "
1437
- "AND (expires_at IS NULL OR julianday(expires_at) > julianday('now'))",
1438
- (ns,),
1439
- ).fetchone()[0]
1440
-
1441
- # Check TTL of latest entry
1442
- remaining: int | None = None
1443
- row = conn.execute(
1444
- "SELECT expires_at FROM kv_store "
1445
- "WHERE namespace = ? AND key = 'latest' AND deleted_at IS NULL",
1446
- (ns,),
1447
- ).fetchone()
1448
- if row and row[0]:
1449
- try:
1450
- exp = datetime.fromisoformat(row[0])
1451
- now = datetime.now(UTC)
1452
- remaining = max(0, int((exp - now).total_seconds()))
1453
- except (ValueError, TypeError):
1454
- pass
1455
-
1456
- return {
1457
- "slug": slug,
1458
- "namespace": ns,
1459
- "entry_count": count,
1460
- "expired_entries": expired,
1461
- "total_bytes": size,
1462
- "ttl_remaining_seconds": remaining,
1463
- }
1464
-
1465
-
1466
- # ── Post-Compaction Injector (WS2 PR #94) ─────────────────────────────────────
1467
- # Deterministic rehydration after a native compaction event: a long session
1468
- # reads ``latest`` + serialized ``tail`` from
1469
- # ``checkpoint:<slug>:<session_id>`` and
1470
- # rebuilds its critical context (active goal, in-flight delegations,
1471
- # current phase) WITHOUT any LLM call or generative embedding.
1472
- #
1473
- # Checkpoint JSON convention (written by Zeus via context_save):
1474
- # {"version": 1,
1475
- # "goal": {"id": ..., "objective": ..., "status": ...},
1476
- # "phase": {"current": ..., "total": ..., "name": ...},
1477
- # "delegations": {"in_flight": [{"alias": ..., "agent": ..., "task_id": ...}]},
1478
- # "tail": ["phase:1 ...", ...], # serialized last-N phase digests
1479
- # "heartbeat": {...}}
1480
- # ``tail`` may also live under a separate ``tail`` key (JSON array).
1481
- #
1482
- # Guarantees: required session_id, kill-switch PANTHEON_COMPACTION=off,
1483
- # TTL-respecting reads, no sibling fallback, conditional heartbeat TTL refresh,
1484
- # and idempotent recovery (no checkpoint rows are added or duplicated).
1485
-
1486
- COMPACTION_KILL_SWITCH_ENV: str = "PANTHEON_COMPACTION"
1487
- SESSION_END_SUMMARY_ENV: str = "PANTHEON_SESSION_END_SUMMARY"
1488
- REHYDRATE_TAIL_CAP: int = 10
1489
- SUMMARY_TAIL_CAP: int = 5
1490
-
1491
-
1492
- def _compaction_disabled() -> bool:
1493
- """True when the PANTHEON_COMPACTION kill-switch is off."""
1494
- return os.environ.get(COMPACTION_KILL_SWITCH_ENV, "").lower() == "off"
1495
-
1496
-
1497
- def _read_checkpoint_value(
1498
- conn: sqlite3.Connection, namespace: str, key: str
1499
- ) -> str | None:
1500
- """Read one unexpired, non-deleted checkpoint value (None when absent)."""
1501
- row = conn.execute(
1502
- "SELECT value FROM kv_store "
1503
- "WHERE namespace = ? AND key = ? "
1504
- "AND (expires_at IS NULL OR julianday(expires_at) > julianday('now')) "
1505
- "AND deleted_at IS NULL",
1506
- (namespace, key),
1507
- ).fetchone()
1508
- return row[0] if row else None
1509
-
1510
-
1511
- def _parse_checkpoint(content: str) -> dict | None:
1512
- """Parse and validate one checkpoint; invalid JSON fails closed."""
1513
- if len(content.encode()) > MAX_CONTEXT_CONTENT_BYTES:
1514
- return None
1515
- try:
1516
- data = json.loads(content)
1517
- except (json.JSONDecodeError, TypeError, ValueError):
1518
- return None
1519
- if not isinstance(data, dict):
1520
- return None
1521
- try:
1522
- _validate_checkpoint_shape(data)
1523
- except ValueError:
1524
- return None
1525
- return data
1526
-
1527
-
1528
- def _checkpoint_tail(checkpoint: dict, tail_raw: str | None) -> list[str]:
1529
- """Tail lines from embedded ``tail`` with fallback to the ``tail`` key."""
1530
- tail = checkpoint.get("tail")
1531
- if isinstance(tail, list):
1532
- try:
1533
- lines = _validate_tail(tail)
1534
- except ValueError:
1535
- return []
1536
- elif isinstance(tail_raw, str):
1537
- if len(tail_raw.encode()) > MAX_CONTEXT_CONTENT_BYTES:
1538
- return []
1539
- try:
1540
- parsed = json.loads(tail_raw)
1541
- lines = _validate_tail(parsed, payload_bytes=len(tail_raw.encode()))
1542
- except (json.JSONDecodeError, TypeError, ValueError):
1543
- return []
1544
- else:
1545
- lines = []
1546
- return [line for line in lines if line.strip()][:REHYDRATE_TAIL_CAP]
1547
-
1548
-
1549
- def _mission_block(checkpoint: dict) -> str | None:
1550
- """<mission_context> for a non-done goal (done goals stay buried)."""
1551
- goal = checkpoint.get("goal")
1552
- if not isinstance(goal, dict):
1553
- return None
1554
- status = str(goal.get("status", ""))
1555
- objective = str(goal.get("objective", "")).strip()
1556
- if status == "done" or not objective:
1557
- return None
1558
- gid = str(goal.get("id", "goal")).strip() or "goal"
1559
- return (
1560
- f"<mission_context>\n{UNTRUSTED_CONTEXT_LABEL}\n"
1561
- f" [{_safe_untrusted_text(gid)}] {_safe_untrusted_text(objective)}"
1562
- f" — {_safe_untrusted_text(status)}"
1563
- )
1564
-
1565
-
1566
- def _phase_block(checkpoint: dict) -> str | None:
1567
- """<phase_context> for the current phase (omitted when unknown)."""
1568
- phase = checkpoint.get("phase")
1569
- if not isinstance(phase, dict) or phase.get("current") is None:
1570
- return None
1571
- total = phase.get("total")
1572
- current = phase.get("current")
1573
- span = f"{current}/{total}" if total is not None else str(current)
1574
- name = str(phase.get("name", "")).strip()
1575
- line = f" phase {_safe_untrusted_text(span)}"
1576
- if name:
1577
- line += f" — {_safe_untrusted_text(name)}"
1578
- return f"<phase_context>\n{UNTRUSTED_CONTEXT_LABEL}\n{line}"
1579
-
1580
-
1581
- def _delegation_block(checkpoint: dict) -> str | None:
1582
- """<delegation_context> for in-flight delegations (never capped)."""
1583
- delegations = checkpoint.get("delegations")
1584
- if not isinstance(delegations, dict):
1585
- return None
1586
- in_flight = delegations.get("in_flight")
1587
- if not isinstance(in_flight, list):
1588
- return None
1589
- lines = []
1590
- for job in in_flight:
1591
- if not isinstance(job, dict):
1592
- continue
1593
- alias = str(job.get("alias") or job.get("task_id") or "?").strip()
1594
- agent = str(job.get("agent", "?")).strip()
1595
- task_id = str(job.get("task_id", "")).strip()
1596
- detail = (
1597
- f" — {_safe_untrusted_text(task_id)}"
1598
- if task_id and task_id != alias
1599
- else ""
1600
- )
1601
- lines.append(
1602
- f" [{_safe_untrusted_text(alias)}] {_safe_untrusted_text(agent)}"
1603
- f"{detail} [in-flight]"
1604
- )
1605
- if not lines:
1606
- return None
1607
- return "<delegation_context>\n" + UNTRUSTED_CONTEXT_LABEL + "\n" + "\n".join(lines)
1608
-
1609
-
1610
- def _tail_block(checkpoint: dict) -> str | None:
1611
- """<tail_context> for the serialized tail (already capped on load)."""
1612
- tail_lines = checkpoint.get("_tail_raw")
1613
- try:
1614
- validated_lines = _validate_tail(tail_lines)
1615
- except ValueError:
1616
- return None
1617
- if not validated_lines:
1618
- return None
1619
- quoted = "\n".join(f" - {_safe_untrusted_text(line)}" for line in validated_lines)
1620
- return f"<tail_context>\n{UNTRUSTED_CONTEXT_LABEL}\n{quoted}"
1621
-
1622
-
1623
- def build_rehydration_blocks(checkpoint: dict) -> list[str] | None:
1624
- """Build deterministic rehydration blocks from a checkpoint dict.
1625
-
1626
- Pure string templating — no LLM, no embeddings. Mirrors the
1627
- ``<mission_context>`` convention of the compaction-context builder: only a
1628
- non-done goal is re-emitted. Returns None when nothing critical remains.
1629
- """
1630
- if not isinstance(checkpoint, dict) or not checkpoint:
1631
- return None
1632
- blocks = [
1633
- block
1634
- for block in (
1635
- _mission_block(checkpoint),
1636
- _phase_block(checkpoint),
1637
- _delegation_block(checkpoint),
1638
- _tail_block(checkpoint),
1639
- )
1640
- if block is not None
1641
- ]
1642
- return blocks if blocks else None
1643
-
1644
-
1645
- def build_session_end_summary(checkpoint: dict) -> str | None:
1646
- """Build the Tier 2 session-end summary deterministically (no LLM).
1647
-
1648
- Fires automatically at session end — no Themis approval gate. Returns
1649
- None when the checkpoint carries nothing worth compressing.
1650
- """
1651
- if not isinstance(checkpoint, dict) or not checkpoint:
1652
- return None
1653
- parts: list[str] = []
1654
-
1655
- goal = checkpoint.get("goal")
1656
- if isinstance(goal, dict):
1657
- objective = str(goal.get("objective", "")).strip()
1658
- if objective:
1659
- parts.append(
1660
- f"Goal: {_safe_untrusted_text(objective)} "
1661
- f"({_safe_untrusted_text(goal.get('status', '?'))})"
1662
- )
1663
-
1664
- phase = checkpoint.get("phase")
1665
- if isinstance(phase, dict) and phase.get("current") is not None:
1666
- total = phase.get("total")
1667
- span = (
1668
- f"{phase.get('current')}/{total}"
1669
- if total is not None
1670
- else phase.get("current")
1671
- )
1672
- name = str(phase.get("name", "")).strip()
1673
- parts.append(
1674
- f"Phase: {_safe_untrusted_text(span)}"
1675
- + (f" {_safe_untrusted_text(name)}" if name else "")
1676
- )
1677
-
1678
- delegations = checkpoint.get("delegations")
1679
- if isinstance(delegations, dict):
1680
- in_flight = delegations.get("in_flight")
1681
- if isinstance(in_flight, list):
1682
- aliases = [
1683
- _safe_untrusted_text(str(job.get("alias") or job.get("task_id") or "?"))
1684
- for job in in_flight
1685
- if isinstance(job, dict)
1686
- ]
1687
- if aliases:
1688
- parts.append(f"In-flight: {', '.join(aliases)}")
1689
-
1690
- tail_raw = checkpoint.get("_tail_raw")
1691
- if isinstance(tail_raw, list) and tail_raw:
1692
- kept = [_safe_untrusted_text(str(line)) for line in tail_raw[:SUMMARY_TAIL_CAP]]
1693
- parts.append("Tail: " + " | ".join(kept))
1694
-
1695
- if not parts:
1696
- return None
1697
- return "# Session summary (Tier 2 auto — no approval gate)\n" + "\n".join(
1698
- f"- {part}" for part in parts
1699
- )
1700
-
1701
-
1702
- def _load_checkpoint_for_rehydrate(
1703
- conn: sqlite3.Connection, namespace: str
1704
- ) -> dict | None:
1705
- """Load exactly ``latest``; expired, malformed, or empty data fails closed."""
1706
- tail_raw = _read_checkpoint_value(conn, namespace, "tail")
1707
- raw = _read_checkpoint_value(conn, namespace, "latest")
1708
- if raw is None:
1709
- return None
1710
- checkpoint = _parse_checkpoint(raw)
1711
- if checkpoint is None:
1712
- return None
1713
- checkpoint["_tail_raw"] = _checkpoint_tail(checkpoint, tail_raw)
1714
- return checkpoint if build_rehydration_blocks(checkpoint) is not None else None
1715
-
1716
-
1717
- def _refresh_heartbeat_ttl(conn: sqlite3.Connection, namespace: str) -> None:
1718
- """Extend an unexpired heartbeat TTL; never shorten, never resurrect."""
1719
- row = conn.execute(
1720
- "SELECT expires_at FROM kv_store "
1721
- "WHERE namespace = ? AND key = 'heartbeat' "
1722
- "AND (expires_at IS NULL OR julianday(expires_at) > julianday('now')) "
1723
- "AND deleted_at IS NULL",
1724
- (namespace,),
1725
- ).fetchone()
1726
- if not row or not row[0]:
1727
- return
1728
- try:
1729
- current_exp = datetime.fromisoformat(row[0])
1730
- except (ValueError, TypeError):
1731
- return
1732
- now = datetime.now(UTC)
1733
- if current_exp.tzinfo is None:
1734
- current_exp = current_exp.replace(tzinfo=UTC)
1735
- fresh_exp = now + timedelta(seconds=CONTEXT_HEARTBEAT_TTL)
1736
- if fresh_exp <= current_exp:
1737
- return
1738
- revision = _next_context_revision(conn, namespace, "heartbeat")
1739
- cursor = conn.execute(
1740
- "UPDATE kv_store SET expires_at = ?, updated_at = datetime('now'), "
1741
- "revision = ? "
1742
- "WHERE namespace = ? AND key = 'heartbeat' AND expires_at = ? "
1743
- "AND (expires_at IS NULL OR julianday(expires_at) > julianday('now')) "
1744
- "AND deleted_at IS NULL",
1745
- (fresh_exp.isoformat(), revision, namespace, row[0]),
1746
- )
1747
- if cursor.rowcount:
1748
- conn.commit()
1749
-
1750
-
1751
- @mcp.tool(
1752
- name="context_rehydrate",
1753
- description="Rehydrate critical context after native compaction. "
1754
- "Reads 'latest' + serialized 'tail' from a session-qualified checkpoint "
1755
- "namespace and rebuilds "
1756
- "goal/phase/delegation blocks deterministically (no LLM). Refreshes the "
1757
- "heartbeat TTL. Requires session_id and honors PANTHEON_COMPACTION=off.",
1758
- )
1759
- async def context_rehydrate(
1760
- slug: str,
1761
- session_id: str,
1762
- scope: str = "project",
1763
- ) -> list[str] | None:
1764
- """Rehydrate one known session; missing IDs fail closed."""
1765
- if _compaction_disabled():
1766
- return None
1767
- normalized_session = _normalize_session_id(session_id)
1768
- errors = _ArgErrors("context_rehydrate")
1769
- valid_slug = _collect_identifier(errors, slug, "slug", MAX_CONTEXT_SLUG_LENGTH)
1770
- if normalized_session is None:
1771
- errors.add("session_id", "is required and must be non-empty")
1772
- errors.example(SESSION_ID_EXAMPLE)
1773
- valid_session = None
1774
- else:
1775
- valid_session = _collect_identifier(
1776
- errors, normalized_session, "session_id", MAX_CONTEXT_SESSION_ID_LENGTH
1777
- )
1778
- _collect_scope_error(errors, scope)
1779
- errors.raise_if_any()
1780
- conn = _db(scope)
1781
- namespace = f"checkpoint:{valid_slug}:{valid_session}"
1782
- checkpoint = _load_checkpoint_for_rehydrate(conn, namespace)
1783
- if checkpoint is None:
1784
- return None
1785
- blocks = build_rehydration_blocks(checkpoint)
1786
- if blocks is None:
1787
- return None
1788
- _refresh_heartbeat_ttl(conn, namespace)
1789
- return blocks
1790
-
1791
-
1792
- @mcp.tool(
1793
- name="context_session_summary",
1794
- description="Tier 2 session-end summary without Themis approval. "
1795
- "Compresses the checkpoint (goal, phase, in-flight, tail) into a "
1796
- "memory-bank-ready summary deterministically (no LLM). "
1797
- "Requires session_id. Opt-out via PANTHEON_SESSION_END_SUMMARY=off.",
1798
- )
1799
- async def context_session_summary(
1800
- slug: str,
1801
- session_id: str,
1802
- scope: str = "project",
1803
- ) -> str | None:
1804
- """Summarize one known session; missing IDs fail closed."""
1805
- if os.environ.get(SESSION_END_SUMMARY_ENV, "").lower() == "off":
1806
- return None
1807
- normalized_session = _normalize_session_id(session_id)
1808
- errors = _ArgErrors("context_session_summary")
1809
- valid_slug = _collect_identifier(errors, slug, "slug", MAX_CONTEXT_SLUG_LENGTH)
1810
- if normalized_session is None:
1811
- errors.add("session_id", "is required and must be non-empty")
1812
- errors.example(SESSION_ID_EXAMPLE)
1813
- valid_session = None
1814
- else:
1815
- valid_session = _collect_identifier(
1816
- errors, normalized_session, "session_id", MAX_CONTEXT_SESSION_ID_LENGTH
1817
- )
1818
- _collect_scope_error(errors, scope)
1819
- errors.raise_if_any()
1820
- conn = _db(scope)
1821
- namespace = f"checkpoint:{valid_slug}:{valid_session}"
1822
- checkpoint = _load_checkpoint_for_rehydrate(conn, namespace)
1823
- if checkpoint is None:
1824
- return None
1825
- return build_session_end_summary(checkpoint)
1826
-
1827
-
1828
- def _resolve_db_path(scope: str) -> Path | None:
1829
- """Resolve the database file path for a given scope.
1830
-
1831
- Returns the actual path used at init (honoring an explicit
1832
- ``--project-db``), so deletelog writes and db_size stats land next to
1833
- the real database file.
1834
- """
1835
- if scope == "global":
1836
- return _global_root / "global.db"
1837
- return _project_db_path
1838
-
1839
-
1840
2325
  # ── Main Entrypoint ─────────────────────────────────────────────────────────────
1841
2326
 
1842
2327
  if __name__ == "__main__":