commit 8af8d0242617a556d7d06d2955bb9c955bb33e91
parent c766cb515fcd61c8b3bf52ce75ecaf2ed6b2d2db
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Thu, 5 Nov 2026 20:14:18 -0500
evidence: archilyzer evidence pack|stamp|upgrade|verify — posts channels as a timestamped evidence package
The operator wants public evidence that Mr. Obvious's X posts existed, and Save Page Now
refuses x.com as a site (HTTP 523); he chose "the timestamped evidence package".
`archilyzer evidence pack <channel>[,<channel>…]` reads the channels' posts shards (read
only; each channel's text guarded by assertChannelTextReadable) and writes a self-contained
folder: posts.jsonl (one record a post, deduped across the channels, the archived record
verbatim under raw, a differing copy under rawElsewhere, the capture record, the availability
check, and the archived record of a post it answers/quotes/reposts as context), posts.csv
(RFC 4180), media/<postId>/ (posts-media copied byte for byte, each hash checked against its
capture.json), pack.json (filter, counts, each source shard's size and SHA-256), README.md
(how to verify), SHA256SUMS (sha256sum -c compatible) and SHA256SUMS.ots (the official
OpenTimestamps client: one request to each of its calendars). --handle, --since/--until,
--no-media, --no-stamp, --dry-run, --json. Default out ~/reports/evidence/<handle>-<date>/;
refused inside the corpus, a channel or its media, over a non-empty dir; built in a sibling
staging dir and renamed into place. `evidence upgrade` fetches the Bitcoin attestation,
`evidence verify` re-checks every file and the stamp, `evidence stamp` stamps later.
Docs: COMMANDS.md rows, OPERATING.md "Package posts as timestamped evidence", changelog.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
6 files changed, 1470 insertions(+), 0 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -69,6 +69,10 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi
| `archilyzer posts fetch` | `--slug <channel> [--full \| --older [--floor YYYY-MM-DD] [--from YYYY-MM-DD] [--force]] [--limit N] [--pages N] [--retry-on-block \| --retry-minutes N --retry-tries M]` | fetch a social channel's posts into its posts corpus (--older: walk back below the oldest archived post; --pages: a forum thread's latest N pages — a run catches up, then continues the history where it stopped; --full: a forum thread's full re-walk; --retry-\*: wait out a challenge or refusal page and run again) *(passthrough)* |
| `archilyzer posts import-html` | `<slug> <file-or-dir>… [--dry-run]` | import forum thread pages saved from a browser ("Save page as", .html) into a forum-thread channel: new posts appended, edited ones updated, nothing fetched |
| `archilyzer posts check` | `--slug <channel> [--mode stale\|unchecked\|all] [--limit N]` | which archived posts were deleted at the source (a Wayback pages channel: each record's ORIGINAL URL, asked at its own site) *(passthrough)* |
+| `archilyzer evidence pack` | `<channel>[,<channel>…] [--handle <h>] [--since YYYY-MM-DD] [--until YYYY-MM-DD] [--out <dir>] [--media\|--no-media] [--stamp\|--no-stamp] [--dry-run] [--json]` | package posts channels' archived posts as timestamped evidence, read only: posts.jsonl (one record a post, deduped across the channels, every archived field under raw, the capture record, the availability check, the archived record of a post it answers or quotes), posts.csv, media/<postId>/ (the files in posts-media/, copied byte for byte, each hash checked against its capture.json), pack.json, README.md (how to verify), SHA256SUMS over every file, and SHA256SUMS.ots (OpenTimestamps: `ots stamp`, one request to each of its calendars). --handle keeps one author's posts; --since/--until the post's UTC day. Default --out ~/reports/evidence/<handle\|channel>-<YYYY-MM-DD>/; refused inside the corpus or a channel's media, over a non-empty dir, or for a channel whose text is unreadable; built in a sibling staging dir and renamed into place. Exit 1 when the package is written but the stamp failed (`evidence stamp` it later) |
+| `archilyzer evidence stamp` | `<dir> [--json]` | OpenTimestamps-stamp an evidence package's SHA256SUMS (one with --no-stamp, or whose stamp failed): SHA256SUMS.ots, one request to each of the client's calendars; refused when it is stamped already |
+| `archilyzer evidence upgrade` | `<dir> [--json]` | upgrade an evidence package's pending SHA256SUMS.ots to its Bitcoin attestation (`ots upgrade`; the calendars attest a few hours after the stamp; the pending proof is kept as SHA256SUMS.ots.bak); exit 0 pending or attested, and says which |
+| `archilyzer evidence verify` | `<dir> [--json]` | check an evidence package: every file against SHA256SUMS (missing, changed, and files it does not list), then the stamp's state (`ots info`: pending calendars or the Bitcoin block); exit 1 on any difference |
| `archilyzer diarize backfill` | `[--dry-run] [--scope transcribed\|channel:<slug>\|video:<slug>/<id>] [--limit N] [--force] …` | diarize videos whose audio is still on disk *(passthrough)* |
| `archilyzer digest plan` | `[--lane local\|remote] [--channels a,b] [--top N] [--json] [--census] …` | price the digest backfill; writes nothing *(passthrough)* |
| `archilyzer digest validate` | `<channel> [<channel> …]` | score digests already on disk *(passthrough)* |
diff --git a/OPERATING.md b/OPERATING.md
@@ -378,6 +378,40 @@ pnpm ops save-page-now-batch --json '{"batch":"spn-<id>"}' # continue after a
citation, the record to cite (`pointTo`) and the citation as a `post` citation of it (`as`); the report itself
is not rewritten. Dry run first: it asks the same paced questions and imports nothing.
+### Package posts as timestamped evidence
+
+When a public archive cannot take the pages (Save Page Now refuses x.com as a site), package what the archive
+already holds — so anyone can check it without this repo — and timestamp it. Read only over the corpus; no editor
+needed.
+
+```sh
+pnpm archilyzer evidence pack acct-x,acct-x-replies --handle acct --dry-run # counts, writes nothing
+pnpm archilyzer evidence pack acct-x,acct-x-replies --handle acct # ~/reports/evidence/acct-<today>/
+pnpm archilyzer evidence upgrade ~/reports/evidence/acct-2026-11-05 # a few hours later: the Bitcoin attestation
+pnpm archilyzer evidence verify ~/reports/evidence/acct-2026-11-05 # every file against SHA256SUMS, the stamp's state
+```
+
+- **What it writes**: `posts.jsonl` (one record a post, oldest first, deduped across the channels named — the first
+ channel's record is `raw`, verbatim, another channel's differing one `rawElsewhere`; plus the capture record
+ `capture`/`capturedAt`, the last availability check, and as `context` the archived record of a post it answers,
+ quotes or reposts when the channels hold it), `posts.csv` (RFC 4180), `media/<postId>/` (every file in the post's
+ `posts-media/<id>/`, copied byte for byte with its mtime — the shots, the media, `capture.json` — and each hash
+ checked against the one its capture recorded), `pack.json` (filter, counts, each source shard's size and SHA-256),
+ `README.md` (how to verify), `SHA256SUMS` over every file (`sha256sum -c SHA256SUMS`), and `SHA256SUMS.ots`.
+- `--handle` keeps one author's posts (their reposts too; other authors' records only as context); `--since` /
+ `--until` the post's UTC day; `--no-media` leaves the files out (the capture records stay); `--no-stamp` skips the
+ stamp (`evidence stamp <dir>` adds it later). Default `--out` is `~/reports/evidence/<handle|channel>-<YYYY-MM-DD>/`.
+- **Refused**: an `--out` inside the corpus, a channel or its media; a directory that is not empty; a channel whose
+ text is unreadable (`assertChannelTextReadable`); a channel with no `posts/`. The package is built in a sibling
+ `.<name>.partial-<pid>` and renamed into place.
+- **The stamp is OpenTimestamps**, through the official client: `uv tool install opentimestamps-client` (or
+ `pipx install opentimestamps-client`) puts `ots` in `~/.local/bin`; `ARCHILYZER_OTS_BIN` names another. `ots stamp`
+ sends the digest once to each of its default calendars (no retries), and the proof is **pending** until a
+ calendar commits it to a Bitcoin block (a few hours): `evidence upgrade` then rewrites `SHA256SUMS.ots` with the
+ attestation (`ots upgrade`; the pending proof stays as `SHA256SUMS.ots.bak`) and says the block. A stamp that
+ fails leaves the package written and exits 1. A third party verifies with `ots verify SHA256SUMS.ots` (against a
+ local bitcoind) or on opentimestamps.org.
+
### Shoot and cite a capture
```sh
diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts
@@ -878,6 +878,61 @@ export const COMMANDS: Command[] = [
},
script(["posts", "check"], "check-post-availability.ts",
"--slug <channel> [--mode stale|unchecked|all] [--limit N] which archived posts were deleted at the source (a Wayback pages channel: each record's ORIGINAL URL, asked at its own site)"),
+ // Evidence packages (bin/evidence-pack.ts): read-only over the corpus.
+ {
+ path: ["evidence", "pack"],
+ usage:
+ "<channel>[,<channel>…] [--handle <h>] [--since YYYY-MM-DD] [--until YYYY-MM-DD] [--out <dir>] [--media|--no-media] [--stamp|--no-stamp] [--dry-run] [--json] package posts channels' archived posts as timestamped evidence, read only: posts.jsonl (one record a post, deduped across the channels, every archived field under raw, the capture record, the availability check, the archived record of a post it answers or quotes), posts.csv, media/<postId>/ (the files in posts-media/, copied byte for byte, each hash checked against its capture.json), pack.json, README.md (how to verify), SHA256SUMS over every file, and SHA256SUMS.ots (OpenTimestamps: `ots stamp`, one request to each of its calendars). --handle keeps one author's posts; --since/--until the post's UTC day. Default --out ~/reports/evidence/<handle|channel>-<YYYY-MM-DD>/; refused inside the corpus or a channel's media, over a non-empty dir, or for a channel whose text is unreadable; built in a sibling staging dir and renamed into place. Exit 1 when the package is written but the stamp failed (`evidence stamp` it later)",
+ flags: {
+ handle: "string",
+ since: "string",
+ until: "string",
+ out: "string",
+ media: "boolean",
+ "no-media": "boolean",
+ stamp: "boolean",
+ "no-stamp": "boolean",
+ "dry-run": "boolean",
+ json: "boolean",
+ },
+ maxPositionals: 100,
+ run: async ({ positionals, flags }) => {
+ const { getPaths } = await import("../lib/paths");
+ const { assertChannelTextReadable } = await import("../lib/channelMedia");
+ const paths = getPaths();
+ return (await import("./evidence-pack")).packMain(positionals, flags, {
+ channelsDir: paths.channelsDir,
+ transcriptsDir: paths.transcriptsDir,
+ guardText: async (slug) => {
+ await assertChannelTextReadable(paths, slug);
+ },
+ });
+ },
+ },
+ {
+ path: ["evidence", "stamp"],
+ usage:
+ "<dir> [--json] OpenTimestamps-stamp an evidence package's SHA256SUMS (one with --no-stamp, or whose stamp failed): SHA256SUMS.ots, one request to each of the client's calendars; refused when it is stamped already",
+ flags: { json: "boolean" },
+ maxPositionals: 1,
+ run: async ({ positionals, flags }) => (await import("./evidence-pack")).dirMain("stamp", positionals, flags),
+ },
+ {
+ path: ["evidence", "upgrade"],
+ usage:
+ "<dir> [--json] upgrade an evidence package's pending SHA256SUMS.ots to its Bitcoin attestation (`ots upgrade`; the calendars attest a few hours after the stamp; the pending proof is kept as SHA256SUMS.ots.bak); exit 0 pending or attested, and says which",
+ flags: { json: "boolean" },
+ maxPositionals: 1,
+ run: async ({ positionals, flags }) => (await import("./evidence-pack")).dirMain("upgrade", positionals, flags),
+ },
+ {
+ path: ["evidence", "verify"],
+ usage:
+ "<dir> [--json] check an evidence package: every file against SHA256SUMS (missing, changed, and files it does not list), then the stamp's state (`ots info`: pending calendars or the Bitcoin block); exit 1 on any difference",
+ flags: { json: "boolean" },
+ maxPositionals: 1,
+ run: async ({ positionals, flags }) => (await import("./evidence-pack")).dirMain("verify", positionals, flags),
+ },
script(["diarize", "backfill"], "diarize-backfill.ts",
"[--dry-run] [--scope transcribed|channel:<slug>|video:<slug>/<id>] [--limit N] [--force] … diarize videos whose audio is still on disk"),
script(["digest", "plan"], "digest-plan.ts",
diff --git a/common/bin/evidence-pack.test.ts b/common/bin/evidence-pack.test.ts
@@ -0,0 +1,324 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { createHash } from "node:crypto";
+import { mkdtemp, mkdir, readFile, readdir, rm, writeFile, stat } from "node:fs/promises";
+import { spawnSync } from "node:child_process";
+import os from "node:os";
+import path from "node:path";
+import {
+ CSV_HEADER,
+ OTS_FILE,
+ SUMS_FILE,
+ csvField,
+ dirMain,
+ inScope,
+ pack,
+ packMain,
+ parseDay,
+ parseOtsInfo,
+ parseSums,
+ postKind,
+ sumsLine,
+ verifyDir,
+ type OtsRunner,
+} from "./evidence-pack";
+
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test bin/evidence-pack.test.ts
+//
+// `archilyzer evidence pack` over a temp corpus: two posts channels (an account
+// and its replies, overlapping), their media, and the OTS client stubbed — it
+// writes a placeholder SHA256SUMS.ots and `ots info` answers a pending line.
+
+const sha = (b: string | Buffer) => createHash("sha256").update(b).digest("hex");
+
+const PENDING_INFO =
+ "File sha256 hash: 00\nTimestamp:\nappend aa\nsha256\n -> verify PendingAttestation('https://a.pool.opentimestamps.org')\n -> verify PendingAttestation('https://b.pool.opentimestamps.org')\n";
+
+function stubOts(calls: string[][] = []): OtsRunner {
+ return async (args, cwd) => {
+ calls.push(args);
+ if (args[0] === "stamp") {
+ await writeFile(path.join(cwd, OTS_FILE), Buffer.from([0x00, 0x4f, 0x70]));
+ return { code: 0, stdout: "", stderr: "Submitting to remote calendar https://a.pool.opentimestamps.org\n" };
+ }
+ if (args[0] === "info") return { code: 0, stdout: PENDING_INFO, stderr: "" };
+ if (args[0] === "upgrade") return { code: 1, stdout: "", stderr: "Timestamp not complete\n" };
+ return { code: 2, stdout: "", stderr: "?" };
+ };
+}
+
+function rec(over: Record<string, unknown>): Record<string, unknown> {
+ return {
+ id: "1",
+ slug: "acct-x/1",
+ channelSlug: "acct-x",
+ author: "Acct",
+ createdAt: "2026-10-01T10:00:00.000Z",
+ uploadDate: "20261001",
+ text: "hello",
+ url: "https://x.com/Acct/status/1",
+ platform: "twitter",
+ isReply: false,
+ isRepost: false,
+ links: [],
+ threadId: "1",
+ authorName: "THE ACCOUNT",
+ engagement: { likes: 3 },
+ ...over,
+ };
+}
+
+async function fixture(): Promise<{ root: string; transcripts: string; channels: string }> {
+ const root = await mkdtemp(path.join(os.tmpdir(), "evidence-pack-"));
+ const transcripts = path.join(root, "transcripts");
+ const channels = path.join(transcripts, "channels");
+ const a = path.join(channels, "acct-x");
+ const b = path.join(channels, "acct-x-replies");
+ await mkdir(path.join(a, "posts"), { recursive: true });
+ await mkdir(path.join(b, "posts"), { recursive: true });
+ await writeFile(path.join(a, "config.json"), JSON.stringify({ sourceKind: "social", platform: "twitter", name: "Acct (X)", url: "https://x.com/Acct", socialHandle: "Acct" }));
+ await writeFile(path.join(b, "config.json"), JSON.stringify({ sourceKind: "social", platform: "twitter", name: "Acct replies", postFetcher: "x-gallery-dl" }));
+ await writeFile(path.join(a, "posts-state.json"), JSON.stringify({ lastFetchedAt: "2026-11-05T03:22:28.024Z" }));
+ const lines = (rs: Record<string, unknown>[]) => rs.map((r) => JSON.stringify(r)).join("\n") + "\n";
+ await writeFile(
+ path.join(a, "posts", "2026-10.jsonl"),
+ lines([
+ rec({ id: "1", text: 'He said "no", then,\nleft.' }),
+ rec({ id: "2", createdAt: "2026-10-20T00:00:00.000Z", text: "RT @x: y", isRepost: true, repostOf: { platform: "twitter", id: "9", author: "x" } }),
+ rec({ id: "3", createdAt: "2026-10-25T00:00:00.000Z", quoted: { platform: "twitter", id: "50", url: "https://x.com/o/status/50" }, mediaCount: 1 }),
+ rec({ id: "4", createdAt: "2026-11-02T00:00:00.000Z", text: "stale four" }),
+ ]) + "{not json\n",
+ );
+ // Post 4 is in both shards (an interrupted write): the later shard wins.
+ await writeFile(path.join(a, "posts", "2026-11.jsonl"), lines([rec({ id: "4", createdAt: "2026-11-02T00:00:00.000Z", text: "four" })]));
+ await writeFile(
+ path.join(b, "posts", "2026-10.jsonl"),
+ lines([
+ // the same post 3, archived with other engagement
+ rec({ id: "3", channelSlug: "acct-x-replies", createdAt: "2026-10-25T00:00:00.000Z", quoted: { platform: "twitter", id: "50", url: "https://x.com/o/status/50" }, mediaCount: 1, engagement: { likes: 9 } }),
+ rec({ id: "50", author: "Other", createdAt: "2026-10-24T00:00:00.000Z", text: "the quoted post", url: "https://x.com/o/status/50" }),
+ rec({ id: "5", createdAt: "2026-10-26T00:00:00.000Z", isReply: true, replyTo: { platform: "twitter", id: "50", author: "Other" }, text: "a reply" }),
+ rec({ id: "../evil", createdAt: "2026-10-26T00:00:00.000Z" }),
+ ]),
+ );
+ // Media for post 3: in both channels, with a capture.json naming one file's hash.
+ const m3 = path.join(a, "posts-media", "3");
+ await mkdir(m3, { recursive: true });
+ await writeFile(path.join(m3, "3_1.jpg"), "JPEGBYTES");
+ await writeFile(path.join(m3, "shot.png"), "PNGBYTES");
+ await writeFile(
+ path.join(m3, "capture.json"),
+ JSON.stringify({ version: 1, id: "3", capturedAt: "2026-11-04T03:32:55.079Z", state: "captured", shot: { name: "shot.png", sha256: sha("PNGBYTES") }, media: [{ name: "3_1.jpg", sha256: sha("JPEGBYTES"), url: "https://pbs.twimg.com/media/A" }] }),
+ );
+ const m3b = path.join(b, "posts-media", "3");
+ await mkdir(m3b, { recursive: true });
+ await writeFile(path.join(m3b, "3_1.jpg"), "OTHER-COPY");
+ await writeFile(path.join(m3b, "shot-thread.png"), "THREADSHOT");
+ // A post whose recorded hash disagrees with its file.
+ const m4 = path.join(a, "posts-media", "4");
+ await mkdir(m4, { recursive: true });
+ await writeFile(path.join(m4, "4_1.mp4"), "VIDEO");
+ await writeFile(path.join(m4, "capture.json"), JSON.stringify({ capturedAt: "2026-11-04T00:00:00.000Z", media: [{ name: "4_1.mp4", sha256: sha("SOMETHING ELSE") }] }));
+ await writeFile(path.join(a, "posts-availability.json"), JSON.stringify({ "1": { availability: "available", checkedAt: "2026-11-04T02:40:57.558Z", history: [] } }));
+ return { root, transcripts, channels };
+}
+
+function opts(f: { root: string; transcripts: string; channels: string }, over: Partial<Parameters<typeof pack>[0]> = {}) {
+ return {
+ channelsDir: f.channels,
+ transcriptsDir: f.transcripts,
+ slugs: ["acct-x", "acct-x-replies"],
+ handle: "Acct",
+ out: path.join(f.root, "out", "pkg"),
+ media: true,
+ stamp: true,
+ dryRun: false,
+ now: new Date("2026-11-05T12:00:00Z"),
+ ots: stubOts(),
+ toolCommit: "abc123",
+ ...over,
+ };
+}
+
+test("helpers: dates, kinds, scope, CSV quoting, sums lines", () => {
+ assert.equal(parseDay("2026-11-05"), "2026-11-05");
+ assert.equal(parseDay("2026-02-30"), null);
+ assert.equal(parseDay("20261105"), null);
+ assert.equal(parseDay(undefined), undefined);
+ assert.equal(postKind({ isRepost: true }), "repost");
+ assert.equal(postKind({ isReply: false, replyTo: { id: "1" } }), "reply");
+ assert.equal(postKind({ quoted: { id: "1" } }), "quote");
+ assert.equal(postKind({}), "post");
+ const r = { author: "@ACCT", createdAt: "2026-10-31T23:59:59.000Z" };
+ assert.equal(inScope(r, { handle: "acct" }), true);
+ assert.equal(inScope(r, { handle: "other" }), false);
+ assert.equal(inScope(r, { since: "2026-10-31", until: "2026-10-31" }), true);
+ assert.equal(inScope(r, { since: "2026-11-01" }), false);
+ assert.equal(csvField("plain"), "plain");
+ assert.equal(csvField('a "b", c'), '"a ""b"", c"');
+ assert.equal(csvField("two\nlines"), '"two\nlines"');
+ assert.equal(csvField("=1+1"), "=1+1");
+ assert.equal(csvField(undefined), "");
+ assert.equal(sumsLine("ab", "media/1/x.jpg"), "ab media/1/x.jpg\n");
+ assert.equal(sumsLine("ab", "a\\b\nc"), "\\ab a\\\\b\\nc\n");
+ const h = "0".repeat(64);
+ assert.deepEqual([...parseSums(sumsLine(h, "a\\b\nc") + sumsLine(h, "x y"))], [["a\\b\nc", h], ["x y", h]]);
+ assert.deepEqual(parseOtsInfo(PENDING_INFO + "verify BitcoinBlockHeaderAttestation(921000)\n"), {
+ calendars: ["https://a.pool.opentimestamps.org", "https://b.pool.opentimestamps.org"],
+ blocks: [921000],
+ });
+});
+
+test("pack: one record a post across the channels, raw kept, context, media copied, sums right", async () => {
+ const f = await fixture();
+ try {
+ const calls: string[][] = [];
+ const r = await pack(opts(f, { ots: stubOts(calls) }));
+ // 1,2,3,4 from acct-x; 5 from replies; 50 is Other's (context only); ../evil is dropped.
+ assert.equal(r.posts, 5);
+ assert.deepEqual(r.byKind, { post: 2, repost: 1, quote: 1, reply: 1 });
+ assert.equal(r.contextRecords, 2); // 3 quotes 50, 5 answers 50
+ assert.equal(r.firstPostAt, "2026-10-01T10:00:00.000Z");
+ assert.equal(r.lastPostAt, "2026-11-02T00:00:00.000Z");
+ assert.deepEqual(calls.map((c) => c[0]), ["stamp", "info"]);
+ assert.equal(r.stamp.status, "pending");
+
+ const out = r.out;
+ const jsonl = (await readFile(path.join(out, "posts.jsonl"), "utf8")).trim().split("\n").map((l) => JSON.parse(l));
+ assert.deepEqual(jsonl.map((x) => x.id), ["1", "2", "3", "5", "4"]);
+ const p1 = jsonl[0];
+ assert.equal(p1.text, 'He said "no", then,\nleft.');
+ assert.equal(p1.raw.slug, "acct-x/1");
+ assert.equal(p1.raw.uploadDate, "20261001");
+ assert.deepEqual(p1.availability, { availability: "available", checkedAt: "2026-11-04T02:40:57.558Z", history: [] });
+ const p3 = jsonl[2];
+ assert.deepEqual(p3.channels, ["acct-x", "acct-x-replies"]);
+ assert.equal(p3.raw.engagement.likes, 3); // the first channel's record
+ assert.equal(p3.rawElsewhere[0].channel, "acct-x-replies");
+ assert.equal(p3.rawElsewhere[0].raw.engagement.likes, 9);
+ assert.equal(p3.context.quoted.text, "the quoted post");
+ assert.equal(p3.capturedAt, "2026-11-04T03:32:55.079Z");
+ // The first channel's files win; a name only the second has is added.
+ assert.deepEqual(p3.files.map((x: { path: string }) => x.path), [
+ "media/3/3_1.jpg",
+ "media/3/capture.json",
+ "media/3/shot.png",
+ "media/3/shot-thread.png",
+ ]);
+ const jpg = p3.files[0];
+ assert.equal(jpg.sha256, sha("JPEGBYTES"));
+ assert.equal(jpg.archivedSha256, sha("JPEGBYTES"));
+ assert.equal(jpg.sourceUrl, "https://pbs.twimg.com/media/A");
+ assert.equal(await readFile(path.join(out, "media/3/3_1.jpg"), "utf8"), "JPEGBYTES");
+ assert.equal(await readFile(path.join(out, "media/3/shot-thread.png"), "utf8"), "THREADSHOT");
+ assert.deepEqual(r.mediaMismatches, ["media/4/4_1.mp4"]);
+ assert.equal(jsonl[3].context.replyTo.author, "Other");
+ assert.equal(jsonl[4].text, "four");
+
+ // CSV: header, a quoted multi-line field, CRLF rows.
+ const csv = await readFile(path.join(out, "posts.csv"), "utf8");
+ assert.ok(csv.startsWith(CSV_HEADER.join(",") + "\r\n"));
+ assert.ok(csv.includes('"He said ""no"", then,\nleft."'));
+ assert.ok(csv.includes("media/3/3_1.jpg media/3/capture.json media/3/shot.png media/3/shot-thread.png"));
+
+ // SHA256SUMS covers every file but itself and the stamp, and each line is right.
+ const sums = parseSums(await readFile(path.join(out, SUMS_FILE), "utf8"));
+ assert.ok(!sums.has(SUMS_FILE) && !sums.has(OTS_FILE));
+ assert.ok(sums.has("README.md") && sums.has("pack.json") && sums.has("posts.jsonl") && sums.has("posts.csv"));
+ for (const [rel, h] of sums) assert.equal(sha(await readFile(path.join(out, rel))), h, rel);
+ assert.equal(sums.size, r.files);
+ assert.equal(sha(await readFile(path.join(out, SUMS_FILE))), r.sumsSha256);
+ if (spawnSync("sha256sum", ["--version"]).status === 0) {
+ assert.equal(spawnSync("sha256sum", ["-c", "--quiet", SUMS_FILE], { cwd: out }).status, 0);
+ }
+ const manifest = JSON.parse(await readFile(path.join(out, "pack.json"), "utf8"));
+ assert.equal(manifest.channels[0].lastFetchedAt, "2026-11-05T03:22:28.024Z");
+ assert.equal(manifest.channels[0].shards[0].malformed, 1);
+ assert.equal(manifest.tool.commit, "abc123");
+ const readme = await readFile(path.join(out, "README.md"), "utf8");
+ assert.ok(readme.includes("ots verify SHA256SUMS.ots") && readme.includes("sha256sum -c SHA256SUMS"));
+ // No staging dir is left beside it.
+ assert.deepEqual(await readdir(path.dirname(out)), ["pkg"]);
+
+ // verify: clean, then a changed and an added file are named.
+ const v = await verifyDir(out, stubOts());
+ assert.equal(v.ok, true);
+ assert.equal(v.stamp.status, "pending");
+ await writeFile(path.join(out, "media/3/shot.png"), "TAMPERED");
+ await writeFile(path.join(out, "extra.txt"), "x");
+ const v2 = await verifyDir(out, stubOts());
+ assert.deepEqual([v2.ok, v2.changed, v2.unlisted], [false, ["media/3/shot.png"], ["extra.txt"]]);
+ } finally {
+ await rm(f.root, { recursive: true, force: true });
+ }
+});
+
+test("pack: --since/--until, --no-media, --dry-run writes nothing, no handle keeps every author", async () => {
+ const f = await fixture();
+ try {
+ const dry = await pack(opts(f, { dryRun: true, handle: undefined }));
+ assert.equal(dry.posts, 6); // Other's post 50 too
+ assert.equal(dry.contextRecords, 0);
+ assert.equal(dry.mediaFiles, 6);
+ await assert.rejects(stat(dry.out));
+
+ const r = await pack(opts(f, { since: "2026-10-20", until: "2026-10-31", media: false, stamp: false }));
+ assert.deepEqual(r.byKind, { repost: 1, quote: 1, reply: 1 });
+ assert.equal(r.mediaFiles, 0);
+ assert.equal(r.stamp.status, "skipped");
+ assert.deepEqual((await readdir(r.out)).sort(), ["README.md", "SHA256SUMS", "pack.json", "posts.csv", "posts.jsonl"]);
+ const jsonl = (await readFile(path.join(r.out, "posts.jsonl"), "utf8")).trim().split("\n").map((l) => JSON.parse(l));
+ assert.ok(jsonl.every((x) => x.files.length === 0));
+ assert.ok(jsonl.find((x) => x.id === "3").capture); // capture metadata kept without media
+ } finally {
+ await rm(f.root, { recursive: true, force: true });
+ }
+});
+
+test("refusals: inside the corpus, over a package, an unreadable channel, not a posts channel, no match", async () => {
+ const f = await fixture();
+ try {
+ await assert.rejects(pack(opts(f, { out: path.join(f.transcripts, "evidence") })), /inside the corpus/);
+ await assert.rejects(pack(opts(f, { out: path.join(f.channels, "acct-x", "posts-media", "pkg") })), /inside the corpus/);
+ const out = path.join(f.root, "taken");
+ await mkdir(out);
+ await writeFile(path.join(out, "x"), "x");
+ await assert.rejects(pack(opts(f, { out })), /not an empty directory/);
+ await assert.rejects(
+ pack(opts(f, { guardText: async (s) => { if (s === "acct-x-replies") throw Object.assign(new Error(`${s}: its text is not readable`), { name: "ChannelTextUnreadableError" }); } })),
+ /text is not readable/,
+ );
+ await mkdir(path.join(f.channels, "videos"), { recursive: true });
+ await assert.rejects(pack(opts(f, { slugs: ["videos"] })), /not a posts channel/);
+ await assert.rejects(pack(opts(f, { slugs: ["nope"] })), /no channel "nope"/);
+ await assert.rejects(pack(opts(f, { handle: "nobody" })), /no post matches/);
+ // None of it wrote anything.
+ assert.deepEqual((await readdir(f.root)).sort(), ["taken", "transcripts"]);
+
+ // The CLI layer: a refusal is exit 2 with its sentence; bad flags are usage errors.
+ const errs: string[] = [];
+ const deps = { channelsDir: f.channels, transcriptsDir: f.transcripts, ots: stubOts(), log: () => {}, error: (s: string) => errs.push(s) };
+ assert.equal(await packMain(["acct-x"], { out: path.join(f.transcripts, "e") }, deps), 2);
+ assert.match(errs.at(-1)!, /inside the corpus/);
+ assert.equal(await packMain(["acct-x"], { since: "Nov 1" }, deps), 2);
+ assert.equal(await packMain(["acct-x"], { media: true, "no-media": true }, deps), 2);
+ // A stamp that fails leaves the package and exits 1.
+ const unavailable: OtsRunner = async () => ({ code: 127, stdout: "", stderr: "not installed" });
+ const pkg = path.join(f.root, "pkg2");
+ assert.equal(await packMain(["acct-x,acct-x-replies"], { handle: "@Acct", out: pkg }, { ...deps, ots: unavailable }), 1);
+ assert.ok((await readdir(pkg)).includes(SUMS_FILE));
+ assert.match(errs.at(-1)!, /not stamped \(unavailable\)/);
+ // …and `evidence stamp` stamps it later, once; upgrade says it is still pending.
+ const logs: string[] = [];
+ const d = { ots: stubOts(), log: (s: string) => logs.push(s), error: (s: string) => errs.push(s) };
+ assert.equal(await dirMain("stamp", [pkg], {}, d), 0);
+ assert.match(logs.at(-1)!, /pending — submitted to 2 calendars/);
+ assert.equal(await dirMain("stamp", [pkg], {}, d), 1);
+ assert.equal(await dirMain("upgrade", [pkg], {}, d), 0);
+ assert.match(logs.at(-1)!, /pending/);
+ assert.equal(await dirMain("verify", [pkg], {}, d), 0);
+ assert.equal(await dirMain("verify", [f.root], {}, d), 2);
+ } finally {
+ await rm(f.root, { recursive: true, force: true });
+ }
+});
diff --git a/common/bin/evidence-pack.ts b/common/bin/evidence-pack.ts
@@ -0,0 +1,1052 @@
+// `archilyzer evidence pack|stamp|upgrade|verify` — a posts channel's archived
+// posts as a self-contained, checksummed and timestamped evidence package.
+//
+// archilyzer evidence pack <channel>[,<channel>…] [--handle <h>] [--since YYYY-MM-DD]
+// [--until YYYY-MM-DD] [--out <dir>] [--media|--no-media] [--stamp|--no-stamp]
+// [--dry-run] [--json]
+// archilyzer evidence stamp <dir> # an unstamped package (--no-stamp, or a stamp that failed)
+// archilyzer evidence upgrade <dir> # the pending stamp, once the calendars have attested it
+// archilyzer evidence verify <dir> # every file against SHA256SUMS, then the stamp's state
+//
+// The need (operator, 5 Nov): public evidence that an account's X posts existed,
+// while archive.org's Save Page Now refuses x.com as a site (HTTP 523). The
+// archive already holds the posts; this packages them so a third party can check
+// them without this repo: one normalised record per post (every archived field
+// kept under `raw`), a CSV, the post media copied byte for byte, a README, a
+// SHA256SUMS over every file, and an OpenTimestamps proof of SHA256SUMS — which
+// proves the package (and so every file it lists) existed no later than the
+// Bitcoin block the calendars commit it to.
+//
+// READ ONLY over the corpus. Each channel's text is guarded
+// (`assertChannelTextReadable`); the media are COPIED (never linked, never
+// touched); the output may not be inside the corpus, a channel or its media; the
+// package is built in a sibling staging dir and renamed into place, so a cut run
+// leaves no half package where the package should be.
+//
+// The stamp is the official OpenTimestamps client (`ots`, Python): `ots stamp`
+// submits the digest once to each of its default calendars (one request each,
+// no retries). Install it with `uv tool install opentimestamps-client` (or
+// `pipx install opentimestamps-client`); ARCHILYZER_OTS_BIN names another binary.
+
+import { createHash } from "node:crypto";
+import { createReadStream, constants as fsConstants } from "node:fs";
+import {
+ copyFile,
+ lstat,
+ mkdir,
+ readFile,
+ readdir,
+ realpath,
+ rename,
+ rmdir,
+ stat,
+ utimes,
+ writeFile,
+} from "node:fs/promises";
+import { spawn, spawnSync } from "node:child_process";
+import os from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import type { FlagValue } from "./_parseFlags";
+
+export const SUMS_FILE = "SHA256SUMS";
+export const OTS_FILE = "SHA256SUMS.ots";
+export const PACK_VERSION = 1;
+
+// ---------------------------------------------------------------------------
+// Types
+
+export type ChannelSource = {
+ slug: string;
+ config: Record<string, unknown> | null;
+ fetchState: Record<string, unknown> | null;
+ shards: { file: string; bytes: number; sha256: string; lines: number; malformed: number }[];
+ records: number;
+};
+
+type Loaded = {
+ channel: string;
+ shard: string;
+ raw: Record<string, unknown>;
+};
+
+export type PackFile = {
+ path: string; // relative to the package, "/"-separated
+ bytes: number;
+ sha256: string;
+ // What the archive's capture.json recorded for this file, when it names it.
+ archivedSha256?: string;
+ sourceUrl?: string;
+ from: string; // the channel whose posts-media it was copied from
+};
+
+export type PackRecord = {
+ id: string;
+ url: string;
+ platform: string;
+ author: string;
+ authorName?: string;
+ createdAt: string;
+ kind: "post" | "reply" | "quote" | "repost";
+ text: string;
+ lang?: string;
+ threadId?: string;
+ replyTo?: unknown;
+ quoted?: unknown;
+ repostOf?: unknown;
+ links: unknown[];
+ engagement?: unknown;
+ mediaCount?: number;
+ channels: string[];
+ capturedAt: string | null;
+ capture: Record<string, unknown> | null;
+ availability: Record<string, unknown> | null;
+ // The archived record of the post this one answers / quotes / reposts, when
+ // the packaged channels hold it (any author): context as archived.
+ context?: { replyTo?: Record<string, unknown>; quoted?: Record<string, unknown>; repostOf?: Record<string, unknown> };
+ files: PackFile[];
+ raw: Record<string, unknown>;
+ // The same post as another packaged channel archived it, when that record differs.
+ rawElsewhere?: { channel: string; raw: Record<string, unknown> }[];
+};
+
+export type PackOptions = {
+ channelsDir: string;
+ transcriptsDir: string;
+ slugs: string[];
+ handle?: string;
+ since?: string;
+ until?: string;
+ out: string;
+ media: boolean;
+ stamp: boolean;
+ dryRun: boolean;
+ now?: Date;
+ // Test seams.
+ guardText?: (slug: string) => Promise<void>;
+ ots?: OtsRunner;
+ toolCommit?: string | null;
+};
+
+export type StampResult =
+ | { status: "pending" | "attested"; calendars: string[]; blocks: number[]; info: string }
+ | { status: "skipped" | "unavailable" | "failed"; error?: string };
+
+export type PackResult = {
+ out: string;
+ dryRun: boolean;
+ channels: { slug: string; records: number; shards: number }[];
+ posts: number;
+ byKind: Record<string, number>;
+ contextRecords: number;
+ mediaFiles: number;
+ mediaBytes: number;
+ mediaMismatches: string[];
+ firstPostAt: string | null;
+ lastPostAt: string | null;
+ files: number;
+ sumsSha256: string | null;
+ stamp: StampResult;
+};
+
+export class EvidenceRefusal extends Error {}
+
+// ---------------------------------------------------------------------------
+// Small pure helpers (unit-tested)
+
+const SAFE_ID = /^[A-Za-z0-9_-]{1,128}$/;
+const DAY = /^\d{4}-\d{2}-\d{2}$/;
+
+export function isSafePostId(id: unknown): id is string {
+ return typeof id === "string" && SAFE_ID.test(id);
+}
+
+export function parseDay(v: string | undefined): string | undefined | null {
+ if (v === undefined) return undefined;
+ if (!DAY.test(v)) return null;
+ const d = new Date(`${v}T00:00:00Z`);
+ return Number.isNaN(d.getTime()) || d.toISOString().slice(0, 10) !== v ? null : v;
+}
+
+export function normHandle(h: string): string {
+ return h.trim().replace(/^@/, "").toLowerCase();
+}
+
+function str(v: unknown): string | undefined {
+ return typeof v === "string" ? v : undefined;
+}
+
+function obj(v: unknown): Record<string, unknown> | undefined {
+ return v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : undefined;
+}
+
+export function postKind(raw: Record<string, unknown>): PackRecord["kind"] {
+ if (raw.isRepost === true || obj(raw.repostOf)) return "repost";
+ if (raw.isReply === true || obj(raw.replyTo)) return "reply";
+ if (obj(raw.quoted)) return "quote";
+ return "post";
+}
+
+/** Whether a record falls in the filter: the author's handle and the UTC day of createdAt. */
+export function inScope(
+ raw: Record<string, unknown>,
+ f: { handle?: string; since?: string; until?: string },
+): boolean {
+ if (f.handle && normHandle(str(raw.author) ?? "") !== normHandle(f.handle)) return false;
+ const day = (str(raw.createdAt) ?? "").slice(0, 10);
+ if (f.since && !(day >= f.since)) return false;
+ if (f.until && !(day <= f.until)) return false;
+ return true;
+}
+
+/** One CSV field, RFC 4180: quoted when it holds a quote, a comma or a line break. Verbatim otherwise. */
+export function csvField(v: unknown): string {
+ const s = v === undefined || v === null ? "" : String(v);
+ return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
+}
+
+export function csvRow(fields: unknown[]): string {
+ return fields.map(csvField).join(",") + "\r\n";
+}
+
+export const CSV_HEADER = [
+ "id",
+ "url",
+ "created_at",
+ "author",
+ "author_name",
+ "kind",
+ "text",
+ "reply_to_url",
+ "quoted_url",
+ "repost_of_url",
+ "media_files",
+ "captured_at",
+ "channels",
+];
+
+function refUrl(v: unknown): string {
+ const o = obj(v);
+ return str(o?.url) ?? (str(o?.id) ? `id:${str(o?.id)}` : "");
+}
+
+export function csvForRecords(records: PackRecord[]): string {
+ let out = csvRow(CSV_HEADER);
+ for (const r of records) {
+ out += csvRow([
+ r.id,
+ r.url,
+ r.createdAt,
+ r.author,
+ r.authorName ?? "",
+ r.kind,
+ r.text,
+ refUrl(r.replyTo),
+ refUrl(r.quoted),
+ refUrl(r.repostOf),
+ r.files.map((f) => f.path).join(" "),
+ r.capturedAt ?? "",
+ r.channels.join(" "),
+ ]);
+ }
+ return out;
+}
+
+/**
+ * One SHA256SUMS line as GNU coreutils writes and `sha256sum -c` reads it: a
+ * name holding a backslash or a line break is escaped and the line starts with
+ * a backslash.
+ */
+export function sumsLine(sha256: string, rel: string): string {
+ if (/[\\\n\r]/.test(rel)) {
+ const esc = rel.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/\r/g, "\\r");
+ return `\\${sha256} ${esc}\n`;
+ }
+ return `${sha256} ${rel}\n`;
+}
+
+/** Parse SHA256SUMS back (the lines sumsLine writes). */
+export function parseSums(text: string): Map<string, string> {
+ const out = new Map<string, string>();
+ for (const line of text.split("\n")) {
+ if (!line) continue;
+ let l = line;
+ let escaped = false;
+ if (l.startsWith("\\")) {
+ escaped = true;
+ l = l.slice(1);
+ }
+ const m = /^([0-9a-f]{64}) [ *](.*)$/.exec(l);
+ if (!m) throw new Error(`SHA256SUMS: a line does not parse: ${JSON.stringify(line.slice(0, 80))}`);
+ let name = m[2];
+ if (escaped) name = name.replace(/\\(\\|n|r)/g, (_, c: string) => (c === "n" ? "\n" : c === "r" ? "\r" : "\\"));
+ out.set(name, m[1]);
+ }
+ return out;
+}
+
+/** Files the sums do not cover: the sums themselves and the stamp (and the client's .bak of it). */
+export function excludedFromSums(rel: string): boolean {
+ return rel === SUMS_FILE || rel === OTS_FILE || rel.startsWith(`${OTS_FILE}.`);
+}
+
+export async function sha256File(file: string): Promise<string> {
+ const h = createHash("sha256");
+ for await (const chunk of createReadStream(file)) h.update(chunk as Buffer);
+ return h.digest("hex");
+}
+
+export function sha256Text(text: string | Buffer): string {
+ return createHash("sha256").update(text).digest("hex");
+}
+
+/** Every regular file under dir, relative and "/"-separated, in byte order. */
+export async function listFiles(dir: string, rel = ""): Promise<string[]> {
+ const out: string[] = [];
+ const entries = await readdir(path.join(dir, rel), { withFileTypes: true });
+ for (const e of entries) {
+ const r = rel ? `${rel}/${e.name}` : e.name;
+ if (e.isDirectory()) out.push(...(await listFiles(dir, r)));
+ else if (e.isFile()) out.push(r);
+ else throw new EvidenceRefusal(`${r} is neither a file nor a directory (a package holds only files)`);
+ }
+ return out.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
+}
+
+/** Write SHA256SUMS over every file in dir (but the sums and the stamp); returns its own sha256. */
+export async function writeSums(dir: string, known: Map<string, string> = new Map()): Promise<{ sha256: string; files: number }> {
+ const files = (await listFiles(dir)).filter((f) => !excludedFromSums(f));
+ let text = "";
+ for (const f of files) text += sumsLine(known.get(f) ?? (await sha256File(path.join(dir, f))), f);
+ await writeFile(path.join(dir, SUMS_FILE), text, "utf8");
+ return { sha256: sha256Text(text), files: files.length };
+}
+
+// ---------------------------------------------------------------------------
+// Paths and refusals
+
+function expandHome(p: string): string {
+ return p === "~" ? os.homedir() : p.startsWith("~/") ? path.join(os.homedir(), p.slice(2)) : p;
+}
+
+/** The real path of p, resolved through its nearest existing ancestor. */
+export async function realpathLoose(p: string): Promise<string> {
+ const abs = path.resolve(p);
+ const rest: string[] = [];
+ let cur = abs;
+ for (;;) {
+ try {
+ const real = await realpath(cur);
+ return path.join(real, ...rest.reverse());
+ } catch {
+ const parent = path.dirname(cur);
+ if (parent === cur) return abs;
+ rest.push(path.basename(cur));
+ cur = parent;
+ }
+ }
+}
+
+export function isInside(child: string, parent: string): boolean {
+ const rel = path.relative(parent, child);
+ return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
+}
+
+export function defaultOutDir(label: string, now: Date): string {
+ const day = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`;
+ return path.join(os.homedir(), "reports", "evidence", `${label}-${day}`);
+}
+
+async function readJson(file: string): Promise<unknown> {
+ try {
+ return JSON.parse(await readFile(file, "utf8"));
+ } catch {
+ return null;
+ }
+}
+
+async function isDir(p: string): Promise<boolean> {
+ try {
+ return (await stat(p)).isDirectory();
+ } catch {
+ return false;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Reading the channels
+
+async function readChannel(
+ channelsDir: string,
+ slug: string,
+): Promise<{ source: ChannelSource; records: Loaded[] }> {
+ const root = path.join(channelsDir, slug);
+ const postsDir = path.join(root, "posts");
+ if (!(await isDir(postsDir))) {
+ throw new EvidenceRefusal(`${slug}: not a posts channel (no posts/ in ${root})`);
+ }
+ const shardFiles = (await readdir(postsDir)).filter((f) => f.endsWith(".jsonl")).sort();
+ const byId = new Map<string, Loaded>();
+ const shards: ChannelSource["shards"] = [];
+ for (const file of shardFiles) {
+ const buf = await readFile(path.join(postsDir, file));
+ let lines = 0;
+ let malformed = 0;
+ for (const line of buf.toString("utf8").split("\n")) {
+ const t = line.trim();
+ if (!t) continue;
+ lines++;
+ let raw: unknown;
+ try {
+ raw = JSON.parse(t);
+ } catch {
+ malformed++;
+ continue;
+ }
+ const o = obj(raw);
+ if (!o || !isSafePostId(o.id) || typeof o.createdAt !== "string") {
+ malformed++;
+ continue;
+ }
+ // A later shard wins (readAllPosts' rule: an interrupted write can leave a post in two).
+ byId.set(o.id as string, { channel: slug, shard: file, raw: o });
+ }
+ shards.push({ file: `posts/${file}`, bytes: buf.length, sha256: sha256Text(buf), lines, malformed });
+ }
+ const config = obj(await readJson(path.join(root, "config.json"))) ?? null;
+ const fetchState = obj(await readJson(path.join(root, "posts-state.json"))) ?? null;
+ return {
+ source: { slug, config, fetchState, shards, records: byId.size },
+ records: [...byId.values()],
+ };
+}
+
+function byCreated(a: { createdAt: string; id: string }, b: { createdAt: string; id: string }): number {
+ return a.createdAt < b.createdAt ? -1 : a.createdAt > b.createdAt ? 1 : a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
+}
+
+function sameJson(a: unknown, b: unknown): boolean {
+ return JSON.stringify(a) === JSON.stringify(b);
+}
+
+// ---------------------------------------------------------------------------
+// Pack
+
+type PlannedCopy = { src: string; rel: string; from: string; archivedSha256?: string; sourceUrl?: string; bytes: number };
+
+async function planMedia(
+ channelsDir: string,
+ id: string,
+ channels: string[],
+ captures: Map<string, Record<string, unknown> | null>,
+): Promise<PlannedCopy[]> {
+ const out: PlannedCopy[] = [];
+ const seen = new Set<string>();
+ for (const ch of channels) {
+ const dir = path.join(channelsDir, ch, "posts-media", id);
+ if (!(await isDir(dir))) continue;
+ const capture = captures.get(ch) ?? null;
+ const named = new Map<string, { sha256?: string; url?: string }>();
+ // Every file the capture names — `shot`, `thread`, `media[]`, an article's —
+ // is an object with a `name` (and the `sha256` it was saved with).
+ for (const v of Object.values(capture ?? {})) {
+ for (const m of Array.isArray(v) ? v.map(obj) : [obj(v)]) {
+ const name = str(m?.name);
+ if (name && !named.has(name)) named.set(name, { sha256: str(m?.sha256), url: str(m?.url) });
+ }
+ }
+ for (const name of (await readdir(dir)).sort()) {
+ if (seen.has(name)) continue;
+ const src = path.join(dir, name);
+ let st;
+ try {
+ st = await stat(src); // follows a link: the bytes are what is copied
+ } catch {
+ continue;
+ }
+ if (!st.isFile()) continue;
+ seen.add(name);
+ const n = named.get(name);
+ out.push({
+ src,
+ rel: `media/${id}/${name}`,
+ from: ch,
+ bytes: st.size,
+ ...(n?.sha256 ? { archivedSha256: n.sha256 } : {}),
+ ...(n?.url ? { sourceUrl: n.url } : {}),
+ });
+ }
+ }
+ return out;
+}
+
+export async function pack(opts: PackOptions): Promise<PackResult> {
+ const now = opts.now ?? new Date();
+ if (!opts.slugs.length) throw new EvidenceRefusal("evidence pack: which channels? Pass one or more slugs, comma-separated.");
+ for (const s of opts.slugs) {
+ if (!/^[A-Za-z0-9._-]+$/.test(s) || s === "." || s === "..") throw new EvidenceRefusal(`evidence pack: "${s}" is not a channel slug`);
+ }
+
+ // THE OUTPUT GUARD: never inside the corpus, a channel, or a channel's media (which may be on another drive).
+ const out = path.resolve(expandHome(opts.out));
+ const outReal = await realpathLoose(out);
+ const forbidden = [opts.transcriptsDir, opts.channelsDir];
+ for (const s of opts.slugs) {
+ forbidden.push(path.join(opts.channelsDir, s));
+ forbidden.push(path.join(opts.channelsDir, s, "posts-media"));
+ forbidden.push(path.join(opts.channelsDir, s, "media"));
+ }
+ for (const f of forbidden) {
+ const real = await realpathLoose(f);
+ if (isInside(outReal, real) || isInside(out, path.resolve(f))) {
+ throw new EvidenceRefusal(`evidence pack: refusing to write inside the corpus (${out} is under ${f}); pick an --out outside it`);
+ }
+ }
+ if (!opts.dryRun) {
+ try {
+ const st = await lstat(out);
+ if (!st.isDirectory() || (await readdir(out)).length > 0) {
+ throw new EvidenceRefusal(`evidence pack: ${out} already exists and is not an empty directory; a package is never written over another`);
+ }
+ } catch (err) {
+ if (err instanceof EvidenceRefusal) throw err;
+ }
+ }
+
+ // Read every channel (the text guard first).
+ const sources: ChannelSource[] = [];
+ const loaded = new Map<string, Loaded[]>(); // id -> per channel, in argument order
+ for (const slug of opts.slugs) {
+ if (!(await isDir(path.join(opts.channelsDir, slug)))) {
+ throw new EvidenceRefusal(`evidence pack: no channel "${slug}" in ${opts.channelsDir}`);
+ }
+ if (opts.guardText) await opts.guardText(slug);
+ const { source, records } = await readChannel(opts.channelsDir, slug);
+ sources.push(source);
+ for (const r of records) {
+ const list = loaded.get(r.raw.id as string) ?? [];
+ list.push(r);
+ loaded.set(r.raw.id as string, list);
+ }
+ }
+
+ const availability = new Map<string, Record<string, unknown>>();
+ for (const slug of opts.slugs) {
+ const a = obj(await readJson(path.join(opts.channelsDir, slug, "posts-availability.json")));
+ if (a) availability.set(slug, a);
+ }
+
+ const filter = { handle: opts.handle, since: opts.since, until: opts.until };
+ const records: PackRecord[] = [];
+ const copies: { rec: PackRecord; plan: PlannedCopy }[] = [];
+ let contextRecords = 0;
+ for (const [id, list] of loaded) {
+ const primary = list[0];
+ if (!inScope(primary.raw, filter)) continue;
+ const raw = primary.raw;
+ const channels = list.map((l) => l.channel);
+ const captures = new Map<string, Record<string, unknown> | null>();
+ for (const ch of channels) {
+ captures.set(ch, obj(await readJson(path.join(opts.channelsDir, ch, "posts-media", id, "capture.json"))) ?? null);
+ }
+ const capture = channels.map((c) => captures.get(c)).find((c) => c) ?? null;
+ const avail = channels.map((c) => obj(availability.get(c)?.[id])).find((a) => a) ?? null;
+ const context: NonNullable<PackRecord["context"]> = {};
+ for (const key of ["replyTo", "quoted", "repostOf"] as const) {
+ const refId = str(obj(raw[key])?.id);
+ const target = refId ? loaded.get(refId)?.[0] : undefined;
+ if (target && !inScope(target.raw, filter)) {
+ context[key] = target.raw;
+ contextRecords++;
+ }
+ }
+ const rec: PackRecord = {
+ id,
+ url: str(raw.url) ?? "",
+ platform: str(raw.platform) ?? "",
+ author: str(raw.author) ?? "",
+ ...(str(raw.authorName) ? { authorName: str(raw.authorName) } : {}),
+ createdAt: raw.createdAt as string,
+ kind: postKind(raw),
+ text: str(raw.text) ?? "",
+ ...(str(raw.lang) ? { lang: str(raw.lang) } : {}),
+ ...(str(raw.threadId) ? { threadId: str(raw.threadId) } : {}),
+ ...(raw.replyTo !== undefined ? { replyTo: raw.replyTo } : {}),
+ ...(raw.quoted !== undefined ? { quoted: raw.quoted } : {}),
+ ...(raw.repostOf !== undefined ? { repostOf: raw.repostOf } : {}),
+ links: Array.isArray(raw.links) ? raw.links : [],
+ ...(raw.engagement !== undefined ? { engagement: raw.engagement } : {}),
+ ...(typeof raw.mediaCount === "number" ? { mediaCount: raw.mediaCount } : {}),
+ channels,
+ capturedAt: str(capture?.capturedAt) ?? null,
+ capture,
+ availability: avail,
+ ...(Object.keys(context).length ? { context } : {}),
+ files: [],
+ raw,
+ };
+ const elsewhere = list.slice(1).filter((l) => !sameJson(l.raw, raw));
+ if (elsewhere.length) rec.rawElsewhere = elsewhere.map((l) => ({ channel: l.channel, raw: l.raw }));
+ if (opts.media) {
+ for (const plan of await planMedia(opts.channelsDir, id, channels, captures)) copies.push({ rec, plan });
+ }
+ records.push(rec);
+ }
+ records.sort(byCreated);
+
+ const byKind: Record<string, number> = {};
+ for (const r of records) byKind[r.kind] = (byKind[r.kind] ?? 0) + 1;
+ const mediaBytes = copies.reduce((n, c) => n + c.plan.bytes, 0);
+ const result: PackResult = {
+ out,
+ dryRun: opts.dryRun,
+ channels: sources.map((s) => ({ slug: s.slug, records: s.records, shards: s.shards.length })),
+ posts: records.length,
+ byKind,
+ contextRecords,
+ mediaFiles: copies.length,
+ mediaBytes,
+ mediaMismatches: [],
+ firstPostAt: records[0]?.createdAt ?? null,
+ lastPostAt: records.at(-1)?.createdAt ?? null,
+ files: 0,
+ sumsSha256: null,
+ stamp: { status: "skipped" },
+ };
+ if (opts.dryRun) return result;
+ if (!records.length) throw new EvidenceRefusal("evidence pack: no post matches (check --handle, --since and --until); nothing written");
+
+ // Build in a sibling staging dir, then rename into place.
+ const parent = path.dirname(out);
+ await mkdir(parent, { recursive: true });
+ const staging = path.join(parent, `.${path.basename(out)}.partial-${process.pid}`);
+ await mkdir(staging);
+ const known = new Map<string, string>();
+ for (const { rec, plan } of copies) {
+ const dest = path.join(staging, plan.rel);
+ await mkdir(path.dirname(dest), { recursive: true });
+ await copyFile(plan.src, dest, fsConstants.COPYFILE_EXCL);
+ const st = await stat(plan.src);
+ await utimes(dest, st.atime, st.mtime);
+ const sha256 = await sha256File(dest);
+ known.set(plan.rel, sha256);
+ const file: PackFile = {
+ path: plan.rel,
+ bytes: plan.bytes,
+ sha256,
+ from: plan.from,
+ ...(plan.archivedSha256 ? { archivedSha256: plan.archivedSha256 } : {}),
+ ...(plan.sourceUrl ? { sourceUrl: plan.sourceUrl } : {}),
+ };
+ if (plan.archivedSha256 && plan.archivedSha256 !== sha256) result.mediaMismatches.push(plan.rel);
+ rec.files.push(file);
+ }
+
+ const postsJsonl = records.map((r) => JSON.stringify(r)).join("\n") + "\n";
+ await writeFile(path.join(staging, "posts.jsonl"), postsJsonl, "utf8");
+ await writeFile(path.join(staging, "posts.csv"), csvForRecords(records), "utf8");
+ const manifest = {
+ version: PACK_VERSION,
+ kind: "archilyzer-evidence-pack",
+ generatedAt: now.toISOString(),
+ tool: { name: "archilyzer evidence pack", commit: opts.toolCommit ?? null },
+ filter: { channels: opts.slugs, handle: opts.handle ?? null, since: opts.since ?? null, until: opts.until ?? null, media: opts.media },
+ counts: {
+ posts: records.length,
+ byKind,
+ contextRecords,
+ mediaFiles: copies.length,
+ mediaBytes,
+ mediaArchivedHashMismatches: result.mediaMismatches,
+ },
+ range: { first: result.firstPostAt, last: result.lastPostAt },
+ channels: sources.map((s) => ({
+ slug: s.slug,
+ name: str(s.config?.name) ?? null,
+ platform: str(s.config?.platform) ?? null,
+ url: str(s.config?.url) ?? null,
+ socialHandle: str(s.config?.socialHandle) ?? null,
+ postFetcher: str(s.config?.postFetcher) ?? null,
+ lastSyncedAt: str(s.config?.lastSyncedAt) ?? null,
+ lastFetchedAt: str(s.fetchState?.lastFetchedAt) ?? null,
+ records: s.records,
+ shards: s.shards,
+ })),
+ };
+ await writeFile(path.join(staging, "pack.json"), JSON.stringify(manifest, null, 2) + "\n", "utf8");
+ await writeFile(path.join(staging, "README.md"), readme(manifest, result), "utf8");
+ const sums = await writeSums(staging, known);
+ result.files = sums.files;
+ result.sumsSha256 = sums.sha256;
+
+ try {
+ await rmdir(out); // an empty dir the operator made for it (checked above)
+ } catch {
+ /* absent */
+ }
+ await rename(staging, out);
+
+ if (opts.stamp) result.stamp = await stampDir(out, opts.ots ?? defaultOtsRunner());
+ return result;
+}
+
+function human(bytes: number): string {
+ const u = ["B", "KB", "MB", "GB", "TB"];
+ let n = bytes;
+ let i = 0;
+ while (n >= 1000 && i < u.length - 1) {
+ n /= 1000;
+ i++;
+ }
+ return `${i ? n.toFixed(1) : n} ${u[i]}`;
+}
+
+type Manifest = {
+ generatedAt: string;
+ filter: { channels: string[]; handle: string | null; since: string | null; until: string | null; media: boolean };
+ channels: { slug: string; name: string | null; url: string | null; postFetcher: string | null; lastFetchedAt: string | null }[];
+ tool: { commit: string | null };
+};
+
+export function readme(m: Manifest, r: PackResult): string {
+ const who = m.filter.handle ? `@${m.filter.handle.replace(/^@/, "")}` : "every author in the channels";
+ const range = r.firstPostAt ? `${r.firstPostAt} to ${r.lastPostAt}` : "none";
+ const kinds = Object.entries(r.byKind)
+ .map(([k, n]) => `${n} ${k}${n === 1 ? "" : "s"}`)
+ .join(", ");
+ return `# Evidence package: archived posts of ${who}
+
+Generated ${m.generatedAt} by \`archilyzer evidence pack\`${m.tool.commit ? ` (Archilyzer commit ${m.tool.commit})` : ""}.
+
+This folder is a copy of posts as an Archilyzer archive recorded them when it fetched them from the
+platform, made so that anyone can check it without the archive or its software.
+
+- **${r.posts} posts** (${kinds}), created ${range} (UTC).
+- **${r.mediaFiles} media files** (${human(r.mediaBytes)})${m.filter.media ? "" : " — media were left out (--no-media)"}.
+- ${r.contextRecords} archived records of other authors' posts these answer, quote or repost, as context.
+- Filter: ${m.filter.handle ? `author @${m.filter.handle}` : "every author"}${m.filter.since ? `, from ${m.filter.since}` : ""}${m.filter.until ? `, to ${m.filter.until}` : ""} (dates are the post's UTC day).
+
+## Where the posts came from
+
+${m.channels
+ .map(
+ (c) =>
+ `- \`${c.slug}\`${c.name ? ` (${c.name})` : ""}${c.url ? `: ${c.url}` : ""}${c.postFetcher ? `, fetched with ${c.postFetcher}` : ""}${c.lastFetchedAt ? `, last fetched ${c.lastFetchedAt}` : ""}`,
+ )
+ .join("\n")}
+
+\`pack.json\` lists each source file read (the channel's month shards of posts) with its size and SHA-256 at
+the time of packing.
+
+## The files
+
+| File | What it is |
+|---|---|
+| \`posts.jsonl\` | One JSON record per post, oldest first: id, url, author, createdAt, kind, text, reply/quote/repost references, engagement as archived, the channels that archived it, the capture record (\`capture\`, when the post was opened and shot in a browser — \`capturedAt\` is that time), its last availability check, and its media files with their SHA-256. **\`raw\` is the archived record exactly as stored**, every field; \`context\` holds the archived record of a post it answers or quotes when the archive holds it. |
+| \`posts.csv\` | The same posts as a table: id, url, created_at, author, author_name, kind, text, reply_to_url, quoted_url, repost_of_url, media_files, captured_at, channels. RFC 4180 (UTF-8, CRLF rows, fields with quotes, commas or line breaks quoted). Text is verbatim: a spreadsheet may read a cell starting with \`=\`, \`+\`, \`-\` or \`@\` as a formula. |
+| \`media/<postId>/\` | The post's files as archived, byte for byte (pictures and videos the post carried, \`shot.png\` — a screenshot of the post's page at capture time — and \`capture.json\`, the capture's own record, which names each file's SHA-256 when it was saved). |
+| \`pack.json\` | How this package was made: the filter, the counts, the source channels and source files. |
+| \`SHA256SUMS\` | The SHA-256 of every file above. |
+| \`SHA256SUMS.ots\` | An OpenTimestamps proof that \`SHA256SUMS\` existed at a point in time. |
+
+## How to verify
+
+1. **The files are what was packaged.** In this folder:
+
+ \`\`\`sh
+ sha256sum -c SHA256SUMS # every line must say OK
+ \`\`\`
+
+2. **The package existed no later than a Bitcoin block.** \`SHA256SUMS.ots\` commits the SHA-256 of
+ \`SHA256SUMS\` (\`sha256sum SHA256SUMS\` prints it; this README is listed in it, so it cannot name it) to public
+ OpenTimestamps calendars, which commit it to the
+ Bitcoin blockchain within a few hours. With the OpenTimestamps client
+ (\`pip install opentimestamps-client\`, or \`uv tool install opentimestamps-client\`):
+
+ \`\`\`sh
+ ots upgrade SHA256SUMS.ots # once, a few hours after packing: fetch the Bitcoin attestation
+ ots info SHA256SUMS.ots # the proof's path, ending in the block height it is attested in
+ ots verify SHA256SUMS.ots # checks it against a Bitcoin node (bitcoind) on this machine
+ \`\`\`
+
+ Without a Bitcoin node, drop \`SHA256SUMS\` and \`SHA256SUMS.ots\` on https://opentimestamps.org, or
+ compare the merkle root \`ots info\` ends with against the block's header on any block explorer.
+ Because \`SHA256SUMS\` names every file's hash, the timestamp covers every file in the folder:
+ a file changed after the timestamp no longer matches its line.
+
+3. **The media are what the archive saved.** Each \`media/<postId>/capture.json\` names the SHA-256 the
+ archive computed when it saved each file; \`posts.jsonl\` repeats it as \`archivedSha256\` beside the
+ copy's \`sha256\`.${r.mediaMismatches.length ? ` ${r.mediaMismatches.length} files differ from it (named in \`pack.json\`, \`counts.mediaArchivedHashMismatches\`).` : " Every one matches."}
+
+## What this does and does not show
+
+It shows that these records and files existed, in this form, no later than the time the timestamp
+attests, and that the archive recorded them as fetched from the URLs given. It is not a capture by an
+independent third party: the posts were fetched by this archive's own tools (see \`pack.json\`). Where a
+public archive (the Wayback Machine, archive.today) holds a copy of a post, that copy is independent
+corroboration.
+`;
+}
+
+// ---------------------------------------------------------------------------
+// OpenTimestamps
+
+export type OtsRunner = (args: string[], cwd: string) => Promise<{ code: number; stdout: string; stderr: string }>;
+
+export function otsBin(env: NodeJS.ProcessEnv = process.env): string | null {
+ if (env.ARCHILYZER_OTS_BIN) return env.ARCHILYZER_OTS_BIN;
+ const which = spawnSync("sh", ["-c", "command -v ots"], { encoding: "utf8" });
+ const found = which.status === 0 ? which.stdout.trim() : "";
+ if (found) return found;
+ const local = path.join(os.homedir(), ".local", "bin", "ots");
+ return spawnSync(local, ["--version"], { encoding: "utf8" }).status === 0 ? local : null;
+}
+
+export function defaultOtsRunner(bin: string | null = otsBin()): OtsRunner {
+ return (args, cwd) =>
+ new Promise((resolve) => {
+ if (!bin) {
+ resolve({ code: 127, stdout: "", stderr: "the OpenTimestamps client (ots) is not installed: uv tool install opentimestamps-client" });
+ return;
+ }
+ const child = spawn(bin, args, { cwd, stdio: ["ignore", "pipe", "pipe"] });
+ let stdout = "";
+ let stderr = "";
+ child.stdout.on("data", (d) => (stdout += d));
+ child.stderr.on("data", (d) => (stderr += d));
+ const timer = setTimeout(() => child.kill("SIGTERM"), 120_000);
+ child.on("error", (err) => {
+ clearTimeout(timer);
+ resolve({ code: 127, stdout, stderr: stderr + String(err) });
+ });
+ child.on("close", (code) => {
+ clearTimeout(timer);
+ resolve({ code: code ?? 1, stdout, stderr });
+ });
+ });
+}
+
+/** The attestations `ots info` names: the calendars still pending, and the Bitcoin blocks. */
+export function parseOtsInfo(info: string): { calendars: string[]; blocks: number[] } {
+ const calendars = [...new Set([...info.matchAll(/PendingAttestation\('([^']+)'\)/g)].map((m) => m[1]))];
+ const blocks = [...new Set([...info.matchAll(/BitcoinBlockHeaderAttestation\((\d+)\)/g)].map((m) => Number(m[1])))].sort(
+ (a, b) => a - b,
+ );
+ return { calendars, blocks };
+}
+
+async function otsInfo(dir: string, ots: OtsRunner): Promise<StampResult> {
+ const info = await ots(["info", OTS_FILE], dir);
+ if (info.code !== 0) return { status: "failed", error: `ots info: ${(info.stderr || info.stdout).trim()}` };
+ const { calendars, blocks } = parseOtsInfo(info.stdout);
+ return { status: blocks.length ? "attested" : "pending", calendars, blocks, info: info.stdout };
+}
+
+async function exists(p: string): Promise<boolean> {
+ try {
+ await lstat(p);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/** `ots stamp SHA256SUMS` in dir (one request to each of the client's calendars), then its state. */
+export async function stampDir(dir: string, ots: OtsRunner): Promise<StampResult> {
+ if (!(await exists(path.join(dir, SUMS_FILE)))) return { status: "failed", error: `${dir} has no ${SUMS_FILE}` };
+ if (await exists(path.join(dir, OTS_FILE))) return { status: "failed", error: `${dir} is stamped already (${OTS_FILE}); use evidence upgrade` };
+ const run = await ots(["stamp", SUMS_FILE], dir);
+ if (run.code === 127) return { status: "unavailable", error: run.stderr.trim() };
+ if (run.code !== 0 || !(await exists(path.join(dir, OTS_FILE)))) {
+ return { status: "failed", error: `ots stamp exited ${run.code}: ${(run.stderr || run.stdout).trim()}` };
+ }
+ return otsInfo(dir, ots);
+}
+
+/** `ots upgrade SHA256SUMS.ots`: the calendars' Bitcoin attestation once they have one. */
+export async function upgradeDir(dir: string, ots: OtsRunner): Promise<StampResult> {
+ if (!(await exists(path.join(dir, OTS_FILE)))) {
+ return { status: "failed", error: `${dir} has no ${OTS_FILE}; run archilyzer evidence stamp ${dir} first` };
+ }
+ const before = await otsInfo(dir, ots);
+ if (before.status === "attested") return before;
+ // The client exits non-zero while the timestamp is still pending; the info after says which it is.
+ const run = await ots(["upgrade", OTS_FILE], dir);
+ if (run.code === 127) return { status: "unavailable", error: run.stderr.trim() };
+ return otsInfo(dir, ots);
+}
+
+export type VerifyResult = {
+ ok: boolean;
+ checked: number;
+ missing: string[];
+ changed: string[];
+ unlisted: string[];
+ sumsSha256: string;
+ stamp: StampResult | { status: "absent" };
+};
+
+export async function verifyDir(dir: string, ots: OtsRunner): Promise<VerifyResult> {
+ const sumsText = await readFile(path.join(dir, SUMS_FILE), "utf8");
+ const sums = parseSums(sumsText);
+ const present = new Set((await listFiles(dir)).filter((f) => !excludedFromSums(f)));
+ const missing: string[] = [];
+ const changed: string[] = [];
+ for (const [rel, want] of sums) {
+ if (!present.has(rel)) {
+ missing.push(rel);
+ continue;
+ }
+ if ((await sha256File(path.join(dir, rel))) !== want) changed.push(rel);
+ }
+ const unlisted = [...present].filter((f) => !sums.has(f));
+ const stamp = (await exists(path.join(dir, OTS_FILE))) ? await otsInfo(dir, ots) : ({ status: "absent" } as const);
+ return {
+ ok: !missing.length && !changed.length && !unlisted.length,
+ checked: sums.size,
+ missing,
+ changed,
+ unlisted,
+ sumsSha256: sha256Text(sumsText),
+ stamp,
+ };
+}
+
+// ---------------------------------------------------------------------------
+// CLI
+
+function flagStr(v: FlagValue | undefined): string | undefined {
+ return typeof v === "string" ? v : undefined;
+}
+
+function toolCommit(): string | null {
+ const repo = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..");
+ const r = spawnSync("git", ["-C", repo, "rev-parse", "HEAD"], { encoding: "utf8" });
+ return r.status === 0 ? r.stdout.trim() : null;
+}
+
+function stampLine(s: StampResult | { status: "absent" }): string {
+ switch (s.status) {
+ case "pending":
+ return `stamp: pending — submitted to ${s.calendars.length} calendar${s.calendars.length === 1 ? "" : "s"} (${s.calendars.join(", ")}); run \`archilyzer evidence upgrade <dir>\` in a few hours for the Bitcoin attestation`;
+ case "attested":
+ return `stamp: attested in Bitcoin block ${s.blocks.join(", ")}`;
+ case "absent":
+ return "stamp: none (no SHA256SUMS.ots)";
+ case "skipped":
+ return "stamp: skipped";
+ default:
+ return `stamp: ${s.status}${s.error ? ` — ${s.error}` : ""}`;
+ }
+}
+
+export async function packMain(
+ positionals: string[],
+ flags: Record<string, FlagValue>,
+ deps: { channelsDir: string; transcriptsDir: string; guardText?: (slug: string) => Promise<void>; ots?: OtsRunner; log?: (s: string) => void; error?: (s: string) => void },
+): Promise<number> {
+ const log = deps.log ?? console.log;
+ const error = deps.error ?? console.error;
+ const slugs = positionals.flatMap((p) => p.split(",")).map((s) => s.trim()).filter(Boolean);
+ if (flags.media === true && flags["no-media"] === true) {
+ error("evidence pack: --media and --no-media together");
+ return 2;
+ }
+ if (flags.stamp === true && flags["no-stamp"] === true) {
+ error("evidence pack: --stamp and --no-stamp together");
+ return 2;
+ }
+ const since = parseDay(flagStr(flags.since));
+ const until = parseDay(flagStr(flags.until));
+ if (since === null || until === null) {
+ error("evidence pack: --since and --until are dates, YYYY-MM-DD");
+ return 2;
+ }
+ if (since && until && since > until) {
+ error("evidence pack: --since is after --until");
+ return 2;
+ }
+ const handle = flagStr(flags.handle)?.trim().replace(/^@/, "") || undefined;
+ const now = new Date();
+ const out = flagStr(flags.out) ?? defaultOutDir(handle ?? slugs[0] ?? "posts", now);
+ try {
+ const r = await pack({
+ channelsDir: deps.channelsDir,
+ transcriptsDir: deps.transcriptsDir,
+ slugs,
+ handle,
+ since,
+ until,
+ out,
+ media: flags["no-media"] !== true,
+ stamp: flags["no-stamp"] !== true,
+ dryRun: flags["dry-run"] === true,
+ now,
+ guardText: deps.guardText,
+ ots: deps.ots,
+ toolCommit: toolCommit(),
+ });
+ if (flags.json === true) {
+ log(JSON.stringify(r, null, 2));
+ } else {
+ log(`${r.dryRun ? "would write" : "wrote"} ${r.out}`);
+ for (const c of r.channels) log(` ${c.slug}: ${c.records} archived records in ${c.shards} shard${c.shards === 1 ? "" : "s"}`);
+ log(
+ ` ${r.posts} posts (${Object.entries(r.byKind).map(([k, n]) => `${n} ${k}`).join(", ") || "none"}), ${r.firstPostAt ?? "-"} to ${r.lastPostAt ?? "-"}; ${r.contextRecords} context records`,
+ );
+ log(` ${r.mediaFiles} media files, ${human(r.mediaBytes)}${r.mediaMismatches.length ? `; ${r.mediaMismatches.length} differ from the hash their capture recorded` : ""}`);
+ if (!r.dryRun) {
+ log(` ${r.files} files in SHA256SUMS; sha256(SHA256SUMS) = ${r.sumsSha256}`);
+ log(` ${stampLine(r.stamp)}`);
+ }
+ }
+ if (!r.dryRun && flags["no-stamp"] !== true && r.stamp.status !== "pending" && r.stamp.status !== "attested") {
+ error(`evidence pack: the package is written, but it is not stamped (${r.stamp.status}); run archilyzer evidence stamp ${r.out}`);
+ return 1;
+ }
+ return 0;
+ } catch (err) {
+ if (err instanceof EvidenceRefusal || (err as Error)?.name === "ChannelTextUnreadableError") {
+ error((err as Error).message);
+ return 2;
+ }
+ throw err;
+ }
+}
+
+export async function dirMain(
+ verb: "stamp" | "upgrade" | "verify",
+ positionals: string[],
+ flags: Record<string, FlagValue>,
+ deps: { ots?: OtsRunner; log?: (s: string) => void; error?: (s: string) => void } = {},
+): Promise<number> {
+ const log = deps.log ?? console.log;
+ const error = deps.error ?? console.error;
+ const [d] = positionals;
+ if (!d) {
+ error(`evidence ${verb}: which package? Pass its directory.`);
+ return 2;
+ }
+ const dir = path.resolve(expandHome(d));
+ if (!(await exists(path.join(dir, SUMS_FILE)))) {
+ error(`evidence ${verb}: ${dir} has no ${SUMS_FILE} — not an evidence package`);
+ return 2;
+ }
+ const ots = deps.ots ?? defaultOtsRunner();
+ if (verb === "verify") {
+ const v = await verifyDir(dir, ots);
+ if (flags.json === true) log(JSON.stringify(v, null, 2));
+ else {
+ log(`${v.ok ? "OK" : "FAILED"}: ${v.checked} files in SHA256SUMS; sha256(SHA256SUMS) = ${v.sumsSha256}`);
+ for (const f of v.missing) log(` missing: ${f}`);
+ for (const f of v.changed) log(` changed: ${f}`);
+ for (const f of v.unlisted) log(` not in SHA256SUMS: ${f}`);
+ log(` ${stampLine(v.stamp)}`);
+ }
+ return v.ok ? 0 : 1;
+ }
+ const s = verb === "stamp" ? await stampDir(dir, ots) : await upgradeDir(dir, ots);
+ if (flags.json === true) log(JSON.stringify(s, null, 2));
+ else log(stampLine(s));
+ return s.status === "pending" || s.status === "attested" ? 0 : 1;
+}
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,7 @@
# Changelog
## [Unreleased]
+- **Archived posts can be packaged as timestamped evidence.** The operator wanted public evidence that Mr. Obvious's X posts existed, and Save Page Now refuses x.com as a site (HTTP 523); he chose "the timestamped evidence package". `archilyzer evidence pack <channel>[,<channel>…] [--handle <h>] [--since/--until YYYY-MM-DD] [--out <dir>] [--no-media] [--no-stamp] [--dry-run] [--json]` writes, read only over the corpus, a self-contained folder (default `~/reports/evidence/<handle>-<date>/`): `posts.jsonl` (one record a post, deduped across the channels, every archived field kept under `raw`, the capture record and availability check, and the archived record of a post it answers or quotes as `context`), `posts.csv`, the post media copied byte for byte from `posts-media/` (each hash checked against its `capture.json`), `pack.json`, a README saying how to verify, `SHA256SUMS` over every file, and an OpenTimestamps proof of it (`SHA256SUMS.ots`, the official `ots` client, one request to each calendar). `evidence upgrade <dir>` fetches the Bitcoin attestation a few hours later, `evidence verify <dir>` checks every file and the stamp, `evidence stamp <dir>` stamps an unstamped one. Refused inside the corpus or a channel's media, over a non-empty dir, and for a channel whose text is unreadable. OPERATING.md, "Package posts as timestamped evidence".
- **Save Page Now works without archive.org keys, and a whole list of pages can be archived politely, with an evidence file.** The operator wanted every Mr. Obvious post on a public archive ("I'm just trying to make sure evidence of the pages exist"), and Save Page Now refused without S3 keys. With no keys configured it now asks archive.org's public endpoint anonymously (`"mode": "anonymous"` in the log and result; with keys, SPN2 as before, `"mode": "keys"`), and the channel page's Save Page Now panel says which. Every save in the editor takes turns through one pacer: one at a time, at least 60 s apart anonymous (10 s with keys), and a 429/503 or archive.org's "slow down" rests it (Retry-After, else 2 min doubling to 1 h). `pnpm ops save-page-now-batch --json '{"file":"/abs/urls.json"}'` runs ONE resumable job over a list: each URL looked up first (the Wayback CDX and archive.today's timemap, paced) and skipped when a copy shows it, else saved; at most 150 saves a day without keys (archive.org allows 200); progress and an ETA on /jobs; cancel, a restart or `{"batch": "<id>"}` continue from the first pending URL. Its evidence JSON + CSV (default `<transcripts>/.spn-batches/<batch>.evidence.*`, or `evidence`) names, per URL, the status, the Wayback and archive.today copy URLs, the capture time and the HTTP status the archive recorded. archive.today and Ghostarchive are looked up only, never asked to save (their forms put a CAPTCHA in front). Save Page Now refuses x.com as a site today (HTTP 523, "limitations when it comes to archiving this site"): a batch asks such a site once, then only looks its other URLs up and records them as not asked. OPERATING.md, "Archive a list of pages politely (evidence)".
- **umtool: a reel can end on an outro card, and open on an intro its master does not have.** A trailer stopped on its last beat, and a reel with "open on the brand intro" was refused when the take had been rendered without one (the Mr. Obvious X trailer). `umtool trailer-beats <p> --reel <r> outro '{"title":"…","image":"promo/thumbnail.jpg"}'` (`on`, `off`, `none`) ends the reel on a card: the full video's title large (default the reel's title, else the project's), "Full video on the channel" under it (`text`), the site's name small in its accent, over the image blurred and darkened (or the dark ground), 3.5 s (`seconds`) with a 0.5 s fade in from the last beat while its sound fades out, then held to the end; `ls` says `· outro 3.5 s` and the length against the limit counts it. With `intro on` and no intro in the master, the take's `render.intro` (else the dark boot with the mark on the chime) is rendered for the reel; `intro '{"style":"boot-dark","mark":"chime","site":"anilyzer"}'` gives a reel an intro of its own. `umtool trailer --reel` cuts both in; a reel with neither is cut exactly as before. The Trailer page has **end on the outro card** and its fields beside **open on the brand intro**. Shorts get both too: `umtool vertical … --intro` opens a short on the brand intro re-laid 9:16 (the drawing centred between the Shorts overlays: the top 8 %, the bottom 20 %, 12 % either side), a reel's `intro` on does the same, and a reel's outro card is laid out 9:16 inside that safe area (`--no-intro`, `--no-outro`). A landscape intro is unchanged.
- **umtool: a take can be previewed fast, and only what changed can be rendered.** A re-render of a 40-minute cut took 5–40 minutes even reusing everything it could, because its picture is encoded at 1920×1080 on a slow preset, and the operator walked each render and waited for the next. `umtool take <p> --id <t> --preview` renders the take (a draft too) composed exactly as its full render -- the same layout, segments, chrome and sound, so timing and levels judged on it hold -- with only the final picture at 1280×720, x264 veryfast, crf 26 (`render.preview`), into `takes/<t>/out/<slug>.preview.mp4`; the take's full render and its records are never touched, and a preview's encoded chunks are keyed apart and never stand in for a full render's. `umtool take <p> --id <t> --changes [--from <t0>] [--pad 3]` renders a reel of ONLY the items that changed against the take it was made from (added, re-read, re-picked, re-voiced, trimmed, held, fx, …), each with its neighbours, cut to the item ± 3 s and labelled with its time in the full cut ("21:19 · p-… · re-voiced"), into `takes/<t>/out/<slug>.changes.mp4`, and lists them in `takes/<t>/changes.json`. Both run through the queue (`umtool queue add -- take … --preview`), the take card's **Preview render** and **Render changes** (and Play's **Fast render**) queue them and show their state, the file's path with Copy and the file itself, and `umtool take status … --json` reports them. umtool/docs/report-video.md, knobs.md, cli.md.