JuliusBrussee/caveman · error · Error

local learn snapshot is unreadable at

Error message

local learn snapshot is unreadable at ${snapshotPath}

What it means

Thrown when the learn-snapshot file at `<cavemanHome>/reports/caveman-learn.json` exists but cannot be parsed as JSON or read. A missing file (ENOENT) is handled gracefully as `no_snapshot`; anything else — corrupt JSON, permission errors, empty/truncated file — raises this error with the full path.

Solutions

  1. Regenerate the snapshot: re-run `caveman learn` so reports/caveman-learn.json is rewritten validly.
  2. Delete the corrupt file (the next read then behaves as no_snapshot) and let learn recreate it.
  3. Fix file permissions (chown/chmod) if the error came from EACCES, not JSON syntax.
  4. Validate the file with `node -e 'JSON.parse(require("fs").readFileSync(process.argv[1],"utf8"))' <path>` to confirm the corruption.

Example fix

// before: truncated snapshot from an interrupted run
$ cat ~/.caveman/reports/caveman-learn.json | tail -c 20
..."sinks": [{"na
// after: regenerate
$ rm ~/.caveman/reports/caveman-learn.json && caveman learn
Defensive patterns

Strategy: try-catch

Validate before calling

// Pre-check the snapshot before relying on it
import { existsSync, readFileSync } from "node:fs";
const p = join(cavemanHome(), "reports", "caveman-learn.json");
const valid = existsSync(p) && (() => { try { JSON.parse(readFileSync(p, "utf8")); return true; } catch { return false; } })();
if (!valid) console.warn("learn snapshot missing or corrupt — re-run `caveman learn`");

Type guard

function isParseableSnapshot(p: string): boolean {
  try { JSON.parse(readFileSync(p, "utf8")); return true; } catch { return false; }
}

Try / catch

try {
  const snap = loadLearnSnapshot();
} catch (e) {
  if (e instanceof Error && e.message.startsWith("local learn snapshot is unreadable")) {
    // corrupt snapshot: delete and regenerate
    rmSync(snapshotPath, { force: true });
    await runLearn();
  } else throw e;
}

Prevention

When it happens

Trigger: Running a learn/scan-consuming command when caveman-learn.json is present but truncated mid-write, contains invalid JSON, has a permissions problem, or is empty.

Common situations: A previous `caveman learn` run was killed mid-write leaving partial JSON; manual edits to the report broke the syntax; file owned by another user after running under sudo; disk-full causing a truncated write.

Understand the failure class

Background: JSON parse error: "Unexpected token" / "not valid JSON" / "failed to parse" — what JSON parsers are really complaining about — this error's family across 45 libraries.

Related errors


AI-assisted analysis of JuliusBrussee/caveman@3ee70a1026 (2026-09-20). Data as JSON: /api/errors/8b2818a3af567ae0. Report an issue: GitHub.

Appendix: source

Thrown at packages/cli/src/index.ts:10422

  const subject = `synced ${out.spans}${local ? " local" : ""} spans`;
  if (out.headlineCompressionRefused) {
    return `${subject} · compression headline refused: cache writes ${out.cacheCreationInputTokens} > cache reads ${out.cachedInputTokens} (inferred; no savings headline)${destination}`;
  }
  return `${subject} · ${out.tokensSaved} estimated tokens saved (inferred; counter basis ${out.tokenCountBasis})${destination}`;
}

// syncLocalPracticeFindings moves only stable ids + non-negative token rates
// from the current learn snapshot. Titles, suggestions, evidence, file paths,
// and payload text never leave the machine. Empty snapshots are sent so stale
// rows for this user are removed server-side.
async function syncLocalPracticeFindings(cfg: Config): Promise<PracticeSyncOutcome> {
  const snapshotPath = join(cavemanHome(), "reports", "caveman-learn.json");
  let raw: Record<string, unknown>;
  try {
    raw = JSON.parse(readFileSync(snapshotPath, "utf8")) as Record<string, unknown>;
  } catch (error) {
    if ((error as NodeJS.ErrnoException).code === "ENOENT") return { kind: "no_snapshot" };
    throw new Error(`local learn snapshot is unreadable at ${snapshotPath}`);
  }

  if (!Array.isArray(raw.sinks)) {
    throw new Error(`local learn snapshot has no sinks array at ${snapshotPath}`);
  }
  const observed = typeof raw.generated_at === "string" ? new Date(raw.generated_at) : null;
  if (!observed || Number.isNaN(observed.valueOf())) {
    throw new Error(`local learn snapshot has no valid generated_at at ${snapshotPath}`);
  }
  const sessions = typeof raw.sessions_scanned === "number" && Number.isFinite(raw.sessions_scanned)
    ? Math.max(0, Math.trunc(raw.sessions_scanned))
    : 0;
  const counter = (value: unknown) =>
    typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.trunc(value)) : 0;

  const findings = raw.sinks
    .filter((sink): sink is Record<string, unknown> =>
      !!sink && typeof sink === "object" && !Array.isArray(sink))

View on GitHub (pinned to 3ee70a1026)