@krysoworks/kryso 0.0.0-stage → 2.0.0-rc.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 (162) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +152 -2
  3. package/bin/kryso +31 -0
  4. package/bin/ship-it-status +14 -0
  5. package/bin/ship-ledger +14 -0
  6. package/bin/ship-loop +14 -0
  7. package/bin/ship-pass +14 -0
  8. package/bin/warden +14 -0
  9. package/dist/answer.d.ts +38 -0
  10. package/dist/answer.js +48 -0
  11. package/dist/bytes.d.ts +5 -0
  12. package/dist/bytes.js +35 -0
  13. package/dist/cleanup.d.ts +1 -0
  14. package/dist/cleanup.js +629 -0
  15. package/dist/commands.d.ts +48 -0
  16. package/dist/commands.js +293 -0
  17. package/dist/completions.d.ts +24 -0
  18. package/dist/completions.js +239 -0
  19. package/dist/daemon.d.ts +15 -0
  20. package/dist/daemon.js +23 -0
  21. package/dist/diagnose.d.ts +47 -0
  22. package/dist/diagnose.js +314 -0
  23. package/dist/doctor.d.ts +1 -0
  24. package/dist/doctor.js +241 -0
  25. package/dist/env.d.ts +9 -0
  26. package/dist/env.js +17 -0
  27. package/dist/evidence.d.ts +39 -0
  28. package/dist/evidence.js +327 -0
  29. package/dist/home.d.ts +3 -0
  30. package/dist/home.js +27 -0
  31. package/dist/install.d.ts +59 -0
  32. package/dist/install.js +137 -0
  33. package/dist/isolate.d.ts +28 -0
  34. package/dist/isolate.js +402 -0
  35. package/dist/leftovers.d.ts +5 -0
  36. package/dist/leftovers.js +156 -0
  37. package/dist/machine.d.ts +6 -0
  38. package/dist/machine.js +185 -0
  39. package/dist/palette.d.ts +147 -0
  40. package/dist/palette.js +167 -0
  41. package/dist/plan.d.ts +1 -0
  42. package/dist/plan.js +133 -0
  43. package/dist/proc.d.ts +23 -0
  44. package/dist/proc.js +23 -0
  45. package/dist/read.d.ts +1 -0
  46. package/dist/read.js +297 -0
  47. package/dist/readiness.d.ts +5 -0
  48. package/dist/readiness.js +64 -0
  49. package/dist/remote.d.ts +6 -0
  50. package/dist/remote.js +85 -0
  51. package/dist/self-update.d.ts +1 -0
  52. package/dist/self-update.js +224 -0
  53. package/dist/semver.d.ts +7 -0
  54. package/dist/semver.js +42 -0
  55. package/dist/style.d.ts +71 -0
  56. package/dist/style.js +187 -0
  57. package/dist/update.d.ts +47 -0
  58. package/dist/update.js +190 -0
  59. package/dist/work.d.ts +25 -0
  60. package/dist/work.js +449 -0
  61. package/dist/workflows.d.ts +4 -0
  62. package/dist/workflows.js +73 -0
  63. package/docker/entrypoint.sh +44 -0
  64. package/docker/runner.Dockerfile +39 -0
  65. package/package.json +65 -4
  66. package/scripts/install-skills.sh +607 -0
  67. package/skills/code-review/SKILL.md +231 -0
  68. package/skills/kryso/SKILL.md +107 -0
  69. package/skills/kryso/golden/help.rounded.ansi +23 -0
  70. package/skills/kryso/golden/help.square.ansi +23 -0
  71. package/skills/kryso/golden/help.txt +23 -0
  72. package/skills/kryso/golden/table-narrow.json +11 -0
  73. package/skills/kryso/golden/table-narrow.rounded.ansi +4 -0
  74. package/skills/kryso/golden/table-narrow.square.ansi +4 -0
  75. package/skills/kryso/golden/table.ansi +5 -0
  76. package/skills/kryso/golden/table.json +11 -0
  77. package/skills/kryso/ledger.sh +2146 -0
  78. package/skills/kryso/palette.json +57 -0
  79. package/skills/kryso/reference/resuming.md +30 -0
  80. package/skills/kryso/reference/routing.md +23 -0
  81. package/skills/kryso/reference/stage-1-claim.md +79 -0
  82. package/skills/kryso/reference/stage-2-build.md +133 -0
  83. package/skills/kryso/reference/stage-3-prove.md +51 -0
  84. package/skills/kryso/reference/stage-4-pr.md +76 -0
  85. package/skills/kryso/reference/stage-5-reconcile.md +81 -0
  86. package/skills/kryso/reference/stage-6-merge-or-park.md +73 -0
  87. package/skills/kryso/reference/stage-7-close-out.md +62 -0
  88. package/skills/kryso/reference/terminal.md +7 -0
  89. package/skills/kryso/ship-it-status.sh +1503 -0
  90. package/skills/kryso/ui.py +274 -0
  91. package/skills/kryso/ui.sh +609 -0
  92. package/skills/kryso-build/SKILL.md +168 -0
  93. package/skills/kryso-shift/SKILL.md +167 -0
  94. package/skills/kryso-shift/archive.py +2784 -0
  95. package/skills/kryso-shift/archive_checker.py +462 -0
  96. package/skills/kryso-shift/archive_checker_lambda.py +155 -0
  97. package/skills/kryso-shift/archive_health.py +364 -0
  98. package/skills/kryso-shift/archive_launchd.py +140 -0
  99. package/skills/kryso-shift/archive_remote.py +990 -0
  100. package/skills/kryso-shift/archiving-checker.md +140 -0
  101. package/skills/kryso-shift/archiving-keep.md +115 -0
  102. package/skills/kryso-shift/archiving-recovery.md +112 -0
  103. package/skills/kryso-shift/archiving-remote.md +166 -0
  104. package/skills/kryso-shift/archiving.md +146 -0
  105. package/skills/kryso-shift/coverage.schema.json +225 -0
  106. package/skills/kryso-shift/deadline.sh +254 -0
  107. package/skills/kryso-shift/feedback.schema.json +35 -0
  108. package/skills/kryso-shift/feedback.sh +228 -0
  109. package/skills/kryso-shift/history-manifest.schema.json +331 -0
  110. package/skills/kryso-shift/keep-after.sh +55 -0
  111. package/skills/kryso-shift/measure.sh +611 -0
  112. package/skills/kryso-shift/merge-ready.sh +207 -0
  113. package/skills/kryso-shift/outcome.schema.json +16 -0
  114. package/skills/kryso-shift/pass-rules.md +8 -0
  115. package/skills/kryso-shift/profile.schema.json +42 -0
  116. package/skills/kryso-shift/reader.sh +692 -0
  117. package/skills/kryso-shift/reads.sh +151 -0
  118. package/skills/kryso-shift/reference/allowance.md +21 -0
  119. package/skills/kryso-shift/reference/driver.md +95 -0
  120. package/skills/kryso-shift/reference/measuring.md +67 -0
  121. package/skills/kryso-shift/reference/outputs.md +21 -0
  122. package/skills/kryso-shift/reference/pass-script.md +115 -0
  123. package/skills/kryso-shift/reference/reconcile-and-merge.md +55 -0
  124. package/skills/kryso-shift/reference/second-reader.md +9 -0
  125. package/skills/kryso-shift/reference/sweeps.md +83 -0
  126. package/skills/kryso-shift/repair.schema.json +14 -0
  127. package/skills/kryso-shift/report-template.html +679 -0
  128. package/skills/kryso-shift/report.py +389 -0
  129. package/skills/kryso-shift/report_fixture.py +65 -0
  130. package/skills/kryso-shift/reporting.md +58 -0
  131. package/skills/kryso-shift/result.sh +91 -0
  132. package/skills/kryso-shift/runner.sh +1178 -0
  133. package/skills/kryso-shift/ship-loop.sh +3977 -0
  134. package/skills/kryso-shift/ship-pass.sh +4987 -0
  135. package/skills/kryso-shift/steps.jq +19 -0
  136. package/skills/kryso-shift/workflow.mjs +830 -0
  137. package/skills/kryso-shift/workflows/default.json +22 -0
  138. package/skills/kryso-shift/workflows/ralph.json +13 -0
  139. package/skills/kryso-watch/SKILL.md +100 -0
  140. package/skills/kryso-watch/answer.schema.json +23 -0
  141. package/skills/kryso-watch/base-refs.sh +44 -0
  142. package/skills/kryso-watch/board.sh +58 -0
  143. package/skills/kryso-watch/reference/config.md +23 -0
  144. package/skills/kryso-watch/reference/outputs.md +30 -0
  145. package/skills/kryso-watch/reference/report.md +29 -0
  146. package/skills/kryso-watch/reference/scheduler.md +32 -0
  147. package/skills/kryso-watch/reference/settlement.md +29 -0
  148. package/skills/kryso-watch/reference/shift.md +44 -0
  149. package/skills/kryso-watch/reference/shim-limits.md +22 -0
  150. package/skills/kryso-watch/reference/triage.md +26 -0
  151. package/skills/kryso-watch/schema.jq +40 -0
  152. package/skills/kryso-watch/settle.schema.json +36 -0
  153. package/skills/kryso-watch/stage-common.sh +187 -0
  154. package/skills/kryso-watch/stages/report.sh +525 -0
  155. package/skills/kryso-watch/stages/settle.sh +722 -0
  156. package/skills/kryso-watch/stages/shift.sh +466 -0
  157. package/skills/kryso-watch/stages/triage.sh +379 -0
  158. package/skills/kryso-watch/tracker.sh +27 -0
  159. package/skills/kryso-watch/triage.schema.json +77 -0
  160. package/skills/kryso-watch/warden.launchd.plist +50 -0
  161. package/skills/kryso-watch/warden.schema.json +98 -0
  162. package/skills/kryso-watch/warden.sh +1004 -0
@@ -0,0 +1,2784 @@
1
+ #!/usr/bin/env python3
2
+ """Snapshot saved shipping evidence into a local archive, verify it, restore it,
3
+ and keep a copy off the machine.
4
+
5
+ The command reads evidence and writes only inside the archive, the restore root
6
+ (with any missing directories above it and a staging directory beside it), a
7
+ restore check's scratch root and a remote. launchd writes its own plist, checker
8
+ run the journal and alerts directories its configuration names, and checker
9
+ package the one file it is given. It changes no model, tracker or repository,
10
+ and the local verbs touch no network. archiving.md, archiving-remote.md,
11
+ archiving-keep.md, archiving-recovery.md and archiving-checker.md beside this
12
+ script hold the contract.
13
+ """
14
+
15
+ import argparse
16
+ import contextlib
17
+ import fcntl
18
+ import fnmatch
19
+ import hashlib
20
+ import json
21
+ import os
22
+ import plistlib
23
+ import re
24
+ import shutil
25
+ import socket
26
+ import sys
27
+ import tempfile
28
+ import time
29
+ from collections import defaultdict
30
+ from datetime import datetime, timedelta, timezone
31
+ from pathlib import Path, PurePosixPath
32
+
33
+ # The command sits in an installed skill directory, so importing its sibling must leave no __pycache__ there.
34
+ sys.dont_write_bytecode = True
35
+ import archive_checker # noqa: E402
36
+ import archive_health # noqa: E402
37
+ import archive_launchd # noqa: E402
38
+ import archive_remote # noqa: E402
39
+ from archive_remote import Refused, publish # noqa: E402
40
+
41
+ MANIFEST_SCHEMA = "ship-archive-manifest/1"
42
+ HISTORY_SCHEMA = "ship-history-manifest/1"
43
+ # Every pass-record version the archive collects; version 2 added the test volume, version 3 the
44
+ # workflow, and version 4 the transcript figures.
45
+ RECORD_SCHEMAS = ("ship-pass-record/1", "ship-pass-record/2", "ship-pass-record/3", "ship-pass-record/4")
46
+ RECORD_NAME = re.compile(r"record(-\d+)?\.json")
47
+ SNAPSHOT_ID = re.compile(r"[0-9a-f]{64}")
48
+ RESTORED_MANIFEST = "archive-manifest.json"
49
+
50
+ # Never collected, whichever evidence root they turn up in.
51
+ SECRET_PATTERNS = (".env", ".env.*", "*.env", ".netrc", ".npmrc", ".pypirc", ".git-credentials",
52
+ "credentials", "credentials.*", "*.pem", "*.key", "*.p12", "*.pfx",
53
+ "id_rsa*", "id_ecdsa*", "id_ed25519*", ".secrets")
54
+ SKIPPED_DIRS = {".git", "node_modules"}
55
+ # A directory holding one of these files at its top is a database's data directory, whatever it is called.
56
+ # A keep configuration's skipped_dirs names more, for one repository. archiving.md says why.
57
+ DATABASE_MARKERS = ("PG_VERSION",)
58
+ DATABASE_REASON = "database data directory, not evidence"
59
+ SKIPPED_REASON = "named in the keep configuration's skipped_dirs, not evidence"
60
+ # The shift directory's files that belong to the whole shift rather than one pass.
61
+ SHIFT_FILES = ("shift.log", "shift.json", "summary.json", "sweep-*.json", "stage-*.log")
62
+ # The ones that belong to pass <n>.
63
+ PASS_FILES = ("pass-{n}.json", "pass-{n}.final.json", "pass-{n}.json.raw", "pass-{n}.err", "pass-{n}.done",
64
+ "ratelimit-{n}-*.json", "report-{n}.json", "report-{n}-*.json", "report-{n}.err")
65
+ # Expected in every completed pass's ledger directory. Absent ones are listed as missing.
66
+ LEDGER_FILES = {"run.md": "ledger", "checkpoint.json": "checkpoint", "brief.md": "brief", "review.md": "review"}
67
+ # The rename to KrysoWorks moved a worktree's ledger directory from .ship-it to .kryso, and a
68
+ # repository's shift state from .claude/ship-loop to .claude/kryso. A writer moves the old directory
69
+ # and leaves a link at its name. Both names are read, the new first, and a link is never followed,
70
+ # so a moved directory is read once and one nobody moved is read where it is. Since #618 a pass
71
+ # keeps its ledger in .kryso/pass, beside the repository's tracked configuration in .kryso, and a
72
+ # .kryso with no pass directory in it is the ledger of a pass from before that move.
73
+ LEDGER_DIRS = (".kryso", ".ship-it")
74
+ PASS_DIR = "pass"
75
+ STATE_DIRS = (".claude/kryso", ".claude/ship-loop")
76
+ CAPTURE_TRIES = 3
77
+ SECRET_REASON = "environment or credential file, never collected"
78
+
79
+
80
+ def sha256(data):
81
+ return hashlib.sha256(data).hexdigest()
82
+
83
+
84
+ def canonical(obj):
85
+ return json.dumps(obj, sort_keys=True, separators=(",", ":")).encode()
86
+
87
+
88
+ def snapshot_id(manifest):
89
+ """The snapshot identity: SHA-256 of the canonical manifest without its `snapshot` field."""
90
+ return sha256(canonical({k: v for k, v in manifest.items() if k != "snapshot"}))
91
+
92
+
93
+ def read_json(path):
94
+ try:
95
+ return json.loads(Path(path).read_text())
96
+ except (OSError, ValueError):
97
+ return None
98
+
99
+
100
+ def matches(name, patterns):
101
+ return any(fnmatch.fnmatch(name, p) for p in patterns)
102
+
103
+
104
+ def archive_path(name, path, repo):
105
+ """Where a file below the repository lives under the restore root."""
106
+ return f"{name}/{path.relative_to(repo).as_posix()}"
107
+
108
+
109
+ def snapshot_path(store, ident):
110
+ return store / "snapshots" / f"{ident}.json"
111
+
112
+
113
+ def object_path(store, digest):
114
+ return store / "objects" / digest[:2] / digest
115
+
116
+
117
+ def now():
118
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
119
+
120
+
121
+ # ---- collect ---------------------------------------------------------------------------
122
+
123
+ def condition(name, data):
124
+ if not data:
125
+ return "empty"
126
+ if name.endswith(".json"):
127
+ try:
128
+ json.loads(data)
129
+ except ValueError:
130
+ return "invalid-json"
131
+ return "valid-json"
132
+ return "present"
133
+
134
+
135
+ def role_of(rel):
136
+ """The evidence role of a file, from its path below the repository."""
137
+ name = rel.name
138
+ if any(part in LEDGER_DIRS for part in rel.parts):
139
+ ledger_dir = rel.parent.name in LEDGER_DIRS or (rel.parent.name == PASS_DIR and rel.parent.parent.name == LEDGER_DIRS[0])
140
+ if ledger_dir and name in LEDGER_FILES:
141
+ return LEDGER_FILES[name]
142
+ if name == "ledger.sh":
143
+ return "module"
144
+ if RECORD_NAME.fullmatch(name):
145
+ return "record"
146
+ if name.endswith(".log"):
147
+ return "receipt"
148
+ if name.startswith("review"):
149
+ return "review"
150
+ if name.endswith(".json"):
151
+ return "result"
152
+ return "other"
153
+ if matches(name, SHIFT_FILES):
154
+ return "shift"
155
+ if name.endswith(".err"):
156
+ return "host-stderr"
157
+ return "result"
158
+
159
+
160
+ def state_roots(repo):
161
+ """The repository's shift state directories, the new name first, each real directory once."""
162
+ roots = []
163
+ for rel in STATE_DIRS:
164
+ path = repo / rel
165
+ if path.is_dir() and not any(path.resolve() == root.resolve() for root in roots):
166
+ roots.append(path)
167
+ return roots
168
+
169
+
170
+ def moved(path):
171
+ """The link the rename left at a ledger directory's old name, pointing at the new one beside it."""
172
+ new = path.parent / LEDGER_DIRS[0]
173
+ return path.name != new.name and path.is_symlink() and new.is_dir() and path.resolve() == new.resolve()
174
+
175
+
176
+ def ledgers_in(parent):
177
+ """A worktree's or shipped copy's ledger directories: .kryso/pass, or the .kryso of a pass from
178
+ before #618 where there is no .kryso/pass, and .ship-it unless it is the link the rename left."""
179
+ kryso = parent / LEDGER_DIRS[0]
180
+ # A .kryso with no pass directory is a ledger only where it holds one: configuration alone is not evidence.
181
+ old = kryso if (kryso / "run.md").exists() or (kryso / "logs").is_dir() else None
182
+ found = (kryso / PASS_DIR if (kryso / PASS_DIR).is_dir() else old, parent / LEDGER_DIRS[1])
183
+ return [path for path in found if path is not None and (path.is_dir() or path.is_symlink()) and not moved(path)]
184
+
185
+
186
+ def ledger_dirs(repo):
187
+ """Every ledger directory below the worktrees and below the shipped archives, as two lists."""
188
+ retained = [path for parent in repo.glob(".claude/worktrees/*") for path in ledgers_in(parent)]
189
+ shipped = [path for root in state_roots(repo) for parent in root.glob("shipped/*") for path in ledgers_in(parent)]
190
+ return sorted(retained), sorted(shipped)
191
+
192
+
193
+ def shift_passes(repo):
194
+ """Every pass-<n>.json, and its kin, under the repository's shift directories."""
195
+ return sorted(path for root in state_roots(repo) for path in root.glob("*/pass-*.json"))
196
+
197
+
198
+ def capture(path):
199
+ """Stage a file, retrying while the source changes. None when it never settles."""
200
+ for _ in range(CAPTURE_TRIES):
201
+ before = os.stat(path, follow_symlinks=False)
202
+ with open(path, "rb") as source, tempfile.TemporaryFile() as staged:
203
+ shutil.copyfileobj(source, staged)
204
+ staged.flush()
205
+ size = staged.tell()
206
+ staged.seek(0)
207
+ data = staged.read()
208
+ after = os.stat(path, follow_symlinks=False)
209
+ if (before.st_size, before.st_mtime_ns) == (after.st_size, after.st_mtime_ns) and size == after.st_size:
210
+ return data
211
+ return None
212
+
213
+
214
+ class Collection:
215
+ def __init__(self, store):
216
+ self.store = store
217
+ self.entries, self.excluded, self.missing, self.errors = [], [], [], []
218
+ self.blobs = {}
219
+
220
+ def exclude(self, path, reason):
221
+ self.excluded.append({"source": str(path), "reason": reason})
222
+
223
+ def add(self, source, dest, role):
224
+ try:
225
+ data = capture(source)
226
+ except OSError as error:
227
+ self.errors.append({"source": str(source), "error": f"unreadable: {error.strerror or error}"})
228
+ return
229
+ if data is None:
230
+ self.errors.append({"source": str(source), "error": f"still changing after {CAPTURE_TRIES} reads"})
231
+ return
232
+ digest = sha256(data)
233
+ self.blobs[digest] = data
234
+ self.entries.append({"path": dest, "source": str(source), "role": role, "bytes": len(data),
235
+ "sha256": digest, "condition": condition(source.name, data)})
236
+
237
+ def bytes_for(self, source):
238
+ """The staged bytes for a source already added to this collection."""
239
+ entry = next((entry for entry in reversed(self.entries) if entry["source"] == str(source)), None)
240
+ return self.blobs.get(entry["sha256"]) if entry else None
241
+
242
+ def json_for(self, source):
243
+ data = self.bytes_for(source)
244
+ if data is None:
245
+ return None
246
+ try:
247
+ return json.loads(data)
248
+ except ValueError:
249
+ return None
250
+
251
+ def walk(self, top, repo, name_prefix, skipped=()):
252
+ """Every regular file under one evidence root. Symlinks are never followed, and a directory whose name
253
+ matches a pattern in `skipped` is left out with everything under it."""
254
+ top_real = top.resolve()
255
+ for current, dirs, files in os.walk(top, followlinks=False):
256
+ current = Path(current)
257
+ for name in sorted(dirs):
258
+ path = current / name
259
+ if path.is_symlink():
260
+ self.exclude(path, self.link_reason(path, top_real))
261
+ dirs.remove(name)
262
+ elif name in SKIPPED_DIRS or path.resolve() == self.store.resolve():
263
+ self.exclude(path, "not evidence")
264
+ dirs.remove(name)
265
+ elif any((path / marker).is_file() for marker in DATABASE_MARKERS):
266
+ self.exclude(path, DATABASE_REASON)
267
+ dirs.remove(name)
268
+ elif matches(name, skipped):
269
+ self.exclude(path, SKIPPED_REASON)
270
+ dirs.remove(name)
271
+ elif matches(name, SECRET_PATTERNS):
272
+ # A credential store can be a directory, and nothing under it is evidence.
273
+ self.exclude(path, SECRET_REASON)
274
+ dirs.remove(name)
275
+ for name in sorted(files):
276
+ path = current / name
277
+ if path.is_symlink():
278
+ self.exclude(path, self.link_reason(path, top_real))
279
+ elif matches(name, SECRET_PATTERNS):
280
+ self.exclude(path, SECRET_REASON)
281
+ elif not path.is_file():
282
+ self.exclude(path, "not a regular file")
283
+ else:
284
+ self.add(path, archive_path(name_prefix, path, repo), role_of(path.relative_to(repo)))
285
+
286
+ @staticmethod
287
+ def link_reason(path, top_real):
288
+ target = path.resolve()
289
+ inside = target == top_real or top_real in target.parents
290
+ return "symlink inside the evidence root, not followed" if inside else "symlink escaping the evidence root, not followed"
291
+
292
+
293
+ def add_named_input(found, path, dest):
294
+ """Apply the evidence rules to one supplied file. False means it was absent."""
295
+ if path.is_symlink():
296
+ found.exclude(path.absolute(), "symlink named as an input, not followed")
297
+ elif matches(path.name, SECRET_PATTERNS):
298
+ found.exclude(path.absolute(), SECRET_REASON)
299
+ elif not path.is_file():
300
+ return False
301
+ else:
302
+ found.add(path.resolve(), dest, "measurement-input")
303
+ return True
304
+
305
+
306
+ def find_records(repo, attempt):
307
+ """The ledger directories holding a pass record for this attempt, with the record path."""
308
+ found = []
309
+ retained, shipped = ledger_dirs(repo)
310
+ for ship in retained + shipped:
311
+ logs = ship / "logs"
312
+ if logs.is_symlink() or ship.is_symlink() or not logs.is_dir():
313
+ continue
314
+ for path in sorted(logs.glob("record*.json")):
315
+ if not RECORD_NAME.fullmatch(path.name) or path.is_symlink():
316
+ continue
317
+ body = read_json(path)
318
+ if isinstance(body, dict) and body.get("schema") in RECORD_SCHEMAS and body.get("attempt_id") == attempt:
319
+ found.append((ship, path, body))
320
+ return found
321
+
322
+
323
+ def find_pass(repo, attempt):
324
+ """The shift directory and pass number whose outcome block names this attempt."""
325
+ for path in shift_passes(repo):
326
+ match = re.fullmatch(r"pass-(\d+)\.json", path.name)
327
+ if not match or path.is_symlink() or path.parent.name == "shipped":
328
+ continue
329
+ body = read_json(path)
330
+ if isinstance(body, dict) and body.get("attempt_id") == attempt:
331
+ return path.parent, match.group(1)
332
+ return None, None
333
+
334
+
335
+ def collect(store, repo, attempt, inputs):
336
+ repo = repo.resolve()
337
+ name = repo.name
338
+ records = find_records(repo, attempt)
339
+ if not records:
340
+ raise Refused(f"no pass record in {repo} names attempt {attempt}, and collect takes only a completed pass with its own attempt id")
341
+ found = Collection(store)
342
+ for ship, _, _ in records:
343
+ found.walk(ship, repo, name)
344
+ for file, role in LEDGER_FILES.items():
345
+ if not (ship / file).is_file():
346
+ found.missing.append({"role": role, "expected": archive_path(name, ship / file, repo)})
347
+ if not any(ship.glob("logs/*.log")):
348
+ found.missing.append({"role": "receipt", "expected": archive_path(name, ship / "logs", repo) + "/*.log"})
349
+ shift_dir, number = find_pass(repo, attempt)
350
+ if shift_dir is None:
351
+ found.missing.append({"role": "result", "expected": f"{name}/.claude/kryso/<shift>/pass-<n>.json naming {attempt}"})
352
+ else:
353
+ mine = [p.format(n=number) for p in PASS_FILES] + list(SHIFT_FILES)
354
+ for path in sorted(shift_dir.iterdir()):
355
+ if path.is_symlink():
356
+ found.exclude(path, Collection.link_reason(path, shift_dir.resolve()))
357
+ elif path.is_dir() or not matches(path.name, mine):
358
+ found.exclude(path, "another attempt's evidence")
359
+ else:
360
+ found.add(path, archive_path(name, path, repo), role_of(path.relative_to(repo)))
361
+ for path in inputs:
362
+ dest = f"inputs/{path.name}"
363
+ if any(e["path"] == dest for e in found.entries):
364
+ raise Refused(f"two supplied inputs share the name {path.name}")
365
+ if not add_named_input(found, path, dest):
366
+ found.missing.append({"role": "measurement-input", "expected": str(path)})
367
+ _, record_path, body = records[0]
368
+ found.entries.sort(key=lambda e: e["path"])
369
+ manifest = {
370
+ "schema": MANIFEST_SCHEMA,
371
+ "repository": {"name": name, "slug": body.get("repository"), "source": str(repo)},
372
+ "shift": {"id": shift_dir.name, "source": str(shift_dir)} if shift_dir else None,
373
+ "attempt": {"id": attempt, "identity": "native", "issue": str(body.get("issue")) if body.get("issue") is not None else None,
374
+ "outcome": body.get("outcome"), "record": archive_path(name, record_path, repo)},
375
+ "collection": {"completeness": "partial" if found.errors else "complete", "errors": found.errors},
376
+ "entries": found.entries,
377
+ "missing": found.missing,
378
+ "excluded": sorted(found.excluded, key=lambda e: e["source"]),
379
+ }
380
+ ident, status = preserve_manifest(store, found, manifest)
381
+ return {"status": status, "snapshot": ident, "completeness": manifest["collection"]["completeness"],
382
+ "manifest": str(snapshot_path(store, ident)), "entries": len(found.entries),
383
+ "missing": len(found.missing), "excluded": len(found.excluded), "errors": len(found.errors)}
384
+
385
+
386
+ def repository_identity(repo):
387
+ """The stable repository component of a legacy identity."""
388
+ return repo.name
389
+
390
+
391
+ def history_records(repo):
392
+ retained, shipped = ledger_dirs(repo)
393
+ return [path for ship in retained + shipped if not ship.is_symlink()
394
+ for path in sorted(ship.glob("logs/record*.json"))]
395
+
396
+
397
+ def legacy_source(source):
398
+ """A source path under the names before the rename, so a pass keeps its legacy identity when a writer moves it."""
399
+ parts = PurePosixPath(source).parts
400
+ if parts[:2] == (".claude", STATE_DIRS[0].split("/")[1]):
401
+ parts = (".claude", STATE_DIRS[1].split("/")[1]) + parts[2:]
402
+ return PurePosixPath(*[LEDGER_DIRS[1] if part == LEDGER_DIRS[0] else part for part in parts]).as_posix()
403
+
404
+
405
+ def legacy_identity(repository, shift, source):
406
+ identity = {"repository": repository, "shift": shift, "source": legacy_source(source)}
407
+ return "legacy-" + sha256(canonical(identity))
408
+
409
+
410
+ def attempt_entry(*, ident, identity, repository, issue, outcome, shift, source,
411
+ copy_of=None, retries=0, session_ids=(), host=None, reported_usd=None,
412
+ activity="unknown", sources=None):
413
+ """One manifest attempt, with the shared identity fields kept in one place."""
414
+ return {"id": ident, "identity": identity, "repository": repository,
415
+ "issue": str(issue) if issue is not None else None, "outcome": outcome,
416
+ "shift": shift, "source": source, "sources": list(sources or [source]),
417
+ "copy_of": copy_of, "retries": retries, "session_ids": sorted(set(session_ids)),
418
+ "host": host, "reported_usd": reported_usd, "activity": activity}
419
+
420
+
421
+ def collect_history(store, repos, inputs, claude_projects=None, codex_sessions=None, skipped=None):
422
+ """Discover and preserve every saved pass source below the named repositories. `skipped` maps a repository's
423
+ directory name to the directory names its evidence roots leave out."""
424
+ found = Collection(store)
425
+ attempts, gaps, repositories, seen_names = [], [], [], set()
426
+ earlier = previous_captures(store, {repository_identity(repo.resolve()) for repo in repos})
427
+ native = {}
428
+ legacy_hashes = {}
429
+ coverage = defaultdict(int)
430
+ for raw_repo in repos:
431
+ repo = raw_repo.resolve()
432
+ if repo.name in seen_names:
433
+ raise Refused(f"two repositories restore as {repo.name}, and each repository needs a directory name of its own")
434
+ seen_names.add(repo.name)
435
+ record_paths = history_records(repo)
436
+ before_entries = len(found.entries)
437
+ before_errors = len(found.errors)
438
+ before_gaps = len(gaps)
439
+
440
+ retained_ships, shipped_ships = ledger_dirs(repo)
441
+ shifts = [path for root in state_roots(repo) for path in sorted(root.glob("*"))
442
+ if path.name != "shipped" and not path.is_symlink() and path.is_dir()]
443
+ coverage["retained_worktrees"] += len(retained_ships)
444
+ coverage["shipped_archives"] += len(shipped_ships)
445
+ coverage["shifts"] += len(shifts)
446
+ left_out = (skipped or {}).get(repo.name, ())
447
+ for ship in sorted(set(retained_ships) | set(shipped_ships)):
448
+ if not ship.is_symlink() and ship.is_dir():
449
+ found.walk(ship, repo, repo.name, left_out)
450
+ for shift in shifts:
451
+ found.walk(shift, repo, repo.name, left_out)
452
+
453
+ records = []
454
+ for path in record_paths:
455
+ body = found.json_for(path)
456
+ if isinstance(body, dict) and body.get("schema") in RECORD_SCHEMAS and body.get("attempt_id"):
457
+ records.append((path, body))
458
+ repo_id = repository_identity(repo)
459
+
460
+ for record_path, body in records:
461
+ key = (repo_id, body["attempt_id"])
462
+ attempt = native.get(key)
463
+ source = record_path.relative_to(repo).as_posix()
464
+ if attempt is None:
465
+ attempt = attempt_entry(ident=body["attempt_id"], identity="native", repository=repo_id,
466
+ issue=body.get("issue"), outcome=body.get("outcome"), shift=None,
467
+ source=source, session_ids=recorded_sessions(body), host=body.get("host"),
468
+ reported_usd=native_total(body), activity="finished")
469
+ native[key] = attempt
470
+ attempts.append(attempt)
471
+ elif source not in attempt["sources"]:
472
+ attempt["sources"].append(source)
473
+ for pass_path in shift_passes(repo):
474
+ pass_body = found.json_for(pass_path)
475
+ if isinstance(pass_body, dict) and pass_body.get("attempt_id") == body["attempt_id"]:
476
+ attempt["shift"] = pass_path.parent.name
477
+ attempt["session_ids"] = sorted(set(attempt["session_ids"] + recorded_sessions(pass_body)))
478
+
479
+ recorded_ships = {path.parent.parent for path, _ in records}
480
+ for ship in sorted(set(retained_ships) | set(shipped_ships)):
481
+ if ship in recorded_ships or ship.is_symlink() or not ship.is_dir():
482
+ continue
483
+ source = ship.relative_to(repo).as_posix()
484
+ shift = ship.parent.name if ship in shipped_ships else None
485
+ checkpoint = found.json_for(ship / "checkpoint.json") or {}
486
+ status = checkpoint.get("status")
487
+ activity = "active" if status == "running" else ("finished" if status in ("done", "parked", "failed") else "unknown")
488
+ evidence_bodies = []
489
+ for path in sorted((ship / "logs").glob("*.json")):
490
+ body = found.json_for(path)
491
+ if isinstance(body, dict):
492
+ evidence_bodies.append(body)
493
+ sessions = sorted({session for body in evidence_bodies for session in recorded_sessions(body)})
494
+ issue = ledger_issue(found.bytes_for(ship / "run.md"))
495
+ ident = legacy_identity(repo_id, shift, source)
496
+ totals = [body.get("total_cost_usd", body.get("cost_usd")) for body in evidence_bodies]
497
+ totals = [value for value in totals if isinstance(value, (int, float))]
498
+ attempts.append(attempt_entry(ident=ident, identity="legacy", repository=repo_id,
499
+ issue=issue, outcome=checkpoint.get("disposition") or status,
500
+ shift=shift, source=source, session_ids=sessions, host="claude",
501
+ reported_usd=sum(totals) if totals else None, activity=activity))
502
+
503
+ covered = {body["attempt_id"] for _, body in records}
504
+ for pass_path in shift_passes(repo):
505
+ match = re.fullmatch(r"pass-(\d+)\.json", pass_path.name)
506
+ if not match or pass_path.parent.name == "shipped" or pass_path.is_symlink():
507
+ continue
508
+ raw = found.bytes_for(pass_path)
509
+ body = found.json_for(pass_path)
510
+ if not isinstance(body, dict):
511
+ if raw is None:
512
+ continue
513
+ gaps.append({"kind": "malformed-attempt", "repository": repo_id,
514
+ "source": pass_path.relative_to(repo).as_posix(),
515
+ "condition": condition(pass_path.name, raw)})
516
+ continue
517
+ if body.get("attempt_id") in covered:
518
+ continue
519
+ number = match.group(1)
520
+ source = pass_path.relative_to(repo).as_posix()
521
+ ident = legacy_identity(repo_id, pass_path.parent.name, source)
522
+ digest = sha256(raw)
523
+ retry_paths = sorted(pass_path.parent.glob(f"ratelimit-{number}-*.json"))
524
+ first = legacy_hashes.get((repo_id, digest))
525
+ attempt = attempt_entry(ident=ident, identity="legacy", repository=repo_id,
526
+ issue=body.get("issue"), outcome=outcome_of(body),
527
+ shift=pass_path.parent.name, source=source, copy_of=first,
528
+ retries=len(retry_paths), session_ids=recorded_sessions(body),
529
+ host=body.get("host", "claude"),
530
+ reported_usd=body.get("total_cost_usd", body.get("cost_usd")))
531
+ attempts.append(attempt)
532
+ legacy_hashes.setdefault((repo_id, digest), ident)
533
+ # A waited-out attempt's body, report-<n>-<k>.json, is a surviving body of the pass too.
534
+ if attempt["issue"] == "94" and not any(pass_path.parent.glob(f"report-{number}.*")) \
535
+ and not any(pass_path.parent.glob(f"report-{number}-*.json")):
536
+ gaps.append({"kind": "report-body-unavailable", "repository": repo_id, "issue": "94",
537
+ "source": source,
538
+ "reason": "no surviving report body; an earlier #94 report may have been overwritten"})
539
+
540
+ gaps.extend(vanished_attempts(repo_id, earlier.get(repo_id), attempts))
541
+ repositories.append({"id": repo_id, "name": repo.name, "source": str(repo),
542
+ "files": len(found.entries) - before_entries,
543
+ "bytes": sum(entry["bytes"] for entry in found.entries[before_entries:]),
544
+ "gaps": len(gaps) - before_gaps,
545
+ "errors": len(found.errors) - before_errors})
546
+
547
+ for path in inputs:
548
+ dest = f"inputs/{path.name}"
549
+ if any(entry["path"] == dest for entry in found.entries):
550
+ raise Refused(f"two supplied inputs share the name {path.name}")
551
+ if not add_named_input(found, path, dest):
552
+ gaps.append({"kind": "missing-input", "source": str(path)})
553
+ found.errors.append({"source": str(path), "error": "supplied input is missing"})
554
+
555
+ sessions = associate_sessions(found, attempts, claude_projects, codex_sessions, gaps)
556
+ found.entries.sort(key=lambda entry: entry["path"])
557
+ conditions = defaultdict(int)
558
+ roles = defaultdict(int)
559
+ for entry in found.entries:
560
+ conditions[entry["condition"]] += 1
561
+ roles[entry["role"]] += 1
562
+ counted_attempts = [attempt for attempt in attempts if attempt["copy_of"] is None]
563
+ known_totals = [attempt["reported_usd"] for attempt in counted_attempts
564
+ if isinstance(attempt.get("reported_usd"), (int, float))]
565
+ transcript_entries = [entry for entry in found.entries if entry["role"] in ("transcript", "session-metadata")]
566
+ exclusive_usage = transcript_usage(found, transcript_entries)
567
+ manifest = {
568
+ "schema": HISTORY_SCHEMA,
569
+ "repositories": repositories,
570
+ "attempts": attempts,
571
+ "sessions": sessions,
572
+ "collection": {"completeness": "partial" if found.errors else "complete", "errors": found.errors},
573
+ "inventory": {"repositories": len(repositories), "attempts": len(attempts),
574
+ "coverage": dict(sorted(coverage.items())),
575
+ "files": len(found.entries), "bytes": sum(entry["bytes"] for entry in found.entries),
576
+ "conditions": dict(sorted(conditions.items())), "roles": dict(sorted(roles.items())),
577
+ "host_totals": {
578
+ "basis": "inclusive host totals from attempts; exact copies counted once",
579
+ "attempts": len(counted_attempts), "reported_usd": sum(known_totals),
580
+ "unknown": len(counted_attempts) - len(known_totals)},
581
+ "transcripts": {
582
+ "basis": "exclusive surviving transcript messages; each source counted once",
583
+ "files": len(transcript_entries),
584
+ "bytes": sum(entry["bytes"] for entry in transcript_entries),
585
+ "exclusive_usage": exclusive_usage}},
586
+ "entries": found.entries,
587
+ "gaps": gaps,
588
+ "excluded": sorted(found.excluded, key=lambda entry: entry["source"]),
589
+ }
590
+ ident, status = preserve_manifest(store, found, manifest)
591
+ record_latest_captures(store, ident, [repo["id"] for repo in repositories])
592
+ return {"status": status, "snapshot": ident, "completeness": manifest["collection"]["completeness"],
593
+ "manifest": str(snapshot_path(store, ident)), "repositories": len(repositories),
594
+ "attempts": len(attempts), "entries": len(found.entries), "gaps": len(gaps),
595
+ "errors": len(found.errors)}
596
+
597
+
598
+ def latest_captures_path(store):
599
+ """The record of the history capture this archive last made of each repository, by repository id."""
600
+ return store / "history" / "latest.json"
601
+
602
+
603
+ def previous_captures(store, repo_ids):
604
+ """For each repository id, the capture this archive last made of it, as (snapshot id, manifest).
605
+
606
+ It is read from the record the capture before this one left, so a capture that named an earlier snapshot
607
+ again, because the evidence went back to it, is the previous one. A recorded snapshot that is missing or does
608
+ not match its identity is not compared with. A capture carries forward every vanished attempt of the one
609
+ before it, so the last capture of a repository is all a later one needs.
610
+ """
611
+ record_path = latest_captures_path(store)
612
+ record = read_json(record_path) if inside(store, record_path) else None
613
+ found = {}
614
+ for repo_id in sorted(repo_ids) if isinstance(record, dict) else ():
615
+ ident = record.get(repo_id)
616
+ path = snapshot_path(store, ident) if isinstance(ident, str) and SNAPSHOT_ID.fullmatch(ident) else None
617
+ if path is None or not inside(store, path):
618
+ continue
619
+ doc = read_json(path)
620
+ try:
621
+ check_manifest(doc, path)
622
+ except Refused:
623
+ continue
624
+ if doc["schema"] == HISTORY_SCHEMA and doc["snapshot"]["id"] == ident:
625
+ found[repo_id] = (ident, doc)
626
+ return found
627
+
628
+
629
+ def record_latest_captures(store, ident, repo_ids):
630
+ """Name this capture as the last one of each of its repositories, keeping the record of any other."""
631
+ path = latest_captures_path(store)
632
+ if not inside(store, path):
633
+ raise Refused(f"the history capture {ident} was preserved, and {path} lies behind a symlink or outside the "
634
+ "archive, so the next capture cannot find it to compare with")
635
+ record = read_json(path)
636
+ record = record if isinstance(record, dict) else {}
637
+ record.update({repo_id: ident for repo_id in repo_ids})
638
+ try:
639
+ replace_atomically(path, (json.dumps(record, indent=2, sort_keys=True) + "\n").encode())
640
+ except OSError as error:
641
+ raise Refused(f"the history capture {ident} was preserved, and {path} could not be written "
642
+ f"({error.strerror or error}), so the next capture cannot find it to compare with") from None
643
+
644
+
645
+ def vanished_gap(repository, attempt, source, last_seen):
646
+ """One vanished-attempt gap: an attempt the capture last_seen held, which this capture no longer finds."""
647
+ return {"kind": "vanished-attempt", "repository": repository, "attempt": attempt, "source": source,
648
+ "last_seen": last_seen}
649
+
650
+
651
+ def vanished_attempts(repo_id, capture, attempts):
652
+ """The vanished-attempt gaps of one repository: every attempt its previous capture held, or reported vanished,
653
+ that this capture no longer finds. Nothing of it is reconstructed. An attempt or gap in the previous capture
654
+ without the fields a gap needs is passed over, since a hand-made manifest can match its own identity."""
655
+ if capture is None:
656
+ return []
657
+ last_seen, doc = capture
658
+ present = {attempt["id"] for attempt in attempts if attempt["repository"] == repo_id}
659
+
660
+ def held(item, *keys):
661
+ return isinstance(item, dict) and item.get("repository") == repo_id \
662
+ and all(isinstance(item.get(key), str) for key in keys)
663
+ gone = {}
664
+ for attempt in doc["attempts"] if isinstance(doc.get("attempts"), list) else []:
665
+ if held(attempt, "id", "source") and attempt["id"] not in present:
666
+ gone[attempt["id"]] = vanished_gap(repo_id, attempt["id"], attempt["source"], last_seen)
667
+ for gap in doc["gaps"] if isinstance(doc.get("gaps"), list) else []:
668
+ if held(gap, "attempt", "source", "last_seen") and gap.get("kind") == "vanished-attempt" \
669
+ and SNAPSHOT_ID.fullmatch(gap["last_seen"]) and gap["attempt"] not in present:
670
+ gone.setdefault(gap["attempt"], vanished_gap(repo_id, gap["attempt"], gap["source"], gap["last_seen"]))
671
+ return sorted(gone.values(), key=lambda gap: (gap["source"], gap["attempt"]))
672
+
673
+
674
+ def recorded_sessions(body):
675
+ sessions = []
676
+ if isinstance(body.get("session_id"), str) and body["session_id"] not in ("", "none"):
677
+ sessions.append(body["session_id"])
678
+ for context in body.get("contexts", []) if isinstance(body.get("contexts"), list) else []:
679
+ if isinstance(context, dict) and isinstance(context.get("session_id"), str) and context["session_id"] not in ("", "none"):
680
+ sessions.append(context["session_id"])
681
+ return sorted(set(sessions))
682
+
683
+
684
+ def ledger_issue(data):
685
+ if data is not None:
686
+ for line in data.decode(errors="replace").splitlines():
687
+ match = re.fullmatch(r"issue:\s*(\S+)", line)
688
+ if match:
689
+ return match.group(1)
690
+ return None
691
+
692
+
693
+ def native_total(body):
694
+ roots = [context for context in body.get("contexts", [])
695
+ if isinstance(context, dict) and context.get("parent") is None]
696
+ values = [context.get("cost_usd") for context in roots]
697
+ return sum(values) if values and all(isinstance(value, (int, float)) for value in values) else None
698
+
699
+
700
+ def codex_session_id(path):
701
+ try:
702
+ with path.open(errors="replace") as handle:
703
+ for line in handle:
704
+ try:
705
+ event = json.loads(line)
706
+ except ValueError:
707
+ continue
708
+ if event.get("type") == "session_meta" and isinstance(event.get("payload"), dict):
709
+ ident = event["payload"].get("id")
710
+ return ident if isinstance(ident, str) else None
711
+ except OSError:
712
+ return None
713
+ return None
714
+
715
+
716
+ def associate_sessions(found, attempts, claude_projects, codex_sessions, gaps):
717
+ """Keep exact recorded session matches and state when zero or many matched."""
718
+ referenced = defaultdict(lambda: {"attempts": [], "hosts": set()})
719
+ for attempt in attempts:
720
+ for session_id in attempt["session_ids"]:
721
+ referenced[session_id]["attempts"].append(attempt["id"])
722
+ if attempt.get("host"):
723
+ referenced[session_id]["hosts"].add(attempt["host"])
724
+ codex_index = defaultdict(list)
725
+ if codex_sessions and codex_sessions.is_dir():
726
+ for path in sorted(codex_sessions.rglob("*.jsonl")):
727
+ ident = codex_session_id(path)
728
+ if ident:
729
+ codex_index[ident].append(path)
730
+ sessions = []
731
+ for session_id, reference in sorted(referenced.items()):
732
+ candidates = []
733
+ expected = reference["hosts"]
734
+ if claude_projects and claude_projects.is_dir() and (not expected or "claude" in expected):
735
+ candidates.extend(("claude", path) for path in sorted(claude_projects.glob(f"*/{session_id}.jsonl")))
736
+ if codex_sessions and codex_sessions.is_dir() and (not expected or "codex" in expected):
737
+ candidates.extend(("codex", path) for path in codex_index.get(session_id, []))
738
+ usable = []
739
+ for host, path in candidates:
740
+ root = claude_projects if host == "claude" else codex_sessions
741
+ if path.is_symlink():
742
+ found.exclude(path, Collection.link_reason(path, root.resolve()))
743
+ elif path.is_file():
744
+ usable.append((host, path))
745
+ candidates = usable
746
+ if not candidates:
747
+ status = "absent"
748
+ gaps.append({"kind": "absent-session", "session_id": session_id,
749
+ "attempts": sorted(set(reference["attempts"]))})
750
+ elif len(candidates) > 1:
751
+ status = "ambiguous"
752
+ gaps.append({"kind": "ambiguous-session", "session_id": session_id,
753
+ "attempts": sorted(set(reference["attempts"])),
754
+ "candidates": [str(path) for _, path in candidates]})
755
+ else:
756
+ status = "associated"
757
+ sources = []
758
+ hosts = set()
759
+ for host, path in candidates:
760
+ hosts.add(host)
761
+ root = claude_projects if host == "claude" else codex_sessions
762
+ dest = f"sessions/{host}/{path.relative_to(root).as_posix()}"
763
+ found.add(path, dest, "transcript")
764
+ sources.append(dest)
765
+ if host == "claude":
766
+ child_root = path.parent / session_id / "subagents"
767
+ if child_root.is_dir() and not child_root.is_symlink():
768
+ for child in sorted(child_root.iterdir()):
769
+ if child.is_file() and not child.is_symlink() and child.suffix in (".jsonl", ".json"):
770
+ child_dest = f"sessions/claude/{child.relative_to(claude_projects).as_posix()}"
771
+ found.add(child, child_dest, "session-metadata" if child.name.endswith(".meta.json") else "transcript")
772
+ sources.append(child_dest)
773
+ host = next(iter(hosts)) if len(hosts) == 1 else (next(iter(expected)) if len(expected) == 1 else None)
774
+ sessions.append({"id": session_id, "host": host, "status": status,
775
+ "attempts": sorted(set(reference["attempts"])), "sources": sources})
776
+ return sessions
777
+
778
+
779
+ def transcript_usage(found, entries):
780
+ """Exclusive Claude-style message usage from each archived transcript source once."""
781
+ usage = defaultdict(int)
782
+ for entry in entries:
783
+ if entry["role"] != "transcript" or not entry["path"].endswith(".jsonl"):
784
+ continue
785
+ data = found.blobs.get(entry["sha256"])
786
+ if data is None:
787
+ continue
788
+ messages = {}
789
+ for raw in data.decode(errors="replace").splitlines():
790
+ try:
791
+ event = json.loads(raw)
792
+ except ValueError:
793
+ continue
794
+ message = event.get("message") or {}
795
+ if event.get("type") == "assistant" and message.get("id") and isinstance(message.get("usage"), dict):
796
+ messages[message["id"]] = message["usage"]
797
+ for message_usage in messages.values():
798
+ for key in ("input_tokens", "output_tokens", "cache_read_input_tokens", "cache_creation_input_tokens"):
799
+ value = message_usage.get(key, 0)
800
+ if isinstance(value, (int, float)):
801
+ usage[key] += value
802
+ return dict(sorted(usage.items()))
803
+
804
+
805
+ def outcome_of(body):
806
+ block = body.get("structured_output")
807
+ if isinstance(block, dict):
808
+ return block.get("outcome")
809
+ return body.get("outcome")
810
+
811
+
812
+ # ---- the coverage report ---------------------------------------------------------------------------------
813
+ #
814
+ # A view over one history capture: how completely it accounts for what was discovered, and why each gap is a gap.
815
+ # It reads the capture's manifest and nothing else, so the report over a restored archive-manifest.json is the
816
+ # report over the original. Every attempt gets a row, copies included, and every gap a sentence saying what is
817
+ # missing or unknown and why. Counts that could double a copy count it once.
818
+
819
+ COVERAGE_SCHEMA = "ship-archive-coverage/1"
820
+ # A file of pass <n> in a shift directory other than pass-<n>.json, as a history capture lays it out.
821
+ PASS_FILE = re.compile(r"(?P<shift>[^/]+/\.claude/(?:kryso|ship-loop)/[^/]+)/(?:pass-(?P<a>\d+)\.(?:final\.json|json\.raw|err|done)"
822
+ r"|ratelimit-(?P<b>\d+)-[^/]*\.json|report-(?P<c>\d+)(?:-[^/]*\.json|\.(?:json|err)))")
823
+
824
+
825
+ def coverage_report(doc):
826
+ """The ship-archive-coverage/1 report of a history capture's manifest."""
827
+ if doc.get("schema") != HISTORY_SCHEMA:
828
+ raise Refused(f"snapshot {doc['snapshot']['id']} is a single attempt's {doc.get('schema')}, and a coverage report reads "
829
+ f"a {HISTORY_SCHEMA} history capture")
830
+ # The identity check proves the manifest is unchanged, not that history wrote it, so a hand-made one may lack a field.
831
+ try:
832
+ return build_coverage(doc)
833
+ except (KeyError, TypeError, AttributeError) as why:
834
+ raise Refused(f"snapshot {doc['snapshot']['id']} is not a {HISTORY_SCHEMA} history capture this report can read: "
835
+ f"{type(why).__name__} {why}") from None
836
+
837
+
838
+ def tally(rows, key, missing="unknown"):
839
+ """How many rows hold each value of key, a missing one counted as `missing`."""
840
+ found = defaultdict(int)
841
+ for row in rows:
842
+ found[row.get(key) or missing] += 1
843
+ return dict(sorted(found.items()))
844
+
845
+
846
+ def build_coverage(doc):
847
+ attempts, entries, inventory = doc["attempts"], doc["entries"], doc["inventory"]
848
+ counted = [attempt for attempt in attempts if attempt["copy_of"] is None]
849
+ gaps = coverage_gaps(doc)
850
+ touches = defaultdict(set)
851
+ for gap in gaps:
852
+ for ident in gap["attempts"]:
853
+ touches[ident].add(gap["kind"])
854
+ statuses = {session["id"]: session["status"] for session in doc["sessions"]}
855
+ sessions = tally(doc["sessions"], "status")
856
+ sources = [{"attempt": attempt["id"], "identity": attempt["identity"], "repository": attempt["repository"],
857
+ "issue": attempt["issue"], "outcome": attempt["outcome"], "activity": attempt["activity"],
858
+ "shift": attempt["shift"], "source": attempt["source"], "copy_of": attempt["copy_of"],
859
+ "retries": attempt["retries"], "reported_usd": attempt["reported_usd"],
860
+ "sessions": [{"id": ident, "status": statuses.get(ident, "absent")} for ident in attempt["session_ids"]],
861
+ "gaps": sorted(touches[attempt["id"]])}
862
+ for attempt in attempts]
863
+ return {
864
+ "schema": COVERAGE_SCHEMA,
865
+ "snapshot": {"id": doc["snapshot"]["id"], "captured_at": doc["snapshot"].get("captured_at"),
866
+ "completeness": doc["collection"]["completeness"]},
867
+ "inventory": {"repositories": len(doc["repositories"]), "attempts": len(attempts), "files": len(entries),
868
+ "bytes": sum(entry["bytes"] for entry in entries), "excluded": len(doc["excluded"]),
869
+ "errors": len(doc["collection"]["errors"]), "locations": inventory["coverage"],
870
+ "gaps": len(gaps), "gap_kinds": tally(gaps, "kind")},
871
+ "repositories": [{"name": repo["name"], "source": repo["source"], "files": repo["files"], "bytes": repo["bytes"],
872
+ "errors": repo["errors"],
873
+ "attempts": sum(attempt["repository"] == repo["id"] for attempt in attempts),
874
+ "gaps": sum(gap["repository"] == repo["id"] for gap in gaps)}
875
+ for repo in doc["repositories"]],
876
+ "attempts": {"total": len(attempts), "counted": len(counted), "copies": len(attempts) - len(counted),
877
+ "identity": tally(counted, "identity"), "outcomes": tally(counted, "outcome"),
878
+ "activity": tally(counted, "activity"),
879
+ # A native pass records a rate limit only as its outcome, with no retry file, so either marks one.
880
+ "rate_limited": sum(attempt["outcome"] == "rate-limited" or attempt["retries"] > 0 for attempt in counted),
881
+ "retries": sum(attempt["retries"] for attempt in counted)},
882
+ "sessions": {"associated": sessions.get("associated", 0), "ambiguous": sessions.get("ambiguous", 0),
883
+ "absent": sessions.get("absent", 0), "unrecorded": sum(not attempt["session_ids"] for attempt in counted)},
884
+ "files": {"conditions": inventory["conditions"], "roles": inventory["roles"]},
885
+ "sources": sources,
886
+ "gaps": gaps,
887
+ "excluded": doc["excluded"],
888
+ }
889
+
890
+
891
+ def coverage_gaps(doc):
892
+ """Every gap in a history capture, each with the sentence that says why it is one, sorted by kind.
893
+
894
+ A gap kind the capture records and this report has no sentence for is refused, so a newer capture is never
895
+ reported with a gap left out.
896
+ """
897
+ attempts = doc["attempts"]
898
+ owner = {attempt["id"]: attempt["repository"] for attempt in attempts}
899
+ roots = [(repo["source"], repo["id"]) for repo in doc["repositories"]]
900
+ names = {repo["id"] for repo in doc["repositories"]}
901
+ paths = {entry["path"] for entry in doc["entries"]}
902
+
903
+ def gap(kind, subject, why, repository=None, ids=()):
904
+ return {"kind": kind, "subject": subject, "repository": repository, "attempts": sorted(set(ids)), "why": why}
905
+
906
+ def one_repository(ids):
907
+ held = {owner.get(ident) for ident in ids}
908
+ return held.pop() if len(held) == 1 else None
909
+
910
+ def repository_of(source):
911
+ return next((ident for top, ident in roots if source == top or source.startswith(top + "/")), None)
912
+ rows, malformed, missing_inputs = [], set(), set()
913
+ for held in doc["gaps"]:
914
+ kind = held["kind"]
915
+ if kind == "malformed-attempt":
916
+ malformed.add(f"{held['repository']}/{held['source']}")
917
+ state = "empty" if held["condition"] == "empty" else "not valid JSON"
918
+ rows.append(gap(kind, held["source"], f"the pass result is {state}, so no attempt, outcome or session can be read "
919
+ "from it. Its bytes are kept as found", held["repository"]))
920
+ elif kind == "report-body-unavailable":
921
+ ids = [a["id"] for a in attempts if a["repository"] == held["repository"] and a["source"] == held["source"]]
922
+ rows.append(gap(kind, held["source"], held["reason"], held["repository"], ids))
923
+ elif kind == "missing-input":
924
+ missing_inputs.add(held["source"])
925
+ rows.append(gap(kind, held["source"], "it was named as an input and was not there when the capture looked, so "
926
+ "the capture is partial"))
927
+ elif kind == "absent-session":
928
+ ids = held["attempts"]
929
+ rows.append(gap(kind, held["session_id"], "an attempt records this session id and no transcript carrying it was "
930
+ "found under the host session directories the capture was given, so the transcript and the usage "
931
+ "in it are missing", one_repository(ids), ids))
932
+ elif kind == "ambiguous-session":
933
+ ids = held["attempts"]
934
+ rows.append(gap(kind, held["session_id"], f"{len(held['candidates'])} transcripts carry this session id. All of "
935
+ "them are kept and none is chosen, so none is counted as the attempt's", one_repository(ids), ids))
936
+ elif kind == "vanished-attempt":
937
+ rows.append(gap(kind, held["source"], f"an earlier capture held this attempt and this one no longer finds it, "
938
+ f"so its evidence is only in snapshot {held['last_seen']}. Nothing of it is reconstructed",
939
+ held["repository"], [held["attempt"]]))
940
+ else:
941
+ raise Refused(f"the capture records a gap of kind {kind!r}, and this report has no reason to give for it, so it "
942
+ "reports nothing rather than leave the gap out")
943
+ for error in doc["collection"]["errors"]:
944
+ # A missing input is a collection error too, and it is already its own gap.
945
+ if error["source"] in missing_inputs:
946
+ continue
947
+ rows.append(gap("capture-error", error["source"], f"the file was there and its bytes are not in this capture "
948
+ f"({error['error']}), so the capture is partial", repository_of(error["source"])))
949
+ for entry in doc["entries"]:
950
+ state, path = entry["condition"], entry["path"]
951
+ if path in malformed or not (state == "invalid-json" or (state == "empty" and path.endswith((".json", ".jsonl")))):
952
+ continue
953
+ first = path.split("/", 1)[0]
954
+ rows.append(gap("invalid-file", path, f"the file is kept byte for byte and it is {'empty' if state == 'empty' else 'not valid JSON'}, "
955
+ "so nothing in it is read", first if first in names else None))
956
+ # A pass that died before writing its result leaves files no attempt holds, and the result's bytes are what is missing.
957
+ orphans = defaultdict(list)
958
+ for path in sorted(paths):
959
+ found = PASS_FILE.fullmatch(path)
960
+ number = found and (found.group("a") or found.group("b") or found.group("c"))
961
+ if number and not found.group("shift").endswith("/shipped") and f"{found.group('shift')}/pass-{number}.json" not in paths:
962
+ orphans[(found.group("shift"), number)].append(path.rsplit("/", 1)[1])
963
+ for (shift, number), files in sorted(orphans.items()):
964
+ repository, below = shift.split("/", 1)
965
+ rows.append(gap("missing-result", f"{below}/pass-{number}.json", f"the shift kept {', '.join(files)} of pass {number} "
966
+ f"and no pass-{number}.json, so no attempt holds them and the pass's outcome, session and cost are "
967
+ "unknown", repository if repository in names else None))
968
+ # A copy is the same bytes saved twice, so its gaps are the original's and are not listed again.
969
+ for attempt in attempts:
970
+ if attempt["copy_of"] is not None:
971
+ continue
972
+ ident, repository, source = attempt["id"], attempt["repository"], attempt["source"]
973
+ if attempt["activity"] == "active":
974
+ rows.append(gap("active-attempt", source, "the pass was still running when the capture was taken, so what it "
975
+ "wrote afterwards is only in a later capture", repository, [ident]))
976
+ if attempt["outcome"] is None:
977
+ rows.append(gap("unknown-outcome", source, "neither its result nor its checkpoint records an outcome", repository, [ident]))
978
+ if attempt["issue"] is None:
979
+ rows.append(gap("unknown-issue", source, "no issue number is recorded with it, and none is guessed from a nearby "
980
+ "file or time", repository, [ident]))
981
+ if not attempt["session_ids"]:
982
+ rows.append(gap("unrecorded-session", source, "it records no session id, so no transcript can be associated "
983
+ "with it", repository, [ident]))
984
+ if attempt["reported_usd"] is None:
985
+ rows.append(gap("unknown-cost", source, "no host total is recorded with it, so its cost is unknown rather than "
986
+ "zero", repository, [ident]))
987
+ return sorted(rows, key=lambda row: (row["kind"], row["repository"] or "", row["subject"]))
988
+
989
+
990
+ def check_held_object(store, digest):
991
+ """Refuse when the archive already holds this object with other bytes."""
992
+ path = object_path(store, digest)
993
+ # A linked directory above the object would let a read or a publish leave the archive.
994
+ if not inside(store, path):
995
+ raise Refused(f"archive object {path} lies behind a symlink or outside the archive, so the archive is unchanged")
996
+ if not os.path.lexists(path):
997
+ return
998
+ try:
999
+ held = path.read_bytes() if path.is_file() else None
1000
+ except OSError as error:
1001
+ raise Refused(f"cannot read archive object {path}: {error.strerror}, so the archive is unchanged") from error
1002
+ if held is None or sha256(held) != digest:
1003
+ raise Refused(f"archive object {path} exists with other bytes, so the archive is corrupt. It is unchanged")
1004
+
1005
+
1006
+ def check_held_snapshot(store, ident):
1007
+ """True when the archive already holds this snapshot intact. Refuse when it holds a corrupt one."""
1008
+ path = snapshot_path(store, ident)
1009
+ if not inside(store, path):
1010
+ raise Refused(f"snapshot {path} lies behind a symlink or outside the archive, so the archive is unchanged")
1011
+ if not os.path.lexists(path):
1012
+ return False
1013
+ held = read_json(path)
1014
+ # The embedded identity is checked as well as the hash, which leaves the `snapshot` field out.
1015
+ embedded = held.get("snapshot") if isinstance(held, dict) else None
1016
+ if not isinstance(embedded, dict) or snapshot_id(held) != ident or embedded.get("id") != ident:
1017
+ raise Refused(f"snapshot {path} exists but does not match its identity, so the archive is corrupt. It is unchanged")
1018
+ return True
1019
+
1020
+
1021
+ def put_manifest(store, ident, manifest):
1022
+ doc = {"schema": manifest["schema"], "snapshot": {"id": ident, "captured_at": now()},
1023
+ **{k: v for k, v in manifest.items() if k != "schema"}}
1024
+ if publish(snapshot_path(store, ident), (json.dumps(doc, indent=2) + "\n").encode()):
1025
+ return "created"
1026
+ # Another collector published the same snapshot between the check and the write.
1027
+ check_held_snapshot(store, ident)
1028
+ return "unchanged"
1029
+
1030
+
1031
+ def preserve_manifest(store, found, manifest):
1032
+ """Publish one immutable manifest and its objects after checking held archive bytes."""
1033
+ ident = snapshot_id(manifest)
1034
+ for digest in found.blobs:
1035
+ check_held_object(store, digest)
1036
+ held = check_held_snapshot(store, ident)
1037
+ for digest, data in found.blobs.items():
1038
+ if not publish(object_path(store, digest), data):
1039
+ check_held_object(store, digest)
1040
+ return ident, "unchanged" if held else put_manifest(store, ident, manifest)
1041
+
1042
+
1043
+ # ---- verify and restore ----------------------------------------------------------------
1044
+
1045
+ def inside(store, path):
1046
+ """Whether path, and every directory between it and the store, is a real non-link path inside the store."""
1047
+ real = store.resolve()
1048
+ current = path
1049
+ while current != store:
1050
+ if current.is_symlink():
1051
+ return False
1052
+ current = current.parent
1053
+ if current == current.parent:
1054
+ return False
1055
+ return real in path.resolve().parents
1056
+
1057
+
1058
+ def read_object(store, entry):
1059
+ """An entry's archived bytes, or the reason they cannot be trusted."""
1060
+ digest = entry.get("sha256")
1061
+ if not isinstance(digest, str) or not SNAPSHOT_ID.fullmatch(digest):
1062
+ return None, f"entry {entry.get('path')!r} has no valid sha256"
1063
+ path = object_path(store, digest)
1064
+ if not inside(store, path):
1065
+ return None, f"object {digest} is a symlink or lies outside the archive"
1066
+ try:
1067
+ data = path.read_bytes()
1068
+ except OSError:
1069
+ return None, f"object {digest} is missing"
1070
+ if sha256(data) != digest or len(data) != entry.get("bytes"):
1071
+ return None, f"object {digest} does not match its hash or size"
1072
+ return data, None
1073
+
1074
+
1075
+ def parse_manifest(raw, source):
1076
+ """A manifest's document, refused unless it is a ship-archive-manifest/1 whose id matches its content."""
1077
+ try:
1078
+ doc = json.loads(raw)
1079
+ except ValueError:
1080
+ doc = None
1081
+ check_manifest(doc, source)
1082
+ return doc
1083
+
1084
+
1085
+ def check_manifest(doc, source):
1086
+ if not isinstance(doc, dict) or doc.get("schema") not in (MANIFEST_SCHEMA, HISTORY_SCHEMA):
1087
+ raise Refused(f"{source} is not a {MANIFEST_SCHEMA} or {HISTORY_SCHEMA} manifest")
1088
+ if not isinstance(doc.get("snapshot"), dict) or doc["snapshot"].get("id") != snapshot_id(doc):
1089
+ raise Refused(f"{source} does not match its snapshot identity, so someone edited it or it is corrupt")
1090
+ if not isinstance(doc.get("entries"), list):
1091
+ raise Refused(f"{source} has no entries list")
1092
+
1093
+
1094
+ def safe_path(path):
1095
+ """A relative POSIX path with no traversal, or None."""
1096
+ if not isinstance(path, str) or not path or "\\" in path or "\0" in path or path.startswith("/"):
1097
+ return None
1098
+ parts = path.split("/")
1099
+ if any(p in ("", ".", "..") for p in parts) or path == RESTORED_MANIFEST:
1100
+ return None
1101
+ return PurePosixPath(path)
1102
+
1103
+
1104
+ def verify(store, wanted):
1105
+ snapshots = sorted((store / "snapshots").glob("*.json")) if (store / "snapshots").is_dir() else []
1106
+ problems, objects = [], {}
1107
+ if wanted:
1108
+ snapshots = [snapshot_path(store, wanted)]
1109
+ if not SNAPSHOT_ID.fullmatch(wanted) or not inside(store, snapshots[0]):
1110
+ return {"snapshots": 0, "objects": 0, "problems": [f"{wanted!r} is not a snapshot id"]}
1111
+ for path in snapshots:
1112
+ if path.is_symlink() or not path.is_file():
1113
+ problems.append(f"snapshot {path.stem} is missing or a symlink")
1114
+ continue
1115
+ doc = read_json(path)
1116
+ try:
1117
+ check_manifest(doc, path)
1118
+ except Refused as why:
1119
+ problems.append(str(why))
1120
+ continue
1121
+ if doc["snapshot"]["id"] != path.stem:
1122
+ problems.append(f"snapshot {path.stem} names identity {doc['snapshot']['id']}")
1123
+ for entry in doc["entries"]:
1124
+ if safe_path(entry.get("path")) is None:
1125
+ problems.append(f"snapshot {path.stem} has an unsafe path {entry.get('path')!r}")
1126
+ if entry.get("sha256") in objects:
1127
+ if objects[entry["sha256"]] != entry.get("bytes"):
1128
+ problems.append(f"snapshot {path.stem}: entry {entry.get('path')!r} gives the wrong size for object {entry['sha256']}")
1129
+ continue
1130
+ _, why = read_object(store, entry)
1131
+ if why:
1132
+ problems.append(f"snapshot {path.stem}: {why}")
1133
+ else:
1134
+ objects[entry["sha256"]] = entry["bytes"]
1135
+ return {"snapshots": len(snapshots), "objects": len(objects), "problems": problems}
1136
+
1137
+
1138
+ def load_snapshot(store, wanted):
1139
+ """The manifest bytes and document of one snapshot the local archive holds."""
1140
+ path = snapshot_path(store, wanted)
1141
+ if not SNAPSHOT_ID.fullmatch(wanted) or not inside(store, path) or not path.is_file():
1142
+ raise Refused(f"no snapshot {wanted} in {store}")
1143
+ try:
1144
+ raw = path.read_bytes()
1145
+ except OSError as error:
1146
+ raise Refused(f"cannot read snapshot {wanted} in {store}: {error.strerror}") from None
1147
+ return parse_manifest(raw, wanted), raw
1148
+
1149
+
1150
+ def read_manifest_file(manifest_file):
1151
+ """(document, bytes) of a manifest named by path, such as a restored archive-manifest.json. A symlink is refused."""
1152
+ if manifest_file.is_symlink():
1153
+ raise Refused(f"{manifest_file} is a symlink")
1154
+ try:
1155
+ raw = manifest_file.read_bytes()
1156
+ except OSError as error:
1157
+ raise Refused(f"cannot read {manifest_file}: {error.strerror}")
1158
+ return parse_manifest(raw, manifest_file), raw
1159
+
1160
+
1161
+ def restore(store, wanted, manifest_file, target):
1162
+ if manifest_file:
1163
+ doc, raw = read_manifest_file(manifest_file)
1164
+ if wanted and doc["snapshot"]["id"] != wanted:
1165
+ raise Refused(f"the manifest is snapshot {doc['snapshot']['id']}, not {wanted}")
1166
+ else:
1167
+ doc, raw = load_snapshot(store, wanted)
1168
+ return rebuild(doc, raw, lambda entry: read_object(store, entry), target)
1169
+
1170
+
1171
+ def plan_layout(doc):
1172
+ """The (path, entry) files a manifest lays out. Refuse an entry restore cannot use, an unsafe path or a collision.
1173
+
1174
+ Restore, remote verification and upload all ask this, so a snapshot is never preserved or reported clean
1175
+ when restoring it would be refused.
1176
+ """
1177
+ plan, files, dirs = [], set(), set()
1178
+ for number, entry in enumerate(doc["entries"], 1):
1179
+ # A bool is an int in Python, and True equals the length of a one-byte file.
1180
+ if not (isinstance(entry, dict) and isinstance(entry.get("sha256"), str)
1181
+ and isinstance(entry.get("bytes"), int) and not isinstance(entry["bytes"], bool)):
1182
+ raise Refused(f"entry {number} has no sha256 or no whole-number size")
1183
+ rel = safe_path(entry.get("path"))
1184
+ if rel is None:
1185
+ raise Refused(f"unsafe path {entry.get('path')!r} in the manifest")
1186
+ parents = set(rel.parents) - {PurePosixPath(".")}
1187
+ # A file twice, or a file where another entry needs a directory, is not a layout.
1188
+ if rel in files or rel in dirs or parents & files:
1189
+ raise Refused(f"unsafe path {entry['path']!r}: it collides with another entry")
1190
+ files.add(rel)
1191
+ dirs |= parents
1192
+ plan.append((rel, entry))
1193
+ return plan
1194
+
1195
+
1196
+ def rebuild(doc, raw, read, target):
1197
+ """Write a snapshot's layout under an empty root. `read` gives each entry's verified bytes, or why it cannot."""
1198
+ # Every path is checked before anything is written.
1199
+ try:
1200
+ plan = plan_layout(doc)
1201
+ except Refused as why:
1202
+ raise Refused(f"{why}, so the restore wrote nothing") from None
1203
+ if target.exists() and (target.is_symlink() or not target.is_dir() or any(target.iterdir())):
1204
+ raise Refused(f"{target} is not an empty directory, so the restore wrote nothing")
1205
+ # The files go into a staging directory, each read and re-hashed, and the staging directory is renamed
1206
+ # into place only once all of them are in. A failure leaves the root, and the directories above it, as found.
1207
+ made, above = [], target.parent
1208
+ while not above.exists():
1209
+ made.append(above)
1210
+ above = above.parent
1211
+ staging = None
1212
+ try:
1213
+ target.parent.mkdir(parents=True, exist_ok=True)
1214
+ staging = Path(tempfile.mkdtemp(dir=target.parent, prefix=f".{target.name}.restore-"))
1215
+ for rel, entry in plan:
1216
+ data, why = read(entry)
1217
+ if why:
1218
+ raise Refused(f"{why}, so the restore wrote nothing")
1219
+ dest = staging.joinpath(*rel.parts)
1220
+ dest.parent.mkdir(parents=True, exist_ok=True)
1221
+ with open(dest, "xb") as out:
1222
+ out.write(data)
1223
+ if sha256(dest.read_bytes()) != entry["sha256"]:
1224
+ raise Refused(f"object {entry['sha256']} changed while it was restored, so the restore wrote nothing")
1225
+ (staging / RESTORED_MANIFEST).write_bytes(raw)
1226
+ if target.exists():
1227
+ target.rmdir()
1228
+ staging.rename(target)
1229
+ except BaseException:
1230
+ if staging:
1231
+ shutil.rmtree(staging, ignore_errors=True)
1232
+ for directory in made:
1233
+ try:
1234
+ directory.rmdir()
1235
+ except OSError:
1236
+ pass
1237
+ raise
1238
+ repos = sorted({str(target / rel.parts[0]) for rel, _ in plan
1239
+ if rel.parts[0] not in ("inputs", "sessions") and len(rel.parts) > 1})
1240
+ return {"restored": len(plan), "root": str(target), "snapshot": doc["snapshot"]["id"],
1241
+ "completeness": doc.get("collection", {}).get("completeness"), "repositories": repos}
1242
+
1243
+
1244
+ # ---- the remote: upload, verify and restore --------------------------------------------------------
1245
+
1246
+ COMPLETE_SCHEMA = "ship-archive-complete/1"
1247
+ COMPLETENESS = ("complete", "partial")
1248
+ ABSENT = "no completion manifest: the snapshot is not preserved on this remote"
1249
+
1250
+
1251
+ def staging_dir(store, remote):
1252
+ """Where encrypted copies are kept between attempts, so a retry uploads the same ciphertext. One per recipient."""
1253
+ return store / "remote" / sha256(remote.get("encryption.recipient").encode())[:16]
1254
+
1255
+
1256
+ def staged_name(digest, cipher_digest):
1257
+ """A kept encrypted copy's file name: the original hash, then the hash of the ciphertext the file holds."""
1258
+ return f"{digest}.{cipher_digest}.age"
1259
+
1260
+
1261
+ def staged_digest(path):
1262
+ """The original hash a kept copy's file name starts with."""
1263
+ return path.name.split(".", 1)[0]
1264
+
1265
+
1266
+ def staged_copies(stage):
1267
+ """Every kept encrypted copy, by the original hash its name starts with, from one listing of the staging directory."""
1268
+ held = {}
1269
+ for path in stage.iterdir() if stage.is_dir() else ():
1270
+ if path.name.endswith(".age"):
1271
+ held.setdefault(staged_digest(path), []).append(path)
1272
+ return held
1273
+
1274
+
1275
+ def staged_ciphertext(paths):
1276
+ """The kept encrypted copy among an object's staged paths, or None. Its name holds its own hash, so a damaged copy is discarded."""
1277
+ for path in paths:
1278
+ try:
1279
+ data = path.read_bytes()
1280
+ except OSError:
1281
+ continue
1282
+ if path.name == staged_name(staged_digest(path), sha256(data)):
1283
+ return data
1284
+ path.unlink()
1285
+ return None
1286
+
1287
+
1288
+ def sync_directory(path):
1289
+ """Flush a directory's own entries to disk, so a name made or renamed in it survives a power loss."""
1290
+ directory = os.open(path, os.O_RDONLY)
1291
+ try:
1292
+ os.fsync(directory)
1293
+ finally:
1294
+ os.close(directory)
1295
+
1296
+
1297
+ def make_durable_directories(path):
1298
+ """Make path and every missing directory above it, each synced into its parent before the next is made.
1299
+
1300
+ A synced file or rename inside a new directory is lost with it when the directory's own name never reached
1301
+ the disk, so the queue and the staged ciphertext rest on this as much as on their own syncs.
1302
+ """
1303
+ missing = []
1304
+ while not path.exists():
1305
+ missing.append(path)
1306
+ path = path.parent
1307
+ for directory in reversed(missing):
1308
+ try:
1309
+ directory.mkdir()
1310
+ except FileExistsError:
1311
+ # Another run made it, and may not have synced it yet, so it is synced here as well.
1312
+ if not directory.is_dir():
1313
+ raise
1314
+ sync_directory(directory.parent)
1315
+
1316
+
1317
+ def replace_atomically(path, data):
1318
+ """Write data at path through a temporary file beside it, so a reader sees the old file or the new one, never half."""
1319
+ make_durable_directories(path.parent)
1320
+ fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=".tmp-")
1321
+ try:
1322
+ with os.fdopen(fd, "wb") as handle:
1323
+ handle.write(data)
1324
+ handle.flush()
1325
+ os.fsync(handle.fileno())
1326
+ os.replace(tmp, path)
1327
+ # The rename is durable only once the directory holding it is, and the queue's promise rests on it.
1328
+ sync_directory(path.parent)
1329
+ finally:
1330
+ if os.path.exists(tmp):
1331
+ os.unlink(tmp)
1332
+
1333
+
1334
+ def write_staged(stage, digest, data):
1335
+ replace_atomically(stage / staged_name(digest, sha256(data)), data)
1336
+
1337
+
1338
+ def read_staged(stage, item):
1339
+ """The staged ciphertext of a queue item about to be sent, checked against the identity the queue holds for it."""
1340
+ path = stage / staged_name(item["sha256"], item["ciphertext_sha256"])
1341
+ try:
1342
+ data = path.read_bytes()
1343
+ except OSError as error:
1344
+ raise Refused(f"the staged copy {path} went before it was sent: {error.strerror or error}. A repeat encrypts "
1345
+ "the object again") from None
1346
+ if sha256(data) != item["ciphertext_sha256"] or len(data) != item["ciphertext_bytes"]:
1347
+ path.unlink(missing_ok=True)
1348
+ raise Refused(f"the staged copy {path} changed after it was encrypted, so it was not sent. A repeat encrypts the "
1349
+ "object again")
1350
+ return data
1351
+
1352
+
1353
+ def completion_problem(completion, ident):
1354
+ """Why a parsed completion manifest is not a usable one for this snapshot, or None."""
1355
+ if not isinstance(completion, dict) or completion.get("schema") != COMPLETE_SCHEMA or completion.get("snapshot") != ident:
1356
+ return f"the completion manifest is not a {COMPLETE_SCHEMA} document for snapshot {ident}"
1357
+ manifest, encryption, objects = completion.get("manifest"), completion.get("encryption"), completion.get("objects")
1358
+
1359
+ def typed(item, kind, *keys):
1360
+ return isinstance(item, dict) and all(isinstance(item.get(k), kind) and not isinstance(item.get(k), bool) for k in keys)
1361
+ shapes = (completion.get("completeness") in COMPLETENESS,
1362
+ typed(manifest, str, "object", "sha256") and typed(manifest, int, "bytes") and manifest["object"] == archive_remote.manifest_name(ident),
1363
+ typed(encryption, str, "tool", "recipient") and encryption["tool"] == "age" and archive_remote.RECIPIENT.fullmatch(encryption["recipient"]),
1364
+ isinstance(objects, list) and all(typed(o, str, "sha256", "object", "ciphertext_sha256") and typed(o, int, "bytes", "ciphertext_bytes")
1365
+ for o in objects))
1366
+ return None if all(shapes) else f"the completion manifest for snapshot {ident} is malformed"
1367
+
1368
+
1369
+ def read_remote(remote_store, ident):
1370
+ """A snapshot as the remote holds it: (completion, manifest document, manifest bytes, problems).
1371
+
1372
+ Only the completion manifest makes a snapshot preserved, so a snapshot without a usable one has no document here.
1373
+ """
1374
+ raw = remote_store.read(archive_remote.complete_name(ident))
1375
+ if raw is None:
1376
+ return None, None, None, [ABSENT]
1377
+ try:
1378
+ completion = json.loads(raw)
1379
+ except ValueError:
1380
+ return None, None, None, ["the completion manifest is not valid JSON"]
1381
+ why = completion_problem(completion, ident)
1382
+ if why:
1383
+ return None, None, None, [why]
1384
+ manifest, problems, doc = completion["manifest"], [], None
1385
+ held = remote_store.read(manifest["object"])
1386
+ if held is None:
1387
+ problems.append(f"manifest {manifest['object']} is missing from the remote")
1388
+ elif sha256(held) != manifest["sha256"] or len(held) != manifest["bytes"]:
1389
+ problems.append(f"manifest {manifest['object']} does not match the completion manifest's hash or size")
1390
+ else:
1391
+ try:
1392
+ doc = parse_manifest(held, manifest["object"])
1393
+ except Refused as why:
1394
+ problems.append(f"manifest {manifest['object']} is not snapshot {ident}: {why}")
1395
+ else:
1396
+ # A valid manifest of another snapshot, vouched for by this completion manifest's hash, is still not this snapshot.
1397
+ if doc["snapshot"]["id"] != ident:
1398
+ problems.append(f"manifest {manifest['object']} is snapshot {doc['snapshot']['id']}, not {ident}")
1399
+ doc = None
1400
+ else:
1401
+ try:
1402
+ plan_layout(doc)
1403
+ except Refused as why:
1404
+ doc = None
1405
+ problems.append(f"manifest {manifest['object']} cannot be restored: {why}")
1406
+ return completion, doc, held, problems
1407
+
1408
+
1409
+ def fetch_ciphertext(remote_store, item):
1410
+ """One data object's ciphertext, checked against the completion manifest, or why it cannot be trusted."""
1411
+ name, digest = item["object"], item["ciphertext_sha256"]
1412
+ found = archive_remote.OBJECT_NAME.fullmatch(name)
1413
+ if not found or found.group(1) != digest:
1414
+ return None, f"completion manifest names an unsafe or mismatched object {name!r}"
1415
+ data = remote_store.read(name)
1416
+ if data is None:
1417
+ return None, f"object {name} is missing from the remote"
1418
+ if sha256(data) != digest or len(data) != item["ciphertext_bytes"]:
1419
+ return None, f"object {name} does not match its ciphertext hash or size"
1420
+ return data, None
1421
+
1422
+
1423
+ def read_plain(remote_store, item, cipher, identity):
1424
+ """One object's original bytes: fetched, checked, decrypted and checked again. (bytes, why)."""
1425
+ data, why = fetch_ciphertext(remote_store, item)
1426
+ if why:
1427
+ return None, why
1428
+ try:
1429
+ plain = cipher.decrypt(data, identity)
1430
+ except Refused as error:
1431
+ return None, f"object {item['object']}: {error}"
1432
+ if sha256(plain) != item["sha256"] or len(plain) != item["bytes"]:
1433
+ return None, f"object {item['object']} decrypted to other bytes than its original hash or size"
1434
+ return plain, None
1435
+
1436
+
1437
+ def coverage_problems(completion, doc):
1438
+ """Manifest entries the completion manifest does not cover, and the reverse."""
1439
+ covered = {o["sha256"]: o["bytes"] for o in completion["objects"]}
1440
+ wanted = {e["sha256"]: e["bytes"] for e in doc["entries"]}
1441
+ return ([f"entry object {d} is not covered by the completion manifest" for d in wanted if covered.get(d) != wanted[d]]
1442
+ + [f"the completion manifest holds object {d}, which the manifest does not name" for d in covered if d not in wanted])
1443
+
1444
+
1445
+ def verify_remote(remote, ident, identity):
1446
+ """Check a snapshot on the remote: the ciphertext always, and the original bytes when an identity is given."""
1447
+ archive_remote.require_ready(remote)
1448
+ remote_store = archive_remote.open_store(remote, "recovery")
1449
+ completion, doc, _, problems = read_remote(remote_store, ident)
1450
+ cipher = archive_remote.Age() if identity else None
1451
+ if doc:
1452
+ problems += coverage_problems(completion, doc)
1453
+ for item in completion["objects"]:
1454
+ _, why = read_plain(remote_store, item, cipher, identity) if cipher else fetch_ciphertext(remote_store, item)
1455
+ if why:
1456
+ problems.append(why)
1457
+ return {"snapshot": ident, "completeness": completion["completeness"] if completion else None,
1458
+ "objects": len(completion["objects"]) if completion else 0, "checked": "plaintext" if identity else "ciphertext",
1459
+ "problems": problems}
1460
+
1461
+
1462
+ def restore_remote(remote, ident, identity, target):
1463
+ archive_remote.require_ready(remote)
1464
+ if identity is None or not identity.is_file():
1465
+ raise Refused(f"no recovery identity at {identity}: the age identity file that decrypts the evidence, so the restore wrote nothing")
1466
+ cipher = archive_remote.Age()
1467
+ remote_store = archive_remote.open_store(remote, "recovery")
1468
+ try:
1469
+ completion, doc, held, problems = read_remote(remote_store, ident)
1470
+ if doc:
1471
+ problems += coverage_problems(completion, doc)
1472
+ if problems:
1473
+ raise Refused(f"snapshot {ident} cannot be recovered from this remote: {'; '.join(problems)}, so the restore wrote nothing")
1474
+ index = {o["sha256"]: o for o in completion["objects"]}
1475
+
1476
+ def read(entry):
1477
+ return read_plain(remote_store, index[entry["sha256"]], cipher, identity)
1478
+ return rebuild(doc, held, read, target)
1479
+ except archive_remote.StoreError as error:
1480
+ raise Refused(f"the remote failed while restoring snapshot {ident}: {error}, so the restore wrote nothing") from error
1481
+
1482
+
1483
+ # ---- the upload queue ---------------------------------------------------------------------
1484
+ #
1485
+ # Each upload is recorded in the local archive before the remote is touched, one entry per snapshot and remote,
1486
+ # so a run that dies or loses the network leaves its pending work on disk for the next one. An item moves from
1487
+ # pending to uploaded when its create returns and to verified when it is read back with the bytes it was sent.
1488
+ # A snapshot is verified only once its completion manifest is. Entries are never removed: the queue is the
1489
+ # local record of what reached the remote, and nothing local deletes anything remote.
1490
+ #
1491
+ # A change to one item is appended to a change log beside the entry, one short line, rather than rewriting the
1492
+ # entry, so what an upload writes grows with its objects and not with objects times the entry's size. Reading an
1493
+ # entry replays its change log, and a save of the whole entry folds the log in and starts the next one.
1494
+
1495
+ QUEUE_SCHEMA = "ship-archive-queue/1"
1496
+ # What names one encrypted object on the remote, as the queue, the known records and the completion manifest hold it.
1497
+ IDENTITY = ("object", "ciphertext_sha256", "ciphertext_bytes")
1498
+ STATES = ("pending", "uploaded", "verified")
1499
+ ITEM_KINDS = ("object", "manifest", "completion")
1500
+
1501
+
1502
+ def destination(remote):
1503
+ """Where a remote's objects go. A queue is kept per destination, so two configurations naming one place share it."""
1504
+ if remote.kind == "local":
1505
+ return f"local:{Path(remote.get('root')).expanduser().resolve()}"
1506
+ # The store treats evidence and evidence/ as one prefix, so the queue does too.
1507
+ prefix = (remote.get("prefix") or "").rstrip("/")
1508
+ return f"s3://{remote.get('bucket')}/{prefix + '/' if prefix else ''}"
1509
+
1510
+
1511
+ def entry_state(entry):
1512
+ """A snapshot's state is its least advanced item's, so it is verified only when its completion manifest is."""
1513
+ return STATES[min(STATES.index(item["state"]) for item in entry["items"])]
1514
+
1515
+
1516
+ def item_problem(item):
1517
+ """Why one queue item cannot be read, or None. Every field status and upload use is checked, so neither trips on it."""
1518
+ if not isinstance(item, dict) or item.get("kind") not in ITEM_KINDS or item.get("state") not in STATES:
1519
+ return "an item has no known kind or state"
1520
+ if not isinstance(item.get("object"), (str, type(None))):
1521
+ return "an item's object name is not a string"
1522
+ if not isinstance(item.get("tried", False), bool):
1523
+ return "an item's create marker is not true or false"
1524
+ if item["kind"] == "completion":
1525
+ return None
1526
+ if not isinstance(item.get("sha256"), str) or not SNAPSHOT_ID.fullmatch(item["sha256"]) \
1527
+ or not isinstance(item.get("bytes"), int) or isinstance(item["bytes"], bool):
1528
+ return f"a {item['kind']} item has no valid sha256 or size"
1529
+ if item["kind"] == "object" and item["object"] is not None:
1530
+ if not (isinstance(item.get("ciphertext_sha256"), str) and SNAPSHOT_ID.fullmatch(item["ciphertext_sha256"])
1531
+ and isinstance(item.get("ciphertext_bytes"), int) and not isinstance(item["ciphertext_bytes"], bool)):
1532
+ return "an object item names an object without its ciphertext hash and size"
1533
+ if item["object"] != archive_remote.object_name(item["ciphertext_sha256"]):
1534
+ return "an object item's name is not the one its ciphertext hash gives"
1535
+ return None
1536
+
1537
+
1538
+ def entry_problem(entry, ident):
1539
+ """Why a queue file is not a usable entry for this snapshot, or None."""
1540
+ if not isinstance(entry, dict) or entry.get("schema") != QUEUE_SCHEMA or entry.get("snapshot") != ident:
1541
+ return "not a queue entry for it"
1542
+ items = entry.get("items")
1543
+ if not isinstance(items, list) or not items:
1544
+ return "it has no items"
1545
+ why = next((why for why in map(item_problem, items) if why), None)
1546
+ if why:
1547
+ return why
1548
+ if sorted(item["kind"] for item in items if item["kind"] != "object") != ["completion", "manifest"]:
1549
+ return "it does not hold exactly one manifest and one completion manifest"
1550
+ if not isinstance(entry.get("attempts"), int) or not isinstance(entry.get("queued"), str) \
1551
+ or not isinstance(entry.get("recipient"), str):
1552
+ return "its attempts, queued time or recipient are malformed"
1553
+ if not isinstance(entry.get("generation", 0), int) or isinstance(entry.get("generation", 0), bool):
1554
+ return "its generation is not a whole number"
1555
+ return None
1556
+
1557
+
1558
+ # What one line of a change log may set on an item. Anything else in a line makes the line unusable.
1559
+ CHANGED = {"state", "tried", "sha256", "bytes", *IDENTITY}
1560
+
1561
+
1562
+ def item_key(item):
1563
+ """What names an item in a change log: an object by its original hash, which an entry holds once, else its kind."""
1564
+ return item.get("sha256") if item.get("kind") == "object" else item.get("kind")
1565
+
1566
+
1567
+ def replay(entry, text):
1568
+ """Apply a change log's lines to an entry read from disk, in order. Why the log cannot be used, or None.
1569
+
1570
+ Only lines written against the entry's generation apply: a save of the whole entry starts a new generation, so
1571
+ a log the save did not get to remove is passed over rather than replayed onto newer state. A last line with no
1572
+ newline is the torn write of a killed run, and nothing relied on it, because a change is only acted on once its
1573
+ whole line is synced, so it is passed over. Any other line that cannot be applied makes the log unusable.
1574
+ """
1575
+ generation, items = entry.get("generation", 0), None
1576
+ *lines, _torn = text.split("\n")
1577
+ for number, line in enumerate(lines, 1):
1578
+ try:
1579
+ change = json.loads(line)
1580
+ except ValueError:
1581
+ change = None
1582
+ if not isinstance(change, dict) or not isinstance(change.get("set"), dict) or not set(change["set"]) <= CHANGED:
1583
+ return f"line {number} of its change log is not a change"
1584
+ if change.get("generation") != generation:
1585
+ continue
1586
+ if items is None:
1587
+ items = {item_key(item): item for item in entry["items"] if isinstance(item, dict)}
1588
+ item = items.get(change.get("item"))
1589
+ # An object is named by its original hash in the log, so a line may not change it.
1590
+ if item is None or (item.get("kind") == "object" and {"sha256", "bytes"} & set(change["set"])):
1591
+ return f"line {number} of its change log names no item it can change"
1592
+ item.update(change["set"])
1593
+ return None
1594
+
1595
+
1596
+ class Queue:
1597
+ """One destination's upload queue: <archive>/queue/<destination hash>/<snapshot>.json, with each change to one
1598
+ of its items appended to <snapshot>.changes beside it.
1599
+
1600
+ The queue owns every change to an entry, so each one is on disk as it is made and a run that dies leaves the
1601
+ last state it reached there.
1602
+ """
1603
+
1604
+ def __init__(self, store, remote):
1605
+ self.store, self.where = store, destination(remote)
1606
+ self.dir = store / "queue" / sha256(self.where.encode())[:16]
1607
+
1608
+ def known_path(self, recipient, digest):
1609
+ """Where the destination remembers the object it verified for one original hash and recipient."""
1610
+ return self.held(self.dir / "known" / sha256(recipient.encode())[:16] / f"{digest}.json")
1611
+
1612
+ def remember(self, recipient, item):
1613
+ """Record a verified object's identity once, so a later snapshot holding the same bytes sends nothing for it.
1614
+
1615
+ Written once and never rewritten: the uploader cannot delete or replace a remote object, so an identity read
1616
+ back with its bytes stays true.
1617
+ """
1618
+ identity = {key: item[key] for key in IDENTITY}
1619
+ self.write_once(self.known_path(recipient, item["sha256"]), (json.dumps(identity, sort_keys=True) + "\n").encode())
1620
+
1621
+ def backfill(self, entries):
1622
+ """Remember the objects of entries verified before this record existed, once per destination."""
1623
+ marker = self.held(self.dir / "known" / "backfilled.json")
1624
+ if marker.exists():
1625
+ return
1626
+ for entry in entries:
1627
+ if entry_state(entry) == "verified":
1628
+ for item in entry["items"]:
1629
+ if item["kind"] == "object" and item["object"]:
1630
+ self.remember(entry["recipient"], item)
1631
+ self.write_once(marker, (json.dumps({"at": now()}) + "\n").encode())
1632
+
1633
+ def write_once(self, path, data):
1634
+ """Publish a record under the queue. A keep's backfill can be the first write here, so the directories it
1635
+ makes are synced into their parents before the upload that follows it saves an entry in one of them."""
1636
+ make_durable_directories(path.parent)
1637
+ publish(path, data)
1638
+
1639
+ def recall(self, recipient, digest):
1640
+ """The identity remembered for an original hash and recipient, or None when there is none or it does not hold together."""
1641
+ held = read_json(self.known_path(recipient, digest))
1642
+ if not isinstance(held, dict):
1643
+ return None
1644
+ named, cipher, size = held.get("object"), held.get("ciphertext_sha256"), held.get("ciphertext_bytes")
1645
+ if not (isinstance(cipher, str) and SNAPSHOT_ID.fullmatch(cipher) and named == archive_remote.object_name(cipher)
1646
+ and isinstance(size, int) and not isinstance(size, bool)):
1647
+ return None
1648
+ return {"object": named, "ciphertext_sha256": cipher, "ciphertext_bytes": size}
1649
+
1650
+ def path(self, ident, suffix=".json"):
1651
+ return self.held(self.dir / f"{ident}{suffix}")
1652
+
1653
+ def held(self, path):
1654
+ """The path, refused when it lies behind a symlink or outside the archive."""
1655
+ # A linked directory would carry the queue's writes out of the archive.
1656
+ if not inside(self.store, path):
1657
+ raise Refused(f"the upload queue {self.dir} lies behind a symlink or outside the archive, so the upload sent nothing "
1658
+ "and the queue is unchanged")
1659
+ return path
1660
+
1661
+ @contextlib.contextmanager
1662
+ def lock(self, ident):
1663
+ """Hold the snapshot's upload to one run at a time. A second run is refused rather than made to wait.
1664
+
1665
+ Two runs with nothing staged would each encrypt the same file, and age is not deterministic, so they would
1666
+ create two objects for one plaintext and one of them would meet the other's completion manifest as a conflict.
1667
+ """
1668
+ path = self.path(ident, ".lock")
1669
+ make_durable_directories(path.parent)
1670
+ with open(path, "a") as handle:
1671
+ try:
1672
+ fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
1673
+ except BlockingIOError:
1674
+ raise Refused(f"another upload of snapshot {ident} to {self.where} is running, so this one did nothing") from None
1675
+ yield
1676
+
1677
+ def load(self, ident):
1678
+ """The entry for a snapshot, None when it has none, and a refusal when the file is there but unusable."""
1679
+ path = self.path(ident)
1680
+ if not path.exists():
1681
+ return None
1682
+ entry = read_json(path)
1683
+ if isinstance(entry, dict) and isinstance(entry.get("items"), list):
1684
+ changes = self.path(ident, ".changes")
1685
+ try:
1686
+ why = replay(entry, changes.read_text())
1687
+ except FileNotFoundError:
1688
+ why = None
1689
+ except (OSError, UnicodeDecodeError) as error:
1690
+ why = f"its change log {changes.name} cannot be read: {error}"
1691
+ if why:
1692
+ raise Refused(f"the upload queue entry {path} is unreadable: {why}; nothing was uploaded. Move it and "
1693
+ f"{changes.name} aside to queue the snapshot afresh")
1694
+ why = entry_problem(entry, ident)
1695
+ if why:
1696
+ raise Refused(f"the upload queue entry {path} is unreadable: {why}, so the upload sent nothing. Move it aside to "
1697
+ "queue the snapshot again")
1698
+ return entry
1699
+
1700
+ def entries(self):
1701
+ """(every usable entry, oldest first, [(snapshot, why) for each unusable file])."""
1702
+ found, unusable = [], []
1703
+ for path in sorted(self.dir.glob("*.json")) if self.dir.is_dir() else []:
1704
+ try:
1705
+ found.append(self.load(path.stem))
1706
+ except Refused as why:
1707
+ unusable.append((path.stem, str(why)))
1708
+ return sorted(found, key=lambda e: (e["queued"], e["snapshot"])), unusable
1709
+
1710
+ def save(self, entry):
1711
+ """Write the whole entry as a new generation, then drop the change log it has folded in.
1712
+
1713
+ A run killed between the two leaves a log of the old generation, which a read passes over.
1714
+ """
1715
+ entry["updated"] = now()
1716
+ entry["generation"] = entry.get("generation", 0) + 1
1717
+ replace_atomically(self.path(entry["snapshot"]), (json.dumps(entry, indent=2, sort_keys=True) + "\n").encode())
1718
+ self.path(entry["snapshot"], ".changes").unlink(missing_ok=True)
1719
+
1720
+ def change(self, entry, item, **values):
1721
+ """Set values on one item and append the change to the entry's change log, durably, before returning."""
1722
+ item.update(values)
1723
+ line = json.dumps({"generation": entry.get("generation", 0), "item": item_key(item), "set": values},
1724
+ sort_keys=True) + "\n"
1725
+ path = self.path(entry["snapshot"], ".changes")
1726
+ made = not path.exists()
1727
+ with open(path, "ab") as handle:
1728
+ handle.write(line.encode())
1729
+ handle.flush()
1730
+ os.fsync(handle.fileno())
1731
+ if made:
1732
+ sync_directory(path.parent)
1733
+
1734
+ def enter(self, ident, doc, raw, recipient, completeness):
1735
+ """The snapshot's entry, created pending on its first upload, with this attempt counted and saved."""
1736
+ entry = self.load(ident)
1737
+ if entry is None:
1738
+ distinct = sorted({e["sha256"]: e["bytes"] for e in doc["entries"]}.items())
1739
+ entry = {"schema": QUEUE_SCHEMA, "snapshot": ident, "destination": self.where, "recipient": recipient,
1740
+ "completeness": completeness, "queued": now(), "verified": None, "attempts": 0, "failure": None,
1741
+ "items": [{"kind": "object", "sha256": digest, "bytes": size, "object": None,
1742
+ "ciphertext_sha256": None, "ciphertext_bytes": None, "state": "pending"}
1743
+ for digest, size in distinct]
1744
+ + [{"kind": "manifest", "object": archive_remote.manifest_name(ident), "sha256": sha256(raw),
1745
+ "bytes": len(raw), "state": "pending"},
1746
+ {"kind": "completion", "object": archive_remote.complete_name(ident), "sha256": None,
1747
+ "bytes": None, "state": "pending"}]}
1748
+ elif entry["recipient"] != recipient:
1749
+ # Ciphertext made for another recipient is not this upload's, so its identities start again.
1750
+ for item in entry["items"]:
1751
+ if item["kind"] == "object":
1752
+ item.update(object=None, ciphertext_sha256=None, ciphertext_bytes=None, state="pending")
1753
+ item.pop("adopted", None)
1754
+ item.pop("tried", None)
1755
+ if item["kind"] == "completion":
1756
+ item.update(sha256=None, bytes=None, state="pending")
1757
+ entry.update(recipient=recipient, verified=None)
1758
+ # An object this destination already verified for the recipient, under another snapshot, is adopted rather
1759
+ # than sent or read again, so a changed history moves only its changed files. So is one this entry named but
1760
+ # never tried to create, whose own ciphertext is then never sent.
1761
+ for item in entry["items"]:
1762
+ if item["kind"] == "object" and item["state"] == "pending" and not item.get("tried"):
1763
+ known = self.recall(recipient, item["sha256"])
1764
+ if known:
1765
+ item.update(known, state="verified", adopted=True)
1766
+ entry["attempts"] += 1
1767
+ self.save(entry)
1768
+ return entry
1769
+
1770
+ def item(self, entry, kind):
1771
+ """The entry's one manifest or completion item."""
1772
+ return next(item for item in entry["items"] if item["kind"] == kind)
1773
+
1774
+ def mark(self, entry, item, state, **identity):
1775
+ self.change(entry, item, state=state, **identity)
1776
+ if item["kind"] == "object" and state == "verified":
1777
+ self.remember(entry["recipient"], item)
1778
+
1779
+ def fail(self, entry, why):
1780
+ entry["failure"] = {"at": now(), "error": str(why)}
1781
+ self.save(entry)
1782
+
1783
+ def fail_held(self, ident, why):
1784
+ """Record a failure on a snapshot's entry when it has one. A snapshot never queued gets none."""
1785
+ try:
1786
+ entry = self.load(ident) if SNAPSHOT_ID.fullmatch(ident) else None
1787
+ except Refused:
1788
+ entry = None
1789
+ if entry is not None:
1790
+ self.fail(entry, why)
1791
+
1792
+ def done(self, entry):
1793
+ entry.update(verified=now(), failure=None)
1794
+ self.save(entry)
1795
+
1796
+ def verified(self, entry, completion):
1797
+ """Mark every item verified from a completion manifest that has just verified end to end."""
1798
+ held = {o["sha256"]: o for o in completion["objects"]}
1799
+ for item in entry["items"]:
1800
+ if item["kind"] == "object" and item["sha256"] in held:
1801
+ item.update({key: held[item["sha256"]][key] for key in IDENTITY})
1802
+ item["state"] = "verified"
1803
+ self.done(entry)
1804
+ for item in entry["items"]:
1805
+ if item["kind"] == "object" and item["object"]:
1806
+ self.remember(entry["recipient"], item)
1807
+
1808
+
1809
+ def queue_status(store, remote, wanted=None):
1810
+ """What one destination's queue holds, with the fields scheduling and health read. Touches no remote."""
1811
+ archive_remote.require_ready(remote)
1812
+ queue = Queue(store, remote)
1813
+ entries, unusable = queue.entries()
1814
+ rows, unsent = [], {}
1815
+ for entry in entries:
1816
+ state = entry_state(entry)
1817
+ missing = [] if state == "verified" else [item for item in entry["items"]
1818
+ if item["kind"] != "completion" and item["state"] != "verified"]
1819
+ # An object two waiting snapshots share is sent once, so the total counts it once.
1820
+ unsent.update({(item["kind"], item["sha256"]): item["bytes"] for item in missing})
1821
+ row = {"snapshot": entry["snapshot"], "state": state, "completeness": entry.get("completeness"),
1822
+ "queued": entry["queued"], "verified": entry.get("verified"), "attempts": entry["attempts"],
1823
+ "pending_bytes": sum(item["bytes"] for item in missing), "failure": entry.get("failure")}
1824
+ if wanted:
1825
+ row["items"] = [{k: item.get(k) for k in ("kind", "sha256", "bytes", "object", "state")} for item in entry["items"]]
1826
+ rows.append(row)
1827
+ waiting = [row for row in rows if row["state"] != "verified"]
1828
+ verified_at = [row["verified"] for row in rows if row["verified"]]
1829
+ return {"remote": remote.kind, "destination": queue.where, "snapshots": len(rows) + len(unusable),
1830
+ "verified": sum(row["state"] == "verified" for row in rows),
1831
+ "uploaded": sum(row["state"] == "uploaded" for row in rows),
1832
+ "pending": sum(row["state"] == "pending" for row in rows) + len(unusable),
1833
+ "last_verified": max(verified_at) if verified_at else None,
1834
+ "oldest_pending": {"snapshot": waiting[0]["snapshot"], "queued": waiting[0]["queued"]} if waiting else None,
1835
+ "pending_bytes": sum(unsent.values()),
1836
+ "failures": [{"snapshot": row["snapshot"], **row["failure"]} for row in rows if row["failure"]]
1837
+ + [{"snapshot": ident, "at": None, "error": why} for ident, why in unusable],
1838
+ "queue": [row for row in rows if not wanted or row["snapshot"] == wanted]}
1839
+
1840
+
1841
+ def upload_pending(store, remote):
1842
+ """Resume every snapshot the destination's queue has not verified, oldest first. One failing does not stop the rest."""
1843
+ archive_remote.require_ready(remote)
1844
+ entries, unusable = Queue(store, remote).entries()
1845
+ results = [{"snapshot": ident, "status": "failed", "error": why} for ident, why in unusable]
1846
+ for entry in entries:
1847
+ if entry_state(entry) == "verified":
1848
+ continue
1849
+ try:
1850
+ results.append(upload(store, entry["snapshot"], remote))
1851
+ except Refused as why:
1852
+ results.append({"snapshot": entry["snapshot"], "status": "failed", "error": str(why)})
1853
+ return {"remote": remote.kind, "results": results}
1854
+
1855
+
1856
+ def upload(store, ident, remote, progress=None):
1857
+ """Encrypt a snapshot's objects, create them on the remote, verify them there, and publish the completion manifest last.
1858
+
1859
+ The snapshot's queue entry is written before the remote is touched and after every step, so a failure of any
1860
+ kind, the process dying included, leaves the next run something to resume from, and every failure a run can
1861
+ see is recorded on the entry before it is reported.
1862
+ """
1863
+ archive_remote.require_ready(remote)
1864
+ queue = Queue(store, remote)
1865
+ if not SNAPSHOT_ID.fullmatch(ident):
1866
+ raise Refused(f"no snapshot {ident} in {store}")
1867
+ # Every write to the entry, a failure included, is made under the lock, so none overwrites a running upload's.
1868
+ with queue.lock(ident):
1869
+ try:
1870
+ doc, raw = load_snapshot(store, ident)
1871
+ except Refused as why:
1872
+ # A queued snapshot whose local copy has gone stays pending with the reason on it. Nothing remote changes.
1873
+ queue.fail_held(ident, why)
1874
+ raise
1875
+ try:
1876
+ # The completion manifest vouches for the snapshot, so a manifest that restore or the completion parser would refuse is not sent.
1877
+ try:
1878
+ plan_layout(doc)
1879
+ except Refused as why:
1880
+ raise Refused(f"snapshot {ident} would not restore: {why}, so the upload sent nothing") from None
1881
+ collection = doc.get("collection")
1882
+ completeness = collection.get("completeness") if isinstance(collection, dict) else None
1883
+ if completeness not in COMPLETENESS:
1884
+ raise Refused(f"snapshot {ident} has no completeness of complete or partial in its manifest, so the upload sent nothing")
1885
+ except Refused as why:
1886
+ queue.fail_held(ident, why)
1887
+ raise
1888
+ # Queued before age or the store is opened, so a machine missing either still holds the snapshot as pending.
1889
+ entry = queue.enter(ident, doc, raw, remote.get("encryption.recipient"), completeness)
1890
+ try:
1891
+ cipher = archive_remote.Age()
1892
+ uploader = archive_remote.open_store(remote, "uploader")
1893
+ return send_snapshot(store, remote, doc, raw, cipher, uploader, queue, entry, progress)
1894
+ except (archive_remote.StoreError, OSError) as error:
1895
+ why = Refused(f"the upload of snapshot {ident} stopped: {error}. The upload cannot confirm whether it published "
1896
+ "the completion manifest. A repeat resumes the upload or reports it unchanged")
1897
+ queue.fail(entry, why)
1898
+ raise why from error
1899
+ except Refused as why:
1900
+ queue.fail(entry, why)
1901
+ raise
1902
+
1903
+
1904
+ def send_snapshot(store, remote, doc, raw, cipher, uploader, queue, entry, progress=None):
1905
+ """The upload of one queued snapshot, each item's state saved through the queue as it changes.
1906
+
1907
+ `progress` is called once for each object read back, encrypted or sent, so a caller can report a long upload.
1908
+ """
1909
+ ident, recipient = entry["snapshot"], entry["recipient"]
1910
+ progress = progress or (lambda: None)
1911
+ completion, remote_doc, _, problems = read_remote(uploader, ident)
1912
+ if completion is None and problems != [ABSENT]:
1913
+ raise Refused(f"the remote holds a completion manifest for snapshot {ident} that cannot be used: {'; '.join(problems)}, so nothing changed")
1914
+ if completion:
1915
+ # Already published: reuse it only when it verifies end to end and names the same evidence.
1916
+ if remote_doc:
1917
+ problems += coverage_problems(completion, remote_doc)
1918
+ for item in completion["objects"]:
1919
+ _, why = fetch_ciphertext(uploader, item)
1920
+ if why:
1921
+ problems.append(why)
1922
+ if problems or completion["encryption"]["recipient"] != recipient:
1923
+ raise Refused(f"the remote already holds a completion manifest for snapshot {ident} that does not match this upload: "
1924
+ f"{'; '.join(problems) or 'it is encrypted to another recipient'}, so nothing changed")
1925
+ queue.verified(entry, completion)
1926
+ return {"status": "unchanged", "snapshot": ident, "completeness": completion["completeness"],
1927
+ "objects": len(completion["objects"]), "uploaded": 0, "reused": len(completion["objects"]),
1928
+ "completion": archive_remote.complete_name(ident), "remote": remote.kind}
1929
+ objects = [item for item in entry["items"] if item["kind"] == "object"]
1930
+ uploaded = reused = 0
1931
+ # Reconcile before retrying. An object an earlier run tried to create may be on the remote whatever that run
1932
+ # heard back, a lost response or a killed process included, and reading it is what tells. Nothing is sent for
1933
+ # one that is. One that was named and never tried cannot be there, so it is not read.
1934
+ for item in objects:
1935
+ # An adopted object was read back under another snapshot, and nothing can since have replaced it.
1936
+ if item["object"] is None or item.get("adopted") or (item["state"] == "pending" and not item.get("tried")):
1937
+ continue
1938
+ progress()
1939
+ held = uploader.read(item["object"])
1940
+ if held is None:
1941
+ queue.mark(entry, item, "pending")
1942
+ elif sha256(held) == item["ciphertext_sha256"] and len(held) == item["ciphertext_bytes"]:
1943
+ queue.mark(entry, item, "verified")
1944
+ reused += 1
1945
+ else:
1946
+ raise Refused(f"identity conflict or corruption: the remote returned {item['object']} with other bytes than its "
1947
+ "name's hash, and nothing was overwritten. A repeat reads it again")
1948
+ # Everything still to send is encrypted before anything is created, so a damaged local object stops the run
1949
+ # with nothing written. A kept ciphertext is sent again rather than a new one, so a retry makes no new object.
1950
+ # Each ciphertext is staged and let go here, and read back from staging when it is sent, so a large snapshot
1951
+ # is never held whole.
1952
+ stage = staging_dir(store, remote)
1953
+ copies = staged_copies(stage)
1954
+ sending = []
1955
+ for item in objects:
1956
+ if item["state"] == "verified":
1957
+ continue
1958
+ data = staged_ciphertext(copies.get(item["sha256"], ()))
1959
+ if data is None:
1960
+ plain, why = read_object(store, item)
1961
+ if why:
1962
+ raise Refused(f"{why}, so the upload sent nothing")
1963
+ data = cipher.encrypt(plain, recipient)
1964
+ write_staged(stage, item["sha256"], data)
1965
+ digest = sha256(data)
1966
+ name = archive_remote.object_name(digest)
1967
+ if item["object"] != name:
1968
+ # A new identity has never been tried, whatever the one it replaces was.
1969
+ queue.mark(entry, item, "pending", object=name, ciphertext_sha256=digest, ciphertext_bytes=len(data), tried=False)
1970
+ sending.append(item)
1971
+ progress()
1972
+ for item in sending:
1973
+ progress()
1974
+ data = read_staged(stage, item)
1975
+ if not item.get("tried"):
1976
+ # Saved before the create, so a run killed during it leaves the object for the next one to read back.
1977
+ queue.change(entry, item, tried=True)
1978
+ if publish_verified(uploader, item["object"], data, lambda state, item=item: queue.mark(entry, item, state)):
1979
+ uploaded += 1
1980
+ else:
1981
+ reused += 1
1982
+ manifest_item, completion_item = queue.item(entry, "manifest"), queue.item(entry, "completion")
1983
+ publish_verified(uploader, archive_remote.manifest_name(ident), raw, lambda state: queue.mark(entry, manifest_item, state))
1984
+ items = [{key: item[key] for key in ("sha256", "bytes", *IDENTITY)} for item in objects]
1985
+ body = {"schema": COMPLETE_SCHEMA, "snapshot": ident, "completeness": entry["completeness"],
1986
+ "manifest": {"object": archive_remote.manifest_name(ident), "sha256": sha256(raw), "bytes": len(raw)},
1987
+ "encryption": {"tool": "age", "recipient": recipient}, "objects": items}
1988
+ published = (json.dumps(body, indent=2, sort_keys=True) + "\n").encode()
1989
+ queue.mark(entry, completion_item, completion_item["state"], sha256=sha256(published), bytes=len(published))
1990
+ publish_verified(uploader, archive_remote.complete_name(ident), published, lambda state: queue.mark(entry, completion_item, state))
1991
+ queue.done(entry)
1992
+ return {"status": "created", "snapshot": ident, "completeness": body["completeness"], "objects": len(items),
1993
+ "uploaded": uploaded, "reused": reused, "completion": archive_remote.complete_name(ident), "remote": remote.kind}
1994
+
1995
+
1996
+ def publish_verified(remote_store, name, data, record):
1997
+ """Create an object once and read it back, recording each state. True when this call created it, False when a matching one was there."""
1998
+ created = remote_store.create(name, data)
1999
+ if created:
2000
+ record("uploaded")
2001
+ held = remote_store.read(name)
2002
+ if held is None:
2003
+ raise Refused(f"object {name} is missing after the upload created it, so the upload is not verified")
2004
+ if held != data:
2005
+ if created:
2006
+ raise Refused(f"object {name} read back with other bytes than were uploaded, so the upload is not verified")
2007
+ raise Refused(f"identity conflict: the remote already holds {name} with other bytes than this upload's, and nothing was overwritten")
2008
+ record("verified")
2009
+ return created
2010
+
2011
+
2012
+ # ---- keeping: the scheduled and post-shift run -------------------------------------------------------------
2013
+ #
2014
+ # A keep is one unattended run over a keep configuration: capture a history over the configured roots, upload the
2015
+ # capture and every snapshot the queue still holds unverified, and publish a health snapshot. launchd starts one
2016
+ # every five minutes and at login, and keep-after.sh starts one when a shift ends. One keep runs per archive at a
2017
+ # time. A keep reads evidence and writes only the archive and the remote: it starts no model, writes no tracker,
2018
+ # prunes nothing, and its failures are the archive's, never a shift's.
2019
+
2020
+ KEEP_FIELDS = {"archive": "path", "repos": "paths", "remote": "path?", "claude_projects": "path?",
2021
+ "codex_sessions": "path?", "inputs": "paths?", "recovery_identity": "path?", "restore_scratch": "path?"}
2022
+ # The one keep setting that is not a path: a repository's directory name to the directory names a capture leaves
2023
+ # out of its evidence roots, on top of SKIPPED_DIRS and the database rule.
2024
+ KEEP_SKIPPED = "skipped_dirs"
2025
+ HEALTH_SCHEMA = archive_health.HEALTH_SCHEMA
2026
+ KEEP_INTERVAL_SECONDS = 300
2027
+ HEALTH_LOOKBACK_DAYS = archive_health.HEALTH_LOOKBACK_DAYS
2028
+
2029
+
2030
+ def load_keep(path):
2031
+ """A keep configuration: absolute paths, every field checked, relative ones taken from the file's directory."""
2032
+ path = Path(path).expanduser().absolute()
2033
+ try:
2034
+ doc = json.loads(path.read_text())
2035
+ except OSError as error:
2036
+ raise Refused(f"cannot read the keep configuration {path}: {error.strerror}") from None
2037
+ except ValueError:
2038
+ raise Refused(f"the keep configuration {path} is not valid JSON") from None
2039
+ if not isinstance(doc, dict):
2040
+ raise Refused(f"the keep configuration {path} is not a JSON object")
2041
+ base, conf, problems = path.parent, {"config": path}, []
2042
+
2043
+ def place(value):
2044
+ held = Path(value).expanduser()
2045
+ return held if held.is_absolute() else base / held
2046
+ for field in sorted(set(doc) - set(KEEP_FIELDS) - {KEEP_SKIPPED}):
2047
+ problems.append(f"{field} is not a keep setting")
2048
+ for field, kind in KEEP_FIELDS.items():
2049
+ value, optional = doc.get(field), kind.endswith("?")
2050
+ if value is None:
2051
+ if not optional:
2052
+ problems.append(f"{field} is required")
2053
+ conf[field] = [] if kind.startswith("paths") else None
2054
+ elif kind.startswith("paths"):
2055
+ if not isinstance(value, list) or not all(isinstance(v, str) and v for v in value) or (not optional and not value):
2056
+ problems.append(f"{field} must be a{'' if optional else ' non-empty'} list of paths")
2057
+ else:
2058
+ conf[field] = [place(v) for v in value]
2059
+ elif not isinstance(value, str) or not value:
2060
+ problems.append(f"{field} must be a path")
2061
+ else:
2062
+ conf[field] = place(value)
2063
+ conf[KEEP_SKIPPED], skip_problems = keep_skipped(doc.get(KEEP_SKIPPED), conf.get("repos") or [])
2064
+ problems += skip_problems
2065
+ # The file names where the identity is, never the key. Key material pasted in would sit beside the uploader's settings.
2066
+ problems += [f"{field} holds private key material: name the age identity file instead"
2067
+ for field in archive_remote.secrets_in(doc)]
2068
+ # A field that failed its own check above is absent from conf, so these read it with get.
2069
+ if conf.get("recovery_identity") and not doc.get("remote"):
2070
+ problems.append("recovery_identity needs remote: the restore check reads the remote it names")
2071
+ if conf.get("restore_scratch"):
2072
+ if not doc.get("recovery_identity"):
2073
+ problems.append("restore_scratch needs recovery_identity: only the restore check uses it")
2074
+ # A scratch root inside what the check must leave alone would write there, however briefly.
2075
+ held = [conf.get(field) for field in ("archive", "claude_projects", "codex_sessions")] + list(conf.get("repos") or [])
2076
+ for top in held:
2077
+ if top and within(conf["restore_scratch"], top):
2078
+ problems.append(f"restore_scratch {conf['restore_scratch']} lies inside {top}, which a restore check never writes")
2079
+ if problems:
2080
+ raise Refused(f"the keep configuration {path} is not usable: {'; '.join(problems)}")
2081
+ return conf
2082
+
2083
+
2084
+ def keep_skipped(value, repos):
2085
+ """The skipped_dirs setting as repository name to patterns, and the problems with it."""
2086
+ if value is None:
2087
+ return {}, []
2088
+ if not isinstance(value, dict) or not all(isinstance(patterns, list) and patterns and
2089
+ all(isinstance(pattern, str) for pattern in patterns)
2090
+ for patterns in value.values()):
2091
+ return {}, [f"{KEEP_SKIPPED} must map a repository's directory name to a non-empty list of directory names"]
2092
+ names, problems = {repo.resolve().name for repo in repos}, []
2093
+ for name, patterns in sorted(value.items()):
2094
+ if name not in names:
2095
+ problems.append(f"{KEEP_SKIPPED}: {name} is not a configured repository's directory name")
2096
+ not_names = [pattern for pattern in patterns if not pattern or "/" in pattern or pattern in (".", "..")]
2097
+ if not_names:
2098
+ problems.append(f"{KEEP_SKIPPED} for {name}: {', '.join(map(repr, not_names))} is not a directory name")
2099
+ return {name: tuple(patterns) for name, patterns in value.items()}, problems
2100
+
2101
+
2102
+ def within(path, top):
2103
+ """Whether path is top or lies below it, once both are resolved."""
2104
+ path, top = Path(path).resolve(), Path(top).resolve()
2105
+ return path == top or top in path.parents
2106
+
2107
+
2108
+ @contextlib.contextmanager
2109
+ def keep_lock(store, wait):
2110
+ """Hold the archive's one keep. Yields False when another keep still holds it after `wait` seconds."""
2111
+ path = store / "keep.lock"
2112
+ if not inside(store, path):
2113
+ raise Refused(f"{path} is a symlink or lies outside the archive, so no keep ran")
2114
+ try:
2115
+ handle = open(path, "a")
2116
+ except OSError as error:
2117
+ raise Refused(f"the keep lock {path} cannot be opened: {error.strerror or error}, so no keep ran") from None
2118
+ with handle:
2119
+ deadline = time.monotonic() + wait
2120
+ while True:
2121
+ try:
2122
+ fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
2123
+ break
2124
+ except BlockingIOError:
2125
+ if time.monotonic() >= deadline:
2126
+ yield False
2127
+ return
2128
+ time.sleep(0.2)
2129
+ yield True
2130
+
2131
+
2132
+ def keep(conf, wait=0, health_every=KEEP_INTERVAL_SECONDS):
2133
+ try:
2134
+ conf["archive"].mkdir(parents=True, exist_ok=True)
2135
+ except OSError as error:
2136
+ raise Refused(f"cannot make the archive {conf['archive']}: {error.strerror or error}, so no keep ran") from None
2137
+ store = conf["archive"].resolve()
2138
+ with keep_lock(store, wait) as held:
2139
+ if not held:
2140
+ return {"status": "skipped", "at": now(), "archive": str(store),
2141
+ "reason": f"another keep of {store} is running, and it or the next one takes this evidence"}
2142
+ return keep_held(conf, store, health_every)
2143
+
2144
+
2145
+ def keep_held(conf, store, health_every=KEEP_INTERVAL_SECONDS):
2146
+ at, errors, uploads = now(), [], []
2147
+ scan = scan_roots(conf, store, at, errors)
2148
+ latest = read_json(store / "keep" / "last-scan.json")
2149
+ held_manifest = read_json(snapshot_path(store, latest["snapshot"])) if isinstance(latest, dict) and latest.get("snapshot") else None
2150
+ remote, queued = None, {}
2151
+ if conf["remote"]:
2152
+ try:
2153
+ remote = archive_remote.load_remote(conf["remote"])
2154
+ archive_remote.require_ready(remote)
2155
+ except Refused as why:
2156
+ remote = None
2157
+ errors.append({"stage": "upload", "error": str(why)})
2158
+
2159
+ def health(queued):
2160
+ last_check = next(restore_check_records(store), None)
2161
+ return {"schema": HEALTH_SCHEMA, "at": at, "host": socket.gethostname(), "archive": str(store),
2162
+ "destination": queued.get("destination"),
2163
+ "latest_scan": latest if isinstance(latest, dict) else None,
2164
+ "last_verified": queued.get("last_verified"),
2165
+ "oldest_pending": queued.get("oldest_pending"),
2166
+ "pending_bytes": queued.get("pending_bytes"),
2167
+ "pending": queued["pending"] + queued["uploaded"] if queued else None,
2168
+ "gaps": held_manifest.get("gaps", []) if isinstance(held_manifest, dict) else None,
2169
+ "restore_check": {key: last_check.get(key) for key in ("at", "snapshot", "status", "problems")}
2170
+ if last_check else None,
2171
+ "errors": list(errors)}
2172
+ if remote:
2173
+ # An upload with more to send than fits in one interval publishes a health snapshot of the queue every
2174
+ # interval while it runs, so the checker judges a long upload as the backlog state, not as a keep that stopped.
2175
+ last = time.monotonic()
2176
+
2177
+ def progress():
2178
+ nonlocal last
2179
+ if time.monotonic() - last < health_every:
2180
+ return
2181
+ last = time.monotonic()
2182
+ try:
2183
+ interim = queue_status(store, remote)
2184
+ except (Refused, OSError) as why:
2185
+ errors.append({"stage": "health", "error": f"the queue could not be read for a health snapshot: {why}"})
2186
+ return
2187
+ publish_health(store, remote, health(interim), errors)
2188
+ uploads = upload_waiting(store, remote, scan["snapshot"] if scan else None, errors, progress)
2189
+ queued = queue_status(store, remote)
2190
+ # After the uploads, so the capture this keep just verified can be the snapshot it restores.
2191
+ checked = keep_restore_check(conf, store, errors)
2192
+ published = publish_health(store, remote, health(queued), errors)
2193
+ return {"status": "kept", "at": at, "archive": str(store), "scan": scan, "uploads": uploads,
2194
+ "restore_check": checked, "health": published, "errors": errors}
2195
+
2196
+
2197
+ def keep_restore_check(conf, store, errors):
2198
+ """Run the restore check when the keep configuration names an identity and one is due. Its record, or None."""
2199
+ if not conf["recovery_identity"] or not restore_check_due(store, datetime.now(timezone.utc)):
2200
+ return None
2201
+ try:
2202
+ record = restore_check(conf)
2203
+ except Refused as why:
2204
+ errors.append({"stage": "restore-check", "error": str(why)})
2205
+ return None
2206
+ if record["status"] == "failed":
2207
+ errors.append({"stage": "restore-check", "snapshot": record["snapshot"], "error": "; ".join(record["problems"])})
2208
+ return record
2209
+
2210
+
2211
+ def scan_roots(conf, store, at, errors):
2212
+ """Capture a history over the configured roots. A configured repository that has gone is an error, not a stop."""
2213
+ repos = []
2214
+ for repo in conf["repos"]:
2215
+ if repo.is_dir():
2216
+ repos.append(repo)
2217
+ else:
2218
+ errors.append({"stage": "scan", "error": f"the configured repository {repo} is missing, so the keep scanned none of it"})
2219
+ if not repos:
2220
+ return None
2221
+ try:
2222
+ scan = collect_history(store, repos, conf["inputs"], conf["claude_projects"], conf["codex_sessions"],
2223
+ skipped=conf[KEEP_SKIPPED])
2224
+ except (Refused, OSError) as why:
2225
+ errors.append({"stage": "scan", "error": str(why)})
2226
+ return None
2227
+ held = read_json(scan["manifest"]) or {}
2228
+ errors.extend({"stage": "capture", **error} for error in held.get("collection", {}).get("errors", []))
2229
+ attempts = held.get("attempts", [])
2230
+ record = {"at": at, "snapshot": scan["snapshot"], "status": scan["status"], "completeness": scan["completeness"],
2231
+ "attempts": len(attempts), "active": sum(attempt.get("activity") == "active" for attempt in attempts)}
2232
+ last = store / "keep" / "last-scan.json"
2233
+ if not inside(store, last):
2234
+ errors.append({"stage": "scan", "error": f"the keep could not record the last scan: {last} lies behind a symlink or outside the archive"})
2235
+ return scan
2236
+ try:
2237
+ replace_atomically(last, (json.dumps(record, indent=2, sort_keys=True) + "\n").encode())
2238
+ except OSError as error:
2239
+ errors.append({"stage": "scan", "error": f"the keep could not record the last scan: {error.strerror or error}"})
2240
+ return scan
2241
+
2242
+
2243
+ def upload_waiting(store, remote, scanned, errors, progress=None):
2244
+ """Upload this keep's capture first, so it is queued before anything can stop the keep, then every snapshot still waiting."""
2245
+ queue = Queue(store, remote)
2246
+ entries, unusable = queue.entries()
2247
+ try:
2248
+ queue.backfill(entries)
2249
+ except (Refused, OSError) as why:
2250
+ errors.append({"stage": "upload", "error": f"the keep could not fill in the record of verified objects: {why}"})
2251
+ waiting = [entry["snapshot"] for entry in entries if entry_state(entry) != "verified"]
2252
+ known = {entry["snapshot"] for entry in entries}
2253
+ order = ([scanned] if scanned and (scanned in waiting or scanned not in known) else []) \
2254
+ + [ident for ident in waiting if ident != scanned]
2255
+ results = []
2256
+ for ident in order:
2257
+ try:
2258
+ results.append(upload(store, ident, remote, progress))
2259
+ # A local write the queue cannot make, a full disk say, fails this snapshot and not the keep.
2260
+ except (Refused, OSError) as why:
2261
+ results.append({"snapshot": ident, "status": "failed", "error": str(why)})
2262
+ errors.append({"stage": "upload", "snapshot": ident, "error": str(why)})
2263
+ errors.extend({"stage": "upload", "snapshot": ident, "error": why} for ident, why in unusable)
2264
+ return results
2265
+
2266
+
2267
+ def publish_health(store, remote, health, errors):
2268
+ """Write a health snapshot to the archive, then create it on the remote and read it back. Neither is ever rewritten."""
2269
+ body = (json.dumps(health, indent=2, sort_keys=True) + "\n").encode()
2270
+ name = archive_health.health_name(datetime.now(timezone.utc), sha256(body))
2271
+ local = store.joinpath(*name.split("/"))
2272
+ try:
2273
+ if not inside(store, local):
2274
+ raise Refused(f"{local} lies behind a symlink or outside the archive")
2275
+ publish(local, body)
2276
+ except (Refused, OSError) as why:
2277
+ errors.append({"stage": "health", "error": f"the keep could not write the health snapshot {name} locally: {why}"})
2278
+ published = False
2279
+ if remote:
2280
+ try:
2281
+ publish_verified(archive_remote.open_store(remote, "uploader"), name, body, lambda state: None)
2282
+ published = True
2283
+ except (Refused, archive_remote.StoreError, OSError) as why:
2284
+ errors.append({"stage": "health", "error": f"the keep could not publish the health snapshot {name}: {why}"})
2285
+ return {"object": name, "local": str(local), "published": published}
2286
+
2287
+
2288
+ def read_health(remote, days):
2289
+ """The newest health snapshot on the remote whose bytes match its name, read as the recovery identity.
2290
+
2291
+ The selection is archive_health's, which the checker uses too, so both trust the same snapshot.
2292
+ """
2293
+ archive_remote.require_ready(remote)
2294
+ reader = archive_remote.open_store(remote, "recovery")
2295
+ return archive_health.newest(reader, datetime.now(timezone.utc).date(), days)
2296
+
2297
+
2298
+ # ---- the restore check -------------------------------------------------------------------------------------
2299
+ #
2300
+ # A restore check proves the remote half of the archive without a person. It restores one recently verified
2301
+ # snapshot from the remote, as the recovery identity, into a scratch root, checks every file written there against
2302
+ # the manifest it restored, removes the scratch root and records what happened. It reads the remote and the local
2303
+ # upload queue and writes only its scratch root and its own record, so no evidence, archive snapshot, queue entry or
2304
+ # remote object changes. A keep runs one when one is due. A check that could not restore, or restored anything the
2305
+ # manifest does not vouch for, is recorded as failed, never as passed.
2306
+
2307
+ RESTORE_CHECK_SCHEMA = "ship-archive-restore-check/1"
2308
+ RESTORE_CHECK_NAME = re.compile(r"\d{8}T\d{12}Z-([0-9a-f]{64})\.json")
2309
+ # Below the archive, one record per check, each named by its time and the hash of its bytes.
2310
+ RESTORE_CHECK_DIR = "restore-checks"
2311
+ # Monthly, counted from the last check. A failed one is tried again a day later rather than at every keep, because
2312
+ # each attempt downloads and decrypts a whole snapshot.
2313
+ RESTORE_CHECK_EVERY = timedelta(days=30)
2314
+ RESTORE_CHECK_RETRY = timedelta(days=1)
2315
+ HASH_CHUNK = 1 << 20
2316
+
2317
+
2318
+ def restore_check_records(store):
2319
+ """Every readable restore check record in the archive whose bytes match its name, newest first.
2320
+
2321
+ An unreadable directory holds none. A record edited or damaged after the check wrote it is skipped, so it can
2322
+ neither put off the next check nor reach a health snapshot.
2323
+ """
2324
+ top = store / RESTORE_CHECK_DIR
2325
+ if not inside(store, top) or not top.is_dir():
2326
+ return
2327
+ try:
2328
+ names = sorted((p for p in top.iterdir() if RESTORE_CHECK_NAME.fullmatch(p.name)), reverse=True)
2329
+ except OSError:
2330
+ return
2331
+ for path in names:
2332
+ try:
2333
+ raw = path.read_bytes() if path.is_file() and not path.is_symlink() else None
2334
+ except OSError:
2335
+ raw = None
2336
+ if raw is None or sha256(raw) != RESTORE_CHECK_NAME.fullmatch(path.name).group(1):
2337
+ continue
2338
+ try:
2339
+ doc = json.loads(raw)
2340
+ except ValueError:
2341
+ doc = None
2342
+ if isinstance(doc, dict) and doc.get("schema") == RESTORE_CHECK_SCHEMA and doc.get("status") in ("passed", "failed"):
2343
+ yield doc
2344
+
2345
+
2346
+ def restore_check_due(store, at):
2347
+ """Whether a keep at `at` runs a restore check: none recorded, a pass 30 days old or a failure a day old.
2348
+
2349
+ Only checks of the newest verified snapshot count. One run by hand on a named snapshot proved that snapshot, not
2350
+ the one a recovery would reach for, so it leaves the schedule where it was.
2351
+ """
2352
+ last = next((doc for doc in restore_check_records(store) if not doc.get("named")), None)
2353
+ if last is None:
2354
+ return True
2355
+ try:
2356
+ when = datetime.strptime(last.get("at"), "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)
2357
+ except (TypeError, ValueError):
2358
+ return True
2359
+ return at - when >= (RESTORE_CHECK_EVERY if last["status"] == "passed" else RESTORE_CHECK_RETRY)
2360
+
2361
+
2362
+ def newest_verified(store, remote):
2363
+ """The snapshot the destination's upload queue verified most recently. Reads the queue and writes nothing."""
2364
+ entries, _ = Queue(store, remote).entries()
2365
+ verified = [entry for entry in entries if entry_state(entry) == "verified" and isinstance(entry.get("verified"), str)]
2366
+ if not verified:
2367
+ raise Refused(f"the upload queue for {destination(remote)} holds no verified snapshot, so there is nothing to restore")
2368
+ return max(verified, key=lambda entry: (entry["verified"], entry["queued"], entry["snapshot"]))["snapshot"]
2369
+
2370
+
2371
+ def file_digest(path):
2372
+ """(sha256, size) of a file, read in blocks so a large transcript is never held whole."""
2373
+ digest, size = hashlib.sha256(), 0
2374
+ with open(path, "rb") as handle:
2375
+ for block in iter(lambda: handle.read(HASH_CHUNK), b""):
2376
+ digest.update(block)
2377
+ size += len(block)
2378
+ return digest.hexdigest(), size
2379
+
2380
+
2381
+ def check_restored(top, ident):
2382
+ """(files, bytes, problems): every file a restore wrote under top, checked against the manifest it restored."""
2383
+ try:
2384
+ doc = parse_manifest((top / RESTORED_MANIFEST).read_bytes(), RESTORED_MANIFEST)
2385
+ plan = plan_layout(doc)
2386
+ except (OSError, Refused) as why:
2387
+ return 0, 0, [f"the restored {RESTORED_MANIFEST} cannot be read as snapshot {ident}'s manifest: {why}"]
2388
+ problems, files, size = [], 0, 0
2389
+ if doc["snapshot"]["id"] != ident:
2390
+ problems.append(f"the restored manifest is snapshot {doc['snapshot']['id']}, not {ident}")
2391
+ named = {PurePosixPath(RESTORED_MANIFEST)}
2392
+ for rel, entry in plan:
2393
+ named.add(rel)
2394
+ path = top.joinpath(*rel.parts)
2395
+ if path.is_symlink() or not path.is_file():
2396
+ problems.append(f"the manifest names {rel}, and the restore did not write it")
2397
+ continue
2398
+ digest, length = file_digest(path)
2399
+ if digest != entry["sha256"] or length != entry["bytes"]:
2400
+ problems.append(f"{rel} does not match the manifest's hash or size")
2401
+ continue
2402
+ files, size = files + 1, size + length
2403
+ for path in sorted(top.rglob("*")):
2404
+ rel = PurePosixPath(path.relative_to(top).as_posix())
2405
+ if (path.is_symlink() or not path.is_dir()) and rel not in named:
2406
+ problems.append(f"the restore wrote {rel}, and the manifest does not name it")
2407
+ return files, size, problems
2408
+
2409
+
2410
+ def run_restore_check(conf, store, wanted, record):
2411
+ """The check itself, filling in the record as it learns each fact. Returns its problems."""
2412
+ remote = archive_remote.load_remote(conf["remote"])
2413
+ archive_remote.require_ready(remote)
2414
+ record["destination"] = destination(remote)
2415
+ ident = wanted or newest_verified(store, remote)
2416
+ record["snapshot"] = ident
2417
+ # Without restore_scratch the system's temporary directory holds the scratch root, and TMPDIR can put that anywhere,
2418
+ # so the parent is checked here whichever it is. A local remote is a directory too, and a restored copy written
2419
+ # into it would sit among the objects it stands for.
2420
+ parent = Path(conf["restore_scratch"] or tempfile.gettempdir())
2421
+ label = f"restore_scratch {parent}" if conf["restore_scratch"] else f"the temporary directory {parent}"
2422
+ held = [("the archive", store), ("claude_projects", conf["claude_projects"]), ("codex_sessions", conf["codex_sessions"])]
2423
+ held += [("the repository", repo) for repo in conf["repos"]]
2424
+ if remote.kind == "local":
2425
+ held.append(("the local remote's root", Path(remote.get("root")).expanduser()))
2426
+ for what, top in held:
2427
+ if top and within(parent, top):
2428
+ raise Refused(f"{label} lies inside {what} {top}, which a restore check never writes")
2429
+ scratch = Path(tempfile.mkdtemp(prefix="ship-restore-check-", dir=parent))
2430
+ record["scratch"] = str(scratch)
2431
+ try:
2432
+ restored = restore_remote(remote, ident, conf["recovery_identity"], scratch / "root")
2433
+ record["completeness"] = restored["completeness"]
2434
+ record["files"], record["bytes"], problems = check_restored(scratch / "root", ident)
2435
+ return problems
2436
+ finally:
2437
+ shutil.rmtree(scratch, ignore_errors=True)
2438
+ record["removed"] = not os.path.lexists(scratch)
2439
+
2440
+
2441
+ def restore_check(conf, wanted=None):
2442
+ """Run one restore check and record it, failed or passed. Returns the record with the path it was written to."""
2443
+ if not conf["recovery_identity"]:
2444
+ raise Refused(f"the keep configuration {conf['config']} has no recovery_identity, the age identity file a restore "
2445
+ "check decrypts with, so no restore check ran")
2446
+ try:
2447
+ conf["archive"].mkdir(parents=True, exist_ok=True)
2448
+ except OSError as error:
2449
+ raise Refused(f"cannot make the archive {conf['archive']}: {error.strerror or error}, so no restore check ran") from None
2450
+ store = conf["archive"].resolve()
2451
+ started = time.monotonic()
2452
+ # `named` says whether a person chose the snapshot. Only a check of the newest verified one counts for the schedule.
2453
+ record = {"schema": RESTORE_CHECK_SCHEMA, "at": now(), "host": socket.gethostname(), "archive": str(store),
2454
+ "destination": None, "snapshot": wanted, "named": wanted is not None, "status": "failed", "completeness": None,
2455
+ "files": 0, "bytes": 0, "problems": [], "scratch": None, "removed": None, "seconds": None}
2456
+ try:
2457
+ record["problems"] = run_restore_check(conf, store, wanted, record)
2458
+ # A full scratch volume, an unreachable remote or a lost key all end here, as a failed check rather than a stop.
2459
+ except (Refused, archive_remote.StoreError, OSError) as why:
2460
+ record["problems"] = [str(why)]
2461
+ # A scratch root still there holds decrypted evidence, so the check failed however the restore went.
2462
+ if record["removed"] is False:
2463
+ record["problems"].append(f"the scratch root {record['scratch']} could not be removed, and the restored files are still in it")
2464
+ record["status"] = "failed" if record["problems"] else "passed"
2465
+ record["seconds"] = round(time.monotonic() - started, 3)
2466
+ body = (json.dumps(record, indent=2, sort_keys=True) + "\n").encode()
2467
+ path = store / RESTORE_CHECK_DIR / f"{datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S%fZ')}-{sha256(body)}.json"
2468
+ try:
2469
+ if not inside(store, path):
2470
+ raise Refused(f"the restore check {record['status']}, but it could not write its record: {path.parent} lies "
2471
+ "behind a symlink or outside the archive")
2472
+ publish(path, body)
2473
+ except OSError as error:
2474
+ raise Refused(f"the restore check {record['status']}, but it could not write its record {path}: "
2475
+ f"{error.strerror or error}") from None
2476
+ return dict(record, record=str(path))
2477
+
2478
+
2479
+ def launchd_job(conf, label):
2480
+ """The launch agent that keeps the archive every five minutes and at login, as a plist dictionary."""
2481
+ return archive_launchd.job(label, Path(__file__).absolute(), conf["config"], conf["archive"] / "logs" / "keep.log",
2482
+ KEEP_INTERVAL_SECONDS)
2483
+
2484
+
2485
+ def launchd_install(conf, agents, label, load):
2486
+ """Check the remote, install this keep's launch agent as archive_launchd.install does, and report its restore check."""
2487
+ if conf["remote"]:
2488
+ archive_remote.require_ready(archive_remote.load_remote(conf["remote"]))
2489
+ result = archive_launchd.install(agents, label, launchd_job(conf, label), load, replace_atomically)
2490
+ # `replaced` comes off and goes back on after restore_check, so the printed keys keep their order from before the
2491
+ # installer moved into archive_launchd.
2492
+ replaced = result.pop("replaced", None)
2493
+ # The restore check rides on this job rather than having one of its own, so installing the keep installs it.
2494
+ # An identity file that is absent now, on an unmounted volume say, is allowed: each due check records it as failed.
2495
+ identity = conf["recovery_identity"]
2496
+ result["restore_check"] = {"identity": str(identity), "present": identity.is_file(),
2497
+ "every_days": RESTORE_CHECK_EVERY.days,
2498
+ "retry_days": RESTORE_CHECK_RETRY.days} if identity else None
2499
+ if replaced:
2500
+ result["replaced"] = replaced
2501
+ return result
2502
+
2503
+
2504
+ def keep_exit(result):
2505
+ """1 for any failure of the archive, 2 for a capture that is only partial, 0 otherwise. A skipped keep is 0."""
2506
+ stages = {error["stage"] for error in result.get("errors", [])}
2507
+ if stages - {"capture"}:
2508
+ return 1
2509
+ return 2 if stages or (result.get("scan") or {}).get("completeness") == "partial" else 0
2510
+
2511
+
2512
+ # ---- command line ----------------------------------------------------------------------
2513
+
2514
+ def kryso_ui():
2515
+ """kryso's ui.py, from the kryso skill beside this one or an installed copy, in the order ui.sh's
2516
+ header names, or None when there is none, and the commands print plain. It holds the parser and
2517
+ the styling archive.py and report.py share. Only what a person reads goes through it: every
2518
+ verb's JSON is printed as it is, attended or not."""
2519
+ here = Path(__file__).resolve().parent
2520
+ for skill in (here.parent / "kryso", Path.home() / ".agents" / "skills" / "kryso", Path.home() / ".claude" / "skills" / "kryso"):
2521
+ if (skill / "ui.py").is_file() and (skill / "palette.json").is_file():
2522
+ if str(skill) not in sys.path:
2523
+ sys.path.insert(0, str(skill))
2524
+ import ui # noqa: E402
2525
+ return ui
2526
+ return None
2527
+
2528
+
2529
+ UI = kryso_ui()
2530
+
2531
+
2532
+ def say_error(message, hint=""):
2533
+ if UI:
2534
+ UI.say_error("archive", message, hint)
2535
+ else:
2536
+ print(f"archive: {message}", file=sys.stderr)
2537
+
2538
+
2539
+ def say_failed(message):
2540
+ if UI:
2541
+ UI.say_failed("archive", message)
2542
+ else:
2543
+ print(f"archive: {message}", file=sys.stderr)
2544
+
2545
+
2546
+ def checker_verb(parser, args):
2547
+ """`checker run` exits 0 for a check that needs nobody and 1 for anything else, so a script can act on it."""
2548
+ if args.action == "package":
2549
+ if not args.out:
2550
+ parser.error("checker package needs --out")
2551
+ print(json.dumps(archive_checker.write_package(args.out)))
2552
+ return 0
2553
+ if not args.config:
2554
+ parser.error(f"checker {args.action} needs --config")
2555
+ now = None
2556
+ if args.now is not None:
2557
+ now = archive_health.parse_time(args.now)
2558
+ if now is None:
2559
+ parser.error(f"--now {args.now!r} is not a UTC time like 2026-10-04T12:00:00Z")
2560
+ conf = archive_checker.load_checker(args.config)
2561
+ if args.action == "provision":
2562
+ print(archive_checker.provision_script(conf), end="")
2563
+ return 0
2564
+ if args.action == "audit":
2565
+ problems = archive_checker.audit(conf)
2566
+ print(json.dumps({"function": archive_checker.FUNCTION, "problems": problems}))
2567
+ return 1 if problems else 0
2568
+ record = archive_checker.run_local(conf, now)
2569
+ print(json.dumps(record))
2570
+ for error in record["errors"] + ([record["alert"]["error"]] if record["alert"]["status"] == "failed" else []):
2571
+ say_failed(f"checker: {error}")
2572
+ return 0 if archive_health.all_clear(record) else 1
2573
+
2574
+
2575
+ class Parser(UI.KrysoParser if UI else argparse.ArgumentParser):
2576
+ """Usage errors exit 64, because 2 means a partial snapshot."""
2577
+
2578
+ code = 64
2579
+
2580
+ if not UI:
2581
+ def error(self, message):
2582
+ self.print_usage(sys.stderr)
2583
+ self.exit(64, f"{self.prog}: error: {message}\n")
2584
+
2585
+
2586
+ def main(argv=None):
2587
+ parser = Parser(prog="kryso archive", description=__doc__)
2588
+ parser._positionals.title = "Verbs"
2589
+ verbs = parser.add_subparsers(dest="verb", required=True, parser_class=Parser, metavar="<verb>")
2590
+ c = verbs.add_parser("collect", help="snapshot one completed pass into content-addressed objects and a manifest")
2591
+ c.add_argument("--archive", type=Path, required=True, help="the archive directory, made when it is absent")
2592
+ c.add_argument("--repo", type=Path, required=True, help="the root of the repository the pass ran in")
2593
+ c.add_argument("--attempt", required=True, help="the attempt_id of the pass record")
2594
+ c.add_argument("--input", type=Path, action="append", default=[], help="a measurement input to keep (repeat it for more)")
2595
+ h = verbs.add_parser("history", help="find the evidence across repositories and keep one history capture")
2596
+ h.add_argument("--archive", type=Path, required=True, help="the archive directory, made when it is absent")
2597
+ h.add_argument("--repo", type=Path, action="append", required=True, help="a repository root (repeat it for more)")
2598
+ h.add_argument("--input", type=Path, action="append", default=[], help="a report, manifest or price table to keep")
2599
+ h.add_argument("--claude-projects", type=Path, help="the Claude projects root, for the session ids a record names")
2600
+ h.add_argument("--codex-sessions", type=Path, help="the Codex sessions root, for the session ids a record names")
2601
+ cv = verbs.add_parser("coverage", help="report how a history capture accounts for each source it found, and why each gap is one")
2602
+ cv.add_argument("--archive", type=Path, help="the archive directory that holds the history capture")
2603
+ cv.add_argument("--snapshot", help="the snapshot id of the history capture, with --archive")
2604
+ cv.add_argument("--manifest", type=Path, help="a history capture's manifest file in place of both, such as a restored archive-manifest.json")
2605
+ u = verbs.add_parser("upload", help="encrypt one snapshot and keep it on a remote, or resume the queue")
2606
+ u.add_argument("--archive", type=Path, required=True, help="the archive directory that holds the snapshot")
2607
+ u.add_argument("--snapshot", help="the snapshot id in the archive. Without it, every queued snapshot the remote has not verified")
2608
+ u.add_argument("--remote", type=Path, required=True, help="the remote's configuration file")
2609
+ st = verbs.add_parser("status", help="report a remote's upload queue from the local archive, without reading the remote")
2610
+ st.add_argument("--archive", type=Path, required=True, help="the archive directory that holds the queue")
2611
+ st.add_argument("--remote", type=Path, required=True, help="the remote's configuration file")
2612
+ st.add_argument("--snapshot", help="only this snapshot, with each of its items")
2613
+ v = verbs.add_parser("verify", help="check snapshots and objects against their hashes")
2614
+ v.add_argument("--archive", type=Path, help="check a local archive")
2615
+ v.add_argument("--remote", type=Path, help="check one snapshot on a remote")
2616
+ v.add_argument("--snapshot", help="only this snapshot id. --remote needs it")
2617
+ v.add_argument("--identity", type=Path, help="with --remote, an age identity file to decrypt and check the original bytes too")
2618
+ r = verbs.add_parser("restore", help="rebuild a snapshot under an empty root from verified bytes")
2619
+ r.add_argument("--archive", type=Path, help="restore from a local archive")
2620
+ r.add_argument("--remote", type=Path, help="restore from a remote")
2621
+ r.add_argument("--identity", type=Path, help="with --remote, the age identity file that decrypts the evidence")
2622
+ r.add_argument("--snapshot", help="the snapshot id")
2623
+ r.add_argument("--manifest", type=Path, help="a manifest file, such as a restored archive-manifest.json (local archive only)")
2624
+ r.add_argument("--to", type=Path, required=True, help="the restore root, absent or an empty directory")
2625
+ k = verbs.add_parser("check", help="check a remote's configuration before any verb uses it")
2626
+ k.add_argument("--remote", type=Path, required=True, help="the remote's configuration file")
2627
+ pv = verbs.add_parser("provision", help="print the script that makes an s3 remote's private bucket and identities")
2628
+ pv.add_argument("--remote", type=Path, required=True, help="the remote's configuration file")
2629
+ au = verbs.add_parser("audit", help="compare a deployed s3 bucket with what that script sets, with your own credentials")
2630
+ au.add_argument("--remote", type=Path, required=True, help="the remote's configuration file")
2631
+ kp = verbs.add_parser("keep", help="capture the configured roots, upload the queue and publish a health snapshot, one keep at a time per archive")
2632
+ kp.add_argument("--config", type=Path, required=True, help="the keep configuration file")
2633
+ kp.add_argument("--wait", type=int, default=0, help="how many seconds to wait for a keep already running (default 0, which skips)")
2634
+ kp.add_argument("--health-every", type=int, default=KEEP_INTERVAL_SECONDS,
2635
+ help=f"how many seconds between health snapshots while an upload runs (default {KEEP_INTERVAL_SECONDS})")
2636
+ rc = verbs.add_parser("restore-check", help="restore the snapshot verified last into a scratch root, check each file "
2637
+ "against its manifest, and record the result")
2638
+ rc.add_argument("--config", type=Path, required=True, help="the keep configuration file, with recovery_identity")
2639
+ rc.add_argument("--snapshot", help="check this snapshot in place of the one the queue verified last")
2640
+ he = verbs.add_parser("health", help="read the newest verified health snapshot from a remote")
2641
+ he.add_argument("--remote", type=Path, required=True, help="the remote's configuration file")
2642
+ he.add_argument("--days", type=int, default=HEALTH_LOOKBACK_DAYS, help=f"how many UTC days to look back (default {HEALTH_LOOKBACK_DAYS})")
2643
+ ck = verbs.add_parser("checker", help="run one check, or provision, audit or package the deployed checker")
2644
+ ck.add_argument("action", choices=("run", "provision", "audit", "package"))
2645
+ ck.add_argument("--config", type=Path, help="the checker configuration file, which every action but package needs")
2646
+ ck.add_argument("--now", help="with run, the UTC time to judge at, YYYY-MM-DDTHH:MM:SSZ (default the clock)")
2647
+ ck.add_argument("--out", type=Path, help="with package, the file to write the deployment package to")
2648
+ ld = verbs.add_parser("launchd", help="install, print or remove the launch agent that runs keep every five minutes and at login")
2649
+ ld.add_argument("action", choices=("install", "print", "remove"))
2650
+ ld.add_argument("--config", type=Path, help="the keep configuration file, which install and print need")
2651
+ ld.add_argument("--agents-dir", type=Path, default=Path("~/Library/LaunchAgents").expanduser(),
2652
+ help="the directory for the plist (default ~/Library/LaunchAgents)")
2653
+ ld.add_argument("--label", default=archive_launchd.LABEL, help=f"the job's label (default {archive_launchd.LABEL})")
2654
+ ld.add_argument("--no-load", action="store_true", help="write the plist and do not load it")
2655
+ args = parser.parse_args(argv)
2656
+ try:
2657
+ if args.verb == "collect":
2658
+ if not args.repo.is_dir():
2659
+ parser.error(f"no repository at {args.repo}")
2660
+ result = collect(args.archive.resolve(), args.repo, args.attempt, args.input)
2661
+ print(json.dumps(result))
2662
+ return 2 if result["completeness"] == "partial" else 0
2663
+ if args.verb == "history":
2664
+ missing = [str(repo) for repo in args.repo if not repo.is_dir()]
2665
+ if missing:
2666
+ parser.error(f"no repository at {missing[0]}")
2667
+ result = collect_history(args.archive.resolve(), args.repo, args.input,
2668
+ args.claude_projects, args.codex_sessions)
2669
+ print(json.dumps(result))
2670
+ return 2 if result["completeness"] == "partial" else 0
2671
+ if args.verb == "coverage":
2672
+ if bool(args.archive) == bool(args.manifest) or bool(args.archive) != bool(args.snapshot):
2673
+ parser.error("coverage takes --archive with --snapshot, or --manifest alone")
2674
+ if args.manifest:
2675
+ doc, _ = read_manifest_file(args.manifest)
2676
+ else:
2677
+ doc, _ = load_snapshot(args.archive.resolve(), args.snapshot)
2678
+ print(json.dumps(coverage_report(doc)))
2679
+ return 0
2680
+ if args.verb == "upload":
2681
+ remote = archive_remote.load_remote(args.remote)
2682
+ if args.snapshot:
2683
+ result = upload(args.archive.resolve(), args.snapshot, remote)
2684
+ print(json.dumps(result))
2685
+ return 2 if result["completeness"] == "partial" else 0
2686
+ result = upload_pending(args.archive.resolve(), remote)
2687
+ print(json.dumps(result))
2688
+ failed = [r for r in result["results"] if r["status"] == "failed"]
2689
+ for row in failed:
2690
+ say_failed(row["error"])
2691
+ return 1 if failed else 2 if any(r["completeness"] == "partial" for r in result["results"]) else 0
2692
+ if args.verb == "status":
2693
+ print(json.dumps(queue_status(args.archive.resolve(), archive_remote.load_remote(args.remote), args.snapshot)))
2694
+ return 0
2695
+ if args.verb == "verify":
2696
+ if bool(args.archive) == bool(args.remote):
2697
+ parser.error("verify takes --archive or --remote, not both or neither")
2698
+ if args.remote:
2699
+ if not args.snapshot:
2700
+ parser.error("verify --remote needs --snapshot")
2701
+ result = verify_remote(archive_remote.load_remote(args.remote), args.snapshot, args.identity)
2702
+ else:
2703
+ if not args.archive.is_dir():
2704
+ raise Refused(f"no archive at {args.archive}")
2705
+ result = verify(args.archive.resolve(), args.snapshot)
2706
+ print(json.dumps(result))
2707
+ return 1 if result["problems"] else 0
2708
+ if args.verb == "restore":
2709
+ if bool(args.archive) == bool(args.remote):
2710
+ parser.error("restore takes --archive or --remote, not both or neither")
2711
+ if bool(args.snapshot) == bool(args.manifest):
2712
+ parser.error("restore takes --snapshot or --manifest, not both or neither")
2713
+ if args.remote:
2714
+ if args.manifest:
2715
+ parser.error("restore --remote takes --snapshot, not --manifest")
2716
+ result = restore_remote(archive_remote.load_remote(args.remote), args.snapshot, args.identity, args.to.absolute())
2717
+ else:
2718
+ result = restore(args.archive.resolve(), args.snapshot, args.manifest, args.to.absolute())
2719
+ print(json.dumps(result))
2720
+ return 0
2721
+ if args.verb == "check":
2722
+ remote = archive_remote.load_remote(args.remote)
2723
+ problems = archive_remote.check(remote)
2724
+ print(json.dumps({"remote": remote.kind, "ready": not problems, "problems": problems}))
2725
+ if problems:
2726
+ raise Refused(archive_remote.explain(remote, problems))
2727
+ return 0
2728
+ if args.verb == "provision":
2729
+ print(archive_remote.provision_script(archive_remote.load_remote(args.remote)), end="")
2730
+ return 0
2731
+ if args.verb == "audit":
2732
+ remote = archive_remote.load_remote(args.remote)
2733
+ problems = archive_remote.audit(remote)
2734
+ print(json.dumps({"bucket": remote.get("bucket"), "problems": problems}))
2735
+ return 1 if problems else 0
2736
+ if args.verb == "keep":
2737
+ if args.wait < 0:
2738
+ parser.error("--wait takes a whole number of seconds, 0 or more")
2739
+ if args.health_every < 0:
2740
+ parser.error("--health-every takes a whole number of seconds, 0 or more")
2741
+ result = keep(load_keep(args.config), args.wait, args.health_every)
2742
+ print(json.dumps(result))
2743
+ for error in result.get("errors", []):
2744
+ say_failed(f"{error['stage']}: {error['error']}")
2745
+ return keep_exit(result)
2746
+ if args.verb == "restore-check":
2747
+ if args.snapshot is not None and not SNAPSHOT_ID.fullmatch(args.snapshot):
2748
+ parser.error(f"--snapshot {args.snapshot!r} is not a snapshot id: 64 lowercase hex characters")
2749
+ record = restore_check(load_keep(args.config), args.snapshot)
2750
+ print(json.dumps(record))
2751
+ for problem in record["problems"]:
2752
+ say_failed(f"restore check: {problem}")
2753
+ return 0 if record["status"] == "passed" else 1
2754
+ if args.verb == "health":
2755
+ if args.days < 1:
2756
+ parser.error("--days takes a whole number of days, 1 or more")
2757
+ result = read_health(archive_remote.load_remote(args.remote), args.days)
2758
+ print(json.dumps(result))
2759
+ return 0 if result["object"] else 1
2760
+ if args.verb == "checker":
2761
+ return checker_verb(parser, args)
2762
+ if args.verb == "launchd":
2763
+ if not archive_launchd.LABEL_SHAPE.fullmatch(args.label):
2764
+ parser.error(f"--label {args.label!r} is not a launchd label: letters, digits, dots and dashes")
2765
+ agents = args.agents_dir.expanduser().absolute()
2766
+ if args.action == "remove":
2767
+ print(json.dumps(archive_launchd.remove(agents, args.label)))
2768
+ return 0
2769
+ if not args.config:
2770
+ parser.error(f"launchd {args.action} needs --config")
2771
+ conf = load_keep(args.config)
2772
+ if args.action == "print":
2773
+ print(plistlib.dumps(launchd_job(conf, args.label)).decode(), end="")
2774
+ return 0
2775
+ print(json.dumps(launchd_install(conf, agents, args.label, not args.no_load)))
2776
+ return 0
2777
+ except (Refused, archive_remote.StoreError) as why:
2778
+ say_error(str(why))
2779
+ return 1
2780
+ return 64
2781
+
2782
+
2783
+ if __name__ == "__main__":
2784
+ sys.exit(main())