{"record":{"id":"5b2b77e4dceae201","repo":"thedotmack/claude-mem","slug":"install-failed-to-parse-existing-settings-json","errorCode":null,"errorMessage":"[install] Failed to parse existing settings.json, starting from empty:","messagePattern":"\\[install\\] Failed to parse existing settings\\.json, starting from empty:","errorType":"console","errorClass":null,"httpStatus":null,"severity":"warning","filePath":"src/npx-cli/commands/install.ts","lineNumber":799,"sourceCode":"    // apiKeyHelper, model, statusLine, etc.). readFlatSettings unwraps the\n    // env subtree for reads, but writing that flattened view back as the\n    // entire file silently drops every non-env top-level key — destroying\n    // user configuration that disableClaudeAutoMemory + writeJsonFileAtomic\n    // had carefully written.\n    //\n    // Track whether the file uses the env-nested shape so we mutate only the\n    // relevant subtree and preserve every other top-level key on write.\n    let document: Record<string, unknown> = {};\n    let envNested = false;\n    if (existsSync(path)) {\n      try {\n        const parsed = parseJsonWithBom(readFileSync(path, 'utf-8'));\n        if (parsed && typeof parsed === 'object') {\n          document = parsed as Record<string, unknown>;\n          envNested = typeof document.env === 'object' && document.env !== null;\n        }\n      } catch (parseError: unknown) {\n        console.warn('[install] Failed to parse existing settings.json, starting from empty:', parseError instanceof Error ? parseError.message : String(parseError));\n        document = {};\n      }\n    } else {\n      const dir = dirname(path);\n      if (!existsSync(dir)) {\n        mkdirSync(dir, { recursive: true });\n      }\n    }\n\n    const target = envNested\n      ? (document.env as Record<string, unknown>)\n      : document;\n    for (const [key, value] of Object.entries(updates)) {\n      target[key] = value;\n    }\n\n    writeSettingsJsonAtomic(path, document);\n    // settings.json can carry tokens (CMEM Pro setup token, provider API","sourceCodeStart":781,"sourceCodeEnd":817,"githubUrl":"https://github.com/thedotmack/claude-mem/blob/e2d1df569a8f04075d40e92461128ece7cf04c82/src/npx-cli/commands/install.ts#L781-L817","documentation":"The installer reads an existing settings.json (with BOM tolerance) before merging updates. If parsing throws, it warns and starts from an empty document — meaning every OTHER top-level key in the broken file will be lost when the new settings are written. The current error message is included so you can locate the syntax problem.","triggerScenarios":"parseJsonWithBom throwing on invalid JSON: trailing commas, comments, unquoted keys, truncated file from a killed concurrent write. The subsequent writeSettingsJsonAtomic overwrites the file with only the installer's keys.","commonSituations":"Hand-edited settings.json with a trailing comma or JSON5-style comment; file truncated by a crash mid-write; another tool wrote JSON-with-BOM plus invalid syntax; symlinked settings file pointing at a broken target.","solutions":["Back up and repair the file BEFORE letting the installer write: `cp ~/.claude-mem/settings.json{,.bak}` then fix the syntax error reported in the warning message.","Validate with `jq . ~/.claude-mem/settings.json` — the parse error location matches what the installer hit.","If the contents are not worth saving, delete the file and let the installer regenerate a clean one.","After install, re-add any custom top-level keys you lost from the backup."],"exampleFix":"// before: ~/.claude-mem/settings.json (invalid — trailing comma)\n{ \"CLAUDE_MEM_PROVIDER\": \"claude\", }\n// after\n{ \"CLAUDE_MEM_PROVIDER\": \"claude\" }","handlingStrategy":"validation","validationCode":"// Validate BEFORE the installer does — protects other keys from the empty-document path:\nimport { readFileSync, existsSync, copyFileSync } from 'node:fs';\nif (existsSync(p)) {\n  copyFileSync(p, `${p}.bak`); // snapshot before any installer write\n  try { JSON.parse(readFileSync(p, 'utf8').replace(/^\\uFEFF/, '')); }\n  catch (e) { console.error('settings.json invalid — fix before install:', e); process.exit(1); }\n}","typeGuard":null,"tryCatchPattern":"catch (parseError: unknown) {\n  // KEEP the parsed document as {} ONLY if you know the file had no other keys;\n// otherwise abort the write instead of clobbering — data preservation beats convenience.\n}","preventionTips":["Snapshot settings.json before every claude-mem install/upgrade run.","Lint settings files in CI (`jq . settings.json > /dev/null`) when you manage them declaratively.","Use JSON editors or jq for edits, never freeform text editors with JSONC habits.","Remember the semantics: this warning means all unmanaged top-level keys WILL be lost on the next write."],"tags":["settings","json","install","data-loss"],"backgroundTag":"json-parse-error","analyzedSha":"e2d1df569a8f04075d40e92461128ece7cf04c82","analyzedAt":"2026-08-20T23:58:13.836Z","schemaVersion":2},"datasetVersion":"2026-08-29T07:17:48.351Z"}