From eac50550d5dccfdfc9976497640a1791439b9293 Mon Sep 17 00:00:00 2001 From: PEEKPerformer <24813380+PEEKPerformer@users.noreply.github.com> Date: Thu, 17 Sep 2026 08:02:41 -0400 Subject: [PATCH 1/6] v2.4.1: turn off git auto-maintenance in the archive git runs `git maintenance run --auto --detach` after every commit. Once the loose-object count passes gc.auto, each commit starts its own detached full repack, and nothing stops a second one from starting while the first is still running. An archive's pack is mostly zstd or git-crypt blobs, so each repack holds gigabytes. One ingest tick makes one commit per changed session, which stacked repacks until a 16 GB Mac with a 7.3 GiB archive ran out of memory and had to be force-restarted. Set maintenance.auto=false and gc.auto=0 in the archive's local git config. init.py sets them after `git init`. ingest.py sets them under the ingest lock before the first commit, which migrates existing archives on their next tick. Loose objects now wait for a manual `git repack -d`. The selftest checks both the init path and the migration path. --- CHANGELOG.md | 25 +++++++++++++++++++++++++ holotype/__init__.py | 2 +- holotype/archive.py | 39 +++++++++++++++++++++++++++++++++++++++ pyproject.toml | 2 +- scripts/ingest.py | 6 ++++++ scripts/init.py | 2 ++ scripts/selftest.py | 22 ++++++++++++++++++++++ 7 files changed, 96 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 226d614..0b1beb2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,31 @@ 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.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`. + +### Tests + +The selftest checks that `init.py` sets both keys, and that `ingest.py` restores them on an archive where they are unset. + ## [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/holotype/__init__.py b/holotype/__init__.py index d586123..61e18c2 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.4.1" 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/pyproject.toml b/pyproject.toml index 650e6ee..8771f9b 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.4.1" 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..437cdac 100644 --- a/scripts/ingest.py +++ b/scripts/ingest.py @@ -42,6 +42,7 @@ 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.env import claude_code_version, git_state_for_path, platform_info @@ -902,6 +903,11 @@ 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} diff --git a/scripts/init.py b/scripts/init.py index 991e126..c08d6dd 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" @@ -525,6 +526,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/selftest.py b/scripts/selftest.py index c4f586d..9f7503e 100644 --- a/scripts/selftest.py +++ b/scripts/selftest.py @@ -171,6 +171,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 +200,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)}") From f5b8b6fac66826b322d009e4b1f885cd5c1a5d15 Mon Sep 17 00:00:00 2001 From: PEEKPerformer <24813380+PEEKPerformer@users.noreply.github.com> Date: Thu, 17 Sep 2026 08:16:21 -0400 Subject: [PATCH 2/6] v2.4.1: stop reporting stale compressed hashes as damage On a real archive 1,832 compressed deposits failed the sweep fsck, yet every one decompressed to its canonical sha256. The v2.3.0 pure migration copied sha256_compressed from the prior manifest instead of hashing the file, so stale values survived, and the fsck compares only the compressed hash. About 40 false failures per sweep slice buried any real one. Hash the file during a pure migration. In the fsck, fall back to the canonical hash when the compressed one disagrees and count a match as stale, not failed. Add scripts/repair_compressed_hashes.py to rewrite the stale values in one commit, touching only that field and only after the canonical hash matches. --- CHANGELOG.md | 12 +- scripts/ingest.py | 48 ++++++-- scripts/repair_compressed_hashes.py | 174 ++++++++++++++++++++++++++++ scripts/selftest.py | 49 ++++++++ 4 files changed, 274 insertions(+), 9 deletions(-) create mode 100644 scripts/repair_compressed_hashes.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 0b1beb2..29fd32d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,9 +23,19 @@ Reproduced on git 2.54 with a scratch repository: four commits in a row left fiv 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. + ### Tests -The selftest checks that `init.py` sets both keys, and that `ingest.py` restores them on an archive where they are unset. +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. ## [2.4.0] — 2026-05-28 diff --git a/scripts/ingest.py b/scripts/ingest.py index 437cdac..af4296e 100644 --- a/scripts/ingest.py +++ b/scripts/ingest.py @@ -44,7 +44,13 @@ 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 ( @@ -265,15 +271,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: @@ -291,6 +304,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" @@ -398,9 +420,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: @@ -1250,9 +1274,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) @@ -1263,6 +1288,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: @@ -1273,6 +1304,7 @@ 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 "") ) if committed and not args.quiet: print("\n".join(committed)) 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 9f7503e..a467826 100644 --- a/scripts/selftest.py +++ b/scripts/selftest.py @@ -1581,6 +1581,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 From 0d5dcdb10f14340d71af8276106d957b9faf3ff2 Mon Sep 17 00:00:00 2001 From: PEEKPerformer <24813380+PEEKPerformer@users.noreply.github.com> Date: Thu, 17 Sep 2026 08:17:51 -0400 Subject: [PATCH 3/6] v2.4.1: skip iCloud-evicted sources instead of failing The preferred Claude Code source on the maintainer's machine is a backup mirror in ~/Documents, which iCloud syncs. iCloud had evicted 3,556 of its 11,311 transcripts to the cloud. The launchd tick may not download an evicted file, so every read failed with EDEADLK and each sweep logged dozens of "Resource deadlock avoided" worker failures. Dedup now prefers a later path whose copy is on disk over an evicted first path. A deposit whose source is still evicted returns skipped-offline and leaves the prior deposit in place. --- CHANGELOG.md | 9 ++++++++- scripts/ingest.py | 39 +++++++++++++++++++++++++++++++++++---- scripts/selftest.py | 14 ++++++++++++++ 3 files changed, 57 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 29fd32d..e9bdaeb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,9 +33,16 @@ The v2.3.0 pure-migration path copied `sha256_compressed` from the prior manifes - 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. + ### 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. +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. ## [2.4.0] — 2026-05-28 diff --git a/scripts/ingest.py b/scripts/ingest.py index af4296e..a751a01 100644 --- a/scripts/ingest.py +++ b/scripts/ingest.py @@ -29,6 +29,7 @@ from __future__ import annotations import argparse +import errno import fcntl import hashlib import json @@ -112,13 +113,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: @@ -148,6 +154,20 @@ 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 + + def is_live_file(path: Path) -> bool: try: age = time.time() - path.stat().st_mtime @@ -361,7 +381,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(): @@ -934,7 +963,8 @@ def main(argv: list[str] | None = None) -> int: 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} committed: list[str] = [] # Per-tick pre-filter: stat each candidate against its stored @@ -1305,6 +1335,7 @@ def main(argv: list[str] | None = None) -> int: 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 "") ) if committed and not args.quiet: print("\n".join(committed)) diff --git a/scripts/selftest.py b/scripts/selftest.py index a467826..01a5df2 100644 --- a/scripts/selftest.py +++ b/scripts/selftest.py @@ -1413,6 +1413,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 From 892588957f27d9f14893cb120dc932fb8fa04628 Mon Sep 17 00:00:00 2001 From: PEEKPerformer <24813380+PEEKPerformer@users.noreply.github.com> Date: Thu, 17 Sep 2026 08:19:11 -0400 Subject: [PATCH 4/6] v2.4.1: time out a stalled auto-push git push ran with no timeout. A push that stalls rather than fails holds the ingest lock, so every later tick exits early and nothing is deposited until someone kills it by hand. Run pushes in their own process group with a one-hour limit and kill the whole group on timeout, so ssh and pack-objects exit too. A timed out push is reported like any other push failure. --- CHANGELOG.md | 6 +++++- scripts/ingest.py | 39 +++++++++++++++++++++++++++++++++++++-- scripts/selftest.py | 13 +++++++++++++ 3 files changed, 55 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e9bdaeb..dac691e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,9 +40,13 @@ Every sweep also logged dozens of `holotype: worker failed on ...: OSError: [Err - 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. +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 diff --git a/scripts/ingest.py b/scripts/ingest.py index a751a01..e8cc63a 100644 --- a/scripts/ingest.py +++ b/scripts/ingest.py @@ -34,6 +34,7 @@ import hashlib import json import os +import signal import subprocess import sys import time @@ -348,6 +349,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 @@ -1246,7 +1281,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") @@ -1354,7 +1389,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/selftest.py b/scripts/selftest.py index 01a5df2..c5ada76 100644 --- a/scripts/selftest.py +++ b/scripts/selftest.py @@ -1456,6 +1456,19 @@ 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()}") + # 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)] From 38d443ea27efe785ae561bfd4d229957ae2b16bf Mon Sep 17 00:00:00 2001 From: PEEKPerformer <24813380+PEEKPerformer@users.noreply.github.com> Date: Thu, 17 Sep 2026 08:28:37 -0400 Subject: [PATCH 5/6] v2.5.0: wait for a session to settle before updating it A session that is still being written changes on almost every tick, and each update stores the whole transcript again: an encrypted, zstd blob gets no delta against its last version. On a real archive one 26 MB session was stored 129 times in two weeks, and history grew by 4.7 GB in 15 days. Defer a content update to an existing deposit until its source has been quiet for deposit.settle_hours (default 6), capped at 24 h after the last deposit. New sessions and pure migrations never wait. --settle-hours overrides the config; 0 deposits every change now. Replaying the archive's last 15 days, a 6 h window cuts history growth from 4.7 GB to about 0.9 GB. --- CHANGELOG.md | 20 +++++++++++++ SKILL.md | 2 +- holotype/__init__.py | 2 +- holotype/parallel.py | 2 ++ pyproject.toml | 2 +- scripts/ingest.py | 71 ++++++++++++++++++++++++++++++++++++++++++-- scripts/init.py | 5 ++++ scripts/selftest.py | 30 +++++++++++++++++++ 8 files changed, 128 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dac691e..611f596 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,26 @@ 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. 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 61e18c2..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.1" +__version__ = "2.5.0" 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 8771f9b..66c5630 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "holotype" -version = "2.4.1" +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 e8cc63a..9da07d2 100644 --- a/scripts/ingest.py +++ b/scripts/ingest.py @@ -38,6 +38,7 @@ import subprocess import sys import time +from datetime import datetime from pathlib import Path REPO_ROOT = Path(__file__).resolve().parent.parent @@ -169,6 +170,33 @@ def is_dataless(path: Path) -> bool: 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 @@ -395,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 @@ -463,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 @@ -793,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, ) @@ -928,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", @@ -999,7 +1054,7 @@ def main(argv: list[str] | None = None) -> int: try: counts: dict[str, int] = {"new": 0, "updated": 0, "skipped-live": 0, "skipped-unchanged": 0, "skipped-empty": 0, - "skipped-offline": 0} + "skipped-offline": 0, "skipped-settling": 0} committed: list[str] = [] # Per-tick pre-filter: stat each candidate against its stored @@ -1070,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. @@ -1111,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 ], ) @@ -1140,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 @@ -1371,6 +1435,7 @@ def main(argv: list[str] | None = None) -> int: + (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)) diff --git a/scripts/init.py b/scripts/init.py index c08d6dd..5b242ea 100644 --- a/scripts/init.py +++ b/scripts/init.py @@ -346,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 diff --git a/scripts/selftest.py b/scripts/selftest.py index c5ada76..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 @@ -331,11 +332,25 @@ 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) expect("updated=1" in result.stdout, f"expected updated=1:\n{result.stdout}") @@ -1469,6 +1484,21 @@ def main(argv: list[str] | None = None) -> int: 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)] From c253b7f2acef21745794b7f053f507bce8ebd549 Mon Sep 17 00:00:00 2001 From: PEEKPerformer <24813380+PEEKPerformer@users.noreply.github.com> Date: Thu, 17 Sep 2026 08:37:59 -0400 Subject: [PATCH 6/6] v2.5.0: add prune_local.py to drop old local history The remote holds the archive's full history, but every local clone keeps every superseded transcript version too, and encrypted zstd blobs get no deltas. On the maintainer's machine .git was 13 GiB. prune_local.py makes the local clone shallow, keeping the last --keep-days days (default 7), then expires reflogs, repacks without a delta search, and prunes. It deletes nothing unless a fresh fetch shows every local commit on origin, no other branch or stash holds unpushed work, and no ingest is running. Without --yes it only prints the plan. It is never run automatically. On an APFS clone of the real archive, keeping 2 days took 13.2 GiB of objects down to 8.1 GiB in 56 s, peaking at 2.6 GiB resident. --- CHANGELOG.md | 13 ++- SKILL.md | 1 + scripts/prune_local.py | 203 +++++++++++++++++++++++++++++++++++++++++ scripts/selftest.py | 54 ++++++++++- 4 files changed, 269 insertions(+), 2 deletions(-) create mode 100644 scripts/prune_local.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 611f596..eed091d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,9 +18,20 @@ A session that is still being written changes on almost every tick, and each upd 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. +### `scripts/prune_local.py`: drop old local history + +The remote keeps the archive's full history, so the local clone doesn't need all of it. `prune_local.py` makes the local clone shallow, keeping commits from the last `--keep-days` days (default 7, at least the current commit), and deletes older objects from disk. + +- It doesn't touch the working tree or the remote. Verify, cite, search, and browse work as before, and the shallow clone still deposits and pushes normally. Local `git log` reaches back only `--keep-days`. +- It deletes nothing unless every check passes: an `origin` remote exists, a fresh fetch shows every local commit on the remote, no other local branch or stash holds unpushed commits, and no ingest is running (it holds the ingest lock throughout). +- Without `--yes` it prints the plan only. +- It is never run automatically. It uses `repack -a -d` with `pack.window=0`, so it doesn't spend memory on a delta search that encrypted, compressed blobs can't use. + +On an APFS clone of the real archive (850 local commits over 15 days, 13.2 GiB of objects): keeping 14 days freed 0.7 GiB, because almost all the local history was younger than that. Keeping 2 days freed another 4.4 GiB, ending at 8.1 GiB. That run took 56 seconds and peaked at 2.6 GiB resident memory. The floor is roughly one encrypted copy of every current transcript plus the window's updates. + ### 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. +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. A new prune step uses a bare remote: prune refuses while a commit is unpushed, plans without `--yes`, and with `--yes` removes a blob that only 30- and 40-day-old commits reach. It keeps the working tree, leaves the remote's history intact, and still pushes afterwards. ## [2.4.1] - 2026-09-17 diff --git a/SKILL.md b/SKILL.md index 24a8985..05a5f06 100644 --- a/SKILL.md +++ b/SKILL.md @@ -236,6 +236,7 @@ Read these before any operation: | Install macOS scheduled-backup job (auto, at setup) | `python scripts/install-launchd.py --archive

` | | Deposit new sessions (preferred — from the rsync backup) | `python scripts/ingest.py --source ~/Documents/Claude-Backups` | | Deposit directly from live Claude Code state | `python scripts/ingest.py --source ~/.claude/projects` | +| Free disk space by dropping local history older than 7 days (remote keeps all of it; refuses unless everything is pushed) | `python scripts/prune_local.py` to see the plan, then `--yes` | | Browse the archive in a browser (localhost server, no disk cache) | `python scripts/browse.py` | | Find sessions matching text (FTS5) | `python scripts/search.py ""` | | Just the citation string for one session | `python scripts/cite.py --citation-only` | diff --git a/scripts/prune_local.py b/scripts/prune_local.py new file mode 100644 index 0000000..5fc6818 --- /dev/null +++ b/scripts/prune_local.py @@ -0,0 +1,203 @@ +#!/usr/bin/env python3 +"""Drop old git history from the local archive clone. The remote keeps all of it. + +Every update to a session stores the whole transcript again, and encrypted, +compressed blobs get no delta against earlier versions. Over time most of +``.git`` is superseded versions that only matter for history, and history +is already on the remote. This script makes the local clone shallow: it +keeps the commits from the last ``--keep-days`` days (at least the current +commit) and deletes older objects from disk. + +What does NOT change: + - The working tree. Every session's current transcript and manifest stay + on disk, so verify, cite, search, and browse work as before. + - The remote. Nothing is pushed or rewritten there. + - Future deposits and pushes. A shallow clone commits and pushes normally. + +What does change: ``git log`` and ``git show`` locally reach back only +``--keep-days``. For older history, clone the remote. + +Safety checks, all before anything is deleted: + - the archive has an ``origin`` remote with the current branch on it; + - after a fetch, every local commit is already on the remote; + - no other local branch or stash holds commits the remote lacks; + - no ingest is running (the ingest lock is held for the whole run). + +Without ``--yes`` the script only prints the plan. + +Usage: + python scripts/prune_local.py # show the plan + python scripts/prune_local.py --yes # keep the last 7 days + python scripts/prune_local.py --keep-days 3 --yes + +Exit codes: + 0 pruned, or plan printed + 1 a safety check failed; nothing was deleted + 2 an ingest is running, or a git step failed +""" + +from __future__ import annotations + +import argparse +import fcntl +import os +import subprocess +import sys +from datetime import datetime, timedelta, timezone +from pathlib import Path + +# A fetch or repack of a multi-GB archive can take a while, but a network +# stall must not hold the ingest lock forever. +GIT_TIMEOUT_SECONDS = 3600 + + +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 git(archive: Path, *args: str) -> subprocess.CompletedProcess: + return subprocess.run( + ["git", "-C", str(archive), *args], + capture_output=True, text=True, timeout=GIT_TIMEOUT_SECONDS, + ) + + +def objects_size(archive: Path) -> int: + total = 0 + for root, _dirs, files in os.walk(archive / ".git" / "objects"): + for name in files: + try: + total += os.lstat(os.path.join(root, name)).st_size + except OSError: + pass + return total + + +def gib(n: int) -> str: + return f"{n / 2**30:.2f} GiB" + + +def fail(msg: str, code: int = 1) -> int: + print(f"prune_local: {msg}", file=sys.stderr) + return code + + +def unpushed_refs(archive: Path, branch: str) -> list[str]: + """Local refs (other than the current branch) with commits the remote lacks.""" + problems = [] + if git(archive, "rev-parse", "--verify", "--quiet", "refs/stash").returncode == 0: + problems.append("refs/stash") + refs = git(archive, "for-each-ref", "--format=%(refname)", "refs/heads").stdout.split() + for ref in refs: + if ref == f"refs/heads/{branch}": + continue + # Commits reachable from this ref but from no remote-tracking ref. + out = git(archive, "rev-list", "--count", ref, "--not", "--remotes=origin") + if out.returncode != 0 or out.stdout.strip() != "0": + problems.append(ref) + return problems + + +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("--keep-days", type=float, default=7, + help="Keep local history from the last N days (default 7).") + p.add_argument("--yes", action="store_true", + help="Prune. Without it, only print the plan.") + args = p.parse_args(argv) + + archive = find_archive(args.archive) + if not (archive / ".git").is_dir(): + return fail(f"{archive} is not a git repository") + + 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: + return fail("an ingest is running; try again when it finishes", 2) + + try: + if git(archive, "remote", "get-url", "origin").returncode != 0: + return fail("no `origin` remote. Local history is the only copy; not pruning.") + branch = git(archive, "symbolic-ref", "--short", "HEAD").stdout.strip() + if not branch: + return fail("HEAD is detached; check out the archive's branch first") + + print(f"prune_local: fetching origin/{branch} ...") + fetch = git(archive, "fetch", "origin", branch) + if fetch.returncode != 0: + return fail(f"fetch failed: {fetch.stderr.strip()}", 2) + remote_ref = f"refs/remotes/origin/{branch}" + if git(archive, "rev-parse", "--verify", "--quiet", remote_ref).returncode != 0: + return fail(f"origin has no branch {branch}; push first") + + ahead = git(archive, "rev-list", "--count", f"{remote_ref}..HEAD").stdout.strip() + if ahead != "0": + return fail(f"{ahead} local commit(s) are not on origin/{branch}. " + f"Push first (`git -C {archive} push`).") + others = unpushed_refs(archive, branch) + if others: + return fail("these refs hold commits the remote lacks: " + ", ".join(others)) + + since = datetime.now(timezone.utc) - timedelta(days=args.keep_days) + since_arg = since.strftime("%Y-%m-%dT%H:%M:%SZ") + total = git(archive, "rev-list", "--count", "HEAD").stdout.strip() + keep = git(archive, "rev-list", "--count", f"--since={since_arg}", "HEAD").stdout.strip() + before = objects_size(archive) + print(f"prune_local: {archive}") + print(f" local objects: {gib(before)}") + print(f" local commits: {total}; keeping {max(int(keep or 0), 1)} " + f"from the last {args.keep_days:g} day(s)") + if not args.yes: + print(" (plan only; re-run with --yes to prune)") + return 0 + + # Move the shallow boundary. With no commit in the window, keep + # just the current one. + out = git(archive, "fetch", f"--shallow-since={since_arg}", "origin", branch) + if out.returncode != 0: + out = git(archive, "fetch", "--depth=1", "origin", branch) + if out.returncode != 0: + return fail(f"shallow fetch failed: {out.stderr.strip()}", 2) + + # Reflogs still point at the dropped commits; expire them, then + # rewrite the packs without unreachable objects. pack.window=0 + # skips the delta search: transcripts are encrypted or compressed, + # so it would find nothing and only cost memory. + steps = [ + ("reflog", ["reflog", "expire", "--expire=now", "--all"]), + ("repack", ["-c", "pack.window=0", "-c", "pack.threads=1", + "repack", "-a", "-d", "-q"]), + ("prune", ["prune", "--expire=now"]), + ("check", ["fsck", "--connectivity-only", "--no-progress"]), + ] + for name, cmd in steps: + print(f"prune_local: {name} ...") + out = git(archive, *cmd) + if out.returncode != 0: + return fail(f"{name} failed: {out.stderr.strip()}", 2) + + after = objects_size(archive) + print(f"prune_local: local objects {gib(before)} -> {gib(after)} " + f"(freed {gib(before - after)})") + return 0 + except subprocess.TimeoutExpired as e: + return fail(f"git timed out after {GIT_TIMEOUT_SECONDS}s: {' '.join(e.cmd)}", 2) + 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 dc64259..eaaf193 100644 --- a/scripts/selftest.py +++ b/scripts/selftest.py @@ -25,7 +25,7 @@ import argparse import hashlib import json -from datetime import datetime, timezone +from datetime import datetime, timedelta, timezone import shutil import subprocess import sqlite3 @@ -1107,6 +1107,58 @@ def main(argv: list[str] | None = None) -> int: expect(len(cloned_manifests) >= 1, f"auto-push didn't deliver any session to the remote (cloned manifests: {len(cloned_manifests)})") + step("prune_local.py makes the archive shallow only when the remote has everything") + def _git(*a, env_extra=None): + env = dict(os.environ, **(env_extra or {})) + return subprocess.run(["git", "-C", str(ap_archive), *a], + capture_output=True, text=True, env=env) + # Two old commits (40 and 30 days ago) holding a blob that the + # newest commit replaces, so the old blob is reachable only from + # history outside a 5-day window. + old_file = ap_archive / "old-history.txt" + old_blobs = [] + for days in (40, 30): + old_file.write_text(f"superseded version from {days} days ago\n") + when = (datetime.now(timezone.utc) - timedelta(days=days)).isoformat() + _git("add", "old-history.txt") + _git("commit", "-q", "-m", f"test: {days} days old", + env_extra={"GIT_AUTHOR_DATE": when, "GIT_COMMITTER_DATE": when}) + old_blobs.append(_git("rev-parse", "HEAD:old-history.txt").stdout.strip()) + old_file.write_text("current version\n") + _git("add", "old-history.txt") + _git("commit", "-q", "-m", "test: current") + prune = REPO_ROOT / "scripts" / "prune_local.py" + + res = run_script(prune, "--archive", str(ap_archive), "--keep-days", "5", "--yes") + expect(res.returncode == 1 and "not on origin" in res.stderr, + f"prune must refuse with unpushed commits (rc={res.returncode}): {res.stderr}") + expect(not (ap_archive / ".git" / "shallow").exists(), "refused prune still made the clone shallow") + + expect(_git("push", "-q", "origin", "HEAD").returncode == 0, "test push failed") + res = run_script(prune, "--archive", str(ap_archive), "--keep-days", "5") + expect(res.returncode == 0 and "plan only" in res.stdout, + f"prune without --yes should only plan: {res.stdout}{res.stderr}") + expect(not (ap_archive / ".git" / "shallow").exists(), "plan-only prune changed the clone") + + res = run_script(prune, "--archive", str(ap_archive), "--keep-days", "5", "--yes") + expect(res.returncode == 0, f"prune failed: {res.stdout}{res.stderr}") + expect((ap_archive / ".git" / "shallow").exists(), "prune did not make the clone shallow") + for blob in old_blobs: + expect(_git("cat-file", "-e", blob).returncode != 0, + f"old blob {blob} still in the local object store after prune") + expect(old_file.read_text() == "current version\n", "prune changed the working tree") + cloned_manifests_after = list((ap_archive / "sessions").rglob("manifest.json")) + expect(len(cloned_manifests_after) >= 1, "prune removed deposited sessions from the working tree") + # The remote still has the full history, and the shallow clone can + # still commit and push. + full = subprocess.run(["git", "-C", str(bare_remote), "cat-file", "-e", old_blobs[0]]) + expect(full.returncode == 0, "old history missing from the remote") + old_file.write_text("after prune\n") + _git("add", "old-history.txt") + _git("commit", "-q", "-m", "test: after prune") + expect(_git("push", "-q", "origin", "HEAD").returncode == 0, + "shallow archive could not push after prune") + step("paper_bundle.py packages multiple sessions with a master manifest") # Pull a Claude Code session + the Codex one + the Antigravity one. bundle_out = tmp / "paper-bundle"