{"record":{"id":"8b2818a3af567ae0","repo":"JuliusBrussee/caveman","slug":"local-learn-snapshot-is-unreadable-at-snapshotpa","errorCode":null,"errorMessage":"local learn snapshot is unreadable at ${snapshotPath}","messagePattern":"local learn snapshot is unreadable at (.+?)","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"packages/cli/src/index.ts","lineNumber":10422,"sourceCode":"  const subject = `synced ${out.spans}${local ? \" local\" : \"\"} spans`;\n  if (out.headlineCompressionRefused) {\n    return `${subject} · compression headline refused: cache writes ${out.cacheCreationInputTokens} > cache reads ${out.cachedInputTokens} (inferred; no savings headline)${destination}`;\n  }\n  return `${subject} · ${out.tokensSaved} estimated tokens saved (inferred; counter basis ${out.tokenCountBasis})${destination}`;\n}\n\n// syncLocalPracticeFindings moves only stable ids + non-negative token rates\n// from the current learn snapshot. Titles, suggestions, evidence, file paths,\n// and payload text never leave the machine. Empty snapshots are sent so stale\n// rows for this user are removed server-side.\nasync function syncLocalPracticeFindings(cfg: Config): Promise<PracticeSyncOutcome> {\n  const snapshotPath = join(cavemanHome(), \"reports\", \"caveman-learn.json\");\n  let raw: Record<string, unknown>;\n  try {\n    raw = JSON.parse(readFileSync(snapshotPath, \"utf8\")) as Record<string, unknown>;\n  } catch (error) {\n    if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return { kind: \"no_snapshot\" };\n    throw new Error(`local learn snapshot is unreadable at ${snapshotPath}`);\n  }\n\n  if (!Array.isArray(raw.sinks)) {\n    throw new Error(`local learn snapshot has no sinks array at ${snapshotPath}`);\n  }\n  const observed = typeof raw.generated_at === \"string\" ? new Date(raw.generated_at) : null;\n  if (!observed || Number.isNaN(observed.valueOf())) {\n    throw new Error(`local learn snapshot has no valid generated_at at ${snapshotPath}`);\n  }\n  const sessions = typeof raw.sessions_scanned === \"number\" && Number.isFinite(raw.sessions_scanned)\n    ? Math.max(0, Math.trunc(raw.sessions_scanned))\n    : 0;\n  const counter = (value: unknown) =>\n    typeof value === \"number\" && Number.isFinite(value) ? Math.max(0, Math.trunc(value)) : 0;\n\n  const findings = raw.sinks\n    .filter((sink): sink is Record<string, unknown> =>\n      !!sink && typeof sink === \"object\" && !Array.isArray(sink))","sourceCodeStart":10404,"sourceCodeEnd":10440,"githubUrl":"https://github.com/JuliusBrussee/caveman/blob/3ee70a102609e550bd2e68004bf5990a9341c851/packages/cli/src/index.ts#L10404-L10440","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Regenerate the snapshot: re-run `caveman learn` so reports/caveman-learn.json is rewritten validly.","Delete the corrupt file (the next read then behaves as no_snapshot) and let learn recreate it.","Fix file permissions (chown/chmod) if the error came from EACCES, not JSON syntax.","Validate the file with `node -e 'JSON.parse(require(\"fs\").readFileSync(process.argv[1],\"utf8\"))' <path>` to confirm the corruption."],"exampleFix":"// before: truncated snapshot from an interrupted run\n$ cat ~/.caveman/reports/caveman-learn.json | tail -c 20\n...\"sinks\": [{\"na\n// after: regenerate\n$ rm ~/.caveman/reports/caveman-learn.json && caveman learn","handlingStrategy":"try-catch","validationCode":"// Pre-check the snapshot before relying on it\nimport { existsSync, readFileSync } from \"node:fs\";\nconst p = join(cavemanHome(), \"reports\", \"caveman-learn.json\");\nconst valid = existsSync(p) && (() => { try { JSON.parse(readFileSync(p, \"utf8\")); return true; } catch { return false; } })();\nif (!valid) console.warn(\"learn snapshot missing or corrupt — re-run `caveman learn`\");","typeGuard":"function isParseableSnapshot(p: string): boolean {\n  try { JSON.parse(readFileSync(p, \"utf8\")); return true; } catch { return false; }\n}","tryCatchPattern":"try {\n  const snap = loadLearnSnapshot();\n} catch (e) {\n  if (e instanceof Error && e.message.startsWith(\"local learn snapshot is unreadable\")) {\n    // corrupt snapshot: delete and regenerate\n    rmSync(snapshotPath, { force: true });\n    await runLearn();\n  } else throw e;\n}","preventionTips":["Don't kill `caveman learn` mid-run — interrupted writes leave truncated JSON.","Don't hand-edit reports/caveman-learn.json.","Run CLI commands under one consistent user to avoid EACCES on the report file.","Check disk space so writes aren't truncated."],"tags":["json","file","snapshot","corruption"],"backgroundTag":"json-parse-error","analyzedSha":"3ee70a102609e550bd2e68004bf5990a9341c851","analyzedAt":"2026-09-20T15:53:39.229Z","contentChangedAt":"2026-09-20T15:53:39.229Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}