diff --git a/CHANGELOG.md b/CHANGELOG.md index 226d614..611f596 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,72 @@ All notable changes to `holotype`. Format adapted from [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); this project uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [2.5.0] - 2026-09-17 + +Keeping the archive's disk use in check. On a real archive holotype used about 21 GB locally, and git history grew by 4.7 GB in 15 days. + +### Settle window for updates + +A session that is still being written changes on almost every tick, and each update stores the whole transcript again. A compressed, git-crypt-encrypted blob gets no delta against its previous version. One 26 MB session was stored 129 times in two weeks (1.8 GB); 605 of the archive's 839 commits were updates. + +- A content update to an existing deposit now waits until the source has been quiet for `deposit.settle_hours` (default 6). The tick counts it as `settling=N`. +- The wait is capped at 24 hours after the last deposit, so a session that never goes quiet is still updated daily. +- New sessions and pure manifest migrations never wait. +- `--settle-hours` overrides the config for one run. `--settle-hours 0` deposits every change now, for example to cite a running session. +- `init.py` writes `settle_hours: 6`. Existing archives without the key get the default. + +Replaying the real archive's last 15 days of history: a 6-hour window keeps 5,438 of 5,921 transcript versions and cuts history growth from 4.7 GB to about 0.9 GB. + +### Tests + +The update step of the selftest now checks that a fresh change waits (`settling=1`) and that `--settle-hours 0` deposits it. New assertions cover the window, the 24-hour cap, and 0 disabling it. + +## [2.4.1] - 2026-09-17 + +Holotype now turns off git's automatic maintenance in the archive. On a large archive it could exhaust the machine's memory. + +### The failure + +git runs `git maintenance run --auto --detach` after every commit. When the loose-object count passes `gc.auto`, that starts a detached full repack (`git repack --cruft` and `git pack-objects --all`). Nothing stops a second repack from starting while the first is still running: each commit starts its own. One ingest tick makes one commit per changed session, so a busy tick starts several repacks at once. + +An archive's pack is mostly zstd or git-crypt blobs, which do not delta or compress. Every repack therefore reads the whole pack and holds gigabytes while it runs. On a real archive (7.3 GiB pack, 16 GB Mac) the repacks stacked up over one tick to 63 `git` processes and about 44 GB of memory. They never finished, the pack was never rewritten, the loose-object count stayed over the threshold, and every later commit started another repack. The machine ran out of memory and had to be force-restarted. + +Reproduced on git 2.54 with a scratch repository: four commits in a row left five concurrent `pack-objects --all` processes. + +### The fix + +- New `holotype.archive.disable_auto_maintenance()` sets `maintenance.auto=false` and `gc.auto=0` in the archive's local `.git/config`. It writes only when a value differs. +- `init.py` calls it right after `git init`. +- `ingest.py` calls it under the ingest lock, before the tick's first commit. Existing archives are migrated on their next tick with no action from you. +- No archive-format change. Nothing tracked in the archive changes. + +Loose objects now accumulate until you pack them. To pack only the loose objects, without rewriting the existing large pack, run `git -C repack -d`. + +### Stale compressed hashes no longer read as integrity failures + +On a real archive, 1,832 of 5,315 compressed deposits failed the rolling-sweep fsck with `ARCHIVE INTEGRITY FAILURE` ("stored bytes do not match manifest hash"). Every one of them decompressed to exactly the canonical `sha256`. The content was intact; only `sha256_compressed` was wrong. All 1,832 were deposited on the same day by v2.1.0 and migrated by v2.3.0. + +The v2.3.0 pure-migration path copied `sha256_compressed` from the prior manifest instead of hashing the file, so a stale value survived the migration. The sweep checks only the compressed hash, so each sweep slice reported about 40 false failures, and the real signal was lost in them. + +- The pure-migration path now hashes the `.zst` file on disk. +- The fsck decompresses a deposit whose compressed hash disagrees. If the canonical `sha256` matches, it counts the deposit as `stale-hash`, not as an integrity failure. Real damage is still reported as before. +- New `scripts/repair_compressed_hashes.py` rewrites stale values in one `repair:` commit. It changes only the `sha256_compressed` string, and only after the canonical hash matches, so transcripts and the ledger are untouched. `--dry-run` reports without writing. Damaged deposits are listed and never rewritten. + +### iCloud-evicted source files are skipped, not failed + +Every sweep also logged dozens of `holotype: worker failed on ...: OSError: [Errno 11] Resource deadlock avoided`. The preferred source was a Claude Code backup mirror under `~/Documents`, which iCloud syncs. With "Optimize Mac Storage" on, iCloud had evicted 3,556 of its 11,311 transcripts: the bytes live in the cloud and only a placeholder (`SF_DATALESS`) is on disk. A background process like the launchd tick may not download it, so the read fails with `EDEADLK`. + +- Discovery still keeps the first path listed for a session, unless that copy is evicted and a later path has the file on disk. On the real archive, every evicted candidate had a local copy in `~/.claude/projects`. +- `deposit_one` skips an evicted source with a new `skipped-offline` status instead of raising. The prior deposit stands, and the session is read again once the file is local. The tick summary shows `offline=N` when any were skipped. + +### Auto-push has a timeout + +`ingest.py` ran `git push` with no timeout. A push that stalls instead of failing (a dropped connection that never resets, a laptop that sleeps mid-push) would hold the ingest lock forever, and every later tick would exit with "another ingest is running". Pushes now go through `run_with_timeout` with a one-hour limit (`PUSH_TIMEOUT_SECONDS`), enough for a `--max-pack-gib` chunk on a slow uplink. On timeout it kills the push's whole process group, so ssh and `pack-objects` don't outlive it. The failure is reported like any other push failure, and the next tick with changes retries. + +### Tests + +The selftest checks that `init.py` sets both keys, and that `ingest.py` restores them on an archive where they are unset. A new step covers stale compressed hashes: the migration rehashes, the fsck reports stale instead of failed, the repair commits, and real damage is still caught. Another step checks that discovery prefers an on-disk copy over an evicted one and that an evicted source is skipped as offline. A third checks that the timeout stops a stalled command and leaves no grandchild running. + ## [2.4.0] — 2026-05-28 The archive's "hash chain" is now a real chain. Until this release, "hash chain" named an aspiration: each `manifest.json` carried the SHA-256 of its own transcript, and `verify.py` checked each file against its *own* manifest. That proves per-file content integrity but binds nothing across deposits — a coordinated edit of a transcript *and* its manifest is internally consistent and passed `verify.py` clean. The only thing recording the set and order of deposits was git's commit DAG, which a self-contained `paper_bundle` `.tar.gz` (shipped with no `.git`) doesn't carry. So a reviewer holding a bundle could confirm self-consistency but not that nothing had been inserted, deleted, or substituted. diff --git a/SKILL.md b/SKILL.md index 9f87b74..24a8985 100644 --- a/SKILL.md +++ b/SKILL.md @@ -219,7 +219,7 @@ When you do this, validate via `python scripts/selftest.py` against a fixture yo Read these before any operation: -1. **Never hand-edit a deposited transcript.** The archive's git tree is append-only from outside. If a session JSONL grows in the source (a session keeps running and adds more turns), the next `ingest.py` will detect the change and record it as an `update` commit — that is the only mechanism by which a deposited transcript ever changes on disk. +1. **Never hand-edit a deposited transcript.** The archive's git tree is append-only from outside. If a session JSONL grows in the source (a session keeps running and adds more turns), the next `ingest.py` will detect the change and record it as an `update` commit — that is the only mechanism by which a deposited transcript ever changes on disk. To bound archive growth, an update waits until the source has been quiet for `config.deposit.settle_hours` (default 6, never more than 24 h after the last deposit); new sessions deposit at once. When the user needs the latest state of a running session now (for example, to cite it), run `python scripts/ingest.py --settle-hours 0`. 2. **Never filter content.** Tool calls, tool results, thinking blocks, system reminders, hook outputs — every byte is part of the scientific record. The skill's whole point is forensic completeness. 3. **Push policy is set at archive-init time, not at ingest time.** When `config.deposit.auto_push` is true (the default when a remote was configured at init), ingest pushes after a successful cycle — that's what the user opted into when they said "yes, back up to GitHub" at setup. When auto-push is false, only push when the user explicitly asks. Never *re-configure* push policy mid-stream without going back through the wizard; the privacy decision lives at init. 4. **The archive is git-tracked.** Every deposit is a commit with a deterministic message of the form `deposit: /` or `update: /`. Both the JSONL and its manifest live under `sessions///`. diff --git a/holotype/__init__.py b/holotype/__init__.py index d586123..f943788 100644 --- a/holotype/__init__.py +++ b/holotype/__init__.py @@ -1,3 +1,3 @@ """holotype: forensic-grade archival of agent-CLI sessions for scientific reproducibility.""" -__version__ = "2.4.0" +__version__ = "2.5.0" diff --git a/holotype/archive.py b/holotype/archive.py index 6631a5f..0286f75 100644 --- a/holotype/archive.py +++ b/holotype/archive.py @@ -12,6 +12,7 @@ from __future__ import annotations import json +import subprocess from pathlib import Path from typing import Iterator @@ -62,3 +63,41 @@ def resolve_session_by_prefix(archive: Path, prefix: str) -> Path | None: sys.stderr.write(f" {m.name}\n") return None return matches[0] + + +# git runs `git maintenance run --auto --detach` after every commit. Once +# the loose-object count crosses gc.auto, each commit starts its own +# detached full repack (`pack-objects --all`), and nothing stops a second +# one from starting while the first is still running. An archive's pack +# is mostly incompressible blobs (zstd or git-crypt), so each repack holds +# gigabytes and runs for a long time. One ingest tick makes one commit +# per changed session, which is enough to stack repacks until the machine +# runs out of memory. Holotype turns automatic maintenance off in the +# archive; repack by hand with `git repack -d` when loose objects pile up. +AUTO_MAINTENANCE_OFF = ( + ("maintenance.auto", "false"), + ("gc.auto", "0"), +) + + +def disable_auto_maintenance(archive: Path) -> None: + """Turn off git's automatic background maintenance for ``archive``. + + Writes to the archive's local ``.git/config`` only, and only when a + value differs, so calling this every ingest tick is cheap. Failures + are ignored: a missing setting costs memory, not correctness. + """ + for key, value in AUTO_MAINTENANCE_OFF: + try: + current = subprocess.run( + ["git", "-C", str(archive), "config", "--local", "--get", key], + capture_output=True, text=True, timeout=10, + ) + if current.stdout.strip() == value: + continue + subprocess.run( + ["git", "-C", str(archive), "config", "--local", key, value], + capture_output=True, text=True, timeout=10, + ) + except (subprocess.SubprocessError, OSError): + pass diff --git a/holotype/parallel.py b/holotype/parallel.py index da02967..67f08ed 100644 --- a/holotype/parallel.py +++ b/holotype/parallel.py @@ -34,6 +34,7 @@ def process_candidate_worker( *, compression: str | None, compression_level: str, + settle_seconds: float = 0, ) -> dict[str, Any]: """Process one deposit candidate inside a worker process. @@ -91,6 +92,7 @@ def process_candidate_worker( archive, source_cls, cand, compression=compression, compression_level=compression_level, + settle_seconds=settle_seconds, ) return { "status": status, diff --git a/pyproject.toml b/pyproject.toml index 650e6ee..66c5630 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "holotype" -version = "2.4.0" +version = "2.5.0" description = "Forensic-grade archival of LLM-driven agent CLI sessions for scientific reproducibility" readme = "README.md" license = { file = "LICENSE" } diff --git a/scripts/ingest.py b/scripts/ingest.py index e65da3c..9da07d2 100644 --- a/scripts/ingest.py +++ b/scripts/ingest.py @@ -29,21 +29,31 @@ from __future__ import annotations import argparse +import errno import fcntl import hashlib import json import os +import signal import subprocess import sys import time +from datetime import datetime from pathlib import Path REPO_ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(REPO_ROOT)) from holotype import __version__ +from holotype.archive import disable_auto_maintenance from holotype.chunking import bin_pack_paths, dir_size_bytes -from holotype.compression import compress_bytes, find_transcript, transcript_filename +from holotype.compression import ( + compress_bytes, + decompress_bytes, + find_transcript, + transcript_filename, + zstd_available, +) from holotype.env import claude_code_version, git_state_for_path, platform_info from holotype.hashing import sha256_bytes from holotype.index import ( @@ -105,13 +115,18 @@ def discover_candidates( Claude Code itself prunes). """ candidates: list[tuple[type[Source], DepositCandidate]] = [] - seen: set[tuple[str, str]] = set() + seen: dict[tuple[str, str], int] = {} def _add(cls: type[Source], c: DepositCandidate) -> None: key = (cls.name, c.session_id) if key in seen: + # Keep the first path, unless its copy has been evicted to the + # cloud and this one is still on disk (see is_dataless). + first = seen[key] + if is_dataless(candidates[first][1].jsonl_path) and not is_dataless(c.jsonl_path): + candidates[first] = (cls, c) return - seen.add(key) + seen[key] = len(candidates) candidates.append((cls, c)) if explicit_source is not None: @@ -141,6 +156,47 @@ def _add(cls: type[Source], c: DepositCandidate) -> None: return candidates +# macOS SF_DATALESS: the file's bytes were evicted to iCloud ("Optimize Mac +# Storage") and only a placeholder is on disk. A background process such as +# the launchd tick is not allowed to download it, so reading fails with +# EDEADLK ("Resource deadlock avoided"). Always 0 on other platforms. +SF_DATALESS = 0x40000000 + + +def is_dataless(path: Path) -> bool: + try: + return bool(getattr(path.stat(), "st_flags", 0) & SF_DATALESS) + except OSError: + return False + + +# Settle window. A session that is still being written changes on nearly +# every tick, and each re-deposit stores the whole transcript again: an +# encrypted, compressed blob gets no delta against its previous version. On +# a real archive one 26 MB session was stored 129 times in two weeks +# (1.8 GiB). So a changed session that already has a deposit waits until its +# source has been quiet for the settle window. New sessions deposit at once. +# The wait is capped: after SETTLE_MAX_DEFER_SECONDS since the last deposit, +# the update goes through even if the session is still active. +DEFAULT_SETTLE_HOURS = 6.0 +SETTLE_MAX_DEFER_SECONDS = 24 * 3600 + + +def should_defer_update(prior_manifest: dict, source_mtime: float, + settle_seconds: float, now: float | None = None) -> bool: + """True if a content update to an existing deposit should wait.""" + if settle_seconds <= 0: + return False + now = time.time() if now is None else now + if now - source_mtime >= settle_seconds: + return False + try: + last = datetime.fromisoformat(prior_manifest["deposited_at"]).timestamp() + except (KeyError, TypeError, ValueError): + return False + return now - last < SETTLE_MAX_DEFER_SECONDS + + def is_live_file(path: Path) -> bool: try: age = time.time() - path.stat().st_mtime @@ -264,15 +320,22 @@ def needs_processing( def verify_deposit_integrity( - archive: Path, candidate: DepositCandidate + archive: Path, + candidate: DepositCandidate, + stale_out: list[str] | None = None, ) -> str | None: """fsck one deposited transcript against its manifest hash. Hashes the on-disk deposit bytes as they sit (compressed bytes vs - ``sha256_compressed`` when zstd, raw bytes vs ``sha256`` otherwise) — - pure bit-rot detection that needs no zstd and never false-alarms. + ``sha256_compressed`` when zstd, raw bytes vs ``sha256`` otherwise). Returns an error string on mismatch/missing, else None. Run on the rolling-sweep slice so the whole archive is re-checked every ~24h. + + When only the compressed hash disagrees, the file is decompressed and + checked against the canonical ``sha256``. If that matches, the content + is intact and only the recorded compressed hash is stale: the session + is appended to ``stale_out`` instead of being reported as a failure. + ``scripts/repair_compressed_hashes.py`` rewrites the stale values. """ m = existing_manifest(archive, candidate) if not m: @@ -290,6 +353,15 @@ def verify_deposit_integrity( except OSError as e: return f"{candidate.archive_subpath}: deposited transcript unreadable ({e})" if sha256_bytes(raw) != expected: + if is_compressed and m.get("sha256") and zstd_available(): + try: + canonical = sha256_bytes(decompress_bytes(raw)) + except Exception: + canonical = None + if canonical == m.get("sha256"): + if stale_out is not None: + stale_out.append(candidate.archive_subpath) + return None return ( f"{candidate.archive_subpath}: ARCHIVE INTEGRITY FAILURE — " f"stored bytes do not match manifest hash" @@ -305,6 +377,40 @@ def run_git(archive: Path, *args: str) -> subprocess.CompletedProcess: ) +# A push that stalls (dropped connection, sleeping laptop, captive portal) +# never returns on its own, and the ingest lock blocks every later tick +# while it waits. One hour covers a --max-pack-gib chunk on a slow uplink. +PUSH_TIMEOUT_SECONDS = 3600 + + +def run_with_timeout(cmd: list[str], timeout: float) -> subprocess.CompletedProcess: + """Run ``cmd``; on timeout, kill its whole process group. + + ``subprocess.run(timeout=...)`` kills only the direct child, so a timed + out ``git push`` would leave its ssh and pack-objects children running. + A new session puts the command and all its descendants in one process + group that can be killed together. + """ + proc = subprocess.Popen( + cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + start_new_session=True, + ) + try: + out, err = proc.communicate(timeout=timeout) + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + out, err = proc.communicate() + err = (err or "") + f"\nholotype: timed out after {timeout:g}s; killed.\n" + return subprocess.CompletedProcess(cmd, proc.returncode, out, err) + + +def push_git(archive: Path, *args: str) -> subprocess.CompletedProcess: + return run_with_timeout(["git", "-C", str(archive), *args], PUSH_TIMEOUT_SECONDS) + + def git_head_short(archive: Path) -> str | None: out = run_git(archive, "rev-parse", "--short", "HEAD") return out.stdout.strip() if out.returncode == 0 and out.stdout.strip() else None @@ -317,9 +423,14 @@ def deposit_one( *, compression: str | None, compression_level: str = "archival", + settle_seconds: float = 0, ) -> tuple[str, str, bool]: """Deposit one candidate. Returns (status, session_id, transcript_changed). + With ``settle_seconds > 0``, a content update to an existing deposit is + returned as ``skipped-settling`` while the source is still changing (see + ``should_defer_update``). New deposits and pure migrations never wait. + ``transcript_changed`` is True only when the on-disk transcript bytes differ from the prior deposit (i.e. a real "new" or content-update). For pure manifest-version migrations (the bytes are unchanged but @@ -338,7 +449,16 @@ def deposit_one( if is_live_file(jsonl_path): return ("skipped-live", session_id, False) - data = read_with_stable_check(jsonl_path) + # An evicted source can't be read from here. The prior deposit, if + # any, stands; the session is picked up once the file is local again. + if is_dataless(jsonl_path): + return ("skipped-offline", session_id, False) + try: + data = read_with_stable_check(jsonl_path) + except OSError as e: + if e.errno == errno.EDEADLK: + return ("skipped-offline", session_id, False) + raise if data is None: return ("skipped-live", session_id, False) if not data.strip(): @@ -376,6 +496,14 @@ def deposit_one( transcript_changed = (prior_sha != new_sha) + if ( + prior_manifest is not None + and transcript_changed + and src_mtime_ns is not None + and should_defer_update(prior_manifest, src_mtime_ns / 1e9, settle_seconds) + ): + return ("skipped-settling", session_id, False) + # Pure manifest-version migration: canonical transcript bytes are # unchanged, only the schema bumped. Do NOT re-write the transcript. # Re-compressing produces cosmetically-different bytes (zstd output is @@ -397,9 +525,11 @@ def deposit_one( if is_pure_migration and dest_transcript.exists(): if compression == "zstd": - sha_compressed = prior_manifest.get("sha256_compressed") or sha256_bytes( - dest_transcript.read_bytes() - ) + # Hash the file as it sits instead of copying the prior + # manifest's value. A copied value can be stale: the v2.3.0 + # migration carried 1,832 stale compressed hashes forward on a + # real archive, and each one read as an integrity failure. + sha_compressed = sha256_bytes(dest_transcript.read_bytes()) else: sha_compressed = None else: @@ -704,11 +834,13 @@ def _parallel_worker_unpack(args_tuple): fixed-config + per-task tuple here so each pool task can unpack it cleanly. Lives at module top so it's picklable. """ - archive_str, source_name, candidate_dict, compression, compression_level = args_tuple + (archive_str, source_name, candidate_dict, compression, compression_level, + settle_seconds) = args_tuple from holotype.parallel import process_candidate_worker return process_candidate_worker( archive_str, source_name, candidate_dict, compression=compression, compression_level=compression_level, + settle_seconds=settle_seconds, ) @@ -839,6 +971,18 @@ def main(argv: list[str] | None = None) -> int: "are deferred to a single bulk INSERT + 'optimize' at end." ), ) + p.add_argument( + "--settle-hours", + type=float, + default=None, + help=( + "Wait until a changed session's source has been quiet this " + "many hours before re-depositing it (new sessions deposit at " + "once; an update is never deferred more than 24 h). Overrides " + "config.deposit.settle_hours (default 6). 0 re-deposits every " + "change on the next tick, e.g. to cite a session right now." + ), + ) p.add_argument( "--fast-compress", action="store_true", @@ -902,9 +1046,15 @@ def main(argv: list[str] | None = None) -> int: print("holotype: another ingest is running, exiting") return 0 + # Before the first commit of this tick, so no commit can start a + # detached repack. Also migrates archives created before this setting. + if not args.dry_run: + disable_auto_maintenance(archive) + try: counts: dict[str, int] = {"new": 0, "updated": 0, "skipped-live": 0, - "skipped-unchanged": 0, "skipped-empty": 0} + "skipped-unchanged": 0, "skipped-empty": 0, + "skipped-offline": 0, "skipped-settling": 0} committed: list[str] = [] # Per-tick pre-filter: stat each candidate against its stored @@ -975,6 +1125,13 @@ def main(argv: list[str] | None = None) -> int: # segment merges across the whole batch. bulk_fts_rows: list[tuple] = [] compression_level = "fast" if args.fast_compress else "archival" + settle_hours = args.settle_hours + if settle_hours is None: + settle_hours = deposit_cfg.get("settle_hours", DEFAULT_SETTLE_HOURS) + try: + settle_seconds = max(0.0, float(settle_hours)) * 3600 + except (TypeError, ValueError): + settle_seconds = DEFAULT_SETTLE_HOURS * 3600 # Resolve worker count. 0 = auto. 1 = explicit serial mode. # Anything > 1 runs the parallel coordinator path. @@ -1016,7 +1173,8 @@ def main(argv: list[str] | None = None) -> int: results_iter = executor.map( _parallel_worker_unpack, [ - (s[0], s[1], s[2], compression, compression_level) + (s[0], s[1], s[2], compression, compression_level, + settle_seconds) for s in submissions ], ) @@ -1045,6 +1203,7 @@ def main(argv: list[str] | None = None) -> int: status, session_id, transcript_changed = deposit_one( archive, source_cls, candidate, compression=compression, compression_level=compression_level, + settle_seconds=settle_seconds, ) counts[status] = counts.get(status, 0) + 1 @@ -1186,7 +1345,7 @@ def main(argv: list[str] | None = None) -> int: # First chunk creates/upgrades the tracking # branch; subsequent chunks fast-forward. push_args = ["push", "-u", "origin", "main"] if ci == 1 else ["push", "origin", "HEAD"] - push = run_git(archive, *push_args) + push = push_git(archive, *push_args) if push.returncode == 0: if not args.quiet: print(f" push chunk {ci}/{len(chunks)} OK") @@ -1244,9 +1403,10 @@ def main(argv: list[str] | None = None) -> int: # Failures are reported loudly and sent to stderr — they indicate # the deposited artifact no longer matches what was recorded. integrity_failures: list[str] = [] + stale_compressed: list[str] = [] if not args.dry_run: for _cls, cand in sweep_candidates: - err = verify_deposit_integrity(archive, cand) + err = verify_deposit_integrity(archive, cand, stale_compressed) if err: integrity_failures.append(err) advance_sweep_cursor(archive, sweep_bucket) @@ -1257,6 +1417,12 @@ def main(argv: list[str] | None = None) -> int: ) for f in integrity_failures: sys.stderr.write(f" {f}\n") + if stale_compressed and not args.quiet: + print( + f"holotype: {len(stale_compressed)} deposit(s) in this sweep have a " + f"stale sha256_compressed (content verified intact). Fix with " + f"`python scripts/repair_compressed_hashes.py`." + ) any_changes = counts["new"] + counts["updated"] > 0 if not args.quiet or any_changes or integrity_failures: @@ -1267,6 +1433,9 @@ def main(argv: list[str] | None = None) -> int: f" empty={counts['skipped-empty']}" f" swept={len(sweep_candidates)}" + (f" INTEGRITY-FAIL={len(integrity_failures)}" if integrity_failures else "") + + (f" stale-hash={len(stale_compressed)}" if stale_compressed else "") + + (f" offline={counts['skipped-offline']}" if counts["skipped-offline"] else "") + + (f" settling={counts['skipped-settling']}" if counts["skipped-settling"] else "") ) if committed and not args.quiet: print("\n".join(committed)) @@ -1285,7 +1454,7 @@ def main(argv: list[str] | None = None) -> int: if any_changes and auto_push and remote_url and not args.dry_run and not bulk_chunks_pushed: if not args.quiet: print(f" pushing to {remote_url}...") - push = run_git(archive, "push", "origin", "HEAD") + push = push_git(archive, "push", "origin", "HEAD") if push.returncode == 0: if not args.quiet: print(" push OK") diff --git a/scripts/init.py b/scripts/init.py index 991e126..5b242ea 100644 --- a/scripts/init.py +++ b/scripts/init.py @@ -35,6 +35,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) from holotype import ledger # noqa: E402 +from holotype.archive import disable_auto_maintenance # noqa: E402 ARCHIVE_FORMAT_VERSION = 1 HOLOTYPE_SUBDIR = ".holotype" @@ -345,6 +346,11 @@ def write_config( "commit_strategy": "per-session", "sign_commits": sign_commits, "compression": compression, + # Hours a changed session must be quiet before it is deposited + # again (new sessions deposit at once). Each update stores the + # whole transcript, so this bounds archive growth from sessions + # that are still being written. 0 deposits every change. + "settle_hours": 6, # When true and a remote is configured, ingest.py runs # `git push` after a successful ingest. Privacy decision was # made at remote-configuration time (the wizard's explicit @@ -525,6 +531,7 @@ def init_archive(args: argparse.Namespace) -> int: is_new_repo = not (archive / ".git").exists() if is_new_repo: run(["git", "init", "-b", "main"], cwd=archive) + disable_auto_maintenance(archive) if args.sign_commits: # Probe for a signing key. Don't fail init outright — the user diff --git a/scripts/repair_compressed_hashes.py b/scripts/repair_compressed_hashes.py new file mode 100644 index 0000000..63e1ae7 --- /dev/null +++ b/scripts/repair_compressed_hashes.py @@ -0,0 +1,174 @@ +#!/usr/bin/env python3 +"""Rewrite stale ``sha256_compressed`` values in deposit manifests. + +A compressed deposit records two hashes: ``sha256`` of the canonical +(uncompressed) transcript, which is what gets cited and chained, and +``sha256_compressed`` of the ``.zst`` file as it sits on disk, which lets a +reviewer without zstd check the file directly. + +Before v2.4.1, a pure manifest-version migration copied +``sha256_compressed`` from the prior manifest instead of hashing the file. +When the prior value was already stale, the migration carried it forward. +The content is intact (the canonical hash still matches), but the ingest +sweep and the no-zstd track of ``verify.py`` both report the deposit as an +integrity failure. + +This script finds every compressed deposit whose file hash differs from +``sha256_compressed``, decompresses it, and checks the result against +``sha256``. Only when the canonical hash matches does it rewrite +``sha256_compressed``. A deposit whose canonical hash does NOT match is real +damage: it is reported and left alone. + +The rewrite changes one hex string in each manifest and nothing else, so the +hash-chain ledger (which links canonical ``sha256`` values only) is +unaffected. All repaired manifests go into one ``repair:`` commit. + +Usage: + python scripts/repair_compressed_hashes.py --dry-run # report only + python scripts/repair_compressed_hashes.py # repair + commit + +Exit codes: + 0 nothing stale, or all stale hashes repaired + 1 at least one deposit has real content damage (never rewritten) + 2 another ingest holds the archive lock, or zstd is missing +""" + +from __future__ import annotations + +import argparse +import fcntl +import json +import os +import subprocess +import sys +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(REPO_ROOT)) + +from holotype.archive import iter_all_sessions # noqa: E402 +from holotype.compression import ( # noqa: E402 + COMPRESSED_TRANSCRIPT, + decompress_bytes, + zstd_available, +) +from holotype.hashing import sha256_bytes # noqa: E402 + + +def find_archive(explicit: Path | None) -> Path: + if explicit: + return explicit.expanduser().resolve() + env = os.environ.get("HOLOTYPE_ARCHIVE") + if env: + return Path(env).expanduser().resolve() + pointer = Path.home() / ".config" / "holotype" / "archive-path" + if pointer.exists(): + return Path(pointer.read_text().strip()).expanduser().resolve() + return (Path.home() / "Documents" / "holotype-archive").resolve() + + +def run_git(archive: Path, *args: str) -> subprocess.CompletedProcess: + return subprocess.run( + ["git", "-C", str(archive), *args], capture_output=True, text=True + ) + + +def main(argv: list[str] | None = None) -> int: + p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + p.add_argument("--archive", type=Path, default=None) + p.add_argument("--dry-run", action="store_true", + help="Report stale hashes without rewriting anything.") + args = p.parse_args(argv) + + if not zstd_available(): + print("repair: zstd not found on PATH; cannot check canonical hashes.", + file=sys.stderr) + return 2 + + archive = find_archive(args.archive) + lock_path = archive / ".holotype" / ".lock" + lock_path.parent.mkdir(parents=True, exist_ok=True) + lock = lock_path.open("w") + try: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + print("repair: an ingest is running; try again when it finishes.", + file=sys.stderr) + return 2 + + try: + stale: list[tuple[Path, str, str]] = [] + damaged: list[Path] = [] + checked = 0 + for sess_dir, manifest in iter_all_sessions(archive): + zst = sess_dir / COMPRESSED_TRANSCRIPT + recorded = manifest.get("sha256_compressed") + if not zst.exists() or not recorded: + continue + checked += 1 + raw = zst.read_bytes() + actual = sha256_bytes(raw) + if actual == recorded: + continue + try: + canonical = sha256_bytes(decompress_bytes(raw)) + except Exception: + canonical = None + if canonical and canonical == manifest.get("sha256"): + stale.append((sess_dir, recorded, actual)) + else: + damaged.append(sess_dir) + + rel = lambda d: d.relative_to(archive) # noqa: E731 + print(f"repair: checked {checked} compressed deposit(s): " + f"{len(stale)} stale hash(es), {len(damaged)} damaged") + for d in damaged: + print(f" DAMAGED (not rewritten): {rel(d)}", file=sys.stderr) + + if args.dry_run or not stale: + return 1 if damaged else 0 + + for sess_dir, old, new in stale: + path = sess_dir / "manifest.json" + text = path.read_text() + if text.count(old) != 1: + print(f" skipped (hash not found exactly once): {rel(sess_dir)}", + file=sys.stderr) + continue + tmp = path.with_suffix(".json.partial") + tmp.write_text(text.replace(old, new)) + os.replace(tmp, path) + + paths = [f"{rel(d)}/manifest.json" for d, _, _ in stale] + for i in range(0, len(paths), 500): + run_git(archive, "add", *paths[i:i + 500]) + if run_git(archive, "diff", "--cached", "--quiet").returncode != 0: + config_path = archive / ".holotype" / "config.json" + try: + config = json.loads(config_path.read_text()) + except (OSError, json.JSONDecodeError): + config = {} + sign = bool((config.get("deposit") or {}).get("sign_commits")) + msg = ( + f"repair: rewrite {len(stale)} stale sha256_compressed value(s)\n\n" + "Each manifest's sha256_compressed no longer matched its .zst\n" + "file. The decompressed content still matches the canonical\n" + "sha256, so only the compressed hash was rewritten. Transcripts\n" + "and the hash-chain ledger are unchanged." + ) + commit_args = ["commit", "-m", msg] + if sign: + commit_args.insert(1, "-S") + out = run_git(archive, *commit_args) + if out.returncode != 0: + print(f"repair: commit failed: {out.stderr.strip()}", file=sys.stderr) + return 2 + print(f"repair: committed {len(stale)} manifest(s)") + return 1 if damaged else 0 + finally: + fcntl.flock(lock, fcntl.LOCK_UN) + lock.close() + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/selftest.py b/scripts/selftest.py index c4f586d..dc64259 100644 --- a/scripts/selftest.py +++ b/scripts/selftest.py @@ -25,6 +25,7 @@ import argparse import hashlib import json +from datetime import datetime, timezone import shutil import subprocess import sqlite3 @@ -171,6 +172,20 @@ def main(argv: list[str] | None = None) -> int: expect((archive / "README.md").exists(), "archive README.md missing") expect((archive / ".git").is_dir(), "archive is not a git repo") + step("init.py turns off git auto-maintenance in the archive") + for key, want in (("maintenance.auto", "false"), ("gc.auto", "0")): + got = subprocess.run( + ["git", "-C", str(archive), "config", "--local", "--get", key], + capture_output=True, text=True, + ).stdout.strip() + expect(got == want, f"archive {key}={got!r}, expected {want!r}") + # Unset again so the first ingest below has to migrate an + # archive created before this setting existed. + subprocess.run( + ["git", "-C", str(archive), "config", "--local", "--unset", key], + check=True, + ) + step("materialize synthetic source") source = materialize_source(tmp) @@ -186,6 +201,14 @@ def main(argv: list[str] | None = None) -> int: expect(result.returncode == 0, f"ingest.py returncode={result.returncode}: {result.stderr}") expect("new=3" in result.stdout, f"expected new=3 in output:\n{result.stdout}") + step("ingest turns off git auto-maintenance on an older archive") + for key, want in (("maintenance.auto", "false"), ("gc.auto", "0")): + got = subprocess.run( + ["git", "-C", str(archive), "config", "--local", "--get", key], + capture_output=True, text=True, + ).stdout.strip() + expect(got == want, f"archive {key}={got!r} after ingest, expected {want!r}") + sessions_dir = archive / "sessions" deposits = sorted(p for p in sessions_dir.rglob("transcript.jsonl")) expect(len(deposits) == 3, f"expected 3 deposits (2 top-level + 1 subagent), got {len(deposits)}") @@ -309,10 +332,24 @@ def main(argv: list[str] | None = None) -> int: older = time.time() - 60 os.utime(basic_in_source, (older, older)) + # Changed a minute ago, so under the default 6 h settle window the + # update waits instead of storing a second full copy. + result = run_script( + REPO_ROOT / "scripts" / "ingest.py", + "--archive", str(archive), + "--source", str(source), + ) + if args.verbose: + print(result.stdout) + expect("updated=0" in result.stdout and "settling=1" in result.stdout, + f"expected the update to wait for the settle window:\n{result.stdout}") + + # --settle-hours 0 deposits the change now. result = run_script( REPO_ROOT / "scripts" / "ingest.py", "--archive", str(archive), "--source", str(source), + "--settle-hours", "0", ) if args.verbose: print(result.stdout) @@ -1391,6 +1428,20 @@ def main(argv: list[str] | None = None) -> int: len(basic_yields) == 1, f"dedup failed: session yielded {len(basic_yields)} times across mirrored paths", ) + + # When the first path's copy is evicted to iCloud (dataless) and + # the mirror's copy is on disk, dedup keeps the readable one, and + # a deposit from an evicted copy is skipped instead of failing. + mod.is_dataless = lambda p: Path(p).is_relative_to(source.resolve()) + cands = mod.discover_candidates({}, None, None) + picked = [c for cls, c in cands + if cls is ClaudeCodeSource and c.session_id == basic_uuid_dup] + expect(len(picked) == 1 and picked[0].jsonl_path.is_relative_to(mirror_src.resolve()), + f"dedup kept an evicted copy: {[str(c.jsonl_path) for c in picked]}") + mod.is_dataless = lambda p: True + status, _, _ = mod.deposit_one(archive, ClaudeCodeSource, picked[0], compression=None) + expect(status == "skipped-offline", + f"evicted source should be skipped-offline, got {status}") finally: ClaudeCodeSource.default_source_paths = saved_paths @@ -1420,6 +1471,34 @@ def main(argv: list[str] | None = None) -> int: _ig = _ilu.module_from_spec(_spec) _spec.loader.exec_module(_ig) + # A stalled push must not hang the tick, and the timeout must kill + # the command's whole process group, grandchildren included. + import time as _t + t0 = _t.monotonic() + res = _ig.run_with_timeout(["sh", "-c", "sleep 37 & sleep 37"], timeout=1) + expect(_t.monotonic() - t0 < 10 and res.returncode != 0 and "timed out" in res.stderr, + f"run_with_timeout did not stop the stalled command (rc={res.returncode}, " + f"{_t.monotonic() - t0:.1f}s)") + _t.sleep(0.5) + orphans = subprocess.run(["pgrep", "-f", "sleep 37"], capture_output=True, text=True) + expect(orphans.stdout.strip() == "", + f"run_with_timeout left grandchildren running: {orphans.stdout.split()}") + + # Settle window: an update waits while the source is recent, goes + # through once it is quiet, and is never deferred past the cap. + _now = 1_800_000_000.0 + _hour = 3600.0 + _prior = {"deposited_at": datetime.fromtimestamp(_now - 2 * _hour, timezone.utc).isoformat()} + expect(_ig.should_defer_update(_prior, _now - 60, 6 * _hour, now=_now) is True, + "recently changed session should wait for the settle window") + expect(_ig.should_defer_update(_prior, _now - 7 * _hour, 6 * _hour, now=_now) is False, + "session quiet longer than the window should deposit") + expect(_ig.should_defer_update(_prior, _now - 60, 0, now=_now) is False, + "settle 0 must never defer") + _old = {"deposited_at": datetime.fromtimestamp(_now - 25 * _hour, timezone.utc).isoformat()} + expect(_ig.should_defer_update(_old, _now - 60, 6 * _hour, now=_now) is False, + "an update deferred past the 24 h cap must go through") + # Rolling-sweep partition must cover every session exactly once # across the full bucket range — no session is permanently skipped. _ids = [f"sess-{i}" for i in range(400)] @@ -1559,6 +1638,55 @@ def main(argv: list[str] | None = None) -> int: expect(res.returncode == 0, f"verify failed after pure migration: {res.stderr or res.stdout}") + step("stale sha256_compressed: migration rehashes, fsck and repair tell it from damage") + # A stale recorded compressed hash (content intact) must not + # survive a migration: the migration hashes the file on disk. + zc_obj = json.loads(zc_manifest.read_text()) + zc_obj["manifest_version"] = 3 + zc_obj["sha256_compressed"] = "0" * 64 + zc_manifest.write_text(json.dumps(zc_obj, indent=2, sort_keys=True) + "\n") + res = run_script( + REPO_ROOT / "scripts" / "ingest.py", "--archive", str(zc_archive), + "--source", str(zc_src), "--source-name", "claude-code", "--workers", "1", + ) + expect(res.returncode == 0, f"zc stale-hash migration failed: {res.stderr}") + post = json.loads(zc_manifest.read_text()) + expect(post.get("sha256_compressed") == hashlib.sha256(zc_zst.read_bytes()).hexdigest(), + "migration carried a stale sha256_compressed forward") + + # The fsck reports a stale hash as stale, not as an integrity failure. + zc_obj = json.loads(zc_manifest.read_text()) + real_hash = zc_obj["sha256_compressed"] + zc_obj["sha256_compressed"] = "0" * 64 + zc_manifest.write_text(json.dumps(zc_obj, indent=2, sort_keys=True) + "\n") + # Commit the stale value, as it would be in a real archive. + subprocess.run(["git", "-C", str(zc_archive), "commit", "-qam", "test: stale hash"], + check=True) + stale: list[str] = [] + fsck_err = _ig.verify_deposit_integrity(zc_archive, zc_cand, stale) + expect(fsck_err is None and stale == [zc_cand.archive_subpath], + f"stale compressed hash misreported (err={fsck_err!r}, stale={stale})") + + # The repair script rewrites it and commits; verify is clean after. + res = run_script(REPO_ROOT / "scripts" / "repair_compressed_hashes.py", + "--archive", str(zc_archive)) + expect(res.returncode == 0, f"repair failed: {res.stderr or res.stdout}") + expect(json.loads(zc_manifest.read_text())["sha256_compressed"] == real_hash, + "repair did not restore the real sha256_compressed") + log = subprocess.run(["git", "-C", str(zc_archive), "log", "-1", "--format=%s"], + capture_output=True, text=True).stdout + expect(log.startswith("repair:"), f"repair did not commit (HEAD: {log!r})") + + # Real damage is still an integrity failure and is never rewritten. + zc_zst.write_bytes(b"not zstd at all") + stale = [] + fsck_err = _ig.verify_deposit_integrity(zc_archive, zc_cand, stale) + expect(fsck_err is not None and "INTEGRITY" in fsck_err and not stale, + f"damaged deposit not reported as failure (err={fsck_err!r})") + res = run_script(REPO_ROOT / "scripts" / "repair_compressed_hashes.py", + "--archive", str(zc_archive)) + expect(res.returncode == 1, f"repair should exit 1 on damage, got {res.returncode}") + print("\nALL CHECKS PASSED") success = True return 0