gitbutlerapp/gitbutler · error

transcript contains malformed JSON before the final record

Error message

transcript contains malformed JSON before the final record

What it means

Thrown by transcript parsing when a JSONL transcript record (from Claude or Codex logs) fails to deserialize, and the malformed record is not the last one in the file. Only a trailing malformed record is tolerated (skipped); any malformed record earlier in the file aborts the whole parse, because the parser cannot trust the structure of the remaining transcript.

Solutions

  1. Open the transcript file and find the first line that is not valid JSON; repair or remove it
  2. Validate each line with a JSONL linter before parsing
  3. Re-generate the transcript by replaying the agent session if repair is not possible
  4. If you only need the last record, extract the trailing line instead of full-parse

Example fix

// before
let transcript = Transcript::parse(path, agent)?; // bails on mid-file malformed JSON
// after
let raw = std::fs::read_to_string(path)?;
let cleaned: Vec<&str> = raw.lines().enumerate().filter(|(i, l)| {
    serde_json::from_str::<serde_json::Value>(l).is_ok() || *i + 1 == raw.lines().count()
}).map(|(_, l)| l).collect();
let transcript = Transcript::parse_lines(cleaned, agent)?;
Defensive patterns

Strategy: validation

Validate before calling

const lines = raw.split("\n").filter(Boolean);
const bad = lines.slice(0, -1).findIndex(l => { try { JSON.parse(l); return false; } catch { return true; } });
if (bad !== -1) throw new Error(`malformed JSONL record at line ${bad + 1}`);

Type guard

function isParseableJsonl(lines: string[]): boolean {
  return lines.slice(0, -1).every(l => { try { JSON.parse(l); return true; } catch { return false; } });
}

Try / catch

try {
  const t = Transcript::parse(path, agent);
} catch (e) {
  if (String(e).includes("malformed JSON before the final record")) {
    t = sanitizeTranscript(path, agent); // drop/repair bad lines, keep valid tail
  } else { throw e; }
}

Prevention

When it happens

Trigger: Parsing an agent transcript file that contains a truncated, partially-written, or corrupted JSON line anywhere except the final line — e.g. a crash or concurrent write left an incomplete record mid-file.

Common situations: Reading Claude Code or Codex session transcripts after an editor/agent crash, appending to a live transcript while parsing, or manually editing a JSONL file and leaving a bad line.

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 gitbutlerapp/gitbutler@58e5313667 (2026-09-18). Data as JSON: /api/errors/c9481332d5b4bac4. Report an issue: GitHub.

Appendix: source

Thrown at crates/but-agentlog/src/transcript.rs:47

            session_id: None,
            provider: match agent {
                Agent::Codex => None,
                Agent::Claude => Some("anthropic".to_string()),
            },
            model: None,
            tool_version: None,
            thread_source: None,
            records: Vec::new(),
        };
        let mut codex_tool_names = HashMap::new();
        let mut codex_spawn_prompts = HashSet::new();
        let mut claude_tool_names = HashMap::new();

        while let Some((index, trimmed)) = raw_records.next() {
            let parsed = match serde_json::from_slice::<Value>(trimmed) {
                Ok(parsed) => parsed,
                Err(_) if raw_records.peek().is_none() => continue,
                Err(_) => bail!("transcript contains malformed JSON before the final record"),
            };

            let record = match agent {
                Agent::Codex => {
                    transcript.apply_codex_metadata(&parsed);
                    ParsedRecord::from_codex_source(
                        index,
                        trimmed,
                        parsed,
                        &mut codex_tool_names,
                        &mut codex_spawn_prompts,
                        transcript.thread_source.as_deref(),
                    )
                }
                Agent::Claude => {
                    transcript.apply_claude_metadata(&parsed);
                    ParsedRecord::from_claude_source(index, trimmed, parsed, &mut claude_tool_names)
                }

View on GitHub (pinned to 58e5313667)