{"record":{"id":"b515fb36e7757e58","repo":"JuliusBrussee/caveman","slug":"cave-artifact-was-not-valid-json","errorCode":null,"errorMessage":"cave artifact was not valid JSON","messagePattern":"cave artifact was not valid JSON","errorType":"http","errorClass":"CaveRequestError","httpStatus":null,"severity":"error","filePath":"packages/sdk/typescript/src/index.ts","lineNumber":2157,"sourceCode":"  }\n  return decoded as Record<string, unknown>;\n}\n\nasync function artifactGet(cave: Cave, artifactId: string, workflow: string, trace: TraceContext): Promise<unknown> {\n  if (typeof artifactId !== \"string\" || artifactId.trim() === \"\") throw new Error(\"artifactId is required\");\n  const path = `/sdk/v1/artifacts/${encodeURIComponent(artifactId)}`;\n  const response = await caveFetch(cave, `${cave.options.baseURL}${path}`, {\n    method: \"GET\",\n    headers: headers(cave, workflow, undefined, undefined, trace)\n  });\n  if (!response.ok) {\n    discardResponse(response);\n    throw new CaveRequestError(response.status, path, `cave request failed (${response.status})`);\n  }\n  try {\n    return JSON.parse(await response.text());\n  } catch {\n    throw new CaveRequestError(response.status, path, \"cave artifact was not valid JSON\");\n  }\n}\n\nfunction headers(cave: Cave, workflow: string, upstreamKey?: string, hint?: Record<string, unknown>, trace?: TraceContext) {\n  return {\n    \"content-type\": \"application/json\",\n    authorization: `Bearer ${cave.options.apiKey}`,\n    \"x-cave-agent\": cave.options.agent,\n    \"x-cave-workflow\": workflow,\n    \"x-cave-retention\": cave.options.retention ?? \"metadata\",\n    ...(cave.options.user ? { \"x-cave-user-hash\": cave.options.user } : {}),\n    ...(upstreamKey ? { \"x-cave-upstream-key\": upstreamKey } : {}),\n    ...(hint?.[\"latencyClass\"] !== undefined ? { \"x-cave-async\": String(hint[\"latencyClass\"] !== \"interactive\") } : {}),\n    ...(typeof hint?.[\"toolSessionId\"] === \"string\" ? { \"x-cave-tool-session\": hint[\"toolSessionId\"] as string } : {}),\n    ...(typeof hint?.[\"assemblyHeader\"] === \"string\" ? { \"x-cave-assembly\": hint[\"assemblyHeader\"] as string } : {}),\n    // Trace continuity: only requests made through a CaveTrace carry these, so\n    // the gateway row's span parents onto the SDK's root span.\n    ...(trace ? { \"x-cave-trace-id\": trace.traceId, \"x-cave-parent-span-id\": trace.parentSpanId } : {})","sourceCodeStart":2139,"sourceCodeEnd":2175,"githubUrl":"https://github.com/JuliusBrussee/caveman/blob/3ee70a102609e550bd2e68004bf5990a9341c851/packages/sdk/typescript/src/index.ts#L2139-L2175","documentation":"artifactGet parses the artifact body with JSON.parse(await response.text()) and wraps any parse failure in CaveRequestError(status, path, \"cave artifact was not valid JSON\"). Unlike the object-request helper, artifacts may legitimately be any JSON value, but they must still be valid JSON — a non-JSON or truncated body triggers this error.","triggerScenarios":"Artifact upload was corrupted or truncated (partial write, connection drop mid-upload); storage layer serving raw binary or an empty string; an intermediary returning an error page with 200 kept alive; non-JSON artifact bytes stored through another tool.","commonSituations":"Network interruption during artifact upload leading to partial body on disk; proxy compressing/encoding the body in a way JSON.parse cannot read; hand-seeded artifact data in a local dev Cave that was never valid JSON.","solutions":["Re-upload the artifact and retry the get to rule out transient truncation","Fetch the artifact URL manually (curl) and inspect the raw bytes to find where the JSON breaks","Verify no proxy/gateway is rewriting, compressing, or chunk-corrupting response bodies","If artifacts are written by a custom pipeline, validate JSON.parse(store) at write time"],"exampleFix":"// before\nawait fetch(uploadUrl, { method: 'PUT', body: maybeStringified }); // partial body persisted\n// after\nconst payload = JSON.stringify(data);\nJSON.parse(payload); // validate before storing\nawait fetch(uploadUrl, { method: 'PUT', body: payload });","handlingStrategy":"retry","validationCode":"// at write time:\nconst payload = JSON.stringify(data); JSON.parse(payload); // throws before upload if data is not serializable","typeGuard":null,"tryCatchPattern":"try { return await sdk.getArtifact(id, wf); } catch (e) { if (e instanceof CaveRequestError && e.message.includes('artifact was not valid JSON')) { await reupload(id, wf); return sdk.getArtifact(id, wf); } throw e; }","preventionTips":["Validate artifacts with JSON.parse immediately after upload (read-back check)","Detect interrupted uploads server-side (checksums/content-length)","Bypass intermediaries for large artifact bodies or verify no rewriting occurs","Seed dev/test artifacts only via the SDK upload path, never raw files"],"tags":["json","artifacts","network","corruption"],"backgroundTag":"invalid-json-response","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"}