|
| 1 | +"""The versioned manifest of a Cortex backup (issue #731, slice 2). |
| 2 | +
|
| 3 | +A manifest names the class A resources of one install (user data that cannot be |
| 4 | +rebuilt) and gives a SHA-256 digest and a size for every file it carries. The |
| 5 | +resource table is the class A set of |
| 6 | +``docs/audits/owned-resources-backup-2026-11-05.md`` §2-3, by backend: |
| 7 | +
|
| 8 | +- every backend: backend marker, wiki pages, raw-output artifacts, MCP |
| 9 | + connection list, cognitive profiles (``domains/``, ``index.json``, legacy |
| 10 | + ``profiles.json*``), session log, capture spool; |
| 11 | +- ``sqlite``: ``methodology/memory.db`` (required); |
| 12 | +- ``managed``: the plugin-managed cluster and its password (both required; the |
| 13 | + password is marked ``secret``); |
| 14 | +- ``postgresql``: nothing more, the server is the user's (class X). |
| 15 | +
|
| 16 | +Paths are POSIX strings relative to the Cortex root (``~/.claude`` or |
| 17 | +``CORTEX_CLAUDE_DIR``). A store relocated outside the root |
| 18 | +(``CORTEX_MEMORY_DB_PATH``) is therefore absent, and a required absent resource |
| 19 | +is refused, never silently omitted. The SQLite ``-wal``/``-shm`` files are not |
| 20 | +entries: a backup carries one consistent copy of the database (slice 3), and the |
| 21 | +manifest describes the tree it is given. |
| 22 | +
|
| 23 | +Pure: the files are read and hashed by ``infrastructure/backup_scan.py``. |
| 24 | +
|
| 25 | +source: issue #731; docs/audits/owned-resources-backup-2026-11-05.md |
| 26 | +""" |
| 27 | + |
| 28 | +from __future__ import annotations |
| 29 | + |
| 30 | +import json |
| 31 | +import re |
| 32 | +from dataclasses import dataclass |
| 33 | +from typing import Any, Mapping, Sequence |
| 34 | + |
| 35 | +FORMAT = "cortex-backup-manifest" |
| 36 | +# source: issue #731 slice 2, the first format; bump on any change to the |
| 37 | +# resource table or to the entry and file fields below. |
| 38 | +VERSION = 1 |
| 39 | + |
| 40 | +SQLITE = "sqlite" |
| 41 | +MANAGED = "managed" |
| 42 | +POSTGRESQL = "postgresql" |
| 43 | +# The marker values of infrastructure/backend_marker.py MARKER_BACKENDS. |
| 44 | +BACKENDS = frozenset({SQLITE, MANAGED, POSTGRESQL}) |
| 45 | + |
| 46 | +FileRecord = tuple[str, str, int] # (path relative to the root, sha256 hex, size) |
| 47 | + |
| 48 | +_SHA256_HEX = re.compile(r"[0-9a-f]{64}") |
| 49 | + |
| 50 | + |
| 51 | +class ManifestError(ValueError): |
| 52 | + """A manifest cannot be built or read as asked; the message names why.""" |
| 53 | + |
| 54 | + |
| 55 | +@dataclass(frozen=True) |
| 56 | +class ResourceSpec: |
| 57 | + """One class A resource: where it lives under the root and for which backends.""" |
| 58 | + |
| 59 | + name: str |
| 60 | + path: str |
| 61 | + kind: str # "file" or "dir" |
| 62 | + backends: frozenset[str] |
| 63 | + required: bool |
| 64 | + secret: bool = False |
| 65 | + |
| 66 | + |
| 67 | +RESOURCES: tuple[ResourceSpec, ...] = ( |
| 68 | + ResourceSpec( |
| 69 | + "sqlite_store", "methodology/memory.db", "file", frozenset({SQLITE}), True |
| 70 | + ), |
| 71 | + ResourceSpec( |
| 72 | + "managed_cluster", |
| 73 | + "methodology/managed-pg/cluster", |
| 74 | + "dir", |
| 75 | + frozenset({MANAGED}), |
| 76 | + True, |
| 77 | + ), |
| 78 | + ResourceSpec( |
| 79 | + "managed_password", |
| 80 | + "methodology/managed-pg/password", |
| 81 | + "file", |
| 82 | + frozenset({MANAGED}), |
| 83 | + True, |
| 84 | + secret=True, |
| 85 | + ), |
| 86 | + ResourceSpec("backend_marker", "methodology/backend.json", "file", BACKENDS, False), |
| 87 | + ResourceSpec("wiki", "methodology/wiki", "dir", BACKENDS, False), |
| 88 | + ResourceSpec("artifacts", "methodology/artifacts", "dir", BACKENDS, False), |
| 89 | + ResourceSpec( |
| 90 | + "mcp_connections", "methodology/mcp-connections.json", "file", BACKENDS, False |
| 91 | + ), |
| 92 | + ResourceSpec("profile_domains", "methodology/domains", "dir", BACKENDS, False), |
| 93 | + ResourceSpec("profile_index", "methodology/index.json", "file", BACKENDS, False), |
| 94 | + ResourceSpec( |
| 95 | + "legacy_profiles", "methodology/profiles.json", "file", BACKENDS, False |
| 96 | + ), |
| 97 | + ResourceSpec( |
| 98 | + "legacy_profiles_backup", |
| 99 | + "methodology/profiles.json.v1_backup", |
| 100 | + "file", |
| 101 | + BACKENDS, |
| 102 | + False, |
| 103 | + ), |
| 104 | + ResourceSpec( |
| 105 | + "session_log", "methodology/session-log.json", "file", BACKENDS, False |
| 106 | + ), |
| 107 | + ResourceSpec("capture_spool", ".capture-worker/spool", "dir", BACKENDS, False), |
| 108 | +) |
| 109 | + |
| 110 | + |
| 111 | +def resources_for(backend: str) -> tuple[ResourceSpec, ...]: |
| 112 | + """The class A resources a ``backend`` install carries, in table order.""" |
| 113 | + if backend not in BACKENDS: |
| 114 | + raise ManifestError( |
| 115 | + f"unknown backend {backend!r}; expected one of {sorted(BACKENDS)}" |
| 116 | + ) |
| 117 | + return tuple(spec for spec in RESOURCES if backend in spec.backends) |
| 118 | + |
| 119 | + |
| 120 | +def _checked_files( |
| 121 | + spec: ResourceSpec, records: Sequence[FileRecord] |
| 122 | +) -> list[dict[str, Any]]: |
| 123 | + """One resource's records as manifest files: sorted, each inside it.""" |
| 124 | + if spec.kind == "file" and [r[0] for r in records] != [spec.path]: |
| 125 | + raise ManifestError(f"{spec.path} is a file resource: one record, its own path") |
| 126 | + files = [] |
| 127 | + for path, sha256, size in sorted(records): |
| 128 | + if spec.kind == "dir" and not path.startswith(spec.path + "/"): |
| 129 | + raise ManifestError(f"{path} is not inside {spec.path}") |
| 130 | + if not _SHA256_HEX.fullmatch(sha256) or size < 0: |
| 131 | + raise ManifestError(f"{path}: invalid digest or size") |
| 132 | + files.append({"path": path, "sha256": sha256, "size": size}) |
| 133 | + return files |
| 134 | + |
| 135 | + |
| 136 | +def _entry( |
| 137 | + spec: ResourceSpec, records: Sequence[FileRecord] | None, backend: str |
| 138 | +) -> dict: |
| 139 | + if records is None and spec.required: |
| 140 | + raise ManifestError( |
| 141 | + f"{spec.path} is required for a {backend} backup and is absent" |
| 142 | + ) |
| 143 | + return { |
| 144 | + "name": spec.name, |
| 145 | + "path": spec.path, |
| 146 | + "kind": spec.kind, |
| 147 | + "secret": spec.secret, |
| 148 | + "present": records is not None, |
| 149 | + "files": [] if records is None else _checked_files(spec, records), |
| 150 | + } |
| 151 | + |
| 152 | + |
| 153 | +def build_manifest( |
| 154 | + backend: str, |
| 155 | + scanned: Mapping[str, Sequence[FileRecord] | None], |
| 156 | + created_at: str, |
| 157 | +) -> dict[str, Any]: |
| 158 | + """The manifest of one install from its scan. |
| 159 | +
|
| 160 | + ``scanned`` maps every resource name of ``resources_for(backend)`` to its |
| 161 | + file records, or to ``None`` when the resource is absent; a missing or an |
| 162 | + extra name is refused, so a scan cannot leave a resource out unnoticed. |
| 163 | + """ |
| 164 | + specs = resources_for(backend) |
| 165 | + expected = {spec.name for spec in specs} |
| 166 | + if set(scanned) != expected: |
| 167 | + raise ManifestError( |
| 168 | + f"scan names {sorted(set(scanned))}, " |
| 169 | + f"the {backend} table names {sorted(expected)}" |
| 170 | + ) |
| 171 | + return { |
| 172 | + "format": FORMAT, |
| 173 | + "version": VERSION, |
| 174 | + "created_at": created_at, |
| 175 | + "backend": backend, |
| 176 | + "entries": [_entry(spec, scanned[spec.name], backend) for spec in specs], |
| 177 | + } |
| 178 | + |
| 179 | + |
| 180 | +def to_json(manifest: Mapping[str, Any]) -> str: |
| 181 | + """Canonical text: ASCII, sorted keys, two-space indent, one trailing newline.""" |
| 182 | + return json.dumps(manifest, sort_keys=True, indent=2) + "\n" |
| 183 | + |
| 184 | + |
| 185 | +def parse_manifest(text: str) -> dict[str, Any]: |
| 186 | + """Read a manifest; refuse another format, another version or another table.""" |
| 187 | + try: |
| 188 | + manifest = json.loads(text) |
| 189 | + except json.JSONDecodeError as exc: |
| 190 | + raise ManifestError(f"not JSON: {exc}") from exc |
| 191 | + if not isinstance(manifest, dict) or manifest.get("format") != FORMAT: |
| 192 | + raise ManifestError(f"not a {FORMAT} document") |
| 193 | + if manifest.get("version") != VERSION: |
| 194 | + raise ManifestError( |
| 195 | + f"manifest version {manifest.get('version')!r}, this Cortex reads {VERSION}" |
| 196 | + ) |
| 197 | + specs = resources_for(manifest.get("backend")) |
| 198 | + entries = manifest.get("entries") |
| 199 | + if not isinstance(entries, list) or not all(isinstance(e, dict) for e in entries): |
| 200 | + raise ManifestError("entries must be a list of objects") |
| 201 | + names = [entry.get("name") for entry in entries] |
| 202 | + if names != [spec.name for spec in specs]: |
| 203 | + raise ManifestError( |
| 204 | + f"entries {names} do not match the {manifest['backend']} table" |
| 205 | + ) |
| 206 | + return manifest |
0 commit comments